python设计一个BP神经网络对给定的波士顿房价数据进行预测
时间: 2024-05-01 22:19:05 浏览: 284
用Python实现BP神经网络(附代码)
5星 · 资源好评率100%
好的,我会给你提供一个基于Python的BP神经网络的实现,用来预测给定的波士顿房价数据。步骤如下:
1. 导入必要的库
```python
import numpy as np
from sklearn.datasets import load_boston
from sklearn.preprocessing import scale
```
2. 加载数据集,对数据进行预处理和划分
```python
# 加载数据集
boston = load_boston()
# 对数据进行预处理
X = scale(boston.data)
y = boston.target
# 随机划分训练集和测试集
np.random.seed(42)
idx = np.random.permutation(len(X))
X_train = X[idx[:-100]]
y_train = y[idx[:-100]]
X_test = X[idx[-100:]]
y_test = y[idx[-100:]]
```
3. 定义BP神经网络模型
```python
class NeuralNetwork:
def __init__(self, input_dim, hidden_dim, output_dim):
# 初始化网络参数
self.input_dim = input_dim
self.hidden_dim = hidden_dim
self.output_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 sigmoid(self, x):
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
return x * (1 - x)
def forward(self, x):
# 前向传播
z1 = np.dot(x, self.w1) + self.b1
a1 = self.sigmoid(z1)
z2 = np.dot(a1, self.w2) + self.b2
output = z2
return output, a1
def backward(self, x, y, output, a1, learning_rate):
# 反向传播
error = output - y
delta2 = error
delta1 = np.dot(delta2, self.w2.T) * self.sigmoid_derivative(a1)
self.w2 -= learning_rate * np.dot(a1.T, delta2)
self.b2 -= learning_rate * np.sum(delta2, axis=0, keepdims=True)
self.w1 -= learning_rate * np.dot(x.T, delta1)
self.b1 -= learning_rate * np.sum(delta1, axis=0)
```
4. 训练BP神经网络
```python
# 定义网络参数
input_dim = X_train.shape[1]
hidden_dim = 10
output_dim = 1
# 定义学习率和训练轮数
learning_rate = 0.1
num_epochs = 1000
# 初始化神经网络
nn = NeuralNetwork(input_dim, hidden_dim, output_dim)
# 训练神经网络
for epoch in range(num_epochs):
# 前向传播
output, a1 = nn.forward(X_train)
# 反向传播
nn.backward(X_train, y_train.reshape(-1, 1), output, a1, learning_rate)
# 计算损失函数
loss = np.mean((output - y_train.reshape(-1, 1)) ** 2)
if epoch % 100 == 0:
print("Epoch %d: loss = %.4f" % (epoch, loss))
```
5. 在测试集上进行预测并计算模型的准确率
```python
# 在测试集上进行预测
y_pred, _ = nn.forward(X_test)
# 计算模型的准确率
accuracy = np.mean((y_pred - y_test.reshape(-1, 1)) ** 2)
print("Accuracy = %.4f" % accuracy)
```
以上就是基于Python的BP神经网络的实现,用来预测给定的波士顿房价数据。
阅读全文