Logistic回歸模型


Logistic回歸模型

Logistich回歸模型也被成為廣義線性回歸模型。
它是將線性回歸模型的預測值經過非線性的Logit函數轉換為[0,1]之間的概率值。
研究得是分類問題,跟之前的線性回歸、嶺回歸、Lasso回歸不同。

混淆矩陣

 					實際值
預				0			1	
測		0		A			B		A+B
值		1		C			D		C+D
			  	A+C			B+D
--------------------------------------------------    
A:表示正確預測負例的樣本個數,⽤TN表示。
B:表示預測為負例但實際為正例的個數,⽤FN表示。
C:表示預測為正例但實際為負例的個數,⽤FP表示。
D:表示正確預測正例的樣本個數,⽤TP表示。
准確率:表示正確預測的正負例樣本數與所有樣本數量的⽐值,即(A+D)/(A+B+C+D)。
正例覆蓋率:表示正確預測的正例數在實際正例數中的⽐例,即D/(B+D)。
負例覆蓋率:表示正確預測的負例數在實際負例數中的⽐例,即A/(A+C)。
正例命中率:表示正確預測的正例數在預測正例數中的⽐例,即D/(C+D)。

ROC曲線

通常繪制ROC曲線,不僅僅是得到左側的圖形,更重要的是計算
折線下的⾯積,即圖中的陰影部分,這個⾯積稱為AUC。
在做模型評估時,希望AUC的值越⼤越好,通常情況下,
當AUC在0.8以上時,模型就基本可以接受了。

KS曲線

# 導入第三方模塊
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# 自定義繪制ks曲線的函數
def plot_ks(y_test, y_score, positive_flag):
    # 對y_test重新設置索引
    y_test.index = np.arange(len(y_test))
    # 構建目標數據集
    target_data = pd.DataFrame({'y_test':y_test, 'y_score':y_score})
    # 按y_score降序排列
    target_data.sort_values(by = 'y_score', ascending = False, inplace = True)
    # 自定義分位點
    cuts = np.arange(0.1,1,0.1)
    # 計算各分位點對應的Score值
    index = len(target_data.y_score)*cuts
    scores = np.array(target_data.y_score)[index.astype('int')]
    # 根據不同的Score值,計算Sensitivity和Specificity
    Sensitivity = []
    Specificity = []
    for score in scores:
        # 正例覆蓋樣本數量與實際正例樣本量
        positive_recall = target_data.loc[(target_data.y_test == positive_flag) & (target_data.y_score>score),:].shape[0]
        positive = sum(target_data.y_test == positive_flag)
        # 負例覆蓋樣本數量與實際負例樣本量
        negative_recall = target_data.loc[(target_data.y_test != positive_flag) & (target_data.y_score<=score),:].shape[0]
        negative = sum(target_data.y_test != positive_flag)
        Sensitivity.append(positive_recall/positive)
        Specificity.append(negative_recall/negative)
    # 構建繪圖數據
    plot_data = pd.DataFrame({'cuts':cuts,'y1':1-np.array(Specificity),'y2':np.array(Sensitivity), 
                              'ks':np.array(Sensitivity)-(1-np.array(Specificity))})
    # 尋找Sensitivity和1-Specificity之差的最大值索引
    max_ks_index = np.argmax(plot_data.ks)
    plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y1.tolist()+[1], label = '1-Specificity')
    plt.plot([0]+cuts.tolist()+[1], [0]+plot_data.y2.tolist()+[1], label = 'Sensitivity')
    # 添加參考線
    plt.vlines(plot_data.cuts[max_ks_index], ymin = plot_data.y1[max_ks_index], 
               ymax = plot_data.y2[max_ks_index], linestyles = '--')
    # 添加文本信息
    plt.text(x = plot_data.cuts[max_ks_index]+0.01,
             y = plot_data.y1[max_ks_index]+plot_data.ks[max_ks_index]/2,
             s = 'KS= %.2f' %plot_data.ks[max_ks_index])
    # 顯示圖例
    plt.legend()
    # 顯示圖形
    plt.show()
    
    
