# Python快速实战机器学习(3) 线性分类器

Python快速实战机器学习(1) 教材准备

1、复习sklearn数据进行预处理；

2、掌握sklearn线性分类器使用；

3、学会使用画图来展示和理解分类结果；

```import numpy as np
from sklearn import datasets
X = iris.data[:,[2,3]]
y = iris.target

print (y.size)```

```import matplotlib.pyplot as plt

plt.scatter(X[:50,0], X[:50,1], color='red', marker = 's', label = '1')
plt.scatter(X[50:100,0], X[50:100,1], color='blue', marker = 'x', label = '2')
plt.scatter(X[100:150,0], X[100:150,1], color='green', marker = 'o', label = '2')
plt.xlabel('\$x_1\$')
plt.ylabel('\$x_2\$')
plt.legend(loc='upper left')
plt.show()```

```from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split( X , y , test_size = 0.3, random_state = 0)

print (X_train.shape)
print (X_test.shape)```

```from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)

print (np.mean(X_train_std))
print (np.var(X_train_std))```

```from sklearn.linear_model import Perceptron

ppn = Perceptron(max_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.pyplot as plt
import warnings

def versiontuple(v):
return tuple(map(int, (v.split("."))))

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

for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0],
y=X[y == cl, 1],
alpha=0.6,
c=cmap(idx),
edgecolor='black',
marker=markers[idx],
label=cl)

# highlight test samples
if test_idx:
# plot all samples
if not versiontuple(np.__version__) >= versiontuple('1.9.0'):
X_test, y_test = X[list(test_idx), :], y[list(test_idx)]
else:
X_test, y_test = X[test_idx, :], y[test_idx]

plt.scatter(X_test[:, 0],
X_test[:, 1],
c='',
alpha=1.0,
edgecolor='black',
linewidths=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.tight_layout()
# plt.savefig('./figures/iris_perceptron_scikit.png', dpi=300)
plt.show()```

121 篇文章24 人订阅

0 条评论

## 相关文章

PowerBI 战友联盟，是中国范围内由 PowerBI 从业者发起的专业学习现代商业智能的组织，我们以 PowerBI 为主题研究如何帮助企业和个人提升数字化...

12330

11140

9230

10220

### lda模型小记

lda模型是一个词袋模型，它认为一个文档由一组关键的词构成，这些词之间没有先后顺序，一篇文档可以有很多个主题，文档中的每个词都来自于这些主题中的其中一个。它是一...

14000

### 手把手教你入门和实践特征工程 的全方位万字笔记，附代码下载

（注：本节用到了两个数据集，分别是Salary_Ranges_by_Job_Classification 和 GlobalLandTemperaturesByC...

7410

23230

9010

### 饕餮盛宴：微软定义BI未来 新PowerBI全解读

2018 PASS峰会于 11.5~11.9 举行完毕，本文描述PASS峰会中有关PowerBI企业现代商务智能的进展以及未来展望，绝对震撼，超乎想象。

11310

11340