感知机算法python代码
时间: 2023-07-23 21:10:16 浏览: 88
以下是感知机算法的Python代码:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=1, num_iterations=1000):
self.learning_rate = learning_rate
self.num_iterations = num_iterations
def fit(self, X, y):
self.weights = np.zeros(X.shape[1])
self.bias = 0
for _ in range(self.num_iterations):
for i in range(len(X)):
activation = np.dot(X[i], self.weights) + self.bias
if y[i]*activation <= 0:
self.weights += self.learning_rate * y[i] * X[i]
self.bias += self.learning_rate * y[i]
def predict(self, X):
return np.sign(np.dot(X, self.weights) + self.bias)
```
其中,`fit`方法用于训练模型,`predict`方法用于预测数据。在`fit`方法中,我们初始化权重和偏置为0,然后通过循环训练样本,如果分类错误则更新权重和偏置。在`predict`方法中,我们计算权重和偏置对输入数据的加权和,并使用`np.sign`函数返回预测结果。
阅读全文