如何運(yùn)用sklearn做邏輯回歸預(yù)測
運(yùn)用sklearn做邏輯回歸預(yù)測
邏輯回歸算是機(jī)器學(xué)習(xí)中最基礎(chǔ)的模型了,回歸模型在做分類問題中有著較好的效果。
下面介紹下利用sklearn做邏輯回歸模型做模型一般分為:
提取數(shù)據(jù)---->了解數(shù)據(jù)(所謂的探索性數(shù)據(jù))---->數(shù)據(jù)預(yù)處理(包括但不限于填充缺失值,特征提取,轉(zhuǎn)換啞變量)---->選擇模型---->驗(yàn)證模型---->模型優(yōu)化
下面先簡單介紹下邏輯回歸的原理
說到邏輯回歸就不得不提一下線性回歸,線性回歸用wiki百科的定義來解釋就是:在統(tǒng)計(jì)學(xué)中,線性回歸是一種用來建立響應(yīng)標(biāo)量(因變量)和一個(gè)或多個(gè)解釋變量(自變量)之間的模型關(guān)系的線性方法。
線性回歸分為一元線性回歸和多元線性回歸。
均方誤差是回歸模型中常用的度量方法。一般用最小二乘法來最小化均方誤差。
線性回歸用的最多的是做預(yù)測,而邏輯回歸最適合的有二分預(yù)測,比如是否垃圾郵件,廣告是否點(diǎn)擊等等;今天的模型用kaggle比賽中的泰坦尼克預(yù)測數(shù)據(jù)集來做邏輯回歸模型,故此次我們做的是監(jiān)督學(xué)習(xí)。
1.在數(shù)據(jù)集從kaggle中下載后我們先讀取數(shù)據(jù)和數(shù)據(jù)預(yù)覽
通過DataFrame的函數(shù)info(),我們可以詳細(xì)看到數(shù)據(jù)的分布等情況
import pandas as pd train=pd.read_csv('D:\\pycm\\kaggle\\titanic\\train.csv',index_col=0) #read train data test=pd.read_csv('D:\\pycm\\kaggle\\titanic\\test.csv',index_col=0) #read test data print(train.info()) #show the information about train data,including counting values of null
2.了解數(shù)據(jù)
查看數(shù)據(jù)中的缺失值
print(train.isnull().sum()
發(fā)現(xiàn)數(shù)據(jù)中缺失數(shù)據(jù)Age有177個(gè),Cabin 有687個(gè),Embarked 有2個(gè);由于Cabin 缺失數(shù)據(jù)占比太大了,我們看下這列數(shù)據(jù)缺失部分和有值部分對(duì)是否獲救的情況是如何的,來判斷該特征是否需要直接刪除。
c=train.Cabin.value_counts() #get the value of Cabin print(c) train.drop(labels=Cabin,axis=1)
3.數(shù)據(jù)處理
看了下結(jié)果發(fā)現(xiàn)都是一些客艙號(hào),由于不具有很大的參考意義,在這里我直接把這個(gè)特征舍棄掉。
另一個(gè)列Embarked是登船的港口,有2個(gè)缺失值,我們用出現(xiàn)頻率最多的值來填充
train.Embarked=train.Embarked.fillna('S') Em=train.Embarked.value_counts() print(Em)
接下來是Age有177個(gè)缺失值,
由于年齡和姓名相關(guān),我們首先把未缺失的值按照姓名的簡稱來做下均值分類
train['cc']=train.Name.map(lambda x: str(re.compile(r',(.*)\.').findall(x)))#獲取名字中的簡稱字樣Mr,Miss,Mrs,Master,Dr等值 #替換上面的寫法:train['cc']=train['Name'].apply(lambda x:x.split(',')[1].split('.')[0].strip()) c=train.loc[:,['cc','Age']].query('Age>0').groupby('cc').mean() #按照名稱輔助列看下各年齡的均值
最后我們看到結(jié)果如下:
在這里我們對(duì)缺失值的年齡填充根據(jù)姓名簡稱的均值來進(jìn)行填充
train['Age']=train['Age'].fillna(0)#先對(duì)缺失值進(jìn)行0填充 for i in range(1,891): if train['Age'][i]==0 and train['cc'][i]=="[' Mr']": train.loc[i, 'Age']=32 if train['Age'][i]==0 and train['cc'][i] =="[' Mrs']": train.loc[i, 'Age']= 35 if train['Age'][i]==0 and train['cc'][i] == "[' Miss']": train.loc[i, 'Age']=20 if train['Age'][i]==0 and train['cc'][i] == "[' Master']": train.loc[i, 'Age']= 4 if train['Age'][i]==0 and train['cc'][i] == "[' Dr']": train.loc[i,'Age']=42
另一種寫法,如下:
value=['Mr','Miss','Mrs','Master','Dr'] for v in value: train.loc[(train.Age==0)&(train.cc==v),'Age']=c.loc[v,'Age']
到這里我們就把缺失值處理完了,下面我們對(duì)類別值進(jìn)行處理,我們先看下目前有哪些特征是類別
categore=train.dtypes[train.dtypes=='object'].index
結(jié)果為:
我們看到,目前有年齡,船票和登船口是類別型的,這里我們對(duì)年齡和登船口做變量賦值
train=train.replace({'Sex':{'male':1,'female':2}, 'Embarked':{'S':1,'C':2,'Q':3}} )
后面我們把Name,Ticket等無意義的字段直接刪掉
data=data.drop(labels=['cc','Name','Ticket'],axis=1)
到這里就數(shù)據(jù)處理完啦。由于kaggle數(shù)據(jù)都是直接把train,test給我們的,所以我一般會(huì)前期把train數(shù)據(jù)集和test數(shù)據(jù)集放一起做數(shù)據(jù)處理。
這里前面我們可以在最初做數(shù)據(jù)拼接操作
data=pd.concat([train,test],keys=(['train','test']))
最后對(duì)所有的數(shù)據(jù)處理完后把數(shù)據(jù)分開
train_data=data.xs('train')#分開得到level 為train的測試數(shù)據(jù) test_data=data.xs('test').drop(labels='Survived',axis=1) x_train=train_data.drop(labels='Survived',axis=1) y_train=train_data['Survived'] test_data=test_data.fillna(0)
4.選擇模型
本次的特征較少,我們就不做特別的特征選取了, 對(duì)數(shù)據(jù)處理完后就直接進(jìn)入模型階段,這次我們?cè)谶@里講解Logistics回歸模型。
首先對(duì)模型做均一化處理
from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression
S=StandardScaler() S.fit(x_train) x_train_stand=S.transform(x_train) x_test_stand=S.transform(test_data) Log=LogisticRegression(C=10) Log.fit(x_train_stand,y_train) #訓(xùn)練模型 prediction=Log.predict(x_test_stand) #用訓(xùn)練的模型Log來預(yù)測測試數(shù)據(jù) result=pd.DataFrame({'PassengerId':test_data.index,'Survived':prediction.astype(np.int32)}) #這里需要注意把prediction的數(shù)據(jù)轉(zhuǎn)換成Int型不然系統(tǒng)判定不了,得分會(huì)為0 result.to_csv('D:\\pycm\\kaggle\\titanic\\result.csv',index=False) #設(shè)置不輸出Index
最后將得到的結(jié)果提交,就完成啦,
后面還可以對(duì)模型進(jìn)行優(yōu)化,調(diào)參,我們放到下一期來進(jìn)行講解。這期講解邏輯回歸就先到這里,我們以一個(gè)是否生存的預(yù)測問題結(jié)尾。
最后附上完整代碼:
import pandas as pd import numpy as np import seaborn as sns import matplotlib import matplotlib.pyplot as plt import re from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.ensemble import RandomForestClassifier train=pd.read_csv('D:\\pycm\\kaggle\\titanic\\train.csv',index_col=0) #讀文件 test=pd.read_csv('D:\\pycm\\kaggle\\titanic\\test.csv',index_col=0) data=pd.concat([train,test],keys=(['train','test'])) print(data.info()) data.Embarked=data.Embarked.fillna('S') data=data.drop(labels='Cabin',axis=1) #data['cc']=data.Name.map(lambda x: str(re.compile(r',(.*)\.').findall(x))) data['cc']=data['Name'].apply(lambda x:x.split(',')[1].split('.')[0].strip()) c=data.loc[:,['cc','Age']].query('Age>0').groupby('cc').mean() print(c.loc['Miss','Age']) value=['Mr','Miss','Mrs','Master','Dr'] data['Age']=data['Age'].fillna(0) for v in value: data.loc[(data.Age==0)&(data.cc==v),'Age']=c.loc[v,'Age'] data=data.drop(labels=['cc','Name','Ticket'],axis=1) data=data.replace({'Sex':{'male':1,'female':2}, 'Embarked':{'S':1,'C':2,'Q':3}} ) train_data=data.xs('train') test_data=data.xs('test').drop(labels='Survived',axis=1) x_train=train_data.drop(labels='Survived',axis=1) y_train=train_data['Survived'] test_data=test_data.fillna(0) S=StandardScaler() S.fit(x_train) x_train_stand=S.transform(x_train) x_test_stand=S.transform(test_data) Log=RandomForestClassifier(oob_score=True,random_state=10) Log.fit(x_train_stand,y_train) prediction=Log.predict(x_test_stand) result=pd.DataFrame({'PassengerId':test_data.index,'Survived':prediction.astype(np.int32)}) result.to_csv('D:\\pycm\\kaggle\\titanic\\result.csv',index=False)
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Python連接MySQL數(shù)據(jù)庫進(jìn)行編程的步驟詳解
Python數(shù)據(jù)庫編程可以使用多種模塊與API,例如SQLite、MySQL、PostgreSQL等,本教程將重點(diǎn)介紹使用Python連接MySQL數(shù)據(jù)庫進(jìn)行編程,需要的朋友可以參考下2023-06-06Python爬取京東商品信息評(píng)論存并進(jìn)MySQL
這篇文章主要介紹了Python爬取京東商品信息評(píng)論存并進(jìn)MySQL,文章通過構(gòu)建mysql數(shù)據(jù)表展開Python爬取信息存進(jìn)MySQL的內(nèi)容,需要的小伙伴可以參考一下2022-04-04python3+PyQt5實(shí)現(xiàn)使用剪貼板做復(fù)制與粘帖示例
本篇文章主要介紹了python3+PyQt5實(shí)現(xiàn)使用剪貼板做復(fù)制與粘帖示例,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01python GUI庫圖形界面開發(fā)之PyQt5單選按鈕控件QRadioButton詳細(xì)使用方法與實(shí)例
這篇文章主要介紹了python GUI庫圖形界面開發(fā)之PyQt5單選按鈕控件QRadioButton詳細(xì)使用方法與實(shí)例,需要的朋友可以參考下2020-02-02django數(shù)據(jù)模型中null和blank的區(qū)別說明
這篇文章主要介紹了django數(shù)據(jù)模型中null和blank的區(qū)別說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-09-09django filters實(shí)現(xiàn)數(shù)據(jù)過濾的示例代碼
這篇文章主要介紹了django filters實(shí)現(xiàn)數(shù)據(jù)過濾的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05