파이썬 로지스틱회귀 열 하나로 정확도 예측하기
조회수 907회
사이킷런 위스콘신 유방암 데이터를 통한 두가지 분류의 정확도를 코드로 나타내는 방법을 공부하고 있습니다.
데이터(행)은 총 569가지 이고, 이를 특징으로 구별해줄 열이 30가지 입니다. 제가 기존에 공부했던 코드는 총 30가지 데이터셋을 이용해서 이진분류(양성, 음성)인지 판별할 경우 82%의 정확도를 가졌는데요, 이를 수정하여 만약 4번째 열에서의 특징만을 가지고 정확도를 분류하려면 어떤 코드를 추가해야할까요??
from sklearn.datasets import load_breast_cancer
cancer = load_breast_cancer()
import numpy as np
import pandas as pd
print(cancer.data.shape, cancer.target.shape)
import matplotlib.pyplot as plt
import numpy as np
plt.boxplot(cancer.data)
plt.xlabel('feature')
plt.ylabel('value')
plt.show()
cancer.feature_names[[3,13,23]]
x = cancer.data (=>이 부분을 수정해야한다고 생각해서 cancer.data[3]이라고 넣고 다음코드를 진행했는데, 실행되지 않습니다..)
y = cancer.target
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, stratify = y, test_size=0.2, random_state=42)
#로지스틱 회귀 구현하기
class LogisticNeuron:
def __init__(self):
self.w = None
self.b = None
def forpass(self, x):
z = np.sum(x*self.w) + self.b #직선의 방정식 계산
return z
def backprop(self, x, err):
w_grad = x*err #가중치에 대한 그레디언트 계산
b_grad = 1*err #절편에 대한 그레디언트 계산
return w_grad, b_grad
#훈련하는 매서드 구현하기
def fit(self, x, y, epochs = 100):
self.w = np.ones(x.shape[1]) #가중치 초기화
self.b = 0 #절편 초기화
for i in range(epochs): #epochs 만큼 반복
for x_i, y_i in zip(x,y): #모든 샘플에 대해 반복
z = self.forpass(x_i) #정방향 계산
a= self.activation(z) #활성화 함수 적용
err = -(y_i - a) #오차 계산
w_grad, b_grad = self.backprop(x_i, err) #역방향 계산
self.w-=w_grad #가중치 업데이트
self.b-=b_grad #절편 업데이트
def activation(self,z):
a=1/(1+np.exp(-z))
return a
#예측하는 매서드 구현하기
def predict(self, x):
z=[self.forpass(x_i) for x_i in x] #정방향 계산
a = self.activation(np.array(z)) #활성화함수 적용
return a>0.5
#로지스틱 회귀 모델 훈련시키기
neuron = LogisticNeuron()
neuron.fit(x_train, y_train)
#예측값 맞는지 테스트 세트 사용해 모델의 정확도 평가하기
np.mean(neuron.predict(x_test) == y_test)
==> 결과:0.8245614035087719 이로서 82%가 나왔습니다.
제가 원하는건,
x = cancer.data
이부분을 수정하여 전체 30개의 특징을 가지고 정확도를 구하는게 아니라, 4번째 특징을 가지고 정확도를 확인하고싶어서
이부분을
x = cancer.data[3]
이렇게 수정했는데요, 그 다음 여기부분에서 오류가 발생합니다.
x_train, x_test, y_train, y_test = train_test_split(x, y, stratify = y, test_size=0.2, random_state=42)
ValueError Traceback (most recent call last)
<ipython-input-51-49b444fce24c> in <module>()
----> 1 x_train, x_test, y_train, y_test = train_test_split(x, y, stratify = y, test_size=0.2, random_state=42)
2 frames
/usr/local/lib/python3.7/dist-packages/sklearn/utils/validation.py in check_consistent_length(*arrays)
210 if len(uniques) > 1:
211 raise ValueError("Found input variables with inconsistent numbers of"
--> 212 " samples: %r" % [int(l) for l in lengths])
213
214
ValueError: Found input variables with inconsistent numbers of samples: [30, 569]
1 답변
-
x = cancer.data[:, 3]
x = cancer.data[:, 3:4]
- 말씀하신 부분 수정하였더니 로지스틱 회귀 구현하는것까지는 막힘없이 잘 실행됩니다! 감사합니다. DAEUNJUNG7 2021.3.17 17:45
- 근데 다만 회귀 모델 훈련시킬때 오류가 발생합니다.. DAEUNJUNG7 2021.3.17 17:46
- --------------------------------------------------------------------------- IndexError Traceback (most recent call last) in () 1 #로지스틱 회귀 모델 훈련시키기 2 neuron = LogisticNeuron() ----> 3 neuron.fit(x_train, y_train) 4 5 #예측값 맞는지 테스트 세트 사용해 모델의 정확도 평가하기 in fit(self, x, y, epochs) 17 #훈련하는 매서드 구현하기 18 def fit(self, x, y, epochs = 100): ---> 19 self.w = np.ones(x.shape[1]) #가중치 초기화 20 self.b = 0 #절편 초기화 21 for i in range(epochs): #epochs 만큼 반복 IndexError: tuple index out of range DAEUNJUNG7 2021.3.17 17:47
- 이런식으로 발생하는데 혹시 이유를 아실까요? DAEUNJUNG7 2021.3.17 17:47
댓글 입력