Notice
Recent Posts
Recent Comments
Link
«   2025/04   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30
Tags
more
Archives
Today
Total
관리 메뉴

공부하자

실습 - sklearn 데이터셋 : Boston (2) 본문

실습

실습 - sklearn 데이터셋 : Boston (2)

맥뚜원샷 2021. 1. 13. 16:27

boston 데이터셋은 찾아보니 보통 sklearn의 선형회귀 모델로 예측하는 듯

 

import sklearn
from sklearn.linear_model import LinearRegression
help(LinearRegression)
###############################################################
'''
myreg = LinearRegression(fit_intercept=True, normalize=False, ...) 이라는 명령으로 class 객체 생성
fit_intercept : 절편을 사용하지 않는다, 즉 데이터가 중심에 있다고 가정
normalize : 만악 fit_intercept가 False면(절편을 사용한다면)고려하지 않음. True면 X가 normalized
나머지는 알필요 없을듯 아직
'''

LinearRegression 객체를 생성하고, DV와 RV를 분리

myreg = LinearRegression() # LinearRegression 객체생성
X, y = boston_df.iloc[:, :-1], boston_df.iloc[:, -1]
# type(X) = Dataframe, type(y) = Series

 

 

train data와 test data 분리해서 Linear Regression 모델 만들기

1) train index, test index를 sampling하여 df.iloc[train_index, :]와 df.iloc[test_index, :] 명령으로 분리(해보려 했음)

train data와 test data를 나누기가 좀 어려웠다. index를 X의 길이의 0.7배만큼 random sampling해서 train index로 만들고, 그 외 나머지를 test index로 나누어 df를 만들어 보았다.

X_train_index = np.random.choice(X.index, int(len(X)*0.7), replace = False) # 비복원추출
X_test_index = np.array(list(filter(lambda x: x not in X_train_index, X.index)), dtype="int64")
# filter 함수를 통해 X.index 중 X_train_index에 있지 않은 요소들만 골라냈다.

 

X_test_index를 filter함수를 통해 만들었는데, 이거 R에서는 간단하게 X.index[-X_train_index] 였나, 여튼 전체 중 제외하고 싶은 요소들의 array에 - 를 붙여주면 알아서 나머지 것들로 리턴해 줬었는데, 파이썬에서도 그렇게 할 수 있는 메소드가 있는지 잘 모르겠음.

X_train = X.iloc[X_train_index, :]
X_train

근데 이러면 에러가 뜬다. 대강 indexor가 너무 많다는 뜻의 error인 것 같고 index가 11개 이상이면 이런 error가 뜨는 듯..  직접 만들어보려 했으나 잘 되지 않으니 그냥 sklearn의 서브패키지를 이용하겠음.

 

 

 

 

 

2) sklearn의 train_test_split 사용

from sklearn.model_selection import train_test_split
help(train_test_split) # 어떻게 쓰는지 확인용
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3)
# 맨 처음 인자부터 길이가 같은 data들을 계속 넣을 수 있다. test_size = 0.3은 train:test = 7:3으로
# 뽑는다는 뜻, data하나당 두 개의 return값이 나옴.

LR.fit(X_train, y_train)
LR.score(X_train, y_train)
0.7406179306112268

LR.predict(X_test)

LR.score(X_test, y_test)
0.718063976028907

복습 위해 Rsquare를 직접 구해봤음

 

### 참고 ###

R^2 = 1-SSE/TSS

SSE : 예측 y와 실제 y의 차이의 Squared sum

TSS : 실제 y와 실제 y 평균의 차이의 Squared sum

 

SSE는 말 그대로 예측값과 실제값의 차이를 제곱하여 더한 것이고, 

TSS는 실제값과 실제값의 평균과의 차이를 제곱하여 더한 것.

왜 실제값의 평균이 뜬금없이 나왔나? -> 가장 기본적이고 단순한 추정 방법.

Rsquare는 추정 방법 중 가장 단순한 방법인 평균값을 이용한 추정에 비해 자신의 예측모델이 얼마나 성능이 좋느냐를 본다.

 

TSS-SSE를 수식으로 정리하면 예측 y와 실제 y 평균의 차이의 Squared sum이라는 걸 알 수 있다.

 

scoredf = pd.DataFrame(LR.predict(X_test), columns = ['X'])
scoredf['y']=y_test.values
scoredf.set_index(y_test.index, inplace = True)

print(scoredf)
             X     y
272  28.085077  24.4
453  21.843819  17.8
78   21.365436  21.2
452  18.469324  16.1
184  22.776506  26.4
299  31.127359  29.0
59   21.466521  19.6
289  26.035548  24.8
434  16.359005  11.7
336  20.388084  19.5
348  27.025206  24.5
...

# 대충 이런 모양이 된다.

y의 평균, SSE, TSS를 구해 scoredf에 붙인다.

scoredf['y_mean']=y_test.mean() # test y의 mean으로 열 하나를 다 채움
scoredf['SSE'] = (scoredf['X']-scoredf['y'])**2 # 각 row의 squared error
scoredf['TSS'] = (scoredf['y']-scoredf['y_mean'])**2 # 각 row의 total..error? 용어가 뭔지모름
SSE_TSS_sum = scoredf[['SSE', 'TSS']].sum() # 두 열의 합을 pandas 데이터구조에 정리

print(SSE_TSS_sum)
SSE    2567.835225
TSS    9107.864931
dtype: float64


SSE, TSS = SSE_TSS_sum['SSE'], SSE_TSS_sum['TSS']
1-SSE/TSS
0.7180639760289071

LR.score(X_test, y_test)값과 같음.

 

가중치값을 보고 싶다. -> LR.coef_

절편값 -> LR.intercept_

 

 

 

##########

 

- Boston (1)에서 LSTAT이랑 Target 간 관계가 어느 정도 뚜렷하게 보였었다. 이걸 이용해서 다른 모델을 만들어볼 수는 없을지

- Linear Regression은 선형적 관계가 있는 경우에 활용 가능한데, 이 데이터가 선형적 관계인지 장담할 수가 없는데 어째서 가장 적합한 모델인지

 

 

###### 정리 #######

# Train, Test data 분리
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3)


# Linear Regression 모델링
from sklearn.linear_model import LinearRegression
LR = LinearRegression()
LR.fit(X_train, y_train)
LR.predict(X_test)
LR.score(X_test, y_test)
LR.coef_ \ LR.intercept_