# scikit-learning小试牛刀

```import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
from matplotlib.colors import ListedColormap

X = iris.data[:, [2, 3]]
y = iris.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)

# 标准化
sc = StandardScaler()
# 按照train样本标准化，
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)
'''sc.scale_标准差, sc.mean_平均值, sc.var_方差'''

# 创建分类器类，设置参数
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())
print('Accuracy: %.2f' % accuracy_score(y_test, y_pred))

x1_min, x1_max = X_train_std[:, 0].min() - 1, X_train_std[:, 0].max() + 1
x2_min, x2_max = X_train_std[:, 1].min() - 1, X_train_std[:, 1].max() + 1

resolution = 0.01
# xx1 X轴，每一个横都是x的分布，所以每一列元素一样，xx2 y轴 每一列y分布，所以每一横元素一样
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),np.arange(x2_min, x2_max, resolution))

# .ravel() 函数是将多维数组降位一维，注意是原数组的视图，转置之后成为两列元素
z = ppn.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
'''
contourf画登高线函数要求 *X* and *Y* must both be 2-D with the same shape as *Z*, or they
must both be 1-D such that ``len(X)`` is the number of columns in
*Z* and ``len(Y)`` is the number of rows in *Z*.
'''
#　ｚ形状要做调整
z = z.reshape(xx1.shape)

# 填充等高线的颜色, 8是等高线分为几部分
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])

for i, value in enumerate(np.unique(y)):
temp = X_train_std[np.where(y_train==value)]
plt.scatter(x=temp[:,0],y=temp[:,1], marker=markers[value],s=69, c=colors[value], label=value)

plt.scatter(x=X_test_std[:, 0],y=X_test_std[:,1], marker= 'o',s=69, c='none', edgecolors='r', label='test test')

plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
plt.xlabel('petal length [standardized]')
plt.ylabel('petal width [standardized]')
plt.contourf(xx1, xx2, z, len(np.unique(y)), alpha = 0.4, cmap = cmap)
plt.legend(loc='upper left')
plt.show()```

95 篇文章31 人订阅

0 条评论

## 相关文章

13930

### 基于RandomForestRegressor的波士顿房价回归预测

2018年8月27日笔记 sklearn官方英文用户使用指南：https://sklearn.org/user_guide.html sklearn翻译中文...

33530

### 【TensorFlow篇】--Tensorflow框架初始，实现机器学习中多元线性回归

TensorFlow是谷歌基于DistBelief进行研发的第二代人工智能学习系统，其命名来源于本身的运行原理。Tensor（张量）意味着N维数组，Flow（流...

12710

77490

1.5K70

40360

### 图像识别（二） cifar10_input.py详解

tf.variable_scope和tf.name_scope的用法：https://blog.csdn.net/uestc_c2_403/article/de...

62760

78560

25440

22240