用python实现感知器的三种算法
时间: 2023-11-18 09:29:42 浏览: 81
Python实现感知器算法
4星 · 用户满意度95%
感知器是一种二元分类器,可以通过多种算法实现。以下是三种常见的感知器算法的Python实现:
1. Rosenblatt感知器算法
```python
import numpy as np
class RosenblattPerceptron:
def __init__(self, learning_rate=0.1, max_iterations=100):
self.learning_rate = learning_rate
self.max_iterations = max_iterations
def fit(self, X, y):
self.w_ = 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.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
if errors == 0:
break
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
```
2. Widrow-Hoff感知器算法
```python
import numpy as np
class WidrowHoffPerceptron:
def __init__(self, learning_rate=0.1):
self.learning_rate = learning_rate
def fit(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for xi, target in zip(X, y):
error = target - self.predict(xi)
self.w_[1:] += self.learning_rate * error * xi
self.w_[0] += self.learning_rate * error
self.errors_.append(error)
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
```
3. Delta规则感知器算法
```python
import numpy as np
class DeltaRulePerceptron:
def __init__(self, learning_rate=0.1):
self.learning_rate = learning_rate
def fit(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for xi, target in zip(X, y):
error = target - self.predict(xi)
self.w_[1:] += self.learning_rate * error * xi
self.w_[0] += self.learning_rate * error
self.errors_.append(0.5 * error ** 2)
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return np.where(self.net_input(X) >= 0.0, 1, -1)
```
以上三种算法都是单层感知器,可用于解决线性可分问题。如果数据集不可线性分割,则需要使用多层感知器或其他算法来解决。
阅读全文