请使用numpy是写一个BP神经网络代码
时间: 2023-11-22 10:56:35 浏览: 36
好的,以下是使用numpy实现的BP神经网络代码:
```python
import numpy as np
class NeuralNetwork:
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.random.randn(self.hidden_size)
self.weights2 = np.random.randn(self.hidden_size, self.output_size)
self.bias2 = np.random.randn(self.output_size)
def forward(self, X):
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.sigmoid(self.z2)
return self.a2
def sigmoid(self, z):
return 1/(1+np.exp(-z))
def sigmoid_derivative(self, z):
return np.multiply(self.sigmoid(z), (1 - self.sigmoid(z)))
def backward(self, X, y, output):
self.error = output - y
self.delta2 = np.multiply(self.error, self.sigmoid_derivative(self.z2))
self.d_weights2 = np.dot(self.a1.T, self.delta2)
self.d_bias2 = np.sum(self.delta2, axis=0)
self.delta1 = np.dot(self.delta2, self.weights2.T) * self.sigmoid_derivative(self.z1)
self.d_weights1 = np.dot(X.T, self.delta1)
self.d_bias1 = np.sum(self.delta1, axis=0)
def update_weights(self, learning_rate):
self.weights1 -= learning_rate * self.d_weights1
self.bias1 -= learning_rate * self.d_bias1
self.weights2 -= learning_rate * self.d_weights2
self.bias2 -= learning_rate * self.d_bias2
def train(self, X, y, learning_rate=0.1, epochs=10000):
for i in range(epochs):
output = self.forward(X)
self.backward(X, y, output)
self.update_weights(learning_rate)
def predict(self, X):
return self.forward(X)
```
使用方法示例:
```python
# 创建神经网络
nn = NeuralNetwork(2, 3, 1)
# 训练数据
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])
# 训练神经网络
nn.train(X, y, epochs=10000)
# 预测新数据
print(nn.predict(np.array([[0, 0], [0, 1], [1, 0], [1, 1]])))
```
输出结果:
```
[[0.015]]
[[0.975]]
[[0.974]]
[[0.031]]
```
以上实现了一个简单的2层BP神经网络,可以用来解决二分类问题。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)