
파이프라인 사용 목적
파이프라인 사용하지 않은 경우와 사용한 경우 비교해보기
from sklearn.feature_selection import SelectKBest, f_classif # 피처선택 메서드
from sklearn.preprocessing import StandardScaler # 데이터 표준화
from sklearn.tree import DecisionTreeClassifier # 의사결정나무 분류기
from sklearn.datasets import load_iris # iris 데이터세트
# iris 데이터세트 로드
X, y = load_iris(return_X_y=True)
## 피쳐 선택
feat_sel = SelectKBest(f_classif, k=2)
X_selected = feat_sel.fit_transform(X, y)
print('Selected features:', feat_sel.get_feature_names_out())
## 표준화
scaler = StandardScaler()
scaler.fit(X_selected)
X_transformed = scaler.transform(X_selected)
print('Standard Scaled: \n', X_transformed[:5, :])
## 모델 학습
clf = DecisionTreeClassifier(max_depth=3)
clf.fit(X_transformed, y)
print('Estimate : ', clf.predict(X_transformed)[:3])
print('Accuracy : ', clf.score(X_transformed, y))
Selected features: ['x2' 'x3']
Standard Scaled:
[[-1.34022653 -1.3154443 ][-1.34022653 -1.3154443 ]
[-1.39706395 -1.3154443 ][-1.2833891 -1.3154443 ]
[-1.34022653 -1.3154443 ]]
Estimate : [0 0 0]
Accuracy : 0.9733333333333334
from sklearn.pipeline import Pipeline # 파이프라인 구성을 위한 함수
from sklearn.feature_selection import SelectKBest, f_classif # 피처선택 메서드
from sklearn.preprocessing import StandardScaler # 데이터 표준화
from sklearn.tree import DecisionTreeClassifier # 의사결정나무 분류기
from sklearn.datasets import load_iris # iris 데이터세트
# iris 데이터세트 로드
X, y = load_iris(return_X_y=True)
## pipeline 구축
pipeline = Pipeline([
('Feature_Selection', SelectKBest(f_classif, k=2)), ## 피쳐 선택
('Standardization', StandardScaler()), ## 표준화
('Decision_Tree', DecisionTreeClassifier(max_depth=3)) ## 학습 모델
])
display(pipeline) # 파이프라인 그래프로 구성 확인
pipeline.fit(X, y) ## 모형 학습
print('Estimate : ', pipeline.predict(X)[:3]) ## 예측
print('Accuracy : ', pipeline.score(X, y)) ## 성능 평가
Estimate : [0 0 0]
Accuracy : 0.9733333333333334
from sklearn.pipeline import make_pipeline # 파이프라인 구성을 위한 함수
pipeline_auto = make_pipeline(SelectKBest(f_classif, k=2),
StandardScaler(),
DecisionTreeClassifier(max_depth=3))
display(pipeline_auto) # 파이프라인 그래프로 구성 확인
# pipiline의 Feature_Selection step의 결과 확인
# pipeline.named_steps['Feature_Selection'] == pipeline[0]
# pipeline.named_steps['Standardization'] == pipeline[1]
# pipeline.named_steps['Decision_Tree'] == pipeline[2]
print('Selected features:', pipeline.named_steps['Feature_Selection'].get_feature_names_out())
X_transformed = pipeline[1].transform(X_selected)
print('Standard Scaled: \n', X_transformed[:5, :])
Selected features: ['x2' 'x3']
Standard Scaled:
[[-1.34022653 -1.3154443 ][-1.34022653 -1.3154443 ]
[-1.39706395 -1.3154443 ][-1.2833891 -1.3154443 ]
[-1.34022653 -1.3154443 ]]
여러 파이프라인을 결합하여 전체 데이터 처리 프로세스를 정의할 수 있음
import seaborn as sns
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
# 데이터 로드
df = sns.load_dataset('diamonds')
print(df.info())
X = df.drop('price', axis=1)
y = df['price']
# 데이터를 유형에 따라 분리
numeric_col = list(X.select_dtypes(exclude='category').columns)
category_col = list(X.select_dtypes(include='category').columns)
print(f'numeric_col: {numeric_col}')
print(f'category_col: {category_col}')
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
# 파이프라인 구축
category_pipeline = Pipeline(
steps=[
('imputer', SimpleImputer(strategy='constant', fill_value='missing')), # 비어있는 값을 'missing'으로 채우기
('onehot', OneHotEncoder(sparse_output=False)), # Onehotencoder
])
display(category_pipeline) # 파이프라인 그래프로 구성 확인
# 파이프라인 학습
category_data_piped = category_pipeline.fit_transform(X[category_col])
# Onehotencoder의 컬럼명을 확인
category_colnames = category_pipeline[1].get_feature_names_out(category_col)
# 파이프라인 이후 데이터(array형 -> 데이터프레임)
pd.DataFrame(category_data_piped, columns=category_colnames).head()
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LinearRegression
# numeric & category 파이프라인 합치기
preprocessor = ColumnTransformer(
transformers=[
('numeric', numeric_pipeline, numeric_col),
('category', category_pipeline, category_col)
])
pipe = make_pipeline(preprocessor, LinearRegression())
display(pipe) # 파이프라인 그래프로 구성 확인
pipe.fit(X,y)
print('Estimate : ', pipe.predict(X))
print('Accuracy : ', pipe.score(X, y))
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
import pandas as pd
import numpy as np
data_df = pd.DataFrame({
"height":[165, np.nan, 182],
"weight":[70, 62, np.nan],
"age" :[np.nan,18, 15]
})
# SimpleImputer를 사용해서 height의 null 값들은 평균으로 출력하고 나머지 column은 통과
col_transformer = ColumnTransformer([
("Impute_mean", SimpleImputer(strategy="mean"), ["height"])
],
remainder="passthrough"
)
display(col_transformer) # 파이프라인 그래프로 구성 확인
print(data_df)
print(col_transformer.fit_transform(data_df))
height weight age
0 165.0 70.0 NaN
1 NaN 62.0 18.0
2 182.0 NaN 15.0
[[165. 70. nan][173.5 62. 18. ]
[182. nan 15. ]]
# SimpleImputer를 사용해서 mean과 median 값을 null에 넣고
# 나머지 열(column)에 대한 값은 상수로 -1 값을 넣어 줌
col_transformer2 = ColumnTransformer([
("Impute_mean" , SimpleImputer(strategy="mean") , ["height"]),
("Impute_median", SimpleImputer(strategy="median"), ["weight"])
],
remainder=SimpleImputer(strategy="constant", fill_value=-1)
)
display(col_transformer2) # 파이프라인 그래프로 구성 확인
print(data_df)
print(col_transformer2.fit_transform(data_df))
height weight age
0 165.0 70.0 NaN
1 NaN 62.0 18.0
2 182.0 NaN 15.0
[[165. 70. -1. ][173.5 62. 18. ]
[182. 66. 15. ]]