研一機器學習小白開始寫博客記錄學習了!請各位CSDN大佬多多指教[抱拳]
讀書筆記1 《Python Machine Learning Blueprints》 Alexander T.Combs 著 《Python機器學習實踐指南》黃申 譯
本文首先介紹機器學習基本流程,然后使用Jupyter Notebook作為編譯器,通過實際項目了解機器學習流程及常用Python機器學習庫,比如numpy(用于科學計算)、pandas(基于numpy,用于大型數據分析)、matplotlib(用于數據可視化)、seaborn(用于圖形風格整潔化)、statsmodels(用于探索數據、評估模型)、scikit-learn(覆蓋分類、回歸、聚類、降維、模型選擇和預處理等領域)。 可提前下載好需要用到的庫, Win+R在命令行分別運行 pip install requests pip install numpy pip install pandas pip install matplotlib pip install seaborn pip install statsmodels conda install scikit-learn 安裝包可參考–Python及其常用模塊庫下載及安裝
機器學習/數據科學的工作流程一般有六個步驟:獲取,檢查和探索,清理和準備,建模,評估和最后的部署。
獲取
機器學習應用中的數據,可以來自不同的的數據源,可能是通過電子郵件發送的CSV文件,也可能是從服務器中拉取出來的日志,或者它可能需要構建自己的Web爬蟲。數據也可能存在不同的格式,大部分情況下數據是基于文本格式的,但基于圖像、甚至視頻文件的機器學習應用也在不斷發展。 簡單例子:
import requests
r
= requests
. get
( r
"https://api.github.com/users/acombs/starred" )
r
. json
( )
檢查和探索
獲得數據之后,下一步就是合理地檢查數據。比如說:如果數據具有唯一的標識,那就檢查數據是否真的只有一個;如果數據是基于價格的,檢查是否總為正數;檢查數據是否缺失或者不完整。無論數據是何種類型,檢查最極端的情況通常是檢查異常的最好辦法。一個良好的實踐是在數據上運行一些簡單的統計測試,并將數據可視化。
清理和準備
當所有數據準備就緒,下一步就是將它轉化為適合于模型使用的格式。這個階段包括若干過程,如過濾、聚集、輸入和轉化。所需操作類型將很大程度上取決于數據的類型,以及所使用的庫和算法的類型。
建模
數據準備完成以后,下一階段就是建模了。在這個階段我們將選擇適當的算法,并在數據上訓練乘?模型。基本步驟包括將數據分割為訓練、測試和驗證的集合。
評估
模型構建完成并開始進行預測,下一步就是了解模型做的有多好。有很多方式來衡量模型的表現,它在很大程度上依賴于所用數據和模型的類型,不過就整體而言評估階段試圖回答:模型的預測和實際值到底有多接近。
部署
一旦模型表現令人滿意。那么下一個步驟就是部署了。根據具體的使用情況,這個階段有不同的形式,但常見的場景包括:將其作為一個大型應用程序中的某個功能特性,一個定制的Web應用程序,甚至一個簡單的cron作業。
下面開始項目實踐以了解機器學習具體步驟。
數據準備及檢查
從網站 http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data 下載一個經典的機器學習數據集:iris.data,并將其寫入iris目錄
import os
import pandas
as pd
import requestsPATH
= r
' C:\Users\Lenovo\Desktop\data\iris'
r
= requests
. get
( 'http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data' ) with open ( PATH
+ 'iris.data' , 'w' ) as f
: f
. write
( r
. text
) os
. chdir
( PATH
)
df
= pd
. read_csv
( PATH
+ 'iris.data' , names
= [ 'sepal length' , 'sepal width' , 'petal length' , 'petal width' , 'class' ] )
df
. head
( )
先學基本操作 在pandas中,操作的基本單位是表格形式的數據列和行,數據列稱為Series,表格稱為DateFrame. 以下通過列名,從數據框中選擇一列
df
= pd
. read_csv
( PATH
+ 'iris.data' , names
= [ 'sepal length' , 'sepal width' , 'petal length' , 'petal width' , 'class' ] )
df
[ 'sepal length' ]
使用.iloc[row,column]標注,執行數據切片,選擇前兩列和前四行
df
. iloc
[ : 3 , : 2 ]
使用.loc標注和Python列表切片的語法,可以選擇數據框中的一小片; 使用列表迭代器并只選擇描述width的列.
df
. loc
[ : 3 , [ x
for x
in df
. columns
if 'width' in x
] ]
另一種選擇數據的方法:根據某些特定的條件選擇數據的一個子集。下面代碼先列出所有可用唯一類,然后選擇其中之一。
df
[ 'class' ] . unique
( )
選擇數據框中只包含Iris-virginica類的數據
df
[ df
[ 'class' ] == "Iris-virginica" ]
計算數據框大小(總數)
df
. count
( )
計算Iris-virginica類總數
df
[ df
[ 'class' ] == 'Iris-virginica' ] . count
( )
將Iris-virginica數據保存為一個新的數據并重置索引
virginica
= df
[ df
[ 'class' ] == 'Iris-virginica' ] . reset_index
( drop
= True )
virginica
我們通過在某個列上放置條件來選擇數據,現在來添加更多的條件。下面我們將回到最初始的數據框,并使用兩個條件來選擇數據。
df
[ ( df
[ 'class' ] == 'Iris-virginica' ) & ( df
[ 'petal width' ] > 2.2 ) ]
下面使用pandas,從虹膜數據集中獲取一些快速的描述性統計數據(類別信息被自動屏蔽了,因為它在這里是不相關的)
df
. describe
( )
下面檢查特征之間是否有相關性,通過在數據魯昂上調用.corr()來完成
df
. corr
( )
數據可視化
創建一個寬6英尺、高4英尺的插圖,通過調用.hist()并傳入數據,依照iris數據框繪制了花瓣寬度的直方圖,將顏色設為black;設置y、x軸標簽;最后一行設置直方圖標題;
import matplotlib
. pyplot
as plt
import numpy
as np
plt
. style
. use
( 'ggplot' )
% matplotlib inlinefig
, ax
= plt
. subplots
( figsize
= ( 6 , 4 ) )
ax
. hist
( df
[ 'petal width' ] , color
= 'black' )
ax
. set_ylabel
( 'Count' , fontsize
= 12 )
ax
. set_xlabel
( 'Width' , fontsize
= 12 )
plt
. title
( 'Iris Petal Width' , fontsize
= 14 , y
= 1.01 )
下面為為iris數據集的每一列生成直方圖ax.hist()
fig
, ax
= plt
. subplots
( 2 , 2 , figsize
= ( 6 , 4 ) ) ax
[ 0 ] [ 0 ] . hist
( df
[ 'petal width' ] , color
= 'black' )
ax
[ 0 ] [ 0 ] . set_ylabel
( 'Count' , fontsize
= 12 )
ax
[ 0 ] [ 0 ] . set_xlabel
( 'width' , fontsize
= 12 )
ax
[ 0 ] [ 0 ] . set_title
( 'Iris Petal Width' , fontsize
= 14 , y
= 1.01 ) ax
[ 0 ] [ 1 ] . hist
( df
[ 'petal length' ] , color
= 'black' )
ax
[ 0 ] [ 1 ] . set_ylabel
( 'Count' , fontsize
= 12 )
ax
[ 0 ] [ 1 ] . set_xlabel
( 'Length' , fontsize
= 12 )
ax
[ 0 ] [ 1 ] . set_title
( 'Iris Petal Length' , fontsize
= 14 , y
= 1.01 ) ax
[ 1 ] [ 0 ] . hist
( df
[ 'sepal width' ] , color
= 'black' )
ax
[ 1 ] [ 0 ] . set_ylabel
( 'Count' , fontsize
= 12 )
ax
[ 1 ] [ 0 ] . set_xlabel
( 'width' , fontsize
= 12 )
ax
[ 1 ] [ 0 ] . set_title
( 'Iris Sepal Width' , fontsize
= 14 , y
= 1.01 ) ax
[ 1 ] [ 1 ] . hist
( df
[ 'sepal length' ] , color
= 'black' )
ax
[ 1 ] [ 1 ] . set_ylabel
( 'Count' , fontsize
= 12 )
ax
[ 1 ] [ 1 ] . set_xlabel
( 'Length' , fontsize
= 12 )
ax
[ 1 ] [ 1 ] . set_title
( 'Iris Sepal Length' , fontsize
= 14 , y
= 1.01 ) plt
. tight_layout
( )
使用scatter繪制散點圖
fig
, ax
= plt
. subplots
( figsize
= ( 6 , 6 ) )
ax
. scatter
( df
[ 'petal width' ] , df
[ 'petal length' ] , color
= 'black' )
ax
. set_xlabel
( 'Petal Width' )
ax
. set_ylabel
( 'Petal Length' )
ax
. set_title
( 'Petal Scatterplot' )
使用ax.plot()繪制線圖
fig
, ax
= plt
. subplots
( figsize
= ( 6 , 6 ) )
ax
. plot
( df
[ 'petal length' ] , color
= 'blue' )
ax
. set_xlabel
( 'Specimen Number' )
ax
. set_ylabel
( 'Petal Length' )
ax
. set_title
( 'Petal Length Plot' )
使用ax.bar()繪制條形圖,以下將三類鳶尾花中每個特征的平均值繪制一個條形圖
fig
, ax
= plt
. subplots
( figsize
= ( 6 , 6 ) )
bar_width
= .8
labels
= [ x
for x
in df
. columns
if 'length' in x
or 'width' in x
]
ver_y
= [ df
[ df
[ 'class' ] == 'Iris-versicolor' ] [ x
] . mean
( ) for x
in labels
]
vir_y
= [ df
[ df
[ 'class' ] == 'Iris-virginica' ] [ x
] . mean
( ) for x
in labels
]
set_y
= [ df
[ df
[ 'class' ] == 'Iris-setosa' ] [ x
] . mean
( ) for x
in labels
]
x
= np
. arange
( len ( labels
) )
ax
. bar
( x
, vir_y
, bar_width
, bottom
= set_y
, color
= 'darkgrey' )
ax
. bar
( x
, set_y
, bar_width
, bottom
= ver_y
, color
= 'white' )
ax
. bar
( x
, ver_y
, bar_width
, color
= 'black' )
ax
. set_xticks
( x
+ ( bar_width
/ 2 ) )
ax
. set_xticklabels
( labels
, rotation
= - 70 , fontsize
= 12 )
ax
. set_title
( 'Mean Feature Measurement By Class' , y
= 1.01 )
ax
. legend
( [ 'Virginica' , 'Setosa' , 'Versicolor' ] )
接下來學習seaborn并使用它將圖形變得更美觀、更整潔 僅通過兩行代碼繪制數據所有特性
import seaborn
as sns
sns
. pairplot
( df
, hue
= 'class' )
使用所學matplotlib來修改seaborn;使用violinplot生成小提琴圖
fig
, ax
= plt
. subplots
( 2 , 2 , figsize
= ( 7 , 7 ) )
sns
. set ( style
= 'white' , palette
= 'muted' )
sns
. violinplot
( x
= df
[ 'class' ] , y
= df
[ 'sepal length' ] , ax
= ax
[ 0 , 0 ] )
sns
. violinplot
( x
= df
[ 'class' ] , y
= df
[ 'sepal width' ] , ax
= ax
[ 0 , 1 ] )
sns
. violinplot
( x
= df
[ 'class' ] , y
= df
[ 'petal length' ] , ax
= ax
[ 1 , 0 ] )
sns
. violinplot
( x
= df
[ 'class' ] , y
= df
[ 'petal width' ] , ax
= ax
[ 1 , 1 ] )
fig
. suptitle
( 'Violin Plots' , fontsize
= 16 , y
= 1.03 )
for i
in ax
. flat
: plt
. setp
( i
. get_xticklabels
( ) , rotation
= - 90 )
fig
. tight_layout
( )
Map方法適用于序列,在我們的例子中將用它來轉變數據框的某個列;以下使用map方法將一個python字典作為其參數
df
[ 'class' ] = df
[ 'class' ] . map ( { "Iris-setosa" : 'SET' , 'Iris-virginica' : 'VIR' , 'Iris-versicolor' : 'VER' } )
df
apple方法使我們既能在數據框上工作,也可以在序列上工作; 以下創建一個新的列,它包含一個基于petal width列的二進制值,之前花瓣寬度均值為1.3,那么現在如果花瓣寬度等于或者寬于中指將其編碼為1,否則編碼為0
df
[ 'wide petal' ] = df
[ 'petal width' ] . apply ( lambda v
: 1 if v
>= 1.3 else 0 )
df
以下在數據框上使用aplly,而不知在一個單獨的列上使用。
df
[ 'petal area' ] = df
. apply ( lambda r
: r
[ 'petal length' ] * r
[ 'petal width' ] , axis
= 1 )
df
groupby操作:基于某些你所選擇的類別對數據進行分組
df
. groupby
( 'class' ) . mean
( )
建模和評估
Statsmodels是用于探索數據、估計模型,并運行統計檢驗的python包; 以下,構建一個簡單的線性回歸模型; 為setosa類中花萼長度和花萼寬度之間的關系進行建模。 首先我們通過散點圖來目測兩者的關系
fig
, ax
= plt
. subplots
( figsize
= ( 7 , 7 ) )
ax
. scatter
( df
[ 'sepal width' ] [ : 50 ] , df
[ 'sepal length' ] [ : 50 ] )
ax
. set_ylabel
( 'Sepal Length' )
ax
. set_xlabel
( 'Sepal Width' )
ax
. set_title
( 'Setosa Sepal Width vs. Sepal Length' , fontsize
= 14 , y
= 1.02 )
從上圖可以看出,它們之間似乎有一個正向的線性關系,接下來用statmodels在這個數據集上運行一個線性回歸模型,來預估這種關系的強度
import statsmodels
. api
as smy
= df
[ 'sepal length' ] [ : 50 ]
x
= df
[ 'sepal width' ] [ : 50 ] results
= sm
. OLS
( y
, x
) . fit
( )
print ( results
. summary
( ) )
接下來使用結果對象來繪制回歸線
fig
, ax
= plt
. subplots
( figsize
= ( 7 , 7 ) )
ax
. plot
( x
, results
. fittedvalues
, label
= 'regression line' )
ax
. scatter
( x
, y
, label
= 'data point' , color
= 'r' )
ax
. set_ylabel
( 'Sepal Length' )
ax
. set_xlabel
( 'Sepal Width' )
ax
. set_title
( 'Setosa Sepal Width vs. Sepal Length' , fontsize
= 14 , y
= 1.02 )
ax
. legend
( loc
= 2 )
scikit-learn覆蓋的一些領域包括:分類、回歸、聚類、降維、模型選擇和預處理; 例子:首先,使用iris數據建立一個分類器,然后學習如何利用scikit-learn的工具來評估得到的模型。
from sklearn
. ensemble
import RandomForestClassifier
from sklearn
. model_selection
import train_test_split clf
= RandomForestClassifier
( max_depth
= 5 , n_estimators
= 10 )
x
= df
. iloc
[ : , : 4 ]
y
= df
. iloc
[ : , 4 ] x_train
, x_test
, y_train
, y_test
= train_test_split
( x
, y
, test_size
= .3 )
y_pred
= clf
. predict
( x_test
) rf
= pd
. DataFrame
( list ( zip ( y_pred
, y_test
) ) , columns
= [ 'predicted' , 'actual' ] )
rf
[ 'correct' ] = rf
. apply ( lambda r
: 1 if r
[ 'predicted' ] == r
[ 'actual' ] else 0 , axis
= 1 )
rf
看看哪些特征提供了最佳的辨別能力,或者說預測能力
f_importances
= clf
. feature_importances_
f_names
= df
. columns
[ : 4 ]
f_std
= np
. std
( [ tree
. feature_importances_
for tree
in clf
. estimators_
] , axis
= 0 ) zz
= zip ( f_importances
, f_names
, f_std
)
zzs
= sorted ( zz
, key
= lambda x
: x
[ 0 ] , reverse
= True )
imps
= [ x
[ 0 ] for x
in zzs
]
labels
= [ x
[ 1 ] for x
in zzs
]
errs
= [ x
[ 2 ] for x
in zzs
]
plt
. bar
( range ( len ( f_importances
) ) , imps
, color
= 'r' , yerr
= errs
, align
= 'center' )
plt
. xticks
( range ( len ( f_importances
) ) , labels
)
另一個使用scikit-learn的例子,切換分類器并使用支持向量機(SVM)
from sklearn
. multiclass
import OneVsRestClassifier
from sklearn
. svm
import SVC
from sklearn
. model_selection
import train_test_split
import numpy
as npclf
= OneVsRestClassifier
( SVC
( kernel
= 'linear' ) ) x
= df
. iloc
[ : , : 4 ]
y
= np
. array
( df
. iloc
[ : , 4 ] ) . astype
( str ) x_train
, x_test
, y_train
, y_test
= train_test_split
( x
, y
, test_size
= .3 )
y_pred
= clf
. predict
( x_test
)
rf
= pd
. DataFrame
( list ( zip ( y_pred
, y_test
) ) , columns
= [ 'predicted' , 'actual' ] )
rf
[ 'correct' ] = rf
. apply ( lambda r
: 1 if r
[ 'predicted' ] == r
[ 'actual' ] else 0 , axis
= 1 )
rf
模型的準確率已經很高!機器學習模型構建好并且評估完成以后最后一步就是部署,將一個機器學習模型放入生產環境時,有許多可用選項。它基本上取決于應用程序的性質。
本文到此結束,供自己參考復習也供大家學習,如有錯誤之處敬請留言。
總結
以上是生活随笔 為你收集整理的一个小项目了解机器学习基本流程(附源码) 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。