感知机python代码
时间: 2023-10-15 20:21:23 浏览: 15
下面是一个简单的感知机的 Python 代码示例:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.01, n_iter=1000):
self.learning_rate = learning_rate
self.n_iter = n_iter
def fit(self, X, y):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(self.n_iter):
for i in range(n_samples):
linear_output = np.dot(X[i], self.weights) + self.bias
y_predicted = self.activation(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(linear_output)
return y_predicted
def activation(self, x):
return np.where(x >= 0, 1, 0)
```
其中,`Perceptron` 类实现了一个感知机模型,包括基本的 `fit` 和 `predict` 方法。`fit` 方法使用输入的训练数据 `X` 和 `y` 进行训练,`predict` 方法用于对给定的输入数据 `X` 进行预测。`activation` 方法则是对输入进行激活的函数,这里使用的是阶跃函数。
在 `fit` 方法中,采用了随机梯度下降法(SGD)进行参数更新,每次迭代只处理一个样本。在 `predict` 方法中,使用学习到的权重和偏置对输入数据进行预测,并返回二元分类结果。