权重更新公式:
代码实现:
from functools import reduce class perceptron: def __init__(self, input_num, activator): """ :param input_num: 入参个数,用于初始化权重 :param activator: 激励函数 """ self.activator = activator self.weights = [0.0 for _ in range(input_num)] self.bias = 0.0 # 权重更新 def var_renew(self, x, y_pre, y_true, lr): self.weights += lr*(y_pre - y_true)*x self.bias += lr*(y_pre - y_true) return self.weights, self.bias # 感知器预测 def predict(self, data): y_pre = self.activator(reduce(lambda a, b: a+b, list(map(lambda x, w: data, self.weights)), self.bias)) return y_pre # 训练 def train(self, data, labels, lr, itreation): """ :param data: 输入数据集合 :param labels: 标签集合 :param lr: 学习率 :param itreation: 迭代轮数 :return: """ for i in range(itreation): for j in range(len(data)): y_pre = self.predict(data[j]) self.weights, self.bias = self.var_renew(data[j], y_pre, labels[j], lr)