자격증/빅데이터분석기사

[빅분기] 실기 시험까지 D-10, 분류/ 로지스틱회귀모델 / 작업형 2유형 예시문제

mabb 2021. 11. 24. 00:20
반응형

 안녕하세요. 삶의질을 높이기 위해 노력하는 영차영차입니다.
빅데이터분석기사 실기 시험을 위한 본인의 메모 및 공부 목적 포스팅입니다.

 

 

작업형 2유형 예시문제를 풀어보았다.
데캠 교재를 보고 학습한 내용을 기반으로 코드를 작성하여 보았다.
아직 외워지지 않은 부분도 있고, 특히 iqr로 이상값을 처리하는 것이 감이 오질 않는다..

내일은 해당 데이터셋을 가지고 구매주기를 예측하는 회귀문제를 선형회귀모델을 가지고 진행해보아야겠다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
#예시 문제의 데이터를 이용한 연습
#분류 :로지스틱 회귀 모델 기본 코드 만들기/ 성별 예측
#회귀 :선형 회귀 모델 기본 코드 만들기 /구매주기 예측
 
#데이터 불러오기
 
import pandas as pd 
 
pd.options.display.float_format = '{:.2f}'.format
 
 
x_train = pd.read_csv('X_train.csv',encoding='euc-kr')
x_test = pd.read_csv('X_test.csv',encoding='euc-kr')
y_train = pd.read_csv('y_train.csv',encoding='euc-kr')
 
#데이터 살펴보기
display(x_train.head())
print('(행,열):',x_train.shape)
print('데이터타입\n',x_train.dtypes)
print('결측값:\n',x_train.isnull().sum())
print('통계치 확인')
display(x_train.describe())
 
display(x_test.head())
print('(행,열):',x_test.shape)
print('데이터타입\n',x_test.dtypes)
print('결측값:\n',x_test.isnull().sum())
display(x_test.describe())
 
display(y_train.head())
print('(행,열):',y_train.shape)
print('데이터타입\n',y_train.dtypes)
print('결측값:\n',y_train.isnull().sum())
print('밸류카운트:\n',y_train.gender.value_counts())
 
# x_train과 x_test 총 10개의 특성치가 있으며 cust_id는 인덱스 역할을 하는 컬럼이다.
# x_train 의 커스터머 id 는 0~3499 , x_test의 커스터머 id는 3500~5981
# 환불금액 컬럼에는 결측치가 다수 존재한다.
# x_train 데이터의 총 구매액과 최대구매액에 음수가 존재하는 것으로 보아 이상값이 존재한다.
#성별 예측과 관계없는 특성치, cust_id, 주구매지점
#주구매상품은 범주형 변수로 onehot인코딩 처리를 해본다.
#cust_id는 인덱스 개념으로 따로 복사를 해두고
#x_train 과 x_test를 합쳐서 결측치와 이상치를 처리하고, object 변수를 분리하여 원핫인코딩 후 합친다.
#제공된 x_train 케이스 3500개와 x_test 케이스 2482개를 보존하기 위하여 전처리시 케이스는 제거하지 않고 대체해본다.
 
#cust_id 컬럼을 복사해두기
x_train_cust_id = x_train[['cust_id']]
x_test_cust_id = x_test[['cust_id']]
y_train_cust_id = y_train[['cust_id']]
 
#y레이블 데이터프레임 만들어두기
 
y_train_gender = y_train[['gender']]
 
#전처리를 위하여 x_train과 x_test를 통합하여 x_total 데이터프레임을 만들기
#원핫인코딩 후 데이터 분리를 위하여 cust_id 데이터프레임을 만들어두기
 
x_total = pd.concat((x_train,x_test),axis = 0)
 
#원핫인코딩을 위하여 주구매상품 컬럼을 분리하여 데이터프레임 만들기
#수치형 변수를 분리한다. 자연스럽게 주구매지점 컬럼을 탈락시킬 예정
#cust_id 는 나중에 다시 원래 제공된 train ,test 케이스대로 분리시키기 위함.
#obj는 원핫 인코딩을 위함
#nume는 수치형 변수로 결측치 및 이상치를 처리하기 위함.
 
x_total_cust_id = x_total[['cust_id']]
x_total_obj = x_total[['주구매상품']]
x_total_nume = x_total.select_dtypes(exclude='object').drop(['cust_id'],axis=1)
 
 
#환불금액의 결측치는 환불금액이 없는 것으로 간주하여 0 으로 대체한다
 
x_total_nume_f = x_total_nume.fillna(0)
 
#컬럼별 이상치를 iqr을 이용하여 걸러내고 평균값으로 대체한다. /이상값이 많아서 그냥 두기로함.
# 사실 어떻게 처리해야할지 감이 오지 않음.
 
