感知器的三种算法用Python实现
时间: 2024-03-24 22:40:15 浏览: 30
感知器的三种算法是原始形式、对偶形式和对称形式。以下是使用Python实现这三种算法的示例代码:
1. 原始形式
```
import numpy as np
class Perceptron:
def __init__(self, eta=0.1, n_iter=10):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.errors_ = []
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
update = self.eta * (target - self.predict(xi))
self.w_[1:] += update * xi
self.w_[0] += update
errors += int(update != 0.0)
self.errors_.append(errors)
return self
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. 对偶形式
```
import numpy as np
class DualPerceptron:
def __init__(self, eta=0.1, n_iter=10):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.alpha_ = np.zeros(X.shape[0])
self.b_ = 0
gram_matrix = np.dot(X, X.T)
for _ in range(self.n_iter):
errors = 0
for i in range(X.shape[0]):
if y[i] * (np.sum(self.alpha_ * y * gram_matrix[i]) + self.b_) <= 0:
self.alpha_[i] += self.eta
self.b_ += self.eta * y[i]
errors += 1
if errors == 0:
break
self.w_ = np.sum(self.alpha_ * y * X.T, axis=1)
return self
def predict(self, X):
return np.where(np.dot(X, self.w_) + self.b_ >= 0, 1, -1)
```
3. 对称形式
```
import numpy as np
class SymmetricPerceptron:
def __init__(self, eta=0.1, n_iter=10):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.w_ = np.zeros(X.shape[1])
self.b_ = 0
self.v_ = np.zeros(X.shape[1])
for _ in range(self.n_iter):
errors = 0
for xi, target in zip(X, y):
if target * (np.dot(xi, self.w_) + self.b_) <= 0:
self.w_ += self.eta * target * xi + self.v_
self.b_ += self.eta * target
self.v_ = self.eta * target * xi
errors += 1
if errors == 0:
break
return self
def predict(self, X):
return np.where(np.dot(X, self.w_) + self.b_ >= 0, 1, -1)
```
相关推荐
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)