bp神经网络预测python代码_纯Python搭建一个深度神经网络并用于房价预测
时间: 2023-07-08 12:19:40 浏览: 98
以下是纯Python搭建一个深度神经网络并用于房价预测的代码:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
data = pd.read_csv('housing.csv')
x = data.iloc[:, 0:13]
y = data.iloc[:, 13]
# 归一化处理
x = (x - np.mean(x)) / np.std(x)
y = (y - np.mean(y)) / np.std(y)
# 划分数据集
train_size = int(len(x) * 0.8)
train_x = x.iloc[:train_size, :]
train_y = y[:train_size]
test_x = x.iloc[train_size:, :]
test_y = y[train_size:]
# 定义网络结构
input_size = 13
hidden_size = 5
output_size = 1
# 初始化权重和偏置
w1 = np.random.randn(input_size, hidden_size)
b1 = np.zeros((1, hidden_size))
w2 = np.random.randn(hidden_size, output_size)
b2 = np.zeros((1, output_size))
# 定义激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 定义损失函数
def mse_loss(y_true, y_pred):
return np.mean(np.square(y_true - y_pred))
# 定义前向传播函数
def forward(x):
z1 = np.dot(x, w1) + b1
a1 = sigmoid(z1)
z2 = np.dot(a1, w2) + b2
y_pred = z2
return y_pred, a1, z1
# 定义反向传播函数
def backward(y_pred, y_true, a1, z1, x):
delta2 = y_pred - y_true
dw2 = np.dot(a1.T, delta2)
db2 = np.sum(delta2, axis=0, keepdims=True)
delta1 = np.dot(delta2, w2.T) * a1 * (1 - a1)
dw1 = np.dot(x.T, delta1)
db1 = np.sum(delta1, axis=0)
return dw1, db1, dw2, db2
# 定义训练函数
def train(x, y, epochs, lr):
losses = []
for epoch in range(epochs):
y_pred, a1, z1 = forward(x)
loss = mse_loss(y, y_pred)
dw1, db1, dw2, db2 = backward(y_pred, y, a1, z1, x)
w1 -= lr * dw1
b1 -= lr * db1
w2 -= lr * dw2
b2 -= lr * db2
losses.append(loss)
if epoch % 1000 == 0:
print(f'Epoch {epoch}, Loss {loss}')
return losses
# 训练模型
losses = train(train_x, train_y, 10000, 0.01)
# 可视化损失函数
plt.plot(losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.show()
# 预测测试集
test_pred, _, _ = forward(test_x)
test_pred = test_pred * np.std(y) + np.mean(y)
test_y = test_y * np.std(y) + np.mean(y)
# 计算测试集损失
test_loss = mse_loss(test_y, test_pred)
print(f'Test Loss: {test_loss}')
# 可视化预测结果
plt.plot(test_y, label='True')
plt.plot(test_pred, label='Predicted')
plt.legend()
plt.show()
```
需要注意的是,该代码中使用的是标准BP神经网络,如果要使用更高级的神经网络结构,可以使用TensorFlow、PyTorch等框架。
阅读全文