分類與預(yù)測(cè)

常見的分類算法

感知機(jī)

感知機(jī)是神經(jīng)網(wǎng)絡(luò)以及支持向量機(jī)的基礎(chǔ)。通過w*x + b = 0這樣一條直線將二維空間劃分為兩個(gè)區(qū)域,落在這兩個(gè)區(qū)域中的點(diǎn)被歸為正類和負(fù)類。
感知機(jī)的學(xué)習(xí)策略是通過極小化下面的損失函數(shù)來選取最終的直線:


Figure_0.png

該損失函數(shù)表達(dá)的含義是誤分類點(diǎn)到分離平面的總距離和。也就是說,誤分類點(diǎn)越少越好,誤分類點(diǎn)離分離平面的總距離和越小越好。

實(shí)現(xiàn)感知機(jī)分類模型:
先導(dǎo)入一個(gè)示例數(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()

可以看到這個(gè)數(shù)據(jù)集是一個(gè)擁有明顯二分類特征的數(shù)據(jù)集。

Figure_1.png

然后使用Scikit-learn提供的感知機(jī)方法來對(duì)上面的數(shù)據(jù)集進(jìn)行分類效果測(cè)試。

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]: # 定義特征變量和目標(biāo)變量
In [8]: feature = data[['x', 'y']].values
In [9]: target = data['class'].values

In [10]: # 對(duì)數(shù)據(jù)集進(jìn)行切分,70%為訓(xùn)練集,30%為測(cè)試集。
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ù)測(cè)
In [20]: results = model.predict(x_test)

In [21]: # 以默認(rèn)樣式繪制訓(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]: # 以方塊樣式繪制測(cè)試數(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ù)測(cè)結(jié)果用標(biāo)簽樣式標(biāo)注在測(cè)試數(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()

測(cè)試集中有兩個(gè)數(shù)據(jù)被錯(cuò)誤分類。綠色的方框被標(biāo)記為了C2。


Figure_2.png

還可以導(dǎo)出分類評(píng)估的數(shù)據(jù):

In [29]: print(model.score(x_test, y_test))
0.990196078431

這里如此高的分類正確率,很大程度上是因?yàn)槭纠龜?shù)據(jù)很好。感知機(jī)作為一種十分基礎(chǔ)的方法,在實(shí)際數(shù)據(jù)分類和預(yù)測(cè)中并不常用。因?yàn)?,?shí)戰(zhàn)過程中的數(shù)據(jù)肯定沒有示例數(shù)據(jù)呈現(xiàn)出的線性可分性。
這并不意味著感知機(jī)不重要。理解感知機(jī),可以更好地理解后面的支持向量機(jī)算法和神經(jīng)網(wǎng)絡(luò)算法。

支持向量機(jī)(SVM)

支持向量機(jī)是一種非常常用的,適用性非常廣的分類方法。與感知機(jī)不同的是,支持向量機(jī)不僅可以用于線性分類,還可以用于非線性分類。支持向量機(jī)引入了最大間隔的思想來劃定分割平面。
通過支持向量機(jī)來重新對(duì)剛剛使用過的感知機(jī)的數(shù)據(jù)進(jìn)行分類:
只需要更改兩行代碼,分別是導(dǎo)入支持向量機(jī)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]: # 定義特征變量和目標(biāo)變量
In [36]: feature = data[['x', 'y']].values
In [37]: target = data['class'].values

In [38]: # 對(duì)數(shù)據(jù)集進(jìn)行切分,70%為訓(xùn)練集,30%為測(cè)試集。
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ù)測(cè)
In [45]: results = model.predict(x_test)

In [46]: # 以默認(rèn)樣式繪制訓(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ù)測(cè)結(jié)果用標(biāo)簽樣式標(biāo)注在測(cè)試數(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()

測(cè)試結(jié)果如下圖:


Figure_3.png

正確率已經(jīng)達(dá)到100%。

除了線性分類,支持向量機(jī)還通過引入核函數(shù)來解決非線性分類的問題。

在將特征映射到高維空間的過程中,常常會(huì)用到多種核函數(shù),包括:線性核函數(shù),多項(xiàng)式核函數(shù),高斯經(jīng)向基核函數(shù)等。其中最常用的就是高斯徑向基核函數(shù),也簡(jiǎn)稱為RBF核。

通過支持向量機(jī)完成一個(gè)非線性分類的任務(wù)。
zoo.csv叫動(dòng)物園數(shù)據(jù)集,總共有18列,第一列為動(dòng)物名稱,最后一列為動(dòng)物分類。


data

數(shù)據(jù)集中間的16列為動(dòng)物特征,比如:是否有毛發(fā),是否下蛋。除了腿的數(shù)量為數(shù)值型,其余特征列均為布爾型數(shù)據(jù)。數(shù)據(jù)集中的動(dòng)物共有7類,通過最后一列的數(shù)字表示。

用支持向量機(jī)完成這個(gè)非線性分類任務(wù)。導(dǎo)入csv文件。定義其中16列為特征,最后一列為目標(biāo)值。

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))

測(cè)試集的正確分類率為0.867

0.866666666667

16個(gè)特征參與運(yùn)算,但得出的正確率并不高。主要原因?yàn)閿?shù)據(jù)集太小了,才100行。

由于存在16個(gè)特征,所以無法進(jìn)行可視化,有一種叫作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維時(shí),就可以通過平面圖畫出來了。


Figure_4.png
0.833333333333

