본문 바로가기
빅데이터분석기사/작업형2

[작업형2] 단계별로 해야할 것 정리

by nemonemonemo 2025. 6. 17.

1. 데이터 불러오기 (문제에서 제공)

 

2. EDA

  • train.shape, test.shape -> 크기 확인하기
  • train.head() / test.head() -> 데이터프레임 대강 파악/ test에 예측해야하는 컬럼 빠져있을 것 
  • train.info() -> 데이터 타입 확인하기 위함
  • train.isnull().sum() / test.isnull().sum() -> 결측값 확인 ( 있다면 결측치 처리 필수, 근데 아직 그런 문제 안 나옴 )
  • <분류> train['Attrition_Flag'].value.counts() -> 분류 문제일 때 타겟값 어떻게 분포해 있는지 확인 
  • <회귀> train['target'].describe() -> 원래 회귀에서는 시각화로 파악하는데 시험환경에서 시각화 안 돼서 이거로 대략적 파악함 
  • + nunique()를 보고 전처리 어떻게 할지 힌트 얻기도 함

3. 데이터 전처리

  • 타겟 분리
# 타겟 분리 (가장 먼저 하는 것을 추천함)
target = train.pop('Item_Outlet_Sales')

 

  • 베이스라인 만들기 (오브젝트만 불러오는 컬럼 만들어두기)
# baseline
cols = train.select_dtypes(include='object').columns
cols

 

  • object 컬럼을 모두 제거하는 경우/ 라벨 인코딩/ 원핫 인코딩
    => 모두 해본 뒤 가장 성능 좋은 것을 선택 
# #object 컬럼을 모두 제거하는 경우

# print(train.shape, test.shape)
train = train.drop(cols, axis = 1)
test = test.drop(cols, axis = 1)
# print(train.shape, test.shape) ##잘 삭제됐는지 확인 
 
 
# # label
## unique 수가 너무 많으면 원핫보다는 라벨 인코딩 씀 

from sklearn.preprocessing import LabelEncoder
for col in cols:
	le = LabelEncoder()
    	train[col] = le.fit_transform(train[col])
    	test[col] = le.transform(test[col])
    
train[cols].head() ##인코딩 잘 됐나 확인     


# # one-hot
train = pd.get_dummies(train, columns = cols)
test = pd.get_dummies(test, columns = cols)

 

  • 모델 학습 전, 구분만을 위한 숫자 컬럼을 drop하기 (무조건 train, test 둘 다 drop 해야한다 )
    ex) 'CLIENTNUM' 같은 컬럼 

4. 검증 데이터 분리

  • 검증 데이터 분리하기  
from sklearn.model_selection import train_test_split

X_tr, X_val, y_tr, y_val = train_test_split(train, target, test_size = 0.2, random_state = 0)

#print(X_tr.shape, X_val.shape, y_tr.shape, y_val.shape)

 

5. 모델 및 평가 

  • 모델 불러오기
from sklearn.ensemble import RandomForestClassifier

model = RandomForestClassifier(random_state=0)
model.fit(X_tr,y_tr)
pred = model.predict(X_val)


## 랜포 하이퍼파라미터튜닝
# max_depth = 3~12
# n_estimators = 100 200 400 800 1000
# ex) model = RandomForestClassifier(random_state=0, max_depth = 5, n_estimators = 400)

 

 

  • 평가지표 출력

<분류>

from sklearn.metrics import accuracy_score, precision_score, reacall_score, f1_score, roc_auc_score

#정확도
print(accuracy_score(y_val, pred))
#정밀도
print(precision_score(y_val, pred))
#재현율
print(recall_score(y_val, pred))
#f1
print(f1_score(y_val, pred))

#roc-auc
pred = model.predict_proba(X_val)
print(roc_auc_score(y_val, pred[:,1]))
  • roc_auc_score
    • 얘만 predict_proba 사용
    • roc_auc_score(y_val, pred[:,1]) -> 얘는 예측값에서 양성값만 넣어줘야하므로 pred[:,1] 이렇게 넣어줌 

<회귀>

from sklearn.metrics import root_mean_squared_error, mean_squared_error, mean_absolute_error, r2_score

#RMSE
result = root_mean_squared_error(y_val, y_pred)
print('RMSE:', result)

#MSE
result = mean_squared_error(y_val, y_pred)
print('MSE:', result)

#MAE
result = mean_absolute_error(y_val, y_pred)
print('MAE:', result)

#R2
result = r2_score(y_val, y_pred)
print('R2:', result)

6. 예측 및 csv 제출

  • 가장 성능 높은 것으로 test 예측 
pred = model.predict_proba(test)
pred

 

  • 문제에서 요구하는 형태로 DataFrame만들고/ csv 형태로 만들어서/ 제출하기 
submit = pd.DataFrame({
	'CLIENTNUM': test_id,
    'Attrition_Flag': pred[:,1]
})

submit.to_csv('result.csv', index=False)

pd.read_csv('result.csv') #저장 후 한 번 확인

 

 

 

암기할 것

  • from sklearn.model_selection import train_test_split

'빅데이터분석기사 > 작업형2' 카테고리의 다른 글

[작업형2] 암기할 것들  (0) 2025.06.20