Scikit-Learn训练机器学习分类感知器
## 1. 在线读取iris数据集```python
import os
import pandas as pd
# 下载
try:
s = 'https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data'
print('From URL:', s)
df = pd.read_csv(s,header=None,encoding='utf-8')
except HTTPError:
s = 'iris.data'
# 读取.data文件,不读取列名
df = pd.read_csv(s,header=None, encoding='utf-8')
df.tail()
```
## 2. 加载 Iris 数据集
从 scikit-learn 加载 Iris 数据集,第三列代表花瓣的长度,第四列代表花瓣的宽度。物种分类已经转换为整数标签,其中**0 = Iris-Setosa,1 = Iris-Versicolor,2 = Iris-Virginia**。
```python
# jupyter
%matplotlib inline
from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
# 提取dataframe的第3列和第4列数据
X = iris.data[:, ]
# 分类标签
y = iris.target
# 打印分类标签
print('Class labels:', np.unique(y))
# Class labels:
```
## 3. 划分 Iris 数据集
将70%数据划分为 的训练集和30% 为测试集。
```python
from sklearn.model_selection import train_test_split
# X_train, y_train为训练集数据和标签
# X_test, y_test为测试集数据和标签
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1, stratify=y)
# 打印各标签的数据包含的数据数量
print('Labels counts in y:', np.bincount(y))
print('Labels counts in y_train:', np.bincount(y_train))
print('Labels counts in y_test:', np.bincount(y_test))
# Labels counts in y:
# Labels counts in y_train:
# Labels counts in y_test:
```
## 4. 标准化特征
```python
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
sc.fit(X_train)
# 标准化训练数据X_train_std , X_test_std
X_train_std = sc.transform(X_train)
X_test_std = sc.transform(X_test)
```
## 5. 通过scikit-learn训练感知器
**学习速率 (learning rate)**: 在训练模型时用于梯度下降的一个变量。在每次迭代期间,梯度下降法都会将学习速率与梯度相乘,得出的乘积称为梯度步长,**设置数据在在0-1之间**。
```python
from sklearn.linear_model import Perceptron
# eta0为学习率
# random_state随机生成器加权数值
ppn = Perceptron(eta0=0.1, random_state=1)
ppn.fit(X_train_std, y_train)
# Perceptron(eta0=0.1, random_state=1)
# 打印测试数据集分类错误数量
y_pred = ppn.predict(X_test_std)
print('Misclassified examples: %d' % (y_test != y_pred).sum())
# Misclassified examples: 1
# 获取感知器准确度
from sklearn.metrics import accuracy_score
print('Accuracy: %.3f' % accuracy_score(y_test, y_pred))
# Accuracy: 0.978
print('Accuracy: %.3f' % ppn.score(X_test_std, y_test))
# Accuracy: 0.978
```
## 6. 训练感知器模型
```python
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
from distutils.version import LooseVersion
def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
# 绘图图形和颜色生成
markers = ('o', 's', '^', 'v', '<')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# 绘图
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))
lab = classifier.predict(np.array().T)
lab = lab.reshape(xx1.shape)
plt.contourf(xx1, xx2, lab, alpha=0.3, 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=X,
alpha=0.8,
c=colors,
marker=markers,
label=f'Class {cl}',
edgecolor='black')
# 高亮显示测试数据集样本
if test_idx:
X_test, y_test = X, y
plt.scatter(X_test[:, 0],
X_test[:, 1],
c='none',
edgecolor='black',
alpha=1.0,
linewidth=1,
marker='o',
s=100,
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 ')
plt.ylabel('Petal width ')
plt.legend(loc='upper left')
plt.tight_layout()
plt.show()
```
**训练的感知器预测标签结果**
从下图可以看出,对于class 1和class2 标签,有个别样本分类错误,无颜色的黑色圈为测试数据集样本。![预测结果](data/attachment/forum/plugin_zhanmishu_markdown/202409/c88472b38f094659d883ae2ac1e093fa_1725166166_3082.png)
## 机器学习文章
[机器学习基本概念](https://www.resbang.com/thread-451-1-1.html)
页:
[1]