如何使用PyTorch库进行波士顿房价的预测并实现一个神经网络模型?
时间: 2024-12-22 14:17:02 浏览: 13
在PyTorch中,我们可以使用其丰富的张量操作和深度学习功能来进行波士顿房价预测。以下是一个简单的步骤概述:
1. **导入所需库**:
```python
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
```
2. **加载数据**:
使用`sklearn`的`load_boston`函数获取波士顿房价数据集,然后将数据划分为特征(X)和目标值(y):
```python
boston = load_boston()
X, y = boston.data, boston.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```
3. **预处理数据**:
转换为PyTorch张量,并标准化数据:
```python
X_train = torch.tensor(X_train, dtype=torch.float32)
X_test = torch.tensor(X_test, dtype=torch.float32)
mean, std = X_train.mean(), X_train.std()
X_train = (X_train - mean) / std
```
4. **创建数据加载器**:
```python
train_dataset = TensorDataset(X_train, y_train)
test_dataset = TensorDataset(X_test, y_test)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)
```
5. **定义神经网络模型**:
```python
class BostonModel(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(BostonModel, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim)
self.relu = nn.ReLU()
self.fc2 = nn.Linear(hidden_dim, output_dim)
def forward(self, x):
out = self.fc1(x)
out = self.relu(out)
out = self.fc2(out)
return out
model = BostonModel(X_train.shape[1], 64, 1)
```
6. **设置损失函数和优化器**:
```python
criterion = nn.MSELoss() # 对于回归任务通常使用均方误差(MSE)
optimizer = torch.optim.Adam(model.parameters())
```
7. **训练模型**:
```python
num_epochs = 100
for epoch in range(num_epochs):
for inputs, labels in train_loader:
outputs = model(inputs)
loss = criterion(outputs, labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
```
8. **评估模型**:
```python
with torch.no_grad():
model.eval()
predictions = model(X_test)
mse = criterion(predictions, y_test)
print(f"Test Mean Squared Error: {mse.item():.4f}")
```
阅读全文