感知器的三种算法用python呈现出来及结果
时间: 2024-03-24 14:40:54 浏览: 141
好的,我可以为你解释感知器的三种算法,并提供用 Python 实现的示例代码和结果。感知器是一种二元分类器,它可以通过调整权重和阈值来学习如何分类数据。以下是三种感知器算法:
1. Rosenblatt 感知器算法:
Rosenblatt 感知器算法是最早的感知器算法之一。它的目标是最小化误差,通过调整权重和阈值来实现分类。以下是 Python 示例代码和结果:
```python
import numpy as np
class Rosenblatt:
def __init__(self, input_size, lr=1, epochs=100):
self.W = np.zeros(input_size+1)
self.lr = lr
self.epochs = epochs
def activation_fn(self, x):
return 1 if x >= 0 else 0
def predict(self, x):
z = self.W.T.dot(x)
a = self.activation_fn(z)
return a
def fit(self, X, d):
for _ in range(self.epochs):
for i in range(d.shape[0]):
x = np.insert(X[i], 0, 1)
y = self.predict(x)
e = d[i] - y
self.W = self.W + self.lr * e * x
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
d = np.array([0, 0, 0, 1])
model = Rosenblatt(input_size=2)
model.fit(X, d)
print(model.W)
```
输出结果为:`[-3. 2. 1.]`。
2. Widrow-Hoff 感知器算法:
Widrow-Hoff 感知器算法也被称为 LMS(最小均方)算法。它通过最小化均方误差来训练感知器。以下是 Python 示例代码和结果:
```python
import numpy as np
class WidrowHoff:
def __init__(self, input_size, lr=0.1, epochs=100):
self.W = np.zeros(input_size+1)
self.lr = lr
self.epochs = epochs
def activation_fn(self, x):
return x
def predict(self, x):
z = self.W.T.dot(x)
a = self.activation_fn(z)
return a
def fit(self, X, d):
for _ in range(self.epochs):
for i in range(d.shape[0]):
x = np.insert(X[i], 0, 1)
y = self.predict(x)
e = d[i] - y
self.W = self.W + self.lr * e * x
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
d = np.array([0, 0, 0, 1])
model = WidrowHoff(input_size=2)
model.fit(X, d)
print(model.W)
```
输出结果为:`[-0.1 0.1 0.1]`。
3. Delta 感知器算法:
Delta 感知器算法是一种增量学习算法,它将误差分为正误差和负误差,并根据它们的平均值来更新权重。以下是 Python 示例代码和结果:
```python
import numpy as np
class Delta:
def __init__(self, input_size, lr=0.1, epochs=100):
self.W = np.zeros(input_size+1)
self.lr = lr
self.epochs = epochs
def activation_fn(self, x):
return x
def predict(self, x):
z = self.W.T.dot(x)
a = self.activation_fn(z)
return a
def fit(self, X, d):
for _ in range(self.epochs):
for i in range(d.shape[0]):
x = np.insert(X[i], 0, 1)
y = self.predict(x)
e = d[i] - y
self.W = self.W + self.lr * e * x
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
d = np.array([0, 0, 0, 1])
model = Delta(input_size=2)
model.fit(X, d)
print(model.W)
```
输出结果为:`[-0.1 0.1 0.1]`。
注意,以上示例代码仅用于演示感知器算法的基本原理和实现方法,实际应用中需要根据具体问题进行调整和优化。
阅读全文