[Tutorial🔥] T2 2회 기출유형 Python
코드
# 분석에 필요하지 않은 컬럼 제거
id=X_test['ID']
X_train.drop(columns='ID',inplace=True)
X_test.drop(columns='ID',inplace=True)
y_train.drop(columns='ID',inplace=True)
# 스케일링 - 수치형 변수
from sklearn.preprocessing import MinMaxScaler
val=[['Customer_care_calls','Customer_rating','Cost_of_the_Product','Prior_purchases','Discount_offered','Weight_in_gms']]
scaler=MinMaxScaler()
for i in val:
X_train[i]=scaler.fit_transform(X_train[i])
X_test[i]=scaler.transform(X_test[i])
# 라벨 인코딩 - 명목형 변수
from sklearn.preprocessing import LabelEncoder
val=['Warehouse_block','Mode_of_Shipment','Product_importance','Gender']
encoder=LabelEncoder()
for i in val:
X_train[i]=encoder.fit_transform(X_train[i])
X_test[i]=encoder.fit_transform(X_test[i])
X_train[i]=X_train[i].astype('category')
X_test[i]=X_test[i].astype('category')
# 더미 변환
X_train=pd.get_dummies(X_train)
X_test=pd.get_dummies(X_test)
# 검증 데이터 분리
from sklearn.model_selection import train_test_split
X_TRAIN,X_VALID,Y_TRAIN,Y_VALID=train_test_split(X_train,y_train,test_size=0.2)
# 모델 생성1(RF)
from sklearn.ensemble import RandomForestClassifier
model1=RandomForestClassifier()
model1.fit(X_TRAIN,Y_TRAIN)
pred1=model1.predict_proba(X_VALID)
# 모델 생성2(LR)
from sklearn.linear_model import LogisticRegression
model2=LogisticRegression()
model2.fit(X_TRAIN,Y_TRAIN)
pred2=model2.predict_proba(X_VALID)
# 모델 생성3(XGB)
from xgboost import XGBClassifier
model3=XGBClassifier()
model3.fit(X_TRAIN,Y_TRAIN)
pred3=model3.predict_proba(X_VALID)
# # 모델 성능 평가
# from sklearn.metrics import roc_auc_score
# print('RF',roc_auc_score(Y_VALID,pred1[:,1])) # 0.7385
# print('LR',roc_auc_score(Y_VALID,pred2[:,1])) # 0.7203
# print('XGB',roc_auc_score(Y_VALID,pred3[:,1])) # 0.7450
# 결과 제출
result=model3.predict_proba(X_test)
pd.DataFrame({'ID':id,'Reached.on.Time_Y.N':result[:,1]}).to_csv('00000.csv',index=False)
# # 결과 채점
# from sklearn.metrics import roc_auc_score
# predict=pd.read_csv('00000.csv')
# print(roc_auc_score(y_test['Reached.on.Time_Y.N'],predict['Reached.on.Time_Y.N'])) # 0.7265
반응형