def outlier_IQR (n):
 
 
    q1 = x_total_nume_f.iloc[:,n].quantile(0.25)
    q3 = x_total_nume_f.iloc[:,n].quantile(0.75)
    iqr = q3 - q1
    over_out = x_total_nume_f[x_total_nume_f.iloc[:,n] > (q3 + iqr * 1.5)] 
    under_out = x_total_nume_f[x_total_nume_f.iloc[:,n] < (q1 - iqr * 1.5)]
 
    outlier = over_out + under_out
 
    return print(n,'컬럼 이상값',len(outlier),'개')
          
 
for n in range(0,len(x_total_nume_f.columns)):
    outlier_IQR(n)
    
    
 
#이제 주구매상품을 원핫인코딩 해보자
 
x_total_dumm = pd.get_dummies(x_total_obj)
 
# 전처리한 수치형변수와 더미변수, cust_id를 합치고 다시 데이터세트를 분할한다.
# cust_id 기준 0~3499는 train, 3500~5981은 test
 
x_total_concat = pd.concat((x_total_cust_id,x_total_nume_f,x_total_dumm),axis=1)
x_total_train = x_total_concat[x_total_concat['cust_id']<3500]
x_total_test = x_total_concat[x_total_concat['cust_id']>=3500]
print(x_total_train.shape)
print(x_total_test.shape)
 
 
#전처리한 x특성치를 정규화하기/ minmax스케일
# 정규화를하면 np array가 되어버림 / 모델적용은 array유형이어야 하는지?
 
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
scaler.fit(x_total_train)
x_train_scaled = scaler.transform(x_total_train)
x_test_scaled = scaler.transform(x_total_test)
 
display(pd.DataFrame(x_train_scaled).describe())
display(pd.DataFrame(x_test_scaled).describe())
 
# 전처리한 x와 y를 가지고 기본 모델에 적용하기
 
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(x_train_scaled,y_train_gender)
train_predict = model.predict(x_train_scaled)
train_proba = model.predict_proba(x_train_scaled)
 
test_predict = model.predict(x_test_scaled)
test_proba = model.predict_proba(x_test_scaled)
print('모델스코어',model.score(x_train_scaled,y_train_gender))
 
 
# 하이퍼파라미터 서치 시 워닝에러 표시하지 않기
import warnings
warnings.filterwarnings('ignore')
 
# 교차검증해보기 cross_val_score ,KFold ,ShuffleSplit
 
# 하이퍼파라미터 값 조정하기 그리드서치, 랜덤서치
# 그리드서치
 
from sklearn.model_selection import GridSearchCV ,RandomizedSearchCV
param_grid = {'C':[0.01,0.1,1,10,100]}
grid_search = GridSearchCV(model,param_grid,cv=5,return_train_score=True)
grid_search.fit(x_train_scaled,y_train_gender)
print('그리드 중 베스트 파라미터',grid_search.best_params_)
print('베스트그리드 이용 스코어',grid_search.best_score_)
 
# 랜덤서치
 
from scipy.stats import randint
param_distribs = {'C': randint(low = 0.01, high = 100)}
random_search = RandomizedSearchCV(model,param_distributions = param_distribs, cv=5,return_train_score=True)
random_search.fit(x_train_scaled,y_train_gender)
print('랜덤 중 베스트 파라미터',random_search.best_params_)
print('베스트랜덤서치 이용 스코어',random_search.best_score_)
 
 
#평가하기
 
#오차행렬 혼동행렬
from sklearn.metrics import confusion_matrix ,classification_report ,roc_curve, auc
confusion_train = confusion_matrix(y_train_gender,train_predict)
print('오차행렬\n',confusion_train)
 
#분류예측 레포트
cfreport_train = classification_report(y_train_gender,train_predict)
print('분류예측레포트\n',cfreport_train)
 
#roc 지표
 
from sklearn import metrics
false_positive_rate, true_positive_rate, thresholds = roc_curve(y_train_gender,model.decision_function(x_train_scaled))
roc_auc = metrics.roc_auc_score(y_train_gender,model.decision_function(x_train_scaled))
print('roc_auc',roc_auc)
 
 
#train예측치 데이터프레임으로 만들고 train_predict로 컬럼이름 변경하기
train_predict_df = pd.DataFrame(train_predict)
train_proba_df = pd.DataFrame(train_proba)
train_predict_df.rename(columns={0:'train_predict'})
 
#test예측치 데이터프레임으로 만들고 test_predict로 컬럼이름 변경하기
 
test_predict_df = pd.DataFrame(test_predict)
 
 
#최종 파일 만들기 x_test의 cust_id와 test 예측값을 concat한다
 
ans = pd.concat((x_test_cust_id,test_predict_df),axis=1)
ans.rename(columns={0:'test_predict'},inplace =True)
ans.to_csv('2150298.csv')
ans
cs

 

반응형