| 항목 | 요소중복 | 순서 |
|---|---|---|
| 시퀀스 | O | O |
| 집합(set) | X | X |
| 순서(order) | X | O |
SciKit-Learn에서는 Pipeline 클래스를 통해 파이프라인을 구현할 수 있음
편의성과 캡슐화
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)) ## 성능 평가

make_pipeline() 함수는 파이프라인의 이름을 자동으로 만들어 줌
파이프라인의 이름은 각 추정기의 클래스 이름을 소문자로 바꾼 것과 같음
파이프라인의 이름을 지정하려면 Pipeline() 클래스를 사용해야 함
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, :])

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))

# 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))
