본문 바로가기

코딩으로 익히는 Python/모델링

[Python] 5. 문자열encoding : LabelEncoder, OneHotEncoder, get_dummies(), make_column_transformer 예제

728x90
반응형
SMALL
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.datasets import load_boston, load_iris
from sklearn.linear_model import Ridge,Lasso,ElasticNet,LinearRegression
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score

from sklearn.preprocessing import OneHotEncoder,LabelEncoder
from sklearn.compose import make_column_transformer

import mglearn
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='Malgun Gothic'
matplotlib.rcParams['axes.unicode_minus'] = False

import warnings
warnings.simplefilter('ignore')

 

데이터 불러오기 (pd.read_excel)

python 파일 경로에 data4 폴더 만든 후 다음의 'hyundaiCar.xlsx'파일 넣어놓기

hyundaiCar.xlsx
0.01MB

df = pd.read_excel('data4/hyundaiCar.xlsx')
df

 

 

train_df = pd.read_excel('data4/hyundaiCar.xlsx',sheet_name='train')
test_df =  pd.read_excel('data4/hyundaiCar.xlsx',sheet_name='test')
x_train = train_df.iloc[:,1:] # '가격;' 제외한 컬럼
y_train = train_df['가격']
x_train

 

x_test = test_df.iloc[:,1:] # '가격;' 제외한 컬럼
y_test = test_df['가격']
x_test

 

print(x_train.shape,x_test.shape)
[OUT]:

(71, 10) (31, 10)

 

print(y_train.shape,y_test.shape)
[OUT]:

(71,) (31,)

문자열 encoding

 

