CNN预测波士顿房价

CNN@TOC

包引入

import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, TensorDataset
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

Load the Boston housing dataset

boston = load_boston()
X = boston.data
y = boston.target

Preprocess the data

scaler = StandardScaler()
X = scaler.fit_transform(X)

Split the data into training and testing sets

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

Convert the data to PyTorch tensors

X_train = torch.tensor(X_train, dtype=torch.float32).unsqueeze(1)
X_test = torch.tensor(X_test, dtype=torch.float32).unsqueeze(1)
y_train = torch.tensor(y_train, dtype=torch.float32)
y_test = torch.tensor(y_test, dtype=torch.float32)

Create a DataLoader for the training data

train_data = TensorDataset(X_train, y_train)
train_loader = DataLoader(train_data, batch_size=32, shuffle=True)

Define the CNN model

class CNN(nn.Module):
def init(self):
super(CNN, self).init()
self.conv1 = nn.Conv1d(1, 16, 3, padding=1)
self.relu = nn.ReLU()
self.pool = nn.MaxPool1d(2)
self.fc1 = nn.Linear(16 * 6, 64)
self.fc2 = nn.Linear(64, 1)

def forward(self, x):
    x = self.pool(self.relu(self.conv1(x)))
    x = x.view(-1, 16 * 6)
    x = self.relu(self.fc1(x))
    x = self.fc2(x)
    return x

Initialize the model, loss function, and optimizer

model = CNN()
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)

Train the model

num_epochs = 100
for epoch in range(num_epochs):
for i, (inputs, targets) in enumerate(train_loader):
# Forward pass
outputs = model(inputs)
loss = criterion(outputs.squeeze(), targets)

    # Backward pass and optimization
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

# Print the loss for this epoch
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值