利用神经网络模型进行分类研究

机器学习的本质就是借助数学模型理解数据。神经网络(ANN,又称为多层感知器MLP)算法可以用于有监督学习——分类和回归。理论上,多层神经网络可以模拟任何复杂的函数。下面介绍神经网络模型进行分类研究的基本用法。

a.导入所需模块
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.生成测试数据
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)

依次执行下列代码可以看到iris数据集结构为150行 X 4列,4列分别为sepal length (cm)、sepal width (cm)、petal length (cm)、petal width (cm)。需要将其整理为“样本行 X 特征列”的模式,然后分类结果为对应样本行的一维数组。结果如图:

iris.data.shape
iris.feature_names
raw_data.shape
result.shape
c.将数据集分解成训练集和测试集,以便进行交叉检验来测试分类器的训练效果
Xtrain, Xtest, ytrain, ytest = train_test_split(raw_data, result, random_state=42)
d.构建模型,用训练集数据对模型进行训练
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.用测试集数据进行模型预测
model = grid.best_estimator_
yfit = model.predict(Xtest)
f.做混淆矩阵热图,展示模型预测效果
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曲线,进行模型评价
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,预测效果极佳。一般,AUC值>0.8就可以认为模型一致性较好了。

补充一下,数据预测效果不佳时,可能需要对原始数据进行一些预处理,例如归一化等。特征变量集较大时,可能需要找到与结局关联较大的特征变量,剔除无关变量,这样也可以提高模型预测效能,可以考虑使用前进法、后退法等等。神经网络模型也适合分析高维数据,但是分析时间会成倍增长,所以维度太高时需要对原始数据进行降维处理。分类结果为二分类时可以用AUC值评价模型效能,多分类时可以用Kappa系数。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容