x_train.info() # object가 많음
[OUT]:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 71 entries, 0 to 70
Data columns (total 10 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   년식      71 non-null     int64  
 1   종류      71 non-null     object 
 2   연비      71 non-null     float64
 3   마력      71 non-null     int64  
 4   토크      71 non-null     float64
 5   연료      71 non-null     object 
 6   하이브리드   71 non-null     int64  
 7   배기량     71 non-null     int64  
 8   중량      71 non-null     int64  
 9   변속기     71 non-null     object 
dtypes: float64(2), int64(5), object(3)
memory usage: 5.7+ KB

 

x_train[:5]

 

x_train['종류']
[OUT]:

0     준중형
1     준중형
2      소형
3      소형
4      대형
     ... 
66     중형
67     소형
68    준중형
69     중형
70     대형
Name: 종류, Length: 71, dtype: object

 

  • LabelEncoder
lbl = LabelEncoder()
x_trainLabel = lbl.fit_transform(x_train['종류']) 
x_trainLabel
[OUT]:

array([2, 2, 1, 1, 0, 3, 3, 1, 3, 1, 2, 3, 2, 0, 1, 0, 0, 0, 3, 0, 0, 3,
       2, 0, 3, 3, 3, 1, 1, 2, 0, 0, 0, 0, 1, 0, 2, 0, 2, 1, 1, 1, 0, 0,
       0, 2, 1, 0, 2, 1, 3, 3, 0, 2, 2, 0, 3, 2, 0, 0, 2, 0, 1, 0, 0, 1,
       3, 1, 2, 3, 0])

 

lbl.classes_ # 0,1,2,3으로 변환
[OUT]:

array(['대형', '소형', '준중형', '중형'], dtype=object)

 

lbl.transform(['소형'])
[OUT]:

array([1], dtype=int64)

 

x_train

 

  • OneHotEncoder(원핫인코딩) : 0 or 1
oneH = OneHotEncoder()
x_trainOne = oneH.fit_transform(x_train['종류'].values.reshape(-1,1))
x_trainOne
[OUT]:

<71x4 sparse matrix of type '<class 'numpy.float64'>'
	with 71 stored elements in Compressed Sparse Row format>

 

x_train['종류'][:5]
[OUT]:

0    준중형
1    준중형
2     소형
3     소형
4     대형
Name: 종류, dtype: object

 

x_trainOne.toarray()
[OUT]:

array([[0., 0., 1., 0.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.],
       [0., 1., 0., 0.],
       [1., 0., 0., 0.],
       [0., 0., 0., 1.],
       [0., 0., 0., 1.],
       [0., 1., 0., 0.],
       [0., 0., 0., 1.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 0., 0., 1.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 0., 0., 1.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [0., 0., 0., 1.],
       [0., 0., 0., 1.],
       [0., 0., 0., 1.],
       [0., 1., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [1., 0., 0., 0.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.],
       [0., 1., 0., 0.],
       [0., 1., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.],
       [1., 0., 0., 0.],
       [0., 0., 1., 0.],
       [0., 1., 0., 0.],
       [0., 0., 0., 1.],
       [0., 0., 0., 1.],
       [1., 0., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [0., 0., 0., 1.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 0., 1., 0.],
       [1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [1., 0., 0., 0.],
       [1., 0., 0., 0.],
       [0., 1., 0., 0.],
       [0., 0., 0., 1.],
       [0., 1., 0., 0.],
       [0., 0., 1., 0.],
       [0., 0., 0., 1.],
       [1., 0., 0., 0.]])

 

oneH.categories_ # 1000,0100,0010,0001 로 변환
[OUT]:

[array(['대형', '소형', '준중형', '중형'], dtype=object)]

 

 

  • 판다스 dummy
pd.get_dummies(x_train['종류']) # 원핫인코딩 느낌

 

x_train # 아래와 비교하기

 

pd.get_dummies(x_train) # string인 컬럼들을 원핫인코딩으로 변경해서 컬럼추가

 

pd.get_dummies(x_train) # string인 컬럼들을 원핫인코딩으로 변경해서 컬럼추가

 

pd.get_dummies(x_train,columns=['연료','변속기']) # 원하는 컬럼만 설정 가능

 

  • replace

x_train['종류'].replace(['대형','중형','준중형','소형'],[0,1,2,3]) # replace함수 이용 원하는 숫자로 변경
[OUT]:

0     2
1     2
2     3
3     3
4     0
     ..
66    1
67    3
68    2
69    1
70    0
Name: 종류, Length: 71, dtype: int64

 

  • make_column_transformer
myt = make_column_transformer((LabelEncoder(),['종류','연료','변속기']))
myt
[OUT]:

ColumnTransformer(n_jobs=None, remainder='drop', sparse_threshold=0.3,
                  transformer_weights=None,
                  transformers=[('labelencoder', LabelEncoder(),
                                 ['종류', '연료', '변속기'])],
                  verbose=False)

 

result = myt.fit_transform(x_train) # 라벨인코더는 2차원이아니고 1차원을 줘야함
result # error

 

myt = make_column_transformer((OneHotEncoder(),['종류','연료','변속기']))
result = myt.fit_transform(x_train)
result
[OUT]:

array([[0., 0., 1., 0., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 1., 0.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.],
       [0., 0., 0., 1., 0., 0., 1., 0., 1.],
       [0., 0., 0., 1., 0., 0., 1., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [0., 0., 0., 1., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 0., 1., 0., 1.],
       [0., 0., 0., 1., 0., 0., 1., 0., 1.],
       [0., 0., 1., 0., 0., 0., 1., 1., 0.],
       [1., 0., 0., 0., 1., 0., 0., 1., 0.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 1., 0.],
       [1., 0., 0., 0., 0., 0., 1., 1., 0.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [0., 0., 0., 1., 0., 0., 1., 0., 1.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 1., 0., 0., 0., 1.],
       [0., 0., 0., 1., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 0., 1., 1., 0.],
       [1., 0., 0., 0., 0., 0., 1., 1., 0.],
       [0., 0., 0., 1., 0., 0., 1., 0., 1.],
       [0., 0., 0., 1., 0., 0., 1., 0., 1.],
       [0., 0., 0., 1., 0., 0., 1., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 1., 0.],
       [0., 0., 1., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.],
       [1., 0., 0., 0., 1., 0., 0., 1., 0.],
       [0., 1., 0., 0., 0., 0., 1., 1., 0.],
       [1., 0., 0., 0., 0., 0., 1., 1., 0.],
       [0., 0., 1., 0., 0., 1., 0., 1., 0.],
       [1., 0., 0., 0., 1., 0., 0., 0., 1.],
       [0., 0., 1., 0., 1., 0., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.],
       [0., 0., 1., 0., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 1., 0.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 0., 1., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 1., 0.],
       [0., 0., 0., 1., 0., 1., 0., 0., 1.],
       [0., 0., 0., 1., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 0., 1., 1., 0.],
       [0., 0., 1., 0., 0., 1., 0., 1., 0.],
       [1., 0., 0., 0., 0., 0., 1., 1., 0.],
       [0., 0., 0., 1., 0., 0., 1., 1., 0.],
       [0., 0., 1., 0., 0., 0., 1., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.],
       [0., 0., 1., 0., 0., 0., 1., 0., 1.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 1., 0.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.],
       [1., 0., 0., 0., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 1., 0.],
       [0., 0., 0., 1., 0., 1., 0., 0., 1.],
       [0., 1., 0., 0., 0., 1., 0., 0., 1.],
       [0., 0., 1., 0., 0., 0., 1., 0., 1.],
       [0., 0., 0., 1., 0., 1., 0., 0., 1.],
       [1., 0., 0., 0., 0., 0., 1., 0., 1.]])

학습

 

model = make_pipeline(myt,StandardScaler(),Ridge())
# param_value = {'ridge__alpha' : range(-10,100)} # ridge__붙여주기
param_value = {'ridge__alpha' : np.linspace(-10,100,num=1000)} 
gridS = GridSearchCV(model,param_grid=param_value, scoring='r2')
gridS.fit(x_train,y_train)
print(gridS.best_params_)
print(gridS.best_score_) # 선형은 r2가 기본
[OUT]:

{'ridge__alpha': 26.116116116116117}
0.12545014872846838

 

gridS.best_estimator_.predict(x_test)
[OUT]:

array([2003.17268252, 1905.157112  , 2748.55522686, 2516.02748514,
       2585.64959399, 1475.59377744, 1602.99937328, 2516.02748514,
       2185.47628475, 2032.56270785, 3178.11856143, 3178.11856143,
       1475.59377744, 2185.47628475, 3528.06773117,  893.11686597,
       1602.99937328, 1905.157112  , 1905.157112  , 2032.56270785,
       1322.68020053, 2032.56270785, 3528.06773117, 2615.03961931,
       2615.03961931, 2615.03961931, 3528.06773117, 2516.02748514,
       3098.50439661, 1905.157112  , 2166.07831539])

review
- label encoding은 숫자의 크고 작음에 대한 특성이 작용할 수 있으므로 선형회귀에서는 지양
- 원핫인코딩 특히 get_dummies() 지향
728x90
반응형
LIST