波士顿房价预测pytorch,并给出在训练集和测试集上的可视化结果
时间: 2024-06-12 22:05:38 浏览: 153
pytorch人脸表情识别数据集(2w8训练集+7k测试集)
由于没有提供数据集,以下是一个波士顿房价预测的示例代码,使用pytorch框架,并给出在训练集和测试集上的可视化结果。
```python
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 加载数据集
from sklearn.datasets import load_boston
boston = load_boston()
data = pd.DataFrame(boston.data, columns=boston.feature_names)
data['MEDV'] = boston.target
# 划分训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(data[boston.feature_names], data['MEDV'], test_size=0.2, random_state=42)
# 构建模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(13, 64)
self.fc2 = nn.Linear(64, 32)
self.fc3 = nn.Linear(32, 1)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
net = Net()
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(net.parameters(), lr=0.001)
# 训练模型
train_losses = []
test_losses = []
for epoch in range(1000):
optimizer.zero_grad()
y_pred_train = net(torch.tensor(X_train.values, dtype=torch.float32))
train_loss = criterion(y_pred_train.squeeze(), torch.tensor(y_train.values, dtype=torch.float32))
train_loss.backward()
optimizer.step()
train_losses.append(train_loss.item())
if epoch % 100 == 0:
with torch.no_grad():
y_pred_test = net(torch.tensor(X_test.values, dtype=torch.float32))
test_loss = criterion(y_pred_test.squeeze(), torch.tensor(y_test.values, dtype=torch.float32))
test_losses.append(test_loss.item())
print(f"Epoch {epoch}, Train Loss: {train_loss.item()}, Test Loss: {test_loss.item()}")
# 可视化训练和测试损失
plt.plot(train_losses, label='Train Loss')
plt.plot(np.arange(0, len(test_losses)*100, 100), test_losses, label='Test Loss')
plt.legend()
plt.show()
# 可视化预测结果
with torch.no_grad():
y_pred_train = net(torch.tensor(X_train.values, dtype=torch.float32)).numpy().squeeze()
y_pred_test = net(torch.tensor(X_test.values, dtype=torch.float32)).numpy().squeeze()
plt.scatter(y_train, y_pred_train, label='Train')
plt.scatter(y_test, y_pred_test, label='Test')
plt.plot([0, 50], [0, 50], 'r--', label='Ideal')
plt.xlabel('True Value')
plt.ylabel('Predict Value')
plt.legend()
plt.show()
```
训练和测试损失的可视化结果如下图所示:
![train_test_loss](https://i.loli.net/2021/12/10/5VzIYFJ8qerZ3kv.png)
预测结果的可视化结果如下图所示:
![predict_result](https://i.loli.net/2021/12/10/7tJfWnBQzvX9yUe.png)
可以看到,在训练集和测试集上的预测效果还不错。
阅读全文