빅데이터 분석기사 실기
작업형 2
샘플문제
# 출력을 원하실 경우 print() 함수 활용
# 예시) print(df.head())
# getcwd(), chdir() 등 작업 폴더 설정 불필요
# 파일 경로 상 내부 드라이브 경로(C: 등) 접근 불가
# 데이터 파일 읽기 예제
import pandas as pd
test = pd.read_csv("data/X_test.csv")
X= pd.read_csv("data/X_train.csv")
Y = pd.read_csv("data/y_train.csv")
# 사용자 코딩
# 답안 제출 참고
# 아래 코드 예측변수와 수험번호를 개인별로 변경하여 활용
# pd.DataFrame({'cust_id': X_test.cust_id, 'gender': pred}).to_csv('003000000.csv', index=False)
#결측치 확인 및 제거
#print(X.isnull().sum())
#print(test.isnull().sum())
test['환불금액']=test['환불금액'].fillna(value=0)
X['환불금액']=X['환불금액'].fillna(value=0)
##drop
Y.drop('cust_id', axis=1, inplace=True)
X.drop('cust_id', axis=1, inplace=True)
cust_id=test.pop('cust_id')
#전처리 범주형 데이터 수치화
import sklearn.preprocessing
#print(dir(sklearn.preprocessing))
#dictory 기능
from sklearn.preprocessing import LabelEncoder
cols=['주구매상품', '주구매지점']
for col in cols:
le=LabelEncoder()
X[col]=le.fit_transform(X[col])
test[col]=le.fit_transform(test[col])
#print(X.head())
#모델링
from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val =train_test_split(X,Y['gender'], test_size=0.2, random_state=2022)
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, roc_auc_score
rf=RandomForestClassifier()
rf.fit(X_tr, y_tr)
#print('acc', rf.score(X_val, y_val))
pred1=rf.predict_proba(X_val)
#print('roc_auc:', roc_auc_score(y_val, pred1[:, 1]))
#최종모델
rf=RandomForestClassifier(n_estimators=100, max_depth=5, random_state=2022)
rf.fit(X, Y['gender'])
pred_fin=rf.predict_proba(test)
#답안 제출
pd.DataFrame({'cust_id': cust_id, 'gender': pred_fin[:, 1]}). to_csv('123.csv', index=False)
print(pd.read_csv('123.csv'))
다시 연습
# 출력을 원하실 경우 print() 함수 활용
# 예시) print(df.head())
# getcwd(), chdir() 등 작업 폴더 설정 불필요
# 파일 경로 상 내부 드라이브 경로(C: 등) 접근 불가
# 데이터 파일 읽기 예제
import pandas as pd
test = pd.read_csv("data/X_test.csv")
X= pd.read_csv("data/X_train.csv")
Y = pd.read_csv("data/y_train.csv")
# 사용자 코딩
# 답안 제출 참고
# 아래 코드 예측변수와 수험번호를 개인별로 변경하여 활용
# pd.DataFrame({'cust_id': X_test.cust_id, 'gender': pred}).to_csv('003000000.csv', index=False)
#결측치 확인 및 제거
#print(X.isnull().sum())
#print(test.isnull().sum())
test['환불금액']=test['환불금액'].fillna(value=0)
X['환불금액']=X['환불금액'].fillna(value=0)
##drop
Y.drop('cust_id', axis=1, inplace=True)
X.drop('cust_id', axis=1, inplace=True)
cust_id=test.pop('cust_id')
#전처리 범주형 데이터 수치화
import sklearn.preprocessing
#print(dir(sklearn.preprocessing))
#dictory 기능
from sklearn.preprocessing import LabelEncoder
cols=['주구매상품', '주구매지점']
for col in cols:
le=LabelEncoder()
X[col]=le.fit_transform(X[col])
test[col]=le.fit_transform(test[col])
#print(X.head())
from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val=train_test_split(X,Y, test_size=0.2, random_state=2022)
import sklearn.ensemble
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score, roc_auc_score
rf=RandomForestClassifier()
rf.fit(X_tr, y_tr)#모델을 tr에게 맞추어라
#print('acc', rf.score(X_val, y_val))#val의 값을 accuracy맞추어라
pred1=rf.predict_proba(X_val)#predict_proba()속할 확률을 구해준다. x-val로 구한다.
#print('roc_auc:', roc_auc_score(y_val, pred1[:,1]))#y_val에 맞추어서 roc 값을 구하여라
#최종모델
rf=RandomForestClassifier(n_estimators=100, max_depth=5, random_state=2022)
rf.fit(X,Y)
pred_fin=rf.predict_proba(test)
#답안제출
pd.DataFrame({'cust_id': cust_id, 'gender': pred_fin[:,1] }).to_csv('123_csv', index=False)#for, if문 삽입할 때
print(pd.read_csv('123_csv'))
'자격증 > 빅데이터 분석기사' 카테고리의 다른 글
빅데이터 분석기사 실기 2022년 1회 후기 (0) | 2022.06.26 |
---|---|
빅데이터 분석기사 실기 예시 문제 작업형#1 (0) | 2022.06.24 |
빅데이터분석기사 실기 (0) | 2022.06.22 |
D-16 빅데이터분석기사 실기 준비 (0) | 2022.06.13 |
D-18 빅데이터분석기사 실기 준비 (0) | 2022.06.08 |