댓글 쓰기 권한이 없습니다. 로그인 하시겠습니까?
사이트 로그인
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | # 0에서 1 사이를 1,000 등분하여 cut off로 대입. # 각각의 cuf off에 대해 ACC, F1, TPR, FPR, BCR 구하기 list = [] for i in np.linspace(0,1,1000): pred = model.predict_proba(X_vld)[:,1] > i cf_mtx = confusion_matrix(y_vld, pred) acc = accuracy_score(y_vld, pred) tpr = cf_mtx[0,0] / cf_mtx[0].sum() fpr = cf_mtx[1,0] / cf_mtx[1].sum() f1 = f1_score(y_vld, pred) # class 0 1 각각에 대한 f1을 구한뒤 가중평균함 bcr = np.sqrt((cf_mtx[0,0]/cf_mtx[0].sum())*(cf_mtx[1,1]/cf_mtx[1].sum())) list.append([i, acc, f1, tpr, fpr, bcr]) cut_off = DataFrame(list) cut_off.columns = ["CUTOFF", "ACC", "F1", "TPR", "FPR", "BCR"] # cut_off별 Performance Evaluation Index cut_off | cs |
1 2 3 4 5 6 7 8 9 10 11 | from sklearn.metrics import roc_curve, auc fpr, tpr, thersholds = roc_curve(y_vld, prediction) roc_auc = auc(fpr, tpr) plt.figure(figsize=(10,10)) plt.plot(cut_off["FPR"],cut_off["TPR"], color="darkorange", lw=1, label="ROC curve (area=%.2f)" %roc_auc) plt.plot([0,1], [0,1], color='navy', lw=1, linestyle='--') plt.title("ROC curve") plt.xlabel("FPR") plt.ylabel("TPR") plt.legend(loc="lower right") | cs |
1 2 3 4 5 | model = LogisticRegression() model.fit(X_tr, y_tr) pred_ACC_MAX = model.predict_proba(X_vld)[:,1] > cut_off_ACC_MAX pred_F1_MAX = model.predict_proba(X_vld)[:,1] > cut_off_F1_MAX pred_ACC_F1 = model.predict_proba(X_vld)[:,1] > cut_off_ACC_F1 | cs |
1 2 3 | print('1. ACC_MAX : 총 {}명 중 {:.2f}% 정확도로 생존을 맞춤'.format(y_vld.shape[0], 100 * accuracy_score(y_vld,pred_ACC_MAX))) print('2. F1_MAX : 총 {}명 중 {:.2f}% 정확도로 생존을 맞춤'.format(y_vld.shape[0], 100 * accuracy_score(y_vld,pred_F1_MAX))) print('3. ACC_F1 : 총 {}명 중 {:.2f}% 정확도로 생존을 맞춤'.format(y_vld.shape[0], 100 * accuracy_score(y_vld,pred_ACC_F1))) | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # 2.1. ACC MAX confusion_matrix(y_vld,pred_ACC_MAX) print(classification_report(y_vld,pred_ACC_MAX)) # 2.2. F1 MAX confusion_matrix(y_vld,pred_F1_MAX) print(classification_report(y_vld,pred_F1_MAX)) # 2.3. F1 MAX of ACC MAX confusion_matrix(y_vld,pred_ACC_F1) print(classification_report(y_vld,pred_ACC_F1)) # 2.4. defult(0.5) confusion_matrix(y_vld,prediction) print(classification_report(y_vld,prediction)) | cs |
array([[109, 6], [ 17, 47]], dtype=int64)
precision recall f1-score support 0 0.87 0.95 0.90 115 1 0.89 0.73 0.80 64 avg / total 0.87 0.87 0.87 179
array([[103, 12], [ 12, 52]], dtype=int64)
precision recall f1-score support 0 0.90 0.90 0.90 115 1 0.81 0.81 0.81 64 avg / total 0.87 0.87 0.87 179
array([[108, 7], [ 16, 48]], dtype=int64)
precision recall f1-score support 0 0.87 0.94 0.90 115 1 0.87 0.75 0.81 64 avg / total 0.87 0.87 0.87 179
array([[103, 12], [ 12, 52]], dtype=int64)
precision recall f1-score support 0 0.90 0.90 0.90 115 1 0.81 0.81 0.81 64 avg / total 0.87 0.87 0.87 179
row : actual(P, N), col : prediction(P, N)
ACC를 최대로 하는 cut off는 F1 최대보다 Positive로 분류하는 경향이 더 커 실제 Positive를 Positive라 분류할 가능성은 커지고(= 1종 오류의 가능성 감소), Negative를 Negative라고 분류할 가능성이 작아짐(= 2종 오류의 가능성 증가)
F1을 최대로 하는 cut off는 ACC 최대보다 Negative로 분류하는 경향이 더 커 실제 Positive를 Positive라 분류할 가능성은 작아지고(= 1종 오류의 가능성 증가), Negative를 Negative라고 분류할 가능성이 커짐(= 2종 오류의 가능성 감소)
Positive로 분류할 경향이 높은 모델(ACC 최대)을 선택할지, Negative로 분류할 경향이 높은 모델(F1 최대)을 선택할지는 분류문제가 무엇이냐에 따라 달리 설정해야한다.
1 2 3 4 | # 내적 -> 회귀계수와 X의 선형결합 def a(X, beta): out_a = X.dot(beta) return out_a |
1 2 3 | def P(a): out_p = 1/(1+np.exp(-a)) return out_p |
1 2 3 | def J(P, Y): out_j = (1/len(X))*( - sum(Y*np.log(P)) - sum ((1-Y)*np.log(1-P))) return out_j | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | # INPUT : Dataset X, Label T, Learning Rate alpha # OUTPUT : bestfit beta alpha = 0.000001 #aplha값이 매우 작아 학습이 더디게 이루어집니다. # 1. 초기값 설정 beta = np.random.randn(3) # 2. repeat until i = 16770000 #최저값을 발견한 지점. 처음부터 횟수를 이렇게 지정하진 않았습니다. i = 0 while(J(P(a(X, beta)), T) > 0): beta = beta - alpha*GD(X, beta, T) i = i +1 if i % 10000 == 0: print(" %d 번째" %i) print(J(P(a(X, beta)), T)) if i == 16770000: break | cs |
# 최적 beta값 저장
1 2 | # 최적 beta 저장 best_fit_01 = deepcopy(beta) | cs |
1 2 3 4 5 | # Classifier Model 만들기 def clf(X, beta, cut_off = 0.5): return P(a(X, beta)) > cut_off clf(X, beta) | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | # Mash grid xx, yy =np.mgrid[min(data.iloc[:,2])-.5:max(data.iloc[:,2])+.5:0.1, min(data.iloc[:,3])-.5:max(data.iloc[:,3])+.5:0.1] # Logistic function P에 넣기 위해 값을 표준화 xx_r = (xx-np.mean(xx))/np.std(xx) yy_r = (yy-np.mean(yy))/np.std(yy) # 각 순서쌍에 대하여 P값을 구함 grid = np.c_[np.repeat(1,len(xx_r.ravel())), xx_r.ravel(), yy_r.ravel()] probs = P(a(grid, best_fit_01)).reshape(xx_r.shape) # grid의 각 지점에 대하여 Logistic Model의 P값을 contour로 표현 f, ax = plt.subplots(figsize=(10,10)) contour = ax.contourf(xx, yy, probs, 25, cmap="RdBu", vmin=0, vmax=1) ax_c = f.colorbar(contour) ax_c.set_label("$P(y=1)$") ax_c.set_ticks([0,.25,.5, .75, 1]) ax.scatter(data.iloc[:,2], data.iloc[:,3], c=T, s=50, cmap = "RdBu", vmin=-.2, vmax=1.2, edgecolor="white", linewidth=1) ax.set(xlim=(min(data.iloc[:,2]-.5), max(data.iloc[:,2])+.5), ylim=(min(data.iloc[:,3]-.5),max(data.iloc[:,3])+.5), xlabel="$X_1$", ylabel="$X_2$") | cs |
1 2 3 4 5 6 7 8 9 | # 분류선 f, ax = plt.subplots(figsize=(12,12)) ax.contour(xx, yy, probs, levels=[.5], cmap="Greys", vmin=0, vmax=.6) ax.scatter(data.iloc[:,2], data.iloc[:,3], c=T, s=50, cmap = "RdBu", vmin=-.2, vmax=1.2, edgecolor="white", linewidth=1) ax.set(xlim=(min(data.iloc[:,2]-.5), max(data.iloc[:,2])+.5), ylim=(min(data.iloc[:,3]-.5),max(data.iloc[:,3])+.5), xlabel='experience', ylabel='salary') | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | # 연속형 그리드를 만들고 각각의 좌표점에 대한 확률 계산 xx, yy = np.mgrid[min(X[:,1])-.5:max(X[:,1])+.5:0.01, min(X[:,2])-.5:max(X[:,2])+.5:0.01] grid = np.c_[np.repeat(1,len(xx.ravel())), xx.ravel(), yy.ravel()] probs = P(a(grid, best_fit_01)).reshape(xx_r.shape) # grid의 각 지점에 대하여 Logistic Model의 P값을 contour로 표현 f, ax = plt.subplots(figsize=(12,12)) contour = ax.contourf(xx, yy, probs, 25, cmap="RdBu", vmin=0, vmax=1) ax_c = f.colorbar(contour) ax_c.set_label("$P(y=1)$") ax_c.set_ticks([0,.25,.5, .75, 1]) ax.scatter(X[:,1], X[:,2], c=T, s=50, cmap = "RdBu", vmin=-.2, vmax=1.2, edgecolor="white", linewidth=1) ax.set(aspect="equal", xlim=(min(X[:,1]-.5), max(X[:,1])+.5), ylim=(min(X[:,2]-.5),max(X[:,2])+), xlabel="$X_1$", ylabel="$X_2$") | cs |
Designed by sketchbooks.co.kr / sketchbook5 board skin
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5
Sketchbook5, 스케치북5