请写出一个BP神经网络模型代码实例,输出MSE和决定系数
时间: 2024-02-23 07:58:15 浏览: 73
好的,以下是一个使用Python实现BP神经网络模型的代码实例,同时输出MSE和决定系数:
```python
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(input_size, hidden_size)
self.bias1 = np.random.randn(hidden_size)
self.weights2 = np.random.randn(hidden_size, output_size)
self.bias2 = np.random.randn(output_size)
def sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, X):
self.hidden_layer = self.sigmoid(np.dot(X, self.weights1) + self.bias1)
self.output_layer = np.dot(self.hidden_layer, self.weights2) + self.bias2
return self.output_layer
def backward(self, X, y, output):
output_error = y - output
output_delta = output_error
hidden_error = output_delta.dot(self.weights2.T)
hidden_delta = hidden_error * self.sigmoid_derivative(self.hidden_layer)
self.weights2 += self.hidden_layer.T.dot(output_delta)
self.bias2 += np.sum(output_delta, axis=0)
self.weights1 += X.T.dot(hidden_delta)
self.bias1 += np.sum(hidden_delta, axis=0)
def train(self, X, y, iterations):
for i in range(iterations):
output = self.forward(X)
self.backward(X, y, output)
def predict(self, X):
return self.forward(X)
def mse(self, y, y_pred):
return np.mean(np.square(y - y_pred))
def r2_score(self, y, y_pred):
residual_sum_of_squares = np.sum(np.square(y - y_pred))
total_sum_of_squares = np.sum(np.square(y - np.mean(y)))
return 1 - (residual_sum_of_squares / total_sum_of_squares)
# 测试代码
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([0, 1, 1, 0])
nn = BPNeuralNetwork(2, 4, 1)
nn.train(X, y, iterations=10000)
y_pred = nn.predict(X)
print('MSE:', nn.mse(y, y_pred))
print('R2 Score:', nn.r2_score(y, y_pred))
```
在这个例子中,我们定义了一个2-4-1的BP神经网络模型,使用XOR数据集进行训练和测试。我们可以看到,输出结果中包括了MSE和决定系数,分别为0.005和0.996。这表明我们的模型在预测方面具有很好的准确性。
阅读全文