对四个坐标点分类,利用单层感知器完成线性可分的二分类模型设计的程序代码
时间: 2023-06-07 22:10:42 浏览: 83
以下是一个利用单层感知器完成线性可分的二分类模型设计的程序代码:
```python
import numpy as np
# 定义单层感知器类
class Perceptron(object):
def __init__(self, learning_rate=0.01, n_iter=1000):
self.learning_rate = learning_rate # 学习率
self.n_iter = n_iter # 迭代次数
self.weights = None # 权重
self.bias = None # 偏置
# 训练模型
def fit(self, X, y):
n_samples, n_features = X.shape # 样本数量和特征维度
self.weights = np.zeros(n_features) # 初始化权重为0
self.bias = 0 # 初始化偏置为0
# 随机梯度下降
for _ in range(self.n_iter):
for i in range(n_samples):
# 计算输出
linear_output = np.dot(self.weights, X[i]) + self.bias
y_predicted = self.activation_function(linear_output)
# 更新权重和偏置
update = self.learning_rate * (y[i] - y_predicted)
self.weights += update * X[i]
self.bias += update
# 预测样本标签
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias
y_predicted = self.activation_function(linear_output)
return y_predicted
# 定义激活函数(这里使用步函数)
def activation_function(self, x):
return np.where(x >= 0, 1, -1)
# 初始化四个坐标点
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([-1, 1, 1, 1]) # 用标签-1表示左下和其他三个点组成一类,用标签1表示其他三个点组成另一类
# 创建感知器对象
perceptron = Perceptron()
# 训练模型
perceptron.fit(X, y)
# 预测样本标签
print(perceptron.predict(X))
```
运行上述代码,得到的输出为`[-1 1 1 1]`,表示模型成功地将四个坐标点分成了两类:左下和其他三个点组成一类,其他三个点组成另一类。