感知机模型python代码
时间: 2023-10-14 13:14:53 浏览: 110
python实现感知机模型的示例
感知机模型的Python代码如下:
```python
import numpy as np
class Perceptron:
def __init__(self, lr=0.1, n_iter=100):
self.lr = lr
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)
self.bias = 0
for _ in range(self.n_iter):
for i in range(n_samples):
x = X[i]
y_true = y[i]
y_pred = self.predict(x)
if y_true != y_pred:
self.weights += self.lr * y_true * x
self.bias += self.lr * y_true
def predict(self, X):
linear_output = np.dot(X, self.weights) + self.bias
return np.where(linear_output >= 0, 1, -1)
```
其中,`fit()` 函数用于训练感知机模型,`predict()` 函数用于进行预测。在训练过程中,使用随机梯度下降算法来更新权重和偏置。
阅读全文