-
데이콘 관련 FAQ & Tip머신러닝/FAQ 2022. 8. 25. 08:46
제출파일을 만들 때 , index = False 꼭 잊지 말기
submission.to_csv("submission_횟수_방법.csv" , index = False)
subplot 플로팅하기 (histogram)
import matplotlib.pyplot as plt import seaborn as sns plt.figure(figsize = (40,40)) ## 해당 셀에서 실행될 fig size 설정 cols = train.columns for i in range(len(cols)): plt.subplot(8 , 3 , i +1) ### cols가 24개보다 크면 8:행 , 3:열 값 키워줘야함 plt.title(cols[i] , fontsize = 25) plt.hist(train[cols[i]] , bins = 40) plt.show() ### seaborn 활용 ### 분류문제일때 , 회귀일때는 hue 쓰면 안됨 for i in range(len(cols)): plt.subplot(8 , 3 , i +1) ### cols가 24개보다 크면 8:행 , 3:열 값 키워줘야함 plt.title(cols[i] , fontsize = 25) sns.histplot(x = cols[i] , hue = "target" , bins = 40 , data = train) plt.show()
subplot 플로팅하기 (scatter) 보통 회귀문제일때 사용
hist와 다 똑같고 ploting 하는 부분만 다름import matplotlib.pyplot as plt import seaborn as sns cols = train.columns for i in range(len(cols)): plt.subplot(8 , 3 , i +1) ### cols가 24개보다 크면 8:행 , 3:열 값 키워줘야함 plt.title(cols[i] , fontsize = 25) plt.scatter(x= train[cols[i]] , y = train["Target"]) plt.show()
seaborn 의 pairplot을 활용 모든 feature들 간의 상관관계 그래프로 띄어보기
sns.pairplot(train)
특정 column의 특정 값을 다른 값으로 변경하기
train.loc를 사용train.loc[train["A"] > 0.5 , "B"] = 1 ### "A"컬럼이 0.5보다 큰 데이터의 "B" 컬럼 값은 1로 바꾼다.
이상치(outlier)제거하기
그래프를 띄워보면 혼자 굉장히 동 떨어진 값을 발견 , 이상치라고 판단하면 제거하기outlier train[train["A"] > 1000] ### 이상치가 있는 컬럼 "A"에서 대략 평균보다 훨씬 큰 1000보다 큰것으로 indexing
위 그림과 같이 특정 인덱스가 나오면 해당 인덱스를 drop
train_01 = train.drop([1248,1249] , axis = 0) ## 행을 삭제하므로 반드시 axis = 0 으로 설정
주의할것은 test데이터는 컬럼은 삭제해도 행은 절대로 삭제하면 안됨
X_train , y_train 합치기 (concat)
나누는것만 하다보면 합치는것에 익숙치 않음train = pd.concat([X_train ,y_train] , axis = 1)
Scaling 할때의 유의점
1) 1개의 컬럼만 할때는 pd.DataFrame 활용A = pd.DataFrame(train["A"]) scaler.fit(pd.DataFrame(A) train["A_Scaled"] = scaler.transform(A)
Scaling 할때의 유의점
2) 전체 데이터를 동일하게 Scaling할땐 , y값(target)까지 한번에 scaling 하지말고 y값은 빼고 scaling'X_train = train.drop("Target" , axis = 1) scaler.fit(X_train) X_train_scaled = scaler.transform(X_train)
Self - Label Encoding
sklearn에서 임의로 정한 encoding 이 아닌 직접 정할 수 있다.### train["A"]value_counts() 에서 "사자" , "호랑이" , "꿩" , "참치" 일때 ### 각각을 별도의 번호로 라벨링해서 학습시키고 싶을 때 사용 ### 가장 직관적인 방법 train.loc[ train["A"] == "사자" , "A"] = 1 train.loc[ train["A"] == "호랑이" , "A"] = 4 train.loc[ train["A"] == "꿩" , "A"] = 5 train.loc[ train["A"] == "참치" , "A"] = 6 ### test데이터도 동일하게 별도 라벨링이 들어가줘야함
회귀분석의 경우 log 씌우는법
보통 y값에 log를 씌우는데
데이터를 읽어온 후에 log 씌우고 - 학습 - 예측 - 역함수 순서로 해야한다. 학습 이후 로그를 하는것은 전혀 의미가 없음y_train = train["Target"] y_train_loged = np.log1p(y_train) model.fit(X_train ,y_train_loged) pred = model.predict(X_test) pred_exp = np.expm1(pred) ### 최종 역함수해서 정상적인 값 도출
학습돌리고 예측하기전에 항상 확인할 것
결측치 , object 있는지 info()로 확인 , shape 확인X_train.shape[0] , y_train.shape[0] ### 행이 같아야함 X_train.shape[1] , X_test.shape[1] ### 열이 같아야함
학습데이터로 예측하는 오류
반드시 test 데이터로 predict 해야함.model.fit(X_train , y_train) pred = model.predict(X_train) ### 실수로 train을 예측할 경우 하지만 인지 못하는 경우 submission = pd.read_csv("sample_submission.csv") submission["Target"] = pred <--- 여기서 에러난다. pred와 submission이 행 갯수가 틀림. ### 꼭 주의하자
GridSearchCV 활용시 유의점
분류문제에선 scoring = 'Accuracy' ,
회귀문제를 활용할땐 scoring = 'neg_mean_squared_error' #MSE 의미
아래 공식홈페이지 참조해서 다양하게 변경 가능https://scikit-learn.org/stable/modules/model_evaluation.html#scoring-parameter 공식홈페이지 참조
'머신러닝 > FAQ' 카테고리의 다른 글
평가 산식 (metrics) , 데이터 타입에 대한 대응 (0) 2023.04.13 PCA를 활용한 차원 축소 방법 (1) 2023.04.13 데이콘 관련 Tip(High scoring) (0) 2022.09.01 Feature Importance를 활용한 피쳐 엔지니어링 (0) 2022.09.01 Scaling - MinMaxScaler (0) 2022.09.01