機(jī)器學(xué)習(xí)的本質(zhì)就是借助數(shù)學(xué)模型理解數(shù)據(jù)。神經(jīng)網(wǎng)絡(luò)(ANN,又稱為多層感知器MLP)算法可以用于有監(jiān)督學(xué)習(xí)——分類和回歸。理論上,多層神經(jīng)網(wǎng)絡(luò)可以模擬任何復(fù)雜的函數(shù)。下面介紹神經(jīng)網(wǎng)絡(luò)模型進(jìn)行分類研究的基本用法。
a.導(dǎo)入所需模塊
import numpy as np
from sklearn.datasets import load_iris
from sklearn.neural_network import MLPClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_curve
from sklearn.metrics import auc
import matplotlib.pyplot as plt
import seaborn as sns
b.生成測試數(shù)據(jù)
iris = load_iris()
sepal_petal_length = np.r_[iris.data[:,0], iris.data[:,2]]
sepal_petal_width = np.r_[iris.data[:,1], iris.data[:,3]]
raw_data = np.c_[sepal_petal_length, sepal_petal_width]
result = np.array(["sepal"] * 150 + ["petal"] * 150)
依次執(zhí)行下列代碼可以看到iris數(shù)據(jù)集結(jié)構(gòu)為150行 X 4列,4列分別為sepal length (cm)、sepal width (cm)、petal length (cm)、petal width (cm)。需要將其整理為“樣本行 X 特征列”的模式,然后分類結(jié)果為對應(yīng)樣本行的一維數(shù)組。結(jié)果如圖:
iris.data.shape
iris.feature_names
raw_data.shape
result.shape

c.將數(shù)據(jù)集分解成訓(xùn)練集和測試集,以便進(jìn)行交叉檢驗(yàn)來測試分類器的訓(xùn)練效果
Xtrain, Xtest, ytrain, ytest = train_test_split(raw_data, result, random_state=42)
d.構(gòu)建模型,用訓(xùn)練集數(shù)據(jù)對模型進(jìn)行訓(xùn)練
Xtrain, Xtest, ytrain, ytest = train_test_split(raw_data, result, random_state=42)
model = MLPClassifier(max_iter=1000, solver='lbfgs', activation='logistic', random_state=1)
parameter_space = {
'hidden_layer_sizes': [(x, y) for x in range(10, 60, 10) for y in range(10, 60, 10)],
'alpha': [1e-5, 0.0001],
'learning_rate': ['constant', 'invscaling', 'adaptive'],
}
grid = GridSearchCV(model, parameter_space, n_jobs=-1, cv=3)
%time grid.fit(Xtrain, ytrain)
e.用測試集數(shù)據(jù)進(jìn)行模型預(yù)測
model = grid.best_estimator_
yfit = model.predict(Xtest)
f.做混淆矩陣熱圖,展示模型預(yù)測效果
sns.set()
%matplotlib
mat = confusion_matrix(ytest, yfit)
sns.heatmap(mat.T, square=True, annot=True, fmt='d', cbar=False)
plt.xlabel('true label')
plt.ylabel('predicted label')

g.做ROC曲線,進(jìn)行模型評(píng)價(jià)
yscore = model.predict_proba(Xtest)[:, 1]
ytest1 = []
for i in ytest:
if i == "petal":
ytest1.append(0)
else:
ytest1.append(1)
fpr, tpr, threshold = roc_curve(ytest1, yscore)
roc_auc = auc(fpr,tpr)
print('roc_auc:', roc_auc)
lw = 2
plt.subplot(1,1,1)
plt.plot(fpr, tpr, color='darkorange',
lw=lw, label='ROC curve (area = %0.4f)' % roc_auc)
plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.0])
plt.xlabel('False positive rate (1 - specificity)')
plt.ylabel('True positive rate (sensitivity)')
plt.title('ROC', y=0.5)
plt.legend(loc="lower right")
plt.show()

可以看到模型AUC值為0.9950,預(yù)測效果極佳。一般,AUC值>0.8就可以認(rèn)為模型一致性較好了。
補(bǔ)充一下,數(shù)據(jù)預(yù)測效果不佳時(shí),可能需要對原始數(shù)據(jù)進(jìn)行一些預(yù)處理,例如歸一化等。特征變量集較大時(shí),可能需要找到與結(jié)局關(guān)聯(lián)較大的特征變量,剔除無關(guān)變量,這樣也可以提高模型預(yù)測效能,可以考慮使用前進(jìn)法、后退法等等。神經(jīng)網(wǎng)絡(luò)模型也適合分析高維數(shù)據(jù),但是分析時(shí)間會(huì)成倍增長,所以維度太高時(shí)需要對原始數(shù)據(jù)進(jìn)行降維處理。分類結(jié)果為二分類時(shí)可以用AUC值評(píng)價(jià)模型效能,多分類時(shí)可以用Kappa系數(shù)。