感知器的三种算法用python实现
时间: 2023-11-18 22:29:29 浏览: 165
以下是三种感知器算法的Python实现示例:
1. Rosenblatt算法:
```python
import numpy as np
class Perceptron:
def __init__(self, learning_rate=0.1):
self.learning_rate = learning_rate
self.weights = None
self.bias = None
def fit(self, X, y, epochs=100):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(epochs):
for idx, sample in enumerate(X):
y_pred = np.dot(sample, self.weights) + self.bias
if y[idx] * y_pred <= 0:
self.weights += self.learning_rate * y[idx] * sample
self.bias += self.learning_rate * y[idx]
def predict(self, X):
y_pred = np.dot(X, self.weights) + self.bias
return np.sign(y_pred)
```
2. Widrow-Hoff算法:
```python
import numpy as np
class Adaline:
def __init__(self, learning_rate=0.1):
self.learning_rate = learning_rate
self.weights = None
self.bias = None
def fit(self, X, y, epochs=100):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(epochs):
for idx, sample in enumerate(X):
y_pred = np.dot(sample, self.weights) + self.bias
error = y[idx] - y_pred
self.weights += self.learning_rate * error * sample
self.bias += self.learning_rate * error
def predict(self, X):
y_pred = np.dot(X, self.weights) + self.bias
return np.sign(y_pred)
```
3. Delta规则:
```python
import numpy as np
class DeltaRule:
def __init__(self, learning_rate=0.1):
self.learning_rate = learning_rate
self.weights = None
self.bias = None
def fit(self, X, y, epochs=100):
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
for _ in range(epochs):
for idx, sample in enumerate(X):
y_pred = np.dot(sample, self.weights) + self.bias
error = y[idx] - y_pred
self.weights += self.learning_rate * error * sample
self.bias += self.learning_rate * error
def predict(self, X):
y_pred = np.dot(X, self.weights) + self.bias
return np.sign(y_pred)
```
阅读全文