Skip to content

Instantly share code, notes, and snippets.

@rkdgusrn1212
Created June 1, 2022 16:44
Show Gist options
  • Save rkdgusrn1212/99bda8a0e4d68b0ccc545c43588266f9 to your computer and use it in GitHub Desktop.
Save rkdgusrn1212/99bda8a0e4d68b0ccc545c43588266f9 to your computer and use it in GitHub Desktop.
Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
#read data
train_data = pd.read_csv('train.csv', index_col='Id')
test_data = pd.read_csv('test.csv', index_col='Id')
#target이 비어있는 row 제거
train_data.dropna(axis=0, subset=['target'], inplace=True)
#데이터 분할하기
y = train_data.target
X = train_data.drop(['target'], axis=1, inplace=True)
X_train, X_valid, y_train, y_valid = train_test_split(X, y, train_size=0.8, test_size=0.2)
#train set 내에서 cardinality가 10 이하인 object column만 선택
cat_cols = [col for col in X_train.columns if X_train[col].nunique() < 10 and X_train[col].dtype == "object"]
#numeric은 굳이 train set에서 찾을 필요는 없지만, 어차피 학습은 train set에서만 이루어지니까...
num_cols = [col for col in X_train.columns if X_train[col].dtype in ['int64', 'float64']]
#쓰는 컬럼만 남겨놓기
my_cols = categorical_cols + numerical_cols
X_train = X_train[my_cols].copy()
X_valid = X_valid[my_cols].copy()
test_data = test_data[my_cols].copy()
#전처리 정의
num_transformer = SimpleImputer(strategy='median')#중위값으로 치환
#파이프라인은 주어진 데이터에 대해서 steps 리스트를 차례대로 수행한다.
obj_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='most_frequent')),#가장 많이쓰인 값으로 치환, 튜플 첫원소는 그냥 이름이다 바꿔도 된다.
#Train value set이 validation value set을 포함한다는 보장이 없다. test set도 마찬가지.
#Encoding할수 없는 value가 나왔을땐 그냥 컬럼들을 전부 0처리하고 넘어간다.
('onehot', OneHotEncoder(handle_unknown='ignore'))
])
preprocessor = ColumnTransformer(
transformers=[
('num', num_transformer, num_cols),#튜플의 첫 원소는 그냥 이름이다 바꿔도 된다.
('cat', obj_transformer, cat_cols)
])
#모델 정의
model = RandomForestRegressor(n_estimators=100, random_state=0)
#정의된 전처리와 모델을 파이프라인으로 묶기, 리스트 순서대로 step이 수행된다. 이름은 순서와 무관하다
my_pipeline = Pipeline(steps=[('preprocessor', preprocessor),
('model', model)
])
#주어진 데이터를 전처리하고 모델 학습시키기
my_pipeline.fit(X_train, y_train)
#validation data를 전처리하고 prediction 수행
preds = my_pipeline.predict(X_valid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment