import numpy as np class BPNeuralNetwork: def __init__(self, input_size, hidden_size, output_size): self.input_size = input_size self.hidden_size = hidden_size self.output_size = output_size self.weights1 = np.random.randn(self.input_size, self.hidden_size) self.bias1 = np.zeros((1, self.hidden_size)) self.weights2 = np.random.randn(self.hidden_size, self.output_size) self.bias2 = np.zeros((1, self.output_size)) def forward(self, X): self.hidden_layer = np.dot(X, self.weights1) + self.bias1 self.activated_hidden_layer = self.sigmoid(self.hidden_layer) self.output_layer = np.dot(self.activated_hidden_layer, self.weights2) + self.bias2 self.activated_output_layer = self.sigmoid(self.output_layer) return self.activated_output_layer def sigmoid(self, s): return 1 / (1 + np.exp(-s)) def sigmoid_derivative(self, s): return s * (1 - s) def backward(self, X, y, o, learning_rate): self.error = y - o self.delta_output = self.error * self.sigmoid_derivative(o) self.error_hidden = self.delta_output.dot(self.weights2.T) self.delta_hidden = self.error_hidden * self.sigmoid_derivative(self.activated_hidden_layer) self.weights1 += X.T.dot(self.delta_hidden) * learning_rate self.bias1 += np.sum(self.delta_hidden, axis=0, keepdims=True) * learning_rate self.weights2 += self.activated_hidden_layer.T.dot(self.delta_output) * learning_rate self.bias2 += np.sum(self.delta_output, axis=0, keepdims=True) * learning_rate def train(self, X, y, learning_rate, epochs): for epoch in range(epochs): output = self.forward(X) self.backward(X, y, output, learning_rate) def predict(self, X): return self.forward(X) X = np.array([[0, 0, 1], [0, 1, 1], [1, 0, 1], [1, 1, 1]]) y = np.array([[0], [1], [1], [0]]) nn = BPNeuralNetwork(3, 4, 1) nn.train(X, y, 0.1, 10000) new_data = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0]]) print(nn.predict(new_data))
时间: 2023-06-17 16:02:01 浏览: 163
这是一个使用反向传播算法实现的简单的三层神经网络,输入层有3个节点,隐藏层有4个节点,输出层有1个节点。它的训练数据X是一个4x3的矩阵,y是一个4x1的矩阵。训练过程中,使用随机初始化的权重和偏置,对训练数据进行前向传播,计算输出值,在计算误差,并使用反向传播算法更新权重和偏置,最终得到一个可以进行二分类的神经网络模型。
在代码的最后,我们使用训练好的模型对新数据进行了预测,输出预测的结果。
阅读全文