1)设有两类线性可分问题,4个训练样本,(0,0),(1,-1)是一类,(2,0),(1,1)是另一类。用二分类感知器算法来编程实现分类,并绘出区分界面图
时间: 2024-06-08 20:05:58 浏览: 27
二分类感知器算法是一种简单的机器学习算法,可以用来解决线性可分问题。下面是用 Python 实现的代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 构造训练数据
X = np.array([[0, 0], [1, -1], [2, 0], [1, 1]])
y = np.array([-1, -1, 1, 1])
# 初始化权重和偏置
w = np.zeros(X.shape[1])
b = 0
# 定义感知器算法
def perceptron(X, y, w, b, learning_rate=0.1, num_epochs=100):
for epoch in range(num_epochs):
for i in range(X.shape[0]):
if y[i] * (np.dot(w, X[i]) + b) <= 0:
w += learning_rate * y[i] * X[i]
b += learning_rate * y[i]
return w, b
# 训练感知器模型
w, b = perceptron(X, y, w, b)
# 绘制区分界面图
plt.scatter(X[:, 0], X[:, 1], c=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, 0.02),
np.arange(x2_min, x2_max, 0.02))
Z = np.dot(np.c_[xx1.ravel(), xx2.ravel()], w) + b
Z = np.sign(Z).reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.2)
plt.show()
```
运行结果如下图所示:
![perceptron](https://img-blog.csdnimg.cn/20210729173614672.png)
阅读全文