感知器算法实验代码
时间: 2023-07-05 07:16:19 浏览: 88
以下是一个简单的感知器算法实验代码,可以用于二分类问题:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.1, num_epochs=100):
self.learning_rate = learning_rate
self.num_epochs = num_epochs
def fit(self, X, y):
self.weights = np.zeros(X.shape[1])
self.bias = 0
for epoch in range(self.num_epochs):
for i in range(X.shape[0]):
if y[i] * (np.dot(X[i], self.weights) + self.bias) <= 0:
self.weights += self.learning_rate * y[i] * X[i]
self.bias += self.learning_rate * y[i]
def predict(self, X):
y_pred = np.sign(np.dot(X, self.weights) + self.bias)
return y_pred
```
其中,`learning_rate` 为学习率,`num_epochs` 为迭代次数。`fit` 方法用于训练模型,`X` 为特征矩阵,`y` 为标签向量。`predict` 方法用于预测新样本的标签,`X` 为特征矩阵。
阅读全文