Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
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
31
Tags
more
Archives
Today
Total
관리 메뉴

kang's study

6일차 ① : 다중회귀_특성공학 본문

[학습 공간]/[혼공머신러닝]

6일차 ① : 다중회귀_특성공학

보끔밥0302 2022. 3. 2. 01:32

다중회귀 (multiple regression)

① 특성공학
 

데이터 준비

 

pandas는 데이터 분석 라이브러리 pandas의 핵심 데이터 구조는 데이터프레임(dataframe)이다.

In [22]:
import pandas as pd
In [23]:
df = pd.read_csv('https://bit.ly/perch_csv_data') # Data.frame형태
perch_full = df.to_numpy() # 넘파이 배열
print(perch_full.shape)
 
(56, 3)
In [24]:
import numpy as np

perch_weight = np.array(
    [5.9, 32.0, 40.0, 51.5, 70.0, 100.0, 78.0, 80.0, 85.0, 85.0, 
     110.0, 115.0, 125.0, 130.0, 120.0, 120.0, 130.0, 135.0, 110.0, 
     130.0, 150.0, 145.0, 150.0, 170.0, 225.0, 145.0, 188.0, 180.0, 
     197.0, 218.0, 300.0, 260.0, 265.0, 250.0, 250.0, 300.0, 320.0, 
     514.0, 556.0, 840.0, 685.0, 700.0, 700.0, 690.0, 900.0, 650.0, 
     820.0, 850.0, 900.0, 1015.0, 820.0, 1100.0, 1000.0, 1100.0, 
     1000.0, 1000.0]
     )
print(perch_weight.shape)
 
(56,)
In [25]:
from sklearn.model_selection import train_test_split

train_input, test_input, train_target, test_target = train_test_split(perch_full, perch_weight, random_state=42)
 

사이킷런의 변환기 (다항 특성 만들기)

변환기 : 특성을 만들거나 전처리하는 클래스

In [26]:
from sklearn.preprocessing import PolynomialFeatures
In [27]:
# degree = 2 (default은 제곱항만 만듬)
#  2개의 특성 2와 3으로 이루어진 샘플 적용
poly = PolynomialFeatures()
poly.fit([[2, 3]])
print(poly.transform([[2, 3]]))
# 2제곱, 3제곱, 2*3, 절편은 1인 특성과 곱해진 계수로 보아 1 추가
 
[[1. 2. 3. 4. 6. 9.]]
 

추정기 estimate (LinearRegression) : fit, predict, score
변환기 transformer (PolynomialFeatures) : fit, transform
훈련(fit)을 해야 변환(transform)이 가능한 점에 유의하자

In [28]:
# 사이킷런은 자동으로 절편을 추가하므로 1은 제외
poly = PolynomialFeatures(include_bias=False)

# 1(bias), 2, 3, 2**2, 2*3, 3**2
poly.fit([[2, 3]])
print(poly.transform([[2, 3]]))
 
[[2. 3. 4. 6. 9.]]
 

LinearRegression

In [29]:
poly = PolynomialFeatures(include_bias=False) 
# 절편의 특성을 제외
# 사이킷런 모델은 특성에 추가된 절편 항을 무시하므로 지정하지 않아도 됨
poly.fit(train_input)
train_poly = poly.transform(train_input)
In [30]:
print(train_poly.shape)
 
(42, 9)
In [31]:
poly.get_feature_names() # 각 특성의 조합 확인
Out[31]:
['x0', 'x1', 'x2', 'x0^2', 'x0 x1', 'x0 x2', 'x1^2', 'x1 x2', 'x2^2']
In [32]:
test_poly = poly.transform(test_input) # 훈련의 변환을 테스트도 같이 변환
 

다중 회귀 모델 훈련하기

In [33]:
from sklearn.linear_model import LinearRegression

lr = LinearRegression()
lr.fit(train_poly, train_target)
print(lr.score(train_poly, train_target))
 
0.9903183436982125
In [34]:
print(lr.score(test_poly, test_target))
 
0.9714559911594155
 

더 많은 특성 만들기

In [35]:
# 5제곱까지 특성
poly = PolynomialFeatures(degree=5, include_bias=False)
poly.fit(train_input)
train_poly = poly.transform(train_input)
test_poly = poly.transform(test_input)
In [36]:
print(train_poly.shape)
 
(42, 55)
In [37]:
lr.fit(train_poly, train_target)
print(lr.score(train_poly, train_target))
 
0.9999999999938143
In [38]:
print(lr.score(test_poly, test_target))
 
-144.40744532797535
 

42개의 샘플을 55개의 특성으로 훈련하여 너무 완벽한 학습을 한다.

특성의 개수를 크게 늘리면 훈련 세트에 너무 과대적합 된다.

출처 : 박해선, 『혼자공부하는머신러닝+딥러닝』, 한빛미디어(2021), p150-158

Comments