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}')