1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
| import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from torchvision import transforms
def load_data(data_path): return []
class SimpleModel(nn.Module): def __init__(self): super(SimpleModel, self).__init__()
self.linear = nn.Linear(1, 1)
def forward(self, x): return self.linear(x)
class CustomerDataset(Dataset): def __init__(self, data_path, transform = None): self.data = load_data(data_path) self.transform = transform def __len__(self): return len(self.data) def __getitem__(self, index): sample, label = self.data[index] if self.transform: sample = self.transform(sample) return sample, label
data_transforms = transforms.Compose([ transforms.Resize(32, 32), transforms.ToTensor(), transforms.Normalize(mean=[0.5], std=[0.5]), ])
dataset = CustomerDataset('./data', transform=data_transforms)
batch_size = 64 shuffle = True num_works = 4 num_epochs = 5
data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle, num_workers=num_works)
model = SimpleModel() optimizer = torch.optim.SGD(model.parameters(), lr=0.01) loss_fn = nn.MSELoss()
criterion = nn.CrossEntropyLoss()
for epoch in range(num_epochs): for batch_idx, (inputs, labels) in enumerate(data_loader): outputs = model(inputs) loss = criterion(outputs, labels) optimizer.zero_grad() loss.backward() optimizer.step()
print(f'Epoch: {epoch}, Batch Index: {batch_idx}, Loss: {loss.item()}')
|