728x90
#1 불균형한 데이터 분포 전처리하기
#2 (Random Forest) train-test 분할 및 간단한 모델 학습
#3 Validation 데이터 분할, K-fold 교차검증 

1. train-test 분할

(1) 기존에 train과 test 데이터를 한꺼번에 전처리시키기 위하여 -> 각각을 'data'라는 이름의 데이터프레임으로 합침

data = pd.concat([train,test], axis=0)

(2) 이후 결측치 제거하고, 불균형한 데이터에 대한 전처리(이전 포스트)를 진행함

data.isnull().sum() 
data = data.drop("occyp_type", axis=1)
#data 데이터프레임에 이를 반영 #concat에서의 문법과 비교할 것.

(3) 전처리가 끝나면, 모델 학습을 시작함 => 전처리가 반영된 data를 train용과 test용으로 다시 분리해야 함.

train.shape
test.shape #기존 train 및 test 데이터의 크기 파악
data.shape #전처리 반영된 data의 크기 파악

train = data[:-10000] #데이터프레임 인덱싱에서 :는 column이 아닌 row만! #train에 해당
test = data[-10000:] #test에 해당

(4) train과 test 데이터 각각, 클라스 정보와 라벨 정보(정답)을 분리

#train
train_x = train.drop("credit", axis=1) #credit column을 제외한 train
train_y = train["credit"]
#test
test_x = test.drop("credit", axis=1)
test_y = test["credit"]
* 데이터프레임 인덱싱에서 loc 유의사항
train.loc[:"credit"]이라고 하면, 전체 행 X credit까지의 열: 즉 표 전체가 출력됨
특정 column만 추출하고 싶다면, train.loc[:,"credit"]과 같이 콤마를 추가해야 함

 

2. Random Forest

트리 기반 앙상블 모델 (사이킷런에서 제공하는 머신러닝 툴)
RandomForestClassifier()
분류기.fit 메소드
분류기.predict_proba 메소드
numpy의 np.argmax(예측확률, axis = 방향)

 

(1) RandomForest 분류기 생성한 후 이것으로 학습 진행

from sklearn.ensemble import RandomForestClassifier
clf = RandomForestClassifier() #랜덤 포레스트 분류기 생성

clf.fit(train_x, train_y) #이미 정답이 주어진 train 데이터에 대해서는, fit을 통해 학습시킴
# 결과를 따로 저장할 필요 없이, 내부에 스스로 저장됨

(2) test_x에 대한 예측 및 결과 저장

학습된 분류기를 test_x에 적용하여, 예측 결과 반환
test_proba = clf.predict_proba(test_x)
print(test_proba)

#데이콘 원칙 상, 주어진 sample_submission에 아래 예측 결과를 집어넣어야 함.
sample_submission.iloc[:,1:] = test_proba

해당 예측 결과를 csv 파일로 변환
데이터프레임.to_csv("파일명")

sample_submission.to_csv("sample_submission_ver1.csv", index=False)

 

출처:

https://www.youtube.com/watch?v=AWfgyln0EOM 

모두 데이콘 합시다아

728x90

+ Recent posts