본문 바로가기
Python

[빅데이터 분석기사] 실기 문제 연습 (작업형2) 모델링과 예측

by 얀나대장 2023. 12. 1.

실기 문제 연습!

 

✨문제 푸는 순서 암기

 

1. 데이터 확인

1) train, test 셋 확인

train.head()
test.head()

 

2) train, test shape 확인

print(train.shape, test.shape)

 

3) train, test의 숫자형, 범주형 확인

print(train.info(), test.info())

 

4) train, test의 null값 확인

print(train.isnull().sum(), test.isnull().sum())

 

 

 

2. 데이터 처리

1) null 값 처리(해당 열 삭제, 혹은 fillna, 혹은 대체값)

# 해당 컬럼의 결측치가 있는 행을 제거
df['해당 컬럼'].dropna()

 

2) target과 상관 없는 열 삭제

df['ID'].drop(axis=1, inplace=True)

 

3) 범주형 → 숫자형

print(train.columns)
cat_cols = [ 'Gender', 'Ever_Married', 'Graduated', 'Profession','Spending_Score',  'Var_1']

from sklearn.preprocessing import LabelEncoder

for i in range(len(cat_cols)):
    Le = LabelEncoder()
    train[cat_cols[i]]=Le.fit_transform(train[cat_cols[i]])
    test[cat_cols[i]]=Le.fit_transform(test[cat_cols[i]])

 

4) Ont-hot Encoding(pd.get_dummies)- 선형회귀일때

train=pd.get_dummies(data=train, columns=cat_cols, drop_first=True)

 

5) target 분류

# ID, target 처리
target = train.pop('Segmentation')
train = train.drop("ID", axis=1)

 

3. 모델링

 

1) Train, Test 셋 구분(혹은 Validation 까지)

from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(X_train, target, test_size=0.15, random_state=2022)
X_tr.shape, X_val.shape, y_tr.shape, y_val.shape

 

2) 데이터 표준화(StandartScaler)

from sklearn.preprocessing import StandardScaler

# StandardScaler객체 생성
sc = StandardScaler()

# StandardScaler 로 데이터 셋 변환
df['특정 컬럼'] = sc.fit_transform(df['특정 컬럼'])

3) 학습 모델 불러와서 train (하이퍼파라미터 지정)

from sklearn.ensemble import RandomForestClassifier

#파라미터 튜닝
rf = RandomForestClassfier(random_state=1, n_estimators=500, max_depth = 7)

 

4) 교차 검증 학습 결과 확인

from sklearn.model_selection import cross_val_score

score = cross_val_score(rf, train, target, scoring='f1_macro', cv=5)
print(score)
print(score.mean())

 

- RMSE확인(회귀분석)

from sklearn.metrics import mean_squared_error, r2_score

def rmse(y, y_pred):
    return np.sqrt(mean_squared_error(y, y_pred))
    
model = RandomForestRegressor()
model.fit(X_tr, y_tr)
pred = model.predict(X_val)

print("R2 : " + str(r2_score(y_val, pred)))
print("RMSE : " + str(rmse(y_val, pred)))

 

5) predict y값 shape 확인

rf.fit(train, target)
pred = rf.predict(test)
print(pred.shape, pred)

 

6) 제출용으로 csv파일 만들기

submit = pd.DataFrame({"ID":test['ID'], "Segmentation":pred})
submit.to_csv('submission.csv', index=False)

댓글