理论
实践
from sklearn.datasets import load_iris
import pandas as pd
import numpy as np
from sklearn.linear_model import Perceptron
import matplotlib.pyplot as plt
# 加载数据
iris = load_iris()
df = pd.Dataframe(iris.data, columns = iris.feature_names)
df['label'] = pd.Dataframe(iris.target)
df.head()
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | label |
|---|
| 0 | 5.1 | 3.5 | 1.4 | 0.2 | 0 |
|---|
| 1 | 4.9 | 3.0 | 1.4 | 0.2 | 0 |
|---|
| 2 | 4.7 | 3.2 | 1.3 | 0.2 | 0 |
|---|
| 3 | 4.6 | 3.1 | 1.5 | 0.2 | 0 |
|---|
| 4 | 5.0 | 3.6 | 1.4 | 0.2 | 0 |
|---|
# 选择两个特征进行二分类 可视化数据
plt.scatter(df[:50]['sepal length (cm)'], df[:50]['sepal width (cm)'], label='0')
plt.scatter(df[50:100]['sepal length (cm)'], df[50:100]['sepal width (cm)'], label='1')
plt.xlabel('sepal length (cm)')
plt.ylabel('sepal width (cm)')
plt.legend()
# 训练感知机模型
model = Perceptron(fit_intercept=True,
max_iter=1000,
tol=None,
shuffle=True)
model.fit(df.iloc[:100, [0,1]], df[0:100]['label'])
Perceptron(tol=None)
print(model.coef_)
print(model.intercept_)
[[ 70.7 -87.9]]
[-117.]
# 可视化
plt.scatter(df[:50]['sepal length (cm)'], df[:50]['sepal width (cm)'], label='0')
plt.scatter(df[50:100]['sepal length (cm)'], df[50:100]['sepal width (cm)'], label='1')
plt.xlabel('sepal length (cm)')
plt.ylabel('sepal width (cm)')
x_points = np.arange(4, 8)
# coef_ : w; intercept_: b
y_ = -(model.coef_[0][0]*x_points + model.intercept_)/model.coef_[0][1]
plt.plot(x_ponits, y_)
plt.legend()