单层感知机python代码
时间: 2023-10-13 09:22:45 浏览: 40
以下是一个单层感知机的Python代码示例:
```
import numpy as np
class Perceptron:
def __init__(self, input_size, lr=1, epochs=100):
self.W = np.zeros(input_size+1)
self.epochs = epochs
self.lr = lr
def activation_fn(self, x):
# Here, we are using a step function as the activation function
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 epoch 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
```
这里的`Perceptron`类实现了单层感知机的训练和预测功能。在训练时,我们使用了随机梯度下降算法来优化参数。在预测时,我们计算输入数据和参数的点积,然后将其输入到激活函数中获得输出。