写一个bp神经网络,输入层三个节点,一个隐藏层,隐藏层有三个节点,输出层一个节点,要求逐行注释
时间: 2024-05-30 07:15:42 浏览: 132
# 导入需要的库
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BP_Network:
def __init__(self):
# 输入层节点数
self.input_layer_size = 3
# 隐藏层节点数
self.hidden_layer_size = 3
# 输出层节点数
self.output_layer_size = 1
# 初始化权重矩阵
self.w1 = np.random.randn(self.input_layer_size, self.hidden_layer_size)
self.w2 = np.random.randn(self.hidden_layer_size, self.output_layer_size)
def forward(self, X):
# 前向传播
self.z2 = np.dot(X, self.w1)
self.a2 = sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.w2)
y_hat = sigmoid(self.z3)
return y_hat
def cost_function(self, X, y):
# 损失函数
self.y_hat = self.forward(X)
J = 0.5 * sum((y - self.y_hat) ** 2)
return J
def cost_function_prime(self, X, y):
# 损失函数的导数
self.y_hat = self.forward(X)
delta3 = np.multiply(-(y - self.y_hat), sigmoid(self.z3) * (1 - sigmoid(self.z3)))
dJdW2 = np.dot(self.a2.T, delta3)
delta2 = np.dot(delta3, self.w2.T) * sigmoid(self.z2) * (1 - sigmoid(self.z2))
dJdW1 = np.dot(X.T, delta2)
return dJdW1, dJdW2
def train(self, X, y):
# 训练模型
learning_rate = 0.1
for i in range(1000):
dJdW1, dJdW2 = self.cost_function_prime(X, y)
self.w1 -= learning_rate * dJdW1
self.w2 -= learning_rate * dJdW2
def predict(self, X):
# 预测
return self.forward(X)
阅读全文