写一段用于多分类的感知机算法程序,python语言
时间: 2023-11-18 10:18:36 浏览: 49
以下是一个简单的多分类感知机算法程序,使用Python语言实现:
```python
import numpy as np
class Perceptron:
def __init__(self, num_classes, input_size, lr=0.1, epochs=1000):
self.num_classes = num_classes
self.input_size = input_size
self.lr = lr
self.epochs = epochs
self.weights = np.zeros((num_classes, input_size))
self.biases = np.zeros(num_classes)
def train(self, X, y):
for epoch in range(self.epochs):
for i in range(X.shape[0]):
x = X[i]
target = y[i]
output = self.predict(x)
if output != target:
self.weights[target] += self.lr * x
self.biases[target] += self.lr
self.weights[output] -= self.lr * x
self.biases[output] -= self.lr
def predict(self, x):
scores = np.dot(self.weights, x) + self.biases
return np.argmax(scores)
if __name__ == '__main__':
X = np.array([[1, 1], [2, 1], [2, 3], [3, 2]])
y = np.array([0, 0, 1, 1])
num_classes = 2
input_size = 2
perceptron = Perceptron(num_classes, input_size)
perceptron.train(X, y)
print(perceptron.predict(np.array([1, 2])))
```
此程序使用了一个简单的数据集,其中包含四个样本,每个样本有两个特征。在训练过程中,该程序会使用感知机算法来更新权重和偏置,直到达到指定的训练次数。最后,该程序会输出一个新样本的预测类别。
阅读全文