|
总结如下:
scikit-learn库不仅提供了大量的学习算法,而且还包含了许多数据预处理、调优和对模型评估的功能;
前面案例中编写的Python代码,在scikit-learn库中都有函数可以调用;
sckit-learn可参考http://sklearn.apachecn.org/cn/0.19.0/index.html 或者http://scikit-learn.org/stable/index.html
本程序,调用scikit-learn库中Perceptron函数对Iris分类;
========================================================
运行结果:
代码如下:
############################################################################################ #sklearn中有鸾尾花的数据,读入的数据中只取【2】【3】两个特征 from sklearn import datasets import numpy as np iris = datasets.load_iris() X = iris.data[:, [2,3]] y = iris.target ############################################################################################ #对读入的数据进行随机分割,按照三七开进行分割 from sklearn.cross_validation import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 0) ############################################################################################ #对训练样本、测试样本进行标准特征缩放,即使数据的具备正态分布特性(均值为0、方差为1) from sklearn.preprocessing import StandardScaler sc = StandardScaler() sc.fit(X_train) #计算X_train中的均值和标准差,用于标准化处理; X_train_std = sc.transform(X_train) X_test_std = sc.transform(X_test) #使用X_train的均值和标准差,保证test和train的值 基本相当; #读取均值和标准差 #X_train_std.mean(axis = 0) #X_train_std.std(axis = 0) ############################################################################################ #训练感知器模型 from sklearn.linear_model import Perceptron ppn = Perceptron(n_iter=40, eta0=0.1, random_state=0)#迭代次数、学习速率、每次迭代后对数据重新排序 ppn.fit(X_train_std,y_train) ############################################################################################ #测试集上进行预测 y_pred = ppn.predict(X_test_std) print('Misclassified samples: %d ' % (y_test != y_pred).sum())#显示错误分类数量 ############################################################################################ #计算分类准确率 from sklearn.metrics import accuracy_score print('Accuracy: %.2f' % accuracy_score(y_test, y_pred)) ############################################################################################ #显示决策区域,并观察不同花朵样本的分类效果 from matplotlib.colors import ListedColormap import matplotlib.pylab as plt def plot_decision_regions(X, y, classifier, test_idx= None, resolution=0.02): #setup marker generator and color map markers = ('s', 'x', 'o', '^','v') colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan') cmap= ListedColormap(colors[:len(np.unique(y))]) #plot the decison surface x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() -1 , X[:, 1].max() + 1 xx1,xx2 = np.meshgrid(np.arange(x1_min, x1_max,resolution), np.arange(x2_min, x2_max,resolution)) Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T) Z = Z.reshape(xx1.shape) plt.contourf(xx1, xx2, Z, alpha = 0.4, cmap = cmap) plt.xlim(xx1.min(), xx1.max()) plt.ylim(xx2.min(), xx2.max()) #plot all samples X_test, y_test = X[test_idx, :], y[test_idx] for idx, cl in enumerate(np.unique(y)): plt.scatter(x= X[y==cl, 0], y = X[y==cl, 1], alpha=0.8, c=cmap(idx), marker= markers[idx],label = cl) #highlight test samples if test_idx: X_test, y_test = X[test_idx, :], y[test_idx] plt.scatter(X_test[:, 0], X_test[:,1], c='',alpha = 1.0, linewidth = 1, marker = 'o', s = 55, label = 'test set') ############################################################################################ X_combined_std = np.vstack((X_train_std, X_test_std)) y_combined = np.hstack((y_train, y_test)) plot_decision_regions(X = X_combined_std, y = y_combined, classifier = ppn, test_idx = range(105, 150)) plt.xlabel('petal length [standardized]') plt.ylabel('petal width [standardized]') plt.legend(loc='upper left') plt.show() ############################################################################################
补充:
vstack: https://docs.scipy.org/doc/numpy/reference/generated/numpy.vstack.html
hstack:https://docs.scipy.org/doc/numpy/reference/generated/numpy.hstack.html
scikit-learn:http://sklearn.apachecn.org/cn/0.19.0/index.html
#摘至《Python 机器学习》,作者:Sebastian Raschaka, 机械工业出版社;
Archiver|手机版|科学网 ( 京ICP备07017567号-12 )
GMT+8, 2024-9-24 01:49
Powered by ScienceNet.cn
Copyright © 2007- 中国科学报社