Python基于Logistic回歸建模計算某銀行在降低貸款拖欠率的數據示例
本文實例講述了Python基于Logistic回歸建模計算某銀行在降低貸款拖欠率的數據。分享給大家供大家參考,具體如下:
一、Logistic回歸模型:
二、Logistic回歸建模步驟
1.根據分析目的設置指標變量(因變量和自變量),根據收集到的數據進行篩選
2.用ln(p/1-p)和自變量x1...xp列出線性回歸方程,估計出模型中的回歸系數
3.進行模型檢驗。模型有效性檢驗的函數有很多,比如正確率、混淆矩陣、ROC曲線、KS值
4.模型應用。
三、對某銀行在降低貸款拖欠率的數據進行建模
源代碼為:
import pandas as pd filename=r'..\data\bankloan.xls' #導入數據路徑 data=pd.read_excel(filename) #讀取該excel文件 x=data.iloc[:,:8].as_matrix() #選取數據集中0-7行的數據,形成一個矩陣 y=data.iloc[:,8].as_matrix() from sklearn.linear_model import LogisticRegression as LR from sklearn.linear_model import RandomizedLogisticRegression as RLR rlr=RLR() rlr.fit(x,y) #訓練模型 rlr.get_support() #獲取特征篩選結果 print(u'通過邏輯回歸模型篩選特征結束。') print(u'有效特征為:%s'%','.join(data.columns[rlr.get_support()])) x=data[data.columns[rlr.get_support()]].as_matrix() #篩選好的特征 lr=LR() lr.fit(x,y) print(u'邏輯回歸模型訓練結束') print(u'模型的平均正確率:%s'%lr.score(x,y))
機器運行結果報錯:
IndexError: boolean index did not match indexed array along dimension 0; dimension is 9 but corresponding boolean dimension is 8
解決辦法:建立一個新的矩陣data2,去掉最后一行,使維數匹配。
修改后代碼如下:
import pandas as pd filename=r'..\data\bankloan.xls' data=pd.read_excel(filename) x=data.iloc[:,:8].as_matrix() y=data.iloc[:,8].as_matrix() from sklearn.linear_model import LogisticRegression as LR from sklearn.linear_model import RandomizedLogisticRegression as RLR rlr=RLR() rlr.fit(x,y) rlr.get_support() print(u'通過邏輯回歸模型篩選特征結束。') data2=data.drop(u'違約',1) print(u'有效特征為:%s'%','.join(data2.columns[rlr.get_support()])) x=data[data2.columns[rlr.get_support()]].as_matrix() lr=LR() lr.fit(x,y) print(u'邏輯回歸模型訓練結束') print(u'模型的平均正確率:%s'%lr.score(x,y))
機器運行結果:
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
相關文章
python免殺技術shellcode的加載與執(zhí)行
本文主要介紹了python免殺技術shellcode的加載與執(zhí)行,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-04-04