三个输入,四个输出,四组数据
对numpy和矩阵运算还不是太熟悉,可能写的复杂了点,矩阵数组来回转换
import numpy as np def acti_fun(x): return x # error = labels - output rate = 0.1 input_vecs = np.mat([[1, -1, 2], [1.5, 2, 1], [1.2, 3, -1.6], [-0.3, -0.5, 0.9]]) labels = np.mat([[0.5, 1.1, 3, -1], [3, -1.2, 0.2, 0.1], [-2.2, 1.7, -1.8, -1.0], [1.4, -0.4, -0.4, 0.6]]) n_x = input_vecs.shape[1] n_h = labels.shape[1] class P: def __init__(self): # self.weights = np.random.random() self.weights = np.arange(n_h * n_x).reshape(n_h, n_x) self.bias = [[0], [0], [0], [0]] # 定义训练函数,包括训练次数count,学习率rate def train(self, input_vecs, labels, count): for i in range(count): #精度d,平方差和 d = 0 for input_vec, label in zip(input_vecs, labels): input_vec = np.mat(input_vec) label = np.array(label).T label = np.mat(label) input_vec = np.array(input_vec).T output = acti_fun(np.dot(self.weights, input_vec) + self.bias) input_vec = np.array(input_vec).T input_vec = np.mat(input_vec) print('self_weights\n%s' % self.weights) error = label - output a = 0 for j in error: a = np.dot(j, j) d += a print('精度%s' % d) print('bias:\n%s' % self.bias) self.bias += rate * error a = acti_fun(np.dot(error, input_vec)) self.weights = a * 0.1 + self.weights print('----') if d < 0.01: print('训练好了,次数为%s,精度为%s' % (i, float(d))) break p = P() p.train(input_vecs, labels, 100)
运行结果片段