帮我写一段bp神经网络预测的python代码,并print训练集和测试集的预测准确度
时间: 2024-05-01 08:20:57 浏览: 92
BP神经网络模型训练集及测试集.zip
好的,以下是一段使用BP神经网络进行预测的Python代码:
```python
import numpy as np
# 定义sigmoid函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义BP神经网络类
class BPNN:
def __init__(self, input_dim, hidden_dim, output_dim):
# 初始化权重和偏置
self.W1 = np.random.randn(input_dim, hidden_dim)
self.b1 = np.zeros((1, hidden_dim))
self.W2 = np.random.randn(hidden_dim, output_dim)
self.b2 = np.zeros((1, output_dim))
def forward(self, X):
# 前向传播
self.z1 = np.dot(X, self.W1) + self.b1
self.a1 = sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.W2) + self.b2
self.a2 = sigmoid(self.z2)
return self.a2
def backward(self, X, y, y_hat, lr):
# 反向传播
delta2 = (y_hat - y) * self.a2 * (1 - self.a2)
dW2 = np.dot(self.a1.T, delta2)
db2 = np.sum(delta2, axis=0, keepdims=True)
delta1 = np.dot(delta2, self.W2.T) * self.a1 * (1 - self.a1)
dW1 = np.dot(X.T, delta1)
db1 = np.sum(delta1, axis=0)
# 更新权重和偏置
self.W2 -= lr * dW2
self.b2 -= lr * db2
self.W1 -= lr * dW1
self.b1 -= lr * db1
def fit(self, X, y, epochs, lr):
# 训练模型
for i in range(epochs):
y_hat = self.forward(X)
self.backward(X, y, y_hat, lr)
# 计算训练集和测试集的准确率
train_accuracy = np.mean(np.round(y_hat) == y)
test_accuracy = np.mean(np.round(self.forward(X_test)) == y_test)
print('训练集准确率:', train_accuracy)
print('测试集准确率:', test_accuracy)
# 生成随机数据
np.random.seed(0)
X = np.random.randn(100, 2)
y = np.random.randint(0, 2, size=(100, 1))
X_test = np.random.randn(20, 2)
y_test = np.random.randint(0, 2, size=(20, 1))
# 初始化BP神经网络并训练模型
model = BPNN(input_dim=2, hidden_dim=4, output_dim=1)
model.fit(X, y, epochs=1000, lr=0.1)
```
运行代码后,会输出训练集和测试集的准确率。其中,训练集准确率是指模型在训练集上的预测准确率,测试集准确率是指模型在测试集上的预测准确率。
阅读全文