用python编写一个三层的BP神经网络的代码
时间: 2024-05-02 07:19:47 浏览: 88
好的,以下是三层BP神经网络的Python代码示例:
```
import numpy as np
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
self.W1 = np.random.randn(input_size, hidden_size)
self.W2 = np.random.randn(hidden_size, output_size)
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def forward(self, X):
self.z2 = np.dot(X, self.W1)
self.a2 = self.sigmoid(self.z2)
self.z3 = np.dot(self.a2, self.W2)
y_hat = self.sigmoid(self.z3)
return y_hat
def sigmoid_prime(self, z):
return np.exp(-z) / ((1 + np.exp(-z)) ** 2)
def cost(self, X, y):
y_hat = self.forward(X)
J = 0.5 * sum((y - y_hat) ** 2)
return J
def cost_prime(self, X, y):
y_hat = self.forward(X)
delta3 = np.multiply(-(y - y_hat), self.sigmoid_prime(self.z3))
dJdW2 = np.dot(self.a2.T, delta3)
delta2 = np.dot(delta3, self.W2.T) * self.sigmoid_prime(self.z2)
dJdW1 = np.dot(X.T, delta2)
return dJdW1, dJdW2
```
希望这个代码对你有帮助!
阅读全文