pytorch框架下的波士顿房价预测
时间: 2023-10-12 15:15:58 浏览: 106
以下是使用PyTorch框架实现的波士顿房价预测代码:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# 加载波士顿房价数据集
boston = load_boston()
X, y = boston.data, boston.target
# 数据预处理,标准化特征值
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义神经网络模型
class Net(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(Net, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_size, output_size)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
# 设置超参数
input_size = X_train.shape[1]
hidden_size = 32
output_size = 1
learning_rate = 0.01
num_epochs = 1000
# 初始化模型、损失函数和优化器
net = Net(input_size, hidden_size, output_size)
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=learning_rate)
# 训练模型
for epoch in range(num_epochs):
inputs = torch.from_numpy(X_train).float()
targets = torch.from_numpy(y_train).view(-1, 1).float()
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if (epoch+1) % 100 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, num_epochs, loss.item()))
# 测试模型
with torch.no_grad():
inputs = torch.from_numpy(X_test).float()
targets = torch.from_numpy(y_test).view(-1, 1).float()
outputs = net(inputs)
test_loss = criterion(outputs, targets)
print('Test Loss: {:.4f}'.format(test_loss.item()))
```
在训练过程中,我们使用了MSE损失函数和Adam优化器,并在每100个epoch时输出当前的损失值。在测试过程中,我们使用了与训练时相同的MSE损失函数来评估模型的性能。
阅读全文