import numpy as np # 生克关系矩阵 matrix = np.array([ [0, 1, 0, 0, -1], [-1, 0, 1, 0, 0], [0, -1, 0, 1, 0], [0, 0, -1, 0, 1], [1, 0, 0, -1, 0] ]) # 每个元素之间的相互作用强度 weights = np.random.randn(5, 5) # 定义模型函数 def model(theta): # 将一维参数转换为二维矩阵 w1 = theta[:25].reshape(5, 5) b1 = theta[25:30] # 计算每个元素之间的相互作用强度 hidden = np.matmul(matrix, w1) + b1 # 使用sigmoid函数进行非线性转换 output = 1 / (1 + np.exp(-hidden)) return output # 定义损失函数 def loss(theta, data): X, y = data y_pred = model(theta) return np.mean((y - y_pred) ** 2) # 定义反向传播函数 def backprop(theta, data): X, y = data # 将一维参数转换为二维矩阵 w1 = theta[:25].reshape(5, 5) b1 = theta[25:30] # 计算每个元素之间的相互作用强度 hidden = np.matmul(matrix, w1) + b1 # 使用sigmoid函数进行非线性转换 output = 1 / (1 + np.exp(-hidden)) # 计算误差 error = y - output # 计算梯度 d_output = error * output * (1 - output) d_hidden = np.matmul(d_output, w1.T) dw1 = np.matmul(matrix.T, d_hidden * hidden * (1 - hidden)) db1 = np.sum(d_hidden * hidden * (1 - hidden), axis=0) d_theta = np.concatenate((dw1.ravel(), db1)) return d_theta # 生成训练数据 X = np.random.randn(100, 5) y = model(weights) # 使用BP算法进行参数调整 theta = np.concatenate((weights.ravel(), np.zeros(5))) lr = 0.1 for i in range(1000): d_theta = backprop(theta, (X, y)) theta -= lr * d
发表评论