這里得出的準(zhǔn)確度變成了0.833,比之前的0.867還要低。原因是特征數(shù)量減少了,影響了準(zhǔn)確度。

K - 近鄰法(KNN)

k 近鄰時(shí)一種十分常用的分類方法。KNN中的三個(gè)關(guān)鍵要素:
1.K值的大小。K值一般通過測(cè)試數(shù)據(jù)交叉驗(yàn)證來選擇。
2.距離的度量。新數(shù)據(jù)與最近鄰數(shù)據(jù)之間的距離計(jì)算方式,有歐式距離或者曼哈頓距離等。
3.分類決策規(guī)則。KNN的決策規(guī)則為多數(shù)表決,即新數(shù)據(jù)屬于圓圈中占比最大的一類。

使用一個(gè)由3種類別構(gòu)成的數(shù)據(jù)集測(cè)試,并將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)練集和測(cè)試集
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的決策邊界:


Figure_5.png

圖中,顏色越深的地方代表屬于某一類別的可能性越高。

決策樹和隨機(jī)森林

除了支持向量機(jī)和KNN之外,決策樹和隨機(jī)森林也是非常不錯(cuò)的分類方法。

在決策分析中,可以用決策樹形象地展示決策過程,而決策數(shù)中,就是類似于if-then規(guī)則的集合。

在用決策進(jìn)行分類時(shí),從跟節(jié)點(diǎn)出發(fā),對(duì)實(shí)例的特征進(jìn)行測(cè)試,然后將其分別分給不同的子節(jié)點(diǎn)。然后對(duì)子節(jié)點(diǎn)重復(fù)上面的步驟,最終所有的實(shí)例被分給葉節(jié)點(diǎn)中。

執(zhí)行決策樹算法,一般分為三步:

1. 特征選項(xiàng)。

特性選擇及選擇判斷規(guī)則。一般情況下,依據(jù)3種指標(biāo)來選擇特征,分別是信息增益,信息增益比,以及基尼指數(shù)。

其中依據(jù)增益來選擇特征,是一種來源于信息論和概率統(tǒng)計(jì)中的方法。通過判斷某一特征對(duì)決策樹前后影響的信息差值,從而選出最關(guān)鍵的特征。這種依據(jù)信息增益來選擇特征的算法,也被稱作ID3算法。

信息增益在劃分訓(xùn)練數(shù)據(jù)特征時(shí),容易偏向取值較多的特征。于是改進(jìn)了 ID3 算法,通過信息增益比值來選擇,發(fā)展出了 C4.5 算法。除此之外,還有一種叫 CART 的生成算法,它利用了基尼指數(shù)最小化的原則。

2. 數(shù)的生成。

選擇完特征之后,通過這些特征來生成一顆完整的決策樹。生成的原則是,所有訓(xùn)練數(shù)據(jù)都能分配到相應(yīng)的葉節(jié)點(diǎn)。

3. 數(shù)的剪枝。

一顆完整的決策樹,使得訓(xùn)練數(shù)據(jù)得到有效的劃分。但是完整的決策樹往往對(duì)于測(cè)試數(shù)據(jù)的效果并不好。因?yàn)槌霈F(xiàn)了過度擬合的問題。過度擬合,指模型對(duì)訓(xùn)練數(shù)據(jù)的效果很好,但是對(duì)測(cè)試數(shù)據(jù)的效果差,泛化能力較弱。

解決決策樹過度擬合的方法是對(duì)決策樹進(jìn)行剪枝。剪枝,也就是去掉一些葉節(jié)點(diǎn)。剪枝并不是隨意亂剪,它的依據(jù)是,剪枝前和剪枝后的決策樹整體損失函數(shù)最小。

對(duì)于決策樹的演示,用到了著名的鳶尾花 iris 數(shù)據(jù)集。

iris是機(jī)器學(xué)習(xí)領(lǐng)域一個(gè)非常經(jīng)典的分類數(shù)據(jù)集,它總共包含150行數(shù)據(jù)。每一行數(shù)據(jù)由4 個(gè)特征值及一個(gè)目標(biāo)值組成。其中 4` 個(gè)特征值分別為:萼片長(zhǎng)度、萼片寬度、花瓣長(zhǎng)度、花瓣寬度。而目標(biāo)值及為三種不同類別的鳶尾花,分別為:Iris Setosa,Iris Versicolour,Iris Virginica。

iris 數(shù)據(jù)集無需導(dǎo)入 csv 文件,作為常用的基準(zhǔn)數(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
Figure_6.png

隨機(jī)森林與決策樹不同的地方在于,它不只是一棵樹,而是建立一堆樹。與決策樹不同,隨機(jī)森林每次只從全部數(shù)據(jù)集中隨機(jī)抽取一部分?jǐn)?shù)據(jù)用于生成樹。隨機(jī)森林在生成樹的時(shí)候不會(huì)剪枝。

隨機(jī)森林優(yōu)點(diǎn)很多,它可以處理大量的數(shù)據(jù);可以在特征不均衡時(shí),依然維持較高的準(zhǔn)確度;隨機(jī)森林學(xué)習(xí)速度快,一般情況下,比單純應(yīng)用決策樹要好。

使用隨機(jī)森林和決策樹算法針對(duì)上面的 iris 數(shù)據(jù)集進(jìn)行分類,比較準(zhǔn)確度。

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)練模型并驗(yà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é)果顯示,隨機(jī)森林的正確分類率比決策數(shù)高 10 個(gè)百分點(diǎn)。

DecisionTree: 0.7333333333333333
RandomForest: 0.8333333333333334
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容