常見的分類算法
感知機
感知機是神經(jīng)網(wǎng)絡(luò)以及支持向量機的基礎(chǔ)。通過w*x + b = 0這樣一條直線將二維空間劃分為兩個區(qū)域皇钞,落在這兩個區(qū)域中的點被歸為正類和負類。
感知機的學(xué)習(xí)策略是通過極小化下面的損失函數(shù)來選取最終的直線:
該損失函數(shù)表達的含義是誤分類點到分離平面的總距離和松捉。也就是說夹界,誤分類點越少越好,誤分類點離分離平面的總距離和越小越好惩坑。
實現(xiàn)感知機分類模型:
先導(dǎo)入一個示例數(shù)據(jù)集掉盅,然后畫出該數(shù)據(jù)集的圖像。
In [1]: from matplotlib import pyplot as plt
In [2]: import pandas as pd
In [3]: data = pd.read_csv("two_class_data.csv", header=0)
In [4]: x = data['x']
In [5]: y = data['y']
In [6]: c = data['class']
In [7]: plt.scatter(x, y, c=c)
Out[7]: <matplotlib.collections.PathCollection at 0x231ca41d9b0>
In [8]: plt.show()
可以看到這個數(shù)據(jù)集是一個擁有明顯二分類特征的數(shù)據(jù)集以舒。
然后使用Scikit-learn提供的感知機方法來對上面的數(shù)據(jù)集進行分類效果測試趾痘。
In [1]: from matplotlib import pyplot as plt
In [2]: import pandas as pd
In [3]: from sklearn.model_selection import train_test_split
In [4]: from sklearn.linear_model import Perceptron
In [5]: # 導(dǎo)入數(shù)據(jù)
In [6]: data = pd.read_csv("two_class_data.csv", header=0)
In [7]: # 定義特征變量和目標變量
In [8]: feature = data[['x', 'y']].values
In [9]: target = data['class'].values
In [10]: # 對數(shù)據(jù)集進行切分,70%為訓(xùn)練集蔓钟,30%為測試集永票。
In [13]: x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.3, random_state=50)
In [14]: # 構(gòu)建模型
In [15]: model = Perceptron()
In [16]: # 訓(xùn)練模型
In [18]: model.fit(x_train, y_train)
C:\Users\yc\Anaconda3\lib\site-packages\sklearn\linear_model\stochastic_gradient.py:128: FutureWarning: max_iter and tol parameters have been added in <class 'sklearn.linear_model.perceptron.Perceptron'> in 0.19. If both are left unset, they default to max_iter=5 and tol=None. If tol is not None, max_iter defaults to max_iter=1000. From 0.21, default max_iter will be 1000, and default tol will be 1e-3.
"and default tol will be 1e-3." % type(self), FutureWarning)
Out[18]:
Perceptron(alpha=0.0001, class_weight=None, eta0=1.0, fit_intercept=True,
max_iter=None, n_iter=None, n_jobs=1, penalty=None, random_state=0,
shuffle=True, tol=None, verbose=0, warm_start=False)
In [19]: # 預(yù)測
In [20]: results = model.predict(x_test)
In [21]: # 以默認樣式繪制訓(xùn)練數(shù)據(jù)
In [22]: plt.scatter(x_train[:, 0], x_train[:, 1], alpha=0.3)
Out[22]: <matplotlib.collections.PathCollection at 0x1d02094a470>
In [23]: # 以方塊樣式繪制測試數(shù)據(jù)
In [24]: plt.scatter(x_test[:, 0], x_test[:, 1], marker=',', c=y_test)
Out[24]: <matplotlib.collections.PathCollection at 0x1d020963f60>
In [25]: # 將預(yù)測結(jié)果用標簽樣式標注在測試數(shù)據(jù)左上方
In [26]: for i, txt in enumerate(results):
...: plt.annotate(txt, (x_test[:, 0][i], x_test[:, 1][i]))
...:
In [27]: plt.show()
測試集中有兩個數(shù)據(jù)被錯誤分類。綠色的方框被標記為了C2滥沫。
還可以導(dǎo)出分類評估的數(shù)據(jù):
In [29]: print(model.score(x_test, y_test))
0.990196078431
這里如此高的分類正確率侣集,很大程度上是因為示例數(shù)據(jù)很好。感知機作為一種十分基礎(chǔ)的方法兰绣,在實際數(shù)據(jù)分類和預(yù)測中并不常用世分。因為,實戰(zhàn)過程中的數(shù)據(jù)肯定沒有示例數(shù)據(jù)呈現(xiàn)出的線性可分性缀辩。
這并不意味著感知機不重要臭埋。理解感知機踪央,可以更好地理解后面的支持向量機算法和神經(jīng)網(wǎng)絡(luò)算法。
支持向量機(SVM)
支持向量機是一種非常常用的瓢阴,適用性非常廣的分類方法畅蹂。與感知機不同的是,支持向量機不僅可以用于線性分類荣恐,還可以用于非線性分類液斜。支持向量機引入了最大間隔的思想來劃定分割平面。
通過支持向量機來重新對剛剛使用過的感知機的數(shù)據(jù)進行分類:
只需要更改兩行代碼叠穆,分別是導(dǎo)入支持向量機SVC和使用SVC構(gòu)建模型少漆。
In [30]: from matplotlib import pyplot as plt
In [31]: import pandas as pd
In [32]: from sklearn.model_selection import train_test_split
In [33]: from sklearn.svm import SVC
In [34]: data = pd.read_csv("two_class_data.csv", header=0)
In [35]: # 定義特征變量和目標變量
In [36]: feature = data[['x', 'y']].values
In [37]: target = data['class'].values
In [38]: # 對數(shù)據(jù)集進行切分,70%為訓(xùn)練集痹束,30%為測試集检疫。
In [39]: x_train, x_test, y_train, y_test = train_test_split(feature, target, test_s
...: ize=0.3, random_state=50)
In [40]: # 構(gòu)建模型
In [41]: model = SVC()
In [42]: # 訓(xùn)練模型
In [43]: model.fit(x_train, y_train)
Out[43]:
SVC(C=1.0, cache_size=200, class_weight=None, coef0=0.0,
decision_function_shape='ovr', degree=3, gamma='auto', kernel='rbf',
max_iter=-1, probability=False, random_state=None, shrinking=True,
tol=0.001, verbose=False)
In [44]: # 預(yù)測
In [45]: results = model.predict(x_test)
In [46]: # 以默認樣式繪制訓(xùn)練數(shù)據(jù)
In [47]: plt.scatter(x_test[:, 0], x_test[:, 1], marker=',', c=y_test)
Out[47]: <matplotlib.collections.PathCollection at 0x1d020fce9b0>
In [48]: # 將預(yù)測結(jié)果用標簽樣式標注在測試數(shù)據(jù)左上方
In [49]: for i, txt in enumerate(results):
...: plt.annotate(txt, (x_test[:, 0][i], x_test[:, 1][i]))
...:
In [50]: plt.show()
測試結(jié)果如下圖:
正確率已經(jīng)達到100%。
除了線性分類祷嘶,支持向量機還通過引入核函數(shù)來解決非線性分類的問題。
在將特征映射到高維空間的過程中夺溢,常常會用到多種核函數(shù)论巍,包括:線性核函數(shù),多項式核函數(shù)风响,高斯經(jīng)向基核函數(shù)等嘉汰。其中最常用的就是高斯徑向基核函數(shù),也簡稱為RBF核状勤。
通過支持向量機完成一個非線性分類的任務(wù)鞋怀。
zoo.csv叫動物園數(shù)據(jù)集,總共有18列持搜,第一列為動物名稱密似,最后一列為動物分類。
數(shù)據(jù)集中間的16列為動物特征葫盼,比如:是否有毛發(fā)残腌,是否下蛋。除了腿的數(shù)量為數(shù)值型贫导,其余特征列均為布爾型數(shù)據(jù)抛猫。數(shù)據(jù)集中的動物共有7類,通過最后一列的數(shù)字表示孩灯。
用支持向量機完成這個非線性分類任務(wù)闺金。導(dǎo)入csv文件。定義其中16列為特征峰档,最后一列為目標值败匹。
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
data = pd.read_csv("zoo.csv", header=0)
feature = data.iloc[:, 1:17].values
target = data['type'].values
x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.3, random_state=50)
model = SVC()
model.fit(x_train, y_train)
result = model.predict(x_test)
print(model.score(x_test, y_test))
測試集的正確分類率為0.867
0.866666666667
16個特征參與運算匣距,但得出的正確率并不高。主要原因為數(shù)據(jù)集太小了哎壳,才100行董栽。
由于存在16個特征嗤谚,所以無法進行可視化,有一種叫作PCA`降維的方法,它的作用是縮減特征的數(shù)量欲逃,從而更方便可視化呈現(xiàn)。
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.decomposition import PCA
data = pd.read_csv("zoo.csv", header=0)
feature = data.iloc[:, 1:17].values
target = data['type'].values
pca = PCA(n_components=2)
feature_pca = pca.fit_transform(feature)
x_train, x_test, y_train, y_test = train_test_split(feature_pca, target, test_size=0.3, random_state=50)
model = SVC()
model.fit(x_train, y_train)
results = model.predict(x_test)
print(model.score(x_test, y_test))
plt.scatter(x_train[:, 0], x_train[:, 1], alpha=0.3)
plt.scatter(x_test[:, 0], x_test[:, 1], marker=',', c=y_test)
for i, txt in enumerate(results):
plt.annotate(txt, (x_test[:, 0][i], x_test[:, 1][i]))
plt.show()
當(dāng)特征降為2維時凡纳,就可以通過平面圖畫出來了疏虫。
0.833333333333
這里得出的準確度變成了0.833,比之前的0.867還要低特石。原因是特征數(shù)量減少了盅蝗,影響了準確度。
K - 近鄰法(KNN)
k 近鄰時一種十分常用的分類方法姆蘸。KNN中的三個關(guān)鍵要素:
1.K值的大小墩莫。K值一般通過測試數(shù)據(jù)交叉驗證來選擇。
2.距離的度量逞敷。新數(shù)據(jù)與最近鄰數(shù)據(jù)之間的距離計算方式狂秦,有歐式距離或者曼哈頓距離等。
3.分類決策規(guī)則推捐。KNN的決策規(guī)則為多數(shù)表決裂问,即新數(shù)據(jù)屬于圓圈中占比最大的一類。
使用一個由3種類別構(gòu)成的數(shù)據(jù)集測試牛柒,并將KNN的決策邊界繪制出來堪簿。
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
data = pd.read_csv('c:/Users/yc/Desktop/data05/three_class_data.csv', header=0)
feature = data[['x', 'y']].values
target = data['class'].values
x_train, x_test, y_train, y_test = train_test_split(feature, target, test_size=0.3, random_state=50)
model = KNeighborsClassifier()
model.fit(x_train, y_train)
results = model.predict(x_test)
print(model.score(x_test, y_test))
# 繪制決策邊界等高線圖
cm0 = plt.cm.Oranges
cm1 = plt.cm.Greens
cm2 = plt.cm.Reds
cm_color = ListedColormap(['red', 'yellow'])
x_min, x_max = data['x'].min() - .5, data['x'].max() + .5
y_min, y_max = data['y'].min() - .5, data['y'].max() + .5
xx, yy = np.meshgrid(np.arange(x_min, x_max, .1),
np.arange(y_min, y_max, .1))
Z0 = model.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 0]
Z1 = model.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 1]
Z2 = model.predict_proba(np.c_[xx.ravel(), yy.ravel()])[:, 2]
Z0 = Z0.reshape(xx.shape)
Z1 = Z1.reshape(xx.shape)
Z2 = Z2.reshape(xx.shape)
plt.contourf(xx, yy, Z0, cmap=cm0, alpha=.9)
plt.contourf(xx, yy, Z1, cmap=cm0, alpha=.5)
plt.contourf(xx, yy, Z2, cmap=cm0, alpha=.4)
# 繪制訓(xùn)練集和測試集
plt.scatter(x_train[:, 0], x_train[:, 1], c=y_train, cmap=cm_color)
plt.scatter(x_test[:, 0], x_test[:, 1], c=y_test, cmap=cm_color, edgecolors='black')
plt.show()
由于示例數(shù)據(jù)集界線清晰,所以分類的正確率為100%皮壁。KNN的決策邊界:
圖中椭更,顏色越深的地方代表屬于某一類別的可能性越高。
決策樹和隨機森林
除了支持向量機和KNN之外闪彼,決策樹和隨機森林也是非常不錯的分類方法甜孤。
在決策分析中,可以用決策樹形象地展示決策過程畏腕,而決策數(shù)中缴川,就是類似于if-then規(guī)則的集合。
在用決策進行分類時描馅,從跟節(jié)點出發(fā)把夸,對實例的特征進行測試,然后將其分別分給不同的子節(jié)點铭污。然后對子節(jié)點重復(fù)上面的步驟恋日,最終所有的實例被分給葉節(jié)點中膀篮。
執(zhí)行決策樹算法,一般分為三步:
1. 特征選項岂膳。
特性選擇及選擇判斷規(guī)則誓竿。一般情況下,依據(jù)3種指標來選擇特征谈截,分別是信息增益筷屡,信息增益比,以及基尼指數(shù)簸喂。
其中依據(jù)增益來選擇特征毙死,是一種來源于信息論和概率統(tǒng)計中的方法。通過判斷某一特征對決策樹前后影響的信息差值喻鳄,從而選出最關(guān)鍵的特征扼倘。這種依據(jù)信息增益來選擇特征的算法,也被稱作ID3算法除呵。
信息增益在劃分訓(xùn)練數(shù)據(jù)特征時再菊,容易偏向取值較多的特征。于是改進了 ID3 算法竿奏,通過信息增益比值來選擇袄简,發(fā)展出了 C4.5 算法。除此之外泛啸,還有一種叫 CART 的生成算法,它利用了基尼指數(shù)最小化的原則秃症。
2. 數(shù)的生成候址。
選擇完特征之后,通過這些特征來生成一顆完整的決策樹种柑。生成的原則是岗仑,所有訓(xùn)練數(shù)據(jù)都能分配到相應(yīng)的葉節(jié)點。
3. 數(shù)的剪枝聚请。
一顆完整的決策樹荠雕,使得訓(xùn)練數(shù)據(jù)得到有效的劃分。但是完整的決策樹往往對于測試數(shù)據(jù)的效果并不好驶赏。因為出現(xiàn)了過度擬合的問題炸卑。過度擬合,指模型對訓(xùn)練數(shù)據(jù)的效果很好煤傍,但是對測試數(shù)據(jù)的效果差盖文,泛化能力較弱。
解決決策樹過度擬合的方法是對決策樹進行剪枝蚯姆。剪枝五续,也就是去掉一些葉節(jié)點洒敏。剪枝并不是隨意亂剪,它的依據(jù)是疙驾,剪枝前和剪枝后的決策樹整體損失函數(shù)最小凶伙。
對于決策樹的演示,用到了著名的鳶尾花 iris 數(shù)據(jù)集它碎。
iris是機器學(xué)習(xí)領(lǐng)域一個非常經(jīng)典的分類數(shù)據(jù)集函荣,它總共包含150行數(shù)據(jù)。每一行數(shù)據(jù)由4 個特征值及一個目標值組成链韭。其中 4` 個特征值分別為:萼片長度偏竟、萼片寬度、花瓣長度敞峭、花瓣寬度踊谋。而目標值及為三種不同類別的鳶尾花,分別為:Iris Setosa旋讹,Iris Versicolour殖蚕,Iris Virginica。
iris 數(shù)據(jù)集無需導(dǎo)入 csv 文件沉迹,作為常用的基準數(shù)據(jù)集之一睦疫,sklearn 提供了相應(yīng)的導(dǎo)入方法。輸出數(shù)據(jù)看一看鞭呕。
from sklearn import datasets
# 載入數(shù)據(jù)集
iris = datasets.load_iris()
print(iris.data, iris.target)
部分輸出:
[[ 5.1 3.5 1.4 0.2]
[ 4.9 3. 1.4 0.2]
[ 4.7 3.2 1.3 0.2]
[ 4.6 3.1 1.5 0.2]
[ 5. 3.6 1.4 0.2]
[ 5.4 3.9 1.7 0.4]
[ 4.6 3.4 1.4 0.3]
[ 5. 3.4 1.5 0.2]
········
[ 6.2 3.4 5.4 2.3]
[ 5.9 3. 5.1 1.8]] [0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
2 2]
構(gòu)建 iris 分類決策樹蛤育。
from sklearn.datasets import load_iris
from sklearn import tree
import graphviz
# 導(dǎo)入數(shù)據(jù)
iris = load_iris()
# 建立模型
model = tree.DecisionTreeClassifier()
# 模擬訓(xùn)練
clf = model.fit(iris.data, iris.target)
完成模型訓(xùn)練,就建立起一顆決策樹了葫松。通過 graphviz 模塊瓦糕,將決策樹繪制出來。
from sklearn.datasets import load_iris
from sklearn import tree
# 導(dǎo)入數(shù)據(jù)
iris = load_iris()
# 建立模型
model = tree.DecisionTreeClassifier()
# 模擬訓(xùn)練
clf = model.fit(iris.data, iris.target)
dot_data = tree.export_graphviz(clf, out_file=None,
feature_names=iris.feature_names,
class_names=iris.target_names,
filled=True,rounded=True,
special_characters=True)
graph = graphviz.Source(dot_data)
graph
隨機森林與決策樹不同的地方在于腋么,它不只是一棵樹咕娄,而是建立一堆樹。與決策樹不同珊擂,隨機森林每次只從全部數(shù)據(jù)集中隨機抽取一部分數(shù)據(jù)用于生成樹圣勒。隨機森林在生成樹的時候不會剪枝。
隨機森林優(yōu)點很多摧扇,它可以處理大量的數(shù)據(jù)圣贸;可以在特征不均衡時,依然維持較高的準確度扳剿;隨機森林學(xué)習(xí)速度快旁趟,一般情況下,比單純應(yīng)用決策樹要好。
使用隨機森林和決策樹算法針對上面的 iris 數(shù)據(jù)集進行分類锡搜,比較準確度橙困。
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
# 導(dǎo)入數(shù)據(jù)
iris = load_iris()
x_train = iris.data[:120]
x_test = iris.data[120:]
y_train = iris.target[:120]
y_test = iris.target[120:]
# 建立模型
model_tree = DecisionTreeClassifier(random_state=10)
model_random = RandomForestClassifier(random_state=10)
# 訓(xùn)練模型并驗證
model_tree.fit(x_train, y_train)
s1 = model_tree.score(x_test, y_test)
model_random.fit(x_train, y_train)
s2 = model_random.score(x_test, y_test)
print('DecisionTree:', s1)
print('RandomForest:', s2)
結(jié)果顯示,隨機森林的正確分類率比決策數(shù)高 10 個百分點耕餐。
DecisionTree: 0.7333333333333333
RandomForest: 0.8333333333333334