编写一个简单的单层感知器,用于多类分类
时间: 2025-02-16 19:15:10 浏览: 0
编写一个简单的单层感知器用于多类分类,可以参考以下步骤和代码示例。这个感知器将使用 numpy
进行数值计算,并使用 sigmoid
激活函数进行输出。
1. 导入库
首先,我们需要导入必要的库,主要是 numpy
和 random
。
import numpy as np
import random
2. 定义激活函数及其导数
我们将使用 sigmoid
激活函数及其导数。
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
3. 定义感知器类
感知器类将包含初始化、前向传播和反向传播的方法。
class Perceptron:
def __init__(self, input_size, output_size, lr=0.1):
# 初始化权重和偏置
self.weights = np.random.rand(input_size, output_size)
self.bias = np.random.rand(output_size)
self.lr = lr # 学习率
def predict(self, inputs):
# 前向传播
weighted_sum = np.dot(inputs, self.weights) + self.bias
output = sigmoid(weighted_sum)
return output
def train(self, training_inputs, labels, epochs=10000):
for _ in range(epochs):
for inputs, label in zip(training_inputs, labels):
# 前向传播
output = self.predict(inputs)
# 计算误差
error = label - output
# 更新权重和偏置
self.weights += self.lr * np.outer(inputs, error * sigmoid_derivative(output))
self.bias += self.lr * (error * sigmoid_derivative(output))
4. 准备训练数据
我们需要准备训练数据,包括输入和对应的标签。假设我们有一个 3x5 的数字图像,每个数字表示为一个 15 维的向量。
digits = {
0: np.array([1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1]),
1: np.array([0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1]),
2: np.array([1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0]),
3: np.array([1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1]),
4: np.array([1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0]),
5: np.array([1, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1]),
6: np.array([1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1]),
7: np.array([1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0]),
8: np.array([1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1]),
9: np.array([1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1])
}
training_inputs = np.array([digits[i] for i in range(10)])
labels = np.eye(10) # 0-9 的独热编码标签
5. 创建并训练感知器
创建感知器实例并训练它。
perceptron = Perceptron(input_size=15, output_size=10)
perceptron.train(training_inputs, labels)
6. 测试感知器
我们可以编写一个函数来测试感知器的性能,例如识别带噪声的数字图像。
def add_noise(digit, noise_level):
noisy_digit = digit.copy()
noise_indices = random.sample(range(len(digit)), noise_level)
for idx in noise_indices:
noisy_digit[idx] = 1 - noisy_digit[idx]
return noisy_digit
def recognize_digit_with_noise(digit_index, noise_level):
original_digit = digits[digit_index]
noisy_digit = add_noise(original_digit, noise_level)
prediction = perceptron.predict(noisy_digit)
recognized_digit = np.argmax(prediction)
return recognized_digit
# 测试
reps = 1000
gols = 0
noise_level = 1
test_digit = int(input("输入你想要识别的数字:\n"))
for _ in range(reps):
recognized_digit = recognize_digit_with_noise(test_digit, noise_level)
if recognized_digit == test_digit:
gols += 1
print(f"在干扰水平 {noise_level} 下,{reps} 次测试中有 {gols} 次精确识别")
总结
以上代码实现了一个简单的单层感知器,用于多类分类。感知器通过训练数据学习权重和偏置,能够在带噪声的数字图像上进行识别。你可以根据需要调整学习率、训练轮数等参数,以优化感知器的性能。
相关推荐


















