728x90
728x170
빅데이터분석기사 실기 기출 복원 문제 - 제2유형
들어가며
- 빅데이터분석기사 실기 기출 제2유형 복원 문제를 정리해본다.
- 2회 ~ 6회까지 분량이다.
- 문제 해결 방법을 쭉 읽어 보는 용도로 정리해보았다.
문제
2021년 2회
- 기업에서 생성된 주문 데이터 (
train.csv
) - 정시 도착 가능 여부 예측 모델을 만들고,
test.csv
파일에 대하여 정시 도착 여부를 예측한 확률을 기록한 CSV 생성하기
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import roc_auc_score
# 훈련용 데이터 불러오기
df1 = pd.read_csv('train.csv')
## 요약 통계량 확인
print(df1.describe())
ID Customer_care_calls Customer_rating Cost_of_the_Product \
count 8009.000000 8009.000000 8009.000000 8009.000000
mean 4005.000000 3.980022 2.997128 206.941691
std 2312.143486 1.123538 1.409124 48.179596
min 1.000000 2.000000 1.000000 96.000000
25% 2003.000000 3.000000 2.000000 166.000000
50% 4005.000000 4.000000 3.000000 208.000000
75% 6007.000000 5.000000 4.000000 248.000000
max 8009.000000 7.000000 5.000000 310.000000
Prior_purchases Discount_offered Weight_in_gms Reached.on.Time_Y.N
count 8009.000000 8009.000000 8009.000000 8009.000000
mean 3.481833 16.295043 3545.574229 0.662005
std 1.534307 18.057606 1601.181104 0.473056
min 2.000000 1.000000 1001.000000 0.000000
25% 2.000000 4.000000 1867.000000 0.000000
50% 3.000000 8.000000 3922.000000 1.000000
75% 4.000000 23.000000 4958.000000 1.000000
max 10.000000 65.000000 7846.000000 1.000000
## 속성 및 결측값 확인
print(df1.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 8009 entries, 0 to 8008
Data columns (total 12 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 8009 non-null int64
1 Warehouse_block 8009 non-null object
2 Mode_of_Shipment 8009 non-null object
3 Customer_care_calls 8009 non-null int64
4 Customer_rating 8009 non-null int64
5 Cost_of_the_Product 8009 non-null int64
6 Prior_purchases 8009 non-null int64
7 Product_importance 8009 non-null object
8 Gender 8009 non-null object
9 Discount_offered 8009 non-null int64
10 Weight_in_gms 8009 non-null int64
11 Reached.on.Time_Y.N 8009 non-null int64
dtypes: int64(8), object(4)
memory usage: 751.0+ KB
None
# 데이터 전처리
## 데이터 형 변환
df1['Reached.on.Time_Y.N'] = df1['Reached.on.Time_Y.N'].astype('category') # 정수형을 범주형으로 변환
# 평가용 데이터 풀러오기
## 두 번째 CSV를 불러와서 정보 파악해보기
df2 = pd.read_csv('test.csv')
## 요약 통계량 확인
print(df2.describe())
ID Customer_care_calls Customer_rating \
count 2990.000000 2990.000000 2990.000000
mean 9504.500000 4.253846 2.972910
std 863.282978 1.165228 1.425618
min 8010.000000 2.000000 1.000000
25% 8757.250000 3.000000 2.000000
50% 9504.500000 4.000000 3.000000
75% 10251.750000 5.000000 4.000000
max 10999.000000 7.000000 5.000000
Cost_of_the_Product Prior_purchases Discount_offered Weight_in_gms
count 2990.000000 2990.000000 2990.000000 2990.000000
mean 218.916054 3.797324 5.546823 3870.918395
std 46.652061 1.467523 2.923180 1701.404250
min 96.000000 2.000000 1.000000 1003.000000
25% 182.000000 3.000000 3.000000 1788.000000
50% 228.000000 4.000000 6.000000 4535.500000
75% 256.000000 5.000000 8.000000 5259.500000
max 310.000000 10.000000 10.000000 6000.000000
## 속성 및 결측값 확인
print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2990 entries, 0 to 2989
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 2990 non-null int64
1 Warehouse_block 2990 non-null object
2 Mode_of_Shipment 2990 non-null object
3 Customer_care_calls 2990 non-null int64
4 Customer_rating 2990 non-null int64
5 Cost_of_the_Product 2990 non-null int64
6 Prior_purchases 2990 non-null int64
7 Product_importance 2990 non-null object
8 Gender 2990 non-null object
9 Discount_offered 2990 non-null int64
10 Weight_in_gms 2990 non-null int64
dtypes: int64(7), object(4)
memory usage: 257.1+ KB
None
## 독립 변수와 종속 변수로 나누기
x = df1.drop('Reached.on.Time_Y.N', axis=1) # 독립 변수
y = df1['Reached.on.Time_Y.N'] # 종속 변수
## 원-핫 인코딩
x_encoded = pd.get_dummies(x)
# 모델링
## 데이터 분할
x_train, x_valid, y_train, y_valid = train_test_split(x_encoded.drop('ID', axis=1), y, test_size=0.25)
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_train, y_train)
## 예측
pred = md.predict(x_valid)
## 평가
cm = confusion_matrix(y_valid, pred, labels=[1, 0])
print(cm)
[[948 352]
[259 444]]
print(accuracy_score(y_valid, pred)) # 정확도
print(recall_score(y_valid, pred)) # 재현율
print(precision_score(y_valid, pred)) # 정밀도
print(roc_auc_score(y_valid, pred)) # ROC AUC
0.6949575636545182
0.7292307692307692
0.7854183927091963
0.6804048582995951
# 평가
x_test = df2
## 원-핫 인코딩
x_test_encoded = pd.get_dummies(x_test)
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_encoded.drop('ID', axis=1), y)
## 예측
pred = md.predict_proba(x_test_encoded.drop('ID', axis=1))
print(pred)
[[0.41 0.59 ]
[0.22333333 0.77666667]
[0.56333333 0.43666667]
...
[0.35 0.65 ]
[0.31 0.69 ]
[0.32666667 0.67333333]]
# CSV 내보내기
result = pd.DataFrame({
"ID": df2["ID"],
"pred": pred[:, 1]
})
print(result)
result.to_csv("./outputs/task2-q1.csv", index=False)
ID pred
0 8010 0.590000
1 8011 0.776667
2 8012 0.436667
3 8013 0.616667
4 8014 0.383333
... ... ...
2985 10995 0.680000
2986 10996 0.670000
2987 10997 0.650000
2988 10998 0.690000
2989 10999 0.673333
[2990 rows x 2 columns]
2021년 3회
- 고객의 예약 현황을 나타낸 데이터 (
train.csv
) - 여행 보험 가입 여부 예측 모델을 만들고,
test.csv
파일에 저장된 테스트 데이터로 여행 보험 패키지 가입 여부를 예측하는 결과를 예시 파일과 동일한 형태의 CSV 파일로 생성하기
- train.csv : 훈련 및 검증 데이터 포함
- test.csv : 여행 보험 가입 여부가 없는 테스트 데이터
예시 파일(CSV)
index | y_pred |
---|---|
1 | 0.5781239 |
2 | 0.8623277 |
3 | 0.9581221 |
... | ... |
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import f1_score
from sklearn.metrics import roc_auc_score
# 훈련용 데이터 불러오기
df1 = pd.read_csv('train.csv')
print(df1.describe())
X Age AnnualIncome FamilyMembers ChronicDiseases \
count 1491.000000 1491.000000 1.491000e+03 1491.000000 1491.000000
mean 745.000000 29.690812 9.355466e+05 4.767270 0.283032
std 430.558939 2.919325 3.751519e+05 1.628241 0.450623
min 0.000000 25.000000 3.000000e+05 2.000000 0.000000
25% 372.500000 28.000000 6.000000e+05 4.000000 0.000000
50% 745.000000 29.000000 9.000000e+05 5.000000 0.000000
75% 1117.500000 32.000000 1.250000e+06 6.000000 1.000000
max 1490.000000 35.000000 1.800000e+06 9.000000 1.000000
TravelInsurance
count 1491.000000
mean 0.362844
std 0.480982
min 0.000000
25% 0.000000
50% 0.000000
75% 1.000000
max 1.000000
## 요약 통계량 확인
print(df1.info())
## 속성 및 결측값 확인
print(df1.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1491 entries, 0 to 1490
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 X 1491 non-null int64
1 Age 1491 non-null int64
2 Employment Type 1491 non-null object
3 GraduateOrNot 1491 non-null object
4 AnnualIncome 1491 non-null int64
5 FamilyMembers 1491 non-null int64
6 ChronicDiseases 1491 non-null int64
7 FrequentFlyer 1491 non-null object
8 EverTravelledAbroad 1491 non-null object
9 TravelInsurance 1491 non-null int64
dtypes: int64(6), object(4)
memory usage: 116.6+ KB
None
# 데이터 전처리
## 데이터 형변환
df1['TravelInsurance'] = df1['TravelInsurance'].astype('category') # 수치형 -> 범주형
# 평가용 데이터 불러오기
df2 = pd.read_csv('test.csv')
## 요약 통계량 확인
print(df2.describe())
X Age AnnualIncome FamilyMembers ChronicDiseases
count 496.000000 496.000000 4.960000e+02 496.000000 496.000000
mean 1738.500000 29.528226 9.243952e+05 4.709677 0.262097
std 143.327132 2.894650 3.821915e+05 1.553226 0.440219
min 1491.000000 25.000000 3.000000e+05 2.000000 0.000000
25% 1614.750000 28.000000 6.000000e+05 4.000000 0.000000
50% 1738.500000 28.500000 9.000000e+05 5.000000 0.000000
75% 1862.250000 32.000000 1.200000e+06 6.000000 1.000000
max 1986.000000 35.000000 1.800000e+06 9.000000 1.000000
## 속성 및 결측값 확인
print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 496 entries, 0 to 495
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 X 496 non-null int64
1 Age 496 non-null int64
2 Employment Type 496 non-null object
3 GraduateOrNot 496 non-null object
4 AnnualIncome 496 non-null int64
5 FamilyMembers 496 non-null int64
6 ChronicDiseases 496 non-null int64
7 FrequentFlyer 496 non-null object
8 EverTravelledAbroad 496 non-null object
dtypes: int64(5), object(4)
memory usage: 35.0+ KB
None
## 독립 변수와 종속 변수로 나누기
x = df1.drop('TravelInsurance', axis=1) # 독립 변수
y = df1['TravelInsurance'] # 종속 변수
## 원-핫 인코딩
x_encoded = pd.get_dummies(x)
# 모델링
## 데이터 분할
x_train, x_valid, y_train, y_valid = train_test_split(x_encoded.drop('X', axis=1), y, test_size=0.25)
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_train, y_train)
## 예측
pred = md.predict(x_valid)
## 평가
cm = confusion_matrix(y_valid, pred, labels=[1, 0])
print(cm)
[[ 92 44]
[ 28 209]]
print(accuracy_score(y_valid, pred)) # 정확도
print(recall_score(y_valid, pred)) # 재현율
print(precision_score(y_valid, pred)) # 정밀도
print(f1_score(y_valid, pred)) # F1 점수
0.806970509383378
0.6764705882352942
0.7666666666666667
0.71875
# 평가
## 원-핫 인코딩
x_test = df2
x_test_encoded = pd.get_dummies(x_test)
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_encoded.drop('X', axis=1), y)
## 예측
pred = md.predict_proba(x_test_encoded.drop('X', axis=1))
print(pred)
[[1.00000000e-01 9.00000000e-01]
[1.99722222e-01 8.00277778e-01]
[7.74809524e-01 2.25190476e-01]
[8.61111111e-01 1.38888889e-01]
[9.95833333e-01 4.16666667e-03]
[7.12433862e-01 2.87566138e-01]
[1.36666667e-01 8.63333333e-01]
[8.23333333e-01 1.76666667e-01]
[6.80769841e-01 3.19230159e-01]
[2.05592833e-01 7.94407167e-01]
[8.68940187e-01 1.31059813e-01]
[9.85436508e-01 1.45634921e-02]
[8.95055556e-01 1.04944444e-01]
[8.52833333e-01 1.47166667e-01]
[5.94221741e-01 4.05778259e-01]
[9.97083333e-01 2.91666667e-03]
[9.37808201e-01 6.21917989e-02]
[3.63333333e-01 6.36666667e-01]
[7.97007937e-01 2.02992063e-01]
[9.99166667e-01 8.33333333e-04]
[8.09722222e-01 1.90277778e-01]
[9.52777778e-01 4.72222222e-02]
[3.33333333e-03 9.96666667e-01]
[3.33333333e-03 9.96666667e-01]
[8.56382275e-01 1.43617725e-01]
# CSV 내보내기
result = pd.DataFrame({'index': df2['X'], 'y_pred': pred[:, 1]})
print(result)
...
494 1985 0.716667
495 1986 0.244693
[496 rows x 2 columns]
result.to_csv('./outputs/task2-q2.csv', index=False)
2022년 4회
- 자동차 보험 회사는 새로운 전략을 수립하기 위하여 고객을 4가지 분류(A, B, C, D)로 세분화하였다.
- 기존 고객에 대한 분류(
train.csv
)를 바탕으로 신규 고객(test.csv
)이 어떤 분류에 속할지 예측하기
답안 작성 유의사항
- 제출 파일명 : 수험번호.csv
- 제출 컬럼명 :
ID
,pred
- 평가 : Macro F1-Score
- 예측할 값 : Segmentation
- 제출되는 파일은 테스트 데이터의 행의 수와 같아야 함.
ID | pred |
---|---|
1 | A |
2 | B |
3 | D |
... | ... |
1500 | D |
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
# 훈련용 데이터 불러오기
df1 = pd.read_csv('train.csv')
# 요약 통계량 확인
print(df1.describe())
ID Age Work_Experience Family_Size
count 6665.00000 6665.000000 6665.000000 6665.000000
mean 463519.84096 43.536084 2.629107 2.841110
std 2566.43174 16.524054 3.405365 1.524743
min 458982.00000 18.000000 0.000000 1.000000
25% 461349.00000 31.000000 0.000000 2.000000
50% 463575.00000 41.000000 1.000000 2.000000
75% 465741.00000 53.000000 4.000000 4.000000
max 467974.00000 89.000000 14.000000 9.000000
# 속성 및 결측값 확인
print(df1.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6665 entries, 0 to 6664
Data columns (total 11 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 6665 non-null int64
1 Gender 6665 non-null object
2 Ever_Married 6665 non-null object
3 Age 6665 non-null int64
4 Graduated 6665 non-null object
5 Profession 6665 non-null object
6 Work_Experience 6665 non-null int64
7 Spending_Score 6665 non-null object
8 Family_Size 6665 non-null int64
9 Var_1 6665 non-null object
10 Segmentation 6665 non-null object
dtypes: int64(4), object(7)
memory usage: 572.9+ KB
None
## 데이터형 변환
df1['Segmentation'] = df1['Segmentation'].astype('category')
# 평가용 데이터 불러오기
df2 = pd.read_csv('test.csv')
# 요약 통계량 확인
print(df2.describe())
ID Age Work_Experience Family_Size
count 2154.000000 2154.000000 2154.000000 2154.000000
mean 463496.744661 43.461467 2.551532 2.837047
std 2591.465156 16.761895 3.344917 1.566872
min 458989.000000 18.000000 0.000000 1.000000
25% 461282.250000 30.000000 0.000000 2.000000
50% 463535.000000 41.000000 1.000000 2.000000
75% 465705.750000 52.000000 4.000000 4.000000
max 467968.000000 89.000000 14.000000 9.000000
# 속성 및 결측값 확인
print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2154 entries, 0 to 2153
Data columns (total 10 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 ID 2154 non-null int64
1 Gender 2154 non-null object
2 Ever_Married 2154 non-null object
3 Age 2154 non-null int64
4 Graduated 2154 non-null object
5 Profession 2154 non-null object
6 Work_Experience 2154 non-null int64
7 Spending_Score 2154 non-null object
8 Family_Size 2154 non-null int64
9 Var_1 2154 non-null object
dtypes: int64(4), object(6)
memory usage: 168.4+ KB
None
# 데이터 전처리
## 독립 변수, 종속 변수 나누기
x = df1.drop('Segmentation', axis=1) # 독립 변수
y = df1['Segmentation'] # 종속 변수
## 원-핫 인코딩
x_encoded = pd.get_dummies(x)
# 모델링
## 데이터 분할
x_train, x_valid, y_train, y_valid = train_test_split(x_encoded, y, test_size=0.25, random_state=42)
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_train.drop('ID', axis=1), y_train)
## 예측
pred = md.predict(x_valid.drop('ID', axis=1))
## 평가
cm = confusion_matrix(y_valid, pred, labels=['A', 'B', 'C', 'D']) # 문제에서 고객을 4가지(A, B, C, D)로 세분화 하였다고 언급되었기 때문에 label 값을 4가지로 설정
print(cm)
[[176 79 66 80]
[107 125 123 32]
[ 58 103 214 52]
[ 99 37 30 286]]
print(accuracy_score(y_valid, pred)) # 정확도
0.48050389922015596
# 평가
## 평가 데이터 불러오기
x_test = df2
## 원-핫 인코딩
x_test_encoded = pd.get_dummies(x_test)
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_encoded.drop('ID', axis=1), y)
## 예측
pred = md.predict(x_test_encoded.drop('ID', axis=1)) # 확률이 아닌 레이블을 반환해야 하기 때문에 predict_proba가 아닌 predict 함수 사용
print(pred)
['B' 'C' 'C' ... 'B' 'C' 'D']
# CSV 내보내기
result = pd.DataFrame({
'ID': df2['ID'],
'pred': pred
})
print(result)
ID pred
0 458989 B
1 458994 C
2 459000 C
3 459003 C
4 459005 A
... ... ...
2149 467950 A
2150 467954 D
2151 467958 B
2152 467961 C
2153 467968 D
[2154 rows x 2 columns]
result.to_csv('./outputs/task2-q3.csv', index=False)
2022년 5회
- 주어진 훈련 데이터(
train.csv
)를 이용하여 중고 차량 가격(price
)을 예측하는 모형을 만들고, 테스트 데이터(test.csv
)를 이용하여 중고 차량 가격 예측하기
답안 작성 유의사항
- 제출 파일명 :
result.csv
- 제출 컬럼명 :
pred
(1개만 있어야 함.) - 평가 : RMSE(Root Mean Squared Error)
- 제출되는 파일은 테스트 데이터의 행의 수와 같아야 함.
파일 형식 예시
pred |
---|
1230 |
2560 |
... |
3761 |
import pandas as pd
from sklearn.ensemble import RandomForestRegressor # 회귀
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
# 평가 데이터 불러오기
df1 = pd.read_csv('train.csv')
## 요약 통계량 확인
print(df1.describe())
year price mileage tax mpg \
count 6899.000000 6899.000000 6899.000000 6899.000000 6899.000000
mean 2017.800406 25620.647050 17069.500797 137.603276 54.386215
std 1.729377 11274.931248 18115.761525 46.786012 29.678184
min 2013.000000 3076.000000 1.000000 0.000000 5.500000
25% 2017.000000 17990.500000 3795.500000 145.000000 43.500000
50% 2019.000000 23450.000000 9612.000000 145.000000 51.400000
75% 2019.000000 30000.000000 26000.000000 145.000000 60.100000
max 2020.000000 123456.000000 97185.000000 570.000000 470.800000
engineSize
count 6899.000000
mean 2.189593
std 0.544294
min 0.000000
25% 2.000000
50% 2.000000
75% 3.000000
max 4.400000
## 속성 및 결측값 확인
print(df1.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6899 entries, 0 to 6898
Data columns (total 9 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 model 6899 non-null object
1 year 6899 non-null int64
2 price 6899 non-null int64
3 transmission 6899 non-null object
4 mileage 6899 non-null int64
5 fuelType 6899 non-null object
6 tax 6899 non-null int64
7 mpg 6899 non-null float64
8 engineSize 6899 non-null float64
dtypes: float64(2), int64(4), object(3)
memory usage: 485.2+ KB
None
# 평가용 데이터 불러오기
df2 = pd.read_csv('test.csv')
## 요약 통계량 확인
print(df2.describe())
year mileage tax mpg engineSize
count 3882.000000 3882.000000 3882.000000 3882.000000 3882.00000
mean 2015.796754 40474.117980 121.214580 59.976172 2.12898
std 2.727920 28671.240945 80.292637 33.795645 0.56357
min 1996.000000 6.000000 0.000000 5.500000 0.00000
25% 2015.000000 19037.500000 30.000000 48.700000 2.00000
50% 2016.000000 35408.000000 145.000000 56.500000 2.00000
75% 2017.000000 57997.750000 150.000000 65.325000 2.00000
max 2020.000000 214000.000000 580.000000 470.800000 6.60000
## 속성 및 결측값 확인
print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3882 entries, 0 to 3881
Data columns (total 8 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 model 3882 non-null object
1 year 3882 non-null int64
2 transmission 3882 non-null object
3 mileage 3882 non-null int64
4 fuelType 3882 non-null object
5 tax 3882 non-null int64
6 mpg 3882 non-null float64
7 engineSize 3882 non-null float64
dtypes: float64(2), int64(3), object(3)
memory usage: 242.8+ KB
None
# 데이터 전처리
## 독립 변수, 종속 변수 분리
x = df1.drop('price', axis=1) # 독립 변수
y = df1['price'] # 종속 변수
## 원-핫 인코딩
x_encoded = pd.get_dummies(x)
# 모델링
## 데이터 분할
x_train, x_valid, y_train, y_valid = train_test_split(x_encoded, y, test_size=0.25)
## 모델링
md = RandomForestRegressor(n_estimators=300)
md.fit(x_train, y_train)
## 예측
pred = md.predict(x_valid)
## 평가
print(mean_squared_error(y_valid, pred, squared=False)) # squared=False -> rmse, squared=True -> mse
3033.410834503241
# 평가용 데이터 불러오기
x_test = df2
## 원-핫 인코딩
x_test_encoded = pd.get_dummies(x_test)
## x_encoded와 x_test_encoded의 열 이름 중에서 공통으로 있는 열 이름을 찾기
### 원-핫 인코딩을 수행하면 x_encoded와 x_test_encoded의 변수가 일치하지 않아서 공통으로 있는 열 이름 추출 필요
common_features = list(set(x_encoded.columns).intersection(x_test_encoded.columns))
x_train_common = x_encoded[common_features]
x_test_common = x_test_encoded[common_features]
## 모델링
md = RandomForestRegressor(n_estimators=300)
md.fit(x_train_common, y)
## 예측
pred = md.predict(x_test_common)
print(pred)
[17925.63666667 29562.83 24140.66 ... 17127.34666667
10891.46666667 16564.74 ]
# CSV 내보내기
result = pd.DataFrame({'pred': pred})
print(result)
pred
0 17925.636667
1 29562.830000
2 24140.660000
3 23431.850000
4 20333.606667
... ...
3877 18869.156667
3878 15831.900000
3879 17127.346667
3880 10891.466667
3881 16564.740000
[3882 rows x 1 columns]
result.to_csv('./outputs/task2-q4.csv', index=False)
2023년 6회
- 모바일 데이터 세트 (
train.csv
) - 분류 모델을 사용하여
price_range
값 예측하기 train.csv
파일의 학습 데이터로 모델을 생성하고,test.csv
파일의 평가 데이터로 평가하여 예측하기- 평가 데이터의 예측값을 출력 형식에 맞게 파일로 저장하기
평가 기준
- Macro F1 Score로 평가한다.
- feature engineering, 하이퍼파라미터 최적화 등을 수행할 수 있으며, 과대적합이 발생할 수 있다.
제출 형식
pred
2
3
0
...
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
# 평가용 데이터 불러오기
df1 = pd.read_csv('train.csv')
## 요약 통계량 확인
print(df1.describe())
battery_power blue clock_speed dual_sim fc \
count 2000.000000 2000.0000 2000.000000 2000.000000 2000.000000
mean 1238.518500 0.4950 1.522250 0.509500 4.309500
std 439.418206 0.5001 0.816004 0.500035 4.341444
min 501.000000 0.0000 0.500000 0.000000 0.000000
25% 851.750000 0.0000 0.700000 0.000000 1.000000
50% 1226.000000 0.0000 1.500000 1.000000 3.000000
75% 1615.250000 1.0000 2.200000 1.000000 7.000000
max 1998.000000 1.0000 3.000000 1.000000 19.000000
four_g int_memory m_dep mobile_wt n_cores ... \
count 2000.000000 2000.000000 2000.000000 2000.000000 2000.000000 ...
mean 0.521500 32.046500 0.501750 140.249000 4.520500 ...
std 0.499662 18.145715 0.288416 35.399655 2.287837 ...
min 0.000000 2.000000 0.100000 80.000000 1.000000 ...
25% 0.000000 16.000000 0.200000 109.000000 3.000000 ...
50% 1.000000 32.000000 0.500000 141.000000 4.000000 ...
75% 1.000000 48.000000 0.800000 170.000000 7.000000 ...
max 1.000000 64.000000 1.000000 200.000000 8.000000 ...
px_height px_width ram sc_h sc_w \
count 2000.000000 2000.000000 2000.000000 2000.000000 2000.000000
mean 645.108000 1251.515500 2124.213000 12.306500 5.767000
std 443.780811 432.199447 1084.732044 4.213245 4.356398
min 0.000000 500.000000 256.000000 5.000000 0.000000
...
75% 16.000000 1.000000 1.000000 1.000000 2.250000
max 20.000000 1.000000 1.000000 1.000000 3.000000
[8 rows x 21 columns]
## 속성 및 결측값 확인
print(df1.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 2000 entries, 0 to 1999
Data columns (total 21 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 battery_power 2000 non-null int64
1 blue 2000 non-null int64
2 clock_speed 2000 non-null float64
3 dual_sim 2000 non-null int64
4 fc 2000 non-null int64
5 four_g 2000 non-null int64
6 int_memory 2000 non-null int64
7 m_dep 2000 non-null float64
8 mobile_wt 2000 non-null int64
9 n_cores 2000 non-null int64
10 pc 2000 non-null int64
11 px_height 2000 non-null int64
12 px_width 2000 non-null int64
13 ram 2000 non-null int64
14 sc_h 2000 non-null int64
15 sc_w 2000 non-null int64
16 talk_time 2000 non-null int64
17 three_g 2000 non-null int64
18 touch_screen 2000 non-null int64
19 wifi 2000 non-null int64
20 price_range 2000 non-null int64
dtypes: float64(2), int64(19)
memory usage: 328.3 KB
None
## 데이터 형변환 (수치형 -> 범주형)
### 범주형이 될만한 것들을 수치형에서 범주형으로 변환하기
df1['price_range'] = df1['price_range'].astype('category')
df1['blue'] = df1['blue'].astype('category')
df1['dual_sim'] = df1['dual_sim'].astype('category')
df1['four_g'] = df1['four_g'].astype('category')
df1['n_cores'] = df1['n_cores'].astype('category')
df1['three_g'] = df1['three_g'].astype('category')
df1['touch_screen'] = df1['touch_screen'].astype('category')
df1['wifi'] = df1['wifi'].astype('category')
# 평가 데이터 불러오기
df2 = pd.read_csv('test.csv')
## 요약 통계량 확인
print(df2.describe())
id battery_power blue clock_speed dual_sim \
count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000
mean 500.500000 1248.510000 0.516000 1.540900 0.517000
std 288.819436 432.458227 0.499994 0.829268 0.499961
min 1.000000 500.000000 0.000000 0.500000 0.000000
25% 250.750000 895.000000 0.000000 0.700000 0.000000
50% 500.500000 1246.500000 1.000000 1.500000 1.000000
75% 750.250000 1629.250000 1.000000 2.300000 1.000000
max 1000.000000 1999.000000 1.000000 3.000000 1.000000
fc four_g int_memory m_dep mobile_wt ... \
count 1000.000000 1000.000000 1000.000000 1000.000000 1000.00000 ...
mean 4.593000 0.487000 33.652000 0.517500 139.51100 ...
std 4.463325 0.500081 18.128694 0.280861 34.85155 ...
min 0.000000 0.000000 2.000000 0.100000 80.00000 ...
25% 1.000000 0.000000 18.000000 0.300000 109.75000 ...
50% 3.000000 0.000000 34.500000 0.500000 139.00000 ...
75% 7.000000 1.000000 49.000000 0.800000 170.00000 ...
max 19.000000 1.000000 64.000000 1.000000 200.00000 ...
pc px_height px_width ram sc_h \
count 1000.000000 1000.000000 1000.000000 1000.000000 1000.000000
mean 10.054000 627.121000 1239.774000 2138.998000 11.995000
std 6.095099 432.929699 439.670981 1088.092278 4.320607
min 0.000000 0.000000 501.000000 263.000000 5.000000
...
75% 8.000000 16.000000 1.000000 1.00000 1.000000
max 18.000000 20.000000 1.000000 1.00000 1.000000
[8 rows x 21 columns]
## 속성 및 결측값 확인
print(df2.info())
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 1000 entries, 0 to 999
Data columns (total 21 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 id 1000 non-null int64
1 battery_power 1000 non-null int64
2 blue 1000 non-null int64
3 clock_speed 1000 non-null float64
4 dual_sim 1000 non-null int64
5 fc 1000 non-null int64
6 four_g 1000 non-null int64
7 int_memory 1000 non-null int64
8 m_dep 1000 non-null float64
9 mobile_wt 1000 non-null int64
10 n_cores 1000 non-null int64
11 pc 1000 non-null int64
12 px_height 1000 non-null int64
13 px_width 1000 non-null int64
14 ram 1000 non-null int64
15 sc_h 1000 non-null int64
16 sc_w 1000 non-null int64
17 talk_time 1000 non-null int64
18 three_g 1000 non-null int64
19 touch_screen 1000 non-null int64
20 wifi 1000 non-null int64
dtypes: float64(2), int64(19)
memory usage: 164.2 KB
None
## 데이터 형변환
df2['blue'] = df2['blue'].astype('category')
df2['dual_sim'] = df2['dual_sim'].astype('category')
df2['four_g'] = df2['four_g'].astype('category')
df2['n_cores'] = df2['n_cores'].astype('category')
df2['three_g'] = df2['three_g'].astype('category')
df2['touch_screen'] = df2['touch_screen'].astype('category')
df2['wifi'] = df2['wifi'].astype('category')
# 데이터 전처리
## 독립 변수, 종속 변수 분리
x = df1.drop('price_range', axis=1) # 독립 변수
y = df1['price_range'] # 종속 변수
## 원-핫 인코딩
x_encoded = pd.get_dummies(x)
# 모델링
## 데이터 분할
x_train, x_valid, y_train, y_valid = train_test_split(x_encoded, y, test_size=0.25, random_state=42)
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_train, y_train)
## 예측
pred = md.predict(x_valid)
## 평가
cm = confusion_matrix(y_valid, pred) # 혼동 행렬
print(cm)
[[124 8 0 0]
[ 10 97 11 0]
[ 0 16 90 14]
[ 0 0 10 120]]
print(accuracy_score(y_valid, pred)) # 정확도
0.862
# 평가 데이터 불러오기
x_test = df2
## 원-핫 인코딩
x_test_encoded = pd.get_dummies(x_test.drop('id', axis=1))
## 모델링
md = RandomForestClassifier(n_estimators=300)
md.fit(x_encoded, y)
## 평가
pred = md.predict(x_test_encoded)
print(pred)
[3 3 2 3 1 3 3 1 3 0 3 3 0 0 2 0 2 1 3 2 1 3 1 1 3 0 2 0 3 0 2 0 3 0 0 1 3
1 2 1 1 2 0 0 0 0 0 3 1 2 2 0 3 0 3 0 3 1 1 3 3 2 0 1 1 1 1 3 1 2 1 2 2 3
3 0 2 0 2 3 0 3 3 0 3 0 3 1 3 0 1 2 2 0 2 1 0 2 1 3 1 0 0 3 1 2 0 1 2 3 3
3 1 3 3 3 3 1 3 0 0 3 2 1 1 0 3 2 3 1 0 2 1 1 3 1 2 0 3 2 1 3 2 2 2 3 3 2
2 3 2 3 0 0 2 2 3 3 3 3 2 2 3 3 3 3 1 0 3 0 0 0 1 1 0 1 0 0 1 2 0 0 0 1 2
2 2 1 0 0 0 1 0 3 1 0 2 2 2 3 1 2 3 3 3 1 2 1 0 0 1 3 0 2 3 3 0 2 0 3 2 2
3 0 0 1 0 3 0 1 0 2 2 1 3 0 3 0 3 1 2 0 0 2 1 3 3 3 1 1 3 0 0 2 3 3 1 3 1
1 3 2 1 2 3 3 3 1 0 1 1 3 1 1 3 2 0 3 0 1 2 0 0 3 2 3 3 2 1 3 3 2 3 2 2 1
1 0 2 3 1 0 0 3 0 3 0 1 1 0 2 2 1 3 1 2 1 2 0 0 0 1 3 2 0 0 0 3 1 0 3 3 1
2 3 2 3 1 3 3 2 2 3 3 3 1 3 0 3 1 3 1 3 3 0 1 1 3 1 3 1 3 0 0 0 0 2 0 0 1
...
# CSV 내보내기
result = pd.DataFrame({ 'pred' : pred })
print(result)
...
998 2
999 2
[1000 rows x 1 columns]
result.to_csv('./outputs/task2-q5.csv', index=False)
728x90
그리드형(광고전용)
'Certificate > BDAE' 카테고리의 다른 글
[빅데이터분석기사 실기] 기출 복원 문제 - 제3유형 (0) | 2024.06.05 |
---|---|
[빅데이터분석기사 실기] 기출 복원 문제 - 제1유형 (0) | 2024.06.05 |
빅데이터분석기사 시험 개요 (0) | 2022.07.11 |