感知机python代码
时间: 2023-06-17 20:08:06 浏览: 98
以下是一个基本的感知机Python代码示例:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, max_iterations=100):
self.learning_rate = learning_rate
self.max_iterations = max_iterations
def fit(self, X, y):
self.weights = np.zeros(1 + X.shape[1])
self.errors = []
for _ in range(self.max_iterations):
errors = 0
for xi, target in zip(X, y):
update = self.learning_rate * (target - self.predict(xi))
self.weights[1:] += update * xi
self.weights[0] += update
errors += int(update != 0.0)
self.errors.append(errors)
return self
def net_input(self, X):
return np.dot(X, self.weights[1:]) + self.weights[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
```
这是一个简单的二元分类感知机实现。其中,`fit`方法用于训练感知机模型;`net_input`方法用于计算输入的加权和;`predict`方法用于预测输出结果。
阅读全文