使用pytorch对房价进行回归预测
时间: 2023-07-08 14:06:57 浏览: 122
pytorch+深度学习+初学者+房价预测+kaggle
好的,下面是一个使用PyTorch进行房价回归预测的示例代码:
首先需要导入必要的库:
```python
import pandas as pd
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
```
然后读取数据集,进行预处理和划分训练集和测试集:
```python
# 读取数据集
data = pd.read_csv('housing.csv')
# 分离特征和标签
X = data.iloc[:, :-1].values
y = data.iloc[:, -1:].values
# 数据标准化
sc = StandardScaler()
X = sc.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
```
接下来定义一个简单的神经网络模型,包含两个全连接层和一个ReLU激活函数:
```python
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.fc1 = nn.Linear(13, 64)
self.fc2 = nn.Linear(64, 1)
self.relu = nn.ReLU()
def forward(self, x):
x = self.fc1(x)
x = self.relu(x)
x = self.fc2(x)
return x
```
然后定义训练函数和测试函数:
```python
def train(model, criterion, optimizer, X_train, y_train):
model.train()
train_loss = 0.0
for i in range(len(X_train)):
x = Variable(torch.FloatTensor(X_train[i]))
y_true = Variable(torch.FloatTensor(y_train[i]))
optimizer.zero_grad()
y_pred = model(x)
loss = criterion(y_pred, y_true)
loss.backward()
optimizer.step()
train_loss += loss.item()
return train_loss / len(X_train)
def test(model, criterion, X_test, y_test):
model.eval()
test_loss = 0.0
with torch.no_grad():
for i in range(len(X_test)):
x = Variable(torch.FloatTensor(X_test[i]))
y_true = Variable(torch.FloatTensor(y_test[i]))
y_pred = model(x)
loss = criterion(y_pred, y_true)
test_loss += loss.item()
return test_loss / len(X_test)
```
最后定义训练和测试过程,使用Mean Squared Error作为损失函数,使用Adam优化器进行优化:
```python
# 定义模型、损失函数和优化器
model = Net()
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练和测试
for epoch in range(100):
train_loss = train(model, criterion, optimizer, X_train, y_train)
test_loss = test(model, criterion, X_test, y_test)
print('Epoch [{}/{}], Train Loss: {:.4f}, Test Loss: {:.4f}'.format(epoch+1, 100, train_loss, test_loss))
```
训练完成后,可以使用模型进行预测:
```python
# 预测
x = Variable(torch.FloatTensor(X_test[0]))
y_true = Variable(torch.FloatTensor(y_test[0]))
y_pred = model(x)
print('True Value: {:.2f}, Predicted Value: {:.2f}'.format(y_true.item(), y_pred.item()))
```
以上就是一个使用PyTorch进行房价回归预测的示例代码。
阅读全文