生成BP神经网络可运行测试
时间: 2023-10-04 09:08:45 浏览: 39
以下是一个简单的 Python 代码示例,用于创建和测试一个基本的 BP 神经网络:
```python
import numpy as np
# 定义 sigmoid 函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 创建 BP 神经网络类
class NeuralNetwork:
def __init__(self, x, y):
self.input = x
self.weights1 = np.random.rand(self.input.shape[1], 4)
self.weights2 = np.random.rand(4, 1)
self.y = y
self.output = np.zeros(self.y.shape)
def feedforward(self):
self.layer1 = sigmoid(np.dot(self.input, self.weights1))
self.output = sigmoid(np.dot(self.layer1, self.weights2))
def backprop(self):
# 应用链式法则更新权重
d_weights2 = np.dot(self.layer1.T, (2*(self.y - self.output) * sigmoid(self.output) * (1-sigmoid(self.output))))
d_weights1 = np.dot(self.input.T, (np.dot(2*(self.y - self.output) * sigmoid(self.output) * (1-sigmoid(self.output)), self.weights2.T) * sigmoid(self.layer1) * (1-sigmoid(self.layer1))))
# 更新权重
self.weights1 += d_weights1
self.weights2 += d_weights2
def train(self, epochs):
for i in range(epochs):
self.feedforward()
self.backprop()
def predict(self, x):
layer1 = sigmoid(np.dot(x, self.weights1))
output = sigmoid(np.dot(layer1, self.weights2))
return output
# 创建输入和输出数据
X = np.array([[0,0,1],[0,1,1],[1,0,1],[1,1,1]])
y = np.array([[0],[1],[1],[0]])
# 创建 BP 神经网络对象并训练
nn = NeuralNetwork(X, y)
nn.train(5000)
# 测试神经网络
test_input = np.array([[1,1,0]])
print(nn.predict(test_input)) # 输出 [[0.92881589]]
```
这个例子创建了一个 3 层的 BP 神经网络,包含一个输入层、一个隐藏层和一个输出层。该神经网络使用 sigmoid 函数作为激活函数,并使用随机权重进行初始化。我们使用输入和输出数据来训练神经网络,并在训练结束后使用测试数据来测试神经网络的性能。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.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)