# 導入虛擬數據
virtual_data = pd.read_excel(r'virtual_data.xlsx')
# 應用自定義函數繪制k-s曲線
plot_ks(y_test = virtual_data.Class, y_score = virtual_data.Score,positive_flag = 'P')
    
    
'''
於KS值⽽⾔,是希望越⼤越好,通常情況下,當KS值⼤於0.4時,模型基本可以接受。
'''

函數說明

LogisticRegression(tol=0.0001, fit_intercept=True,class_weight=None, max_iter=100)

tol:⽤於指定模型跌倒收斂的閾值
fit_intercept:bool類型參數,是否擬合模型的截距項,默認為True
class_weight:⽤於指定因變量類別的權重,如果為字典,則通過字典的形式{class_label:weight}傳
遞每個類別的權重;如果為字符串'balanced',則每個分類的權重與實際樣本中的⽐例成反⽐,當各分
類存在嚴重不平衡時,設置為'balanced'會⽐較好;如果為None,則表示每個分類的權重相等
max_iter:指定模型求解過程中的最⼤迭代次數, 默認為100

演示

# 導入第三方模塊
import pandas as pd
import numpy as np
from sklearn import model_selection
from sklearn import linear_model

# 讀取數據
sports = pd.read_csv(r'Run or Walk.csv')
# 提取出所有自變量名稱
predictors = sports.columns[4:]
# 構建自變量矩陣
X = sports.ix[:,predictors]
# 提取y變量值
y = sports.activity
# 將數據集拆分為訓練集和測試集
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.25, random_state = 1234)

# 利用訓練集建模
sklearn_logistic = linear_model.LogisticRegression()
sklearn_logistic.fit(X_train, y_train)
# 返回模型的各個參數
print(sklearn_logistic.intercept_, sklearn_logistic.coef_)

# 模型預測
sklearn_predict = sklearn_logistic.predict(X_test)
# 預測結果統計
pd.Series(sklearn_predict).value_counts()

# 導入第三方模塊
from sklearn import metrics
# 混淆矩陣
cm = metrics.confusion_matrix(y_test, sklearn_predict, labels = [0,1])
cm

# 計算正確與覆蓋率
Accuracy = metrics.scorer.accuracy_score(y_test, sklearn_predict)
Sensitivity = metrics.scorer.recall_score(y_test, sklearn_predict)
Specificity = metrics.scorer.recall_score(y_test, sklearn_predict, pos_label=0)
print('模型准確率為%.2f%%:' %(Accuracy*100))
print('正例覆蓋率為%.2f%%' %(Sensitivity*100))
print('負例覆蓋率為%.2f%%' %(Specificity*100))

# 混淆矩陣的可視化
# 導入第三方模塊
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib
# 繪制熱力圖
sns.heatmap(cm, annot = True, fmt = '.2e',cmap = 'GnBu')
# 圖形顯示
plt.show()

sklearn_logistic.predict_proba(X_test)
# y得分為模型預測正例的概率
y_score = sklearn_logistic.predict_proba(X_test)[:,1]
# 計算不同閾值下,fpr和tpr的組合值,其中fpr表示1-Specificity,tpr表示Sensitivity
fpr,tpr,threshold = metrics.roc_curve(y_test, y_score)

# 計算AUC的值
roc_auc = metrics.auc(fpr,tpr)

# 繪制面積圖
plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')
# 添加邊際線
plt.plot(fpr, tpr, color='black', lw = 1)
# 添加對角線
plt.plot([0,1],[0,1], color = 'red', linestyle = '--')
# 添加文本信息
plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)
# 添加x軸與y軸標簽
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
# 顯示圖形
plt.show()

# 調用自定義函數,繪制K-S曲線
plot_ks(y_test = y_test, y_score = y_score, positive_flag = 1)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM