一个bp神经网络的测试函数用python
时间: 2024-05-29 15:04:58 浏览: 94
基于python实现BP神经网络
一个BP神经网络的测试函数可以用Python编写,如下所示:
```python
import numpy as np
def sigmoid(x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(x):
return x * (1 - x)
def train(inputs, outputs, epochs, learning_rate):
input_layer_size = inputs.shape
hidden_layer_size = 4
output_layer_size = 1
weights_hidden = np.random.uniform(size=(input_layer_size, hidden_layer_size))
weights_output = np.random.uniform(size=(hidden_layer_size, output_layer_size))
for epoch in range(epochs):
# Forward pass
hidden_layer_input = np.dot(inputs, weights_hidden)
hidden_layer_output = sigmoid(hidden_layer_input)
output_layer_input = np.dot(hidden_layer_output, weights_output)
output_layer_output = sigmoid(output_layer_input)
# Backward pass
output_error = outputs - output_layer_output
output_delta = output_error * sigmoid_derivative(output_layer_output)
hidden_error = np.dot(output_delta, weights_output.T)
hidden_delta = hidden_error * sigmoid_derivative(hidden_layer_output)
# Update weights
weights_output += np.dot(hidden_layer_output.T, output_delta) * learning_rate
weights_hidden += np.dot(inputs.T, hidden_delta) * learning_rate
return weights_hidden, weights_output
def predict(inputs, weights_hidden, weights_output):
hidden_layer_input = np.dot(inputs, weights_hidden)
hidden_layer_output = sigmoid(hidden_layer_input)
output_layer_input = np.dot(hidden_layer_output, weights_output)
output_layer_output = sigmoid(output_layer_input)
return output_layer_output
# Example usage:
inputs = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
outputs = np.array([, , , ])
weights_hidden, weights_output = train(inputs, outputs, epochs=10000, learning_rate=0.1)
predictions = predict(inputs, weights_hidden, weights_output)
print(predictions)
```
这个测试函数包含了一个简单的BP神经网络的训练和预测过程。首先定义了激活函数(sigmoid)及其导数,然后实现了训练函数(train)和预测函数(predict)。在示例用法中,我们创建了一个简单的异或(XOR)问题的输入和输出数据,并使用训练好的神经网络进行预测。
阅读全文