YAML Metadata
Warning:
empty or missing yaml metadata in repo card
(https://huggingface.co/docs/hub/model-cards#model-card-metadata)
import numpy as np
import torch
import torch.nn as nn
from torchvision import datasets
from torchvision import transforms
from torch.utils.data.sampler import SubsetRandomSampler
from tqdm import tqdm
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(device)
cuda
def data_loader(data_dir,
batch_size,
random_seed=42,
valid_size=0.1,
shuffle=True,
test=False):
normalize = transforms.Normalize(
mean=[0.4914, 0.4822, 0.4465],
std=[0.2023, 0.1994, 0.2010],
)
transform = transforms.Compose([
transforms.Resize((224,224)),
transforms.ToTensor(),
normalize,
])
if test:
dataset = datasets.CIFAR10(
root=data_dir, train=False,
download=True, transform=transform,
)
data_loader = torch.utils.data.DataLoader(
dataset, batch_size=batch_size, shuffle=shuffle
)
return data_loader
train_dataset = datasets.CIFAR10(
root=data_dir, train=True,
download=True, transform=transform,
)
valid_dataset = datasets.CIFAR10(
root=data_dir, train=True,
download=True, transform=transform,
)
num_train = len(train_dataset)
indices = list(range(num_train))
split = int(np.floor(valid_size * num_train))
if shuffle:
np.random.seed(42)
np.random.shuffle(indices)
train_idx, valid_idx = indices[split:], indices[:split]
train_sampler = SubsetRandomSampler(train_idx)
valid_sampler = SubsetRandomSampler(valid_idx)
train_loader = torch.utils.data.DataLoader(
train_dataset, batch_size=batch_size, sampler=train_sampler)
valid_loader = torch.utils.data.DataLoader(
valid_dataset, batch_size=batch_size, sampler=valid_sampler)
return (train_loader, valid_loader)
train_loader, valid_loader = data_loader(data_dir='./data',
batch_size=64)
test_loader = data_loader(data_dir='./data',
batch_size=64,
test=True)
Files already downloaded and verified
Files already downloaded and verified
Files already downloaded and verified
class ResidualBlock(nn.Module):
def __init__(self, in_channels, out_channels, stride = 1, downsample = None):
super(ResidualBlock, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size = 3, stride = stride, padding = 1),
nn.BatchNorm2d(out_channels),
nn.ReLU())
self.conv2 = nn.Sequential(
nn.Conv2d(out_channels, out_channels, kernel_size = 3, stride = 1, padding = 1),
nn.BatchNorm2d(out_channels))
self.downsample = downsample
self.relu = nn.ReLU()
self.out_channels = out_channels
def forward(self, x):
residual = x
out = self.conv1(x)
out = self.conv2(out)
if self.downsample:
residual = self.downsample(x)
out += residual
out = self.relu(out)
return out
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes = 10):
super(ResNet, self).__init__()
self.inplanes = 64
self.conv1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size = 7, stride = 2, padding = 3),
nn.BatchNorm2d(64),
nn.ReLU())
self.maxpool = nn.MaxPool2d(kernel_size = 3, stride = 2, padding = 1)
self.layer0 = self._make_layer(block, 64, layers[0], stride = 1)
self.layer1 = self._make_layer(block, 128, layers[1], stride = 2)
self.layer2 = self._make_layer(block, 256, layers[2], stride = 2)
self.layer3 = self._make_layer(block, 512, layers[3], stride = 2)
self.avgpool = nn.AvgPool2d(7, stride=1)
self.fc = nn.Linear(512, num_classes)
def _make_layer(self, block, planes, blocks, stride=1):
downsample = None
if stride != 1 or self.inplanes != planes:
downsample = nn.Sequential(
nn.Conv2d(self.inplanes, planes, kernel_size=1, stride=stride),
nn.BatchNorm2d(planes),
)
layers = []
layers.append(block(self.inplanes, planes, stride, downsample))
self.inplanes = planes
for i in range(1, blocks):
layers.append(block(self.inplanes, planes))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.maxpool(x)
x = self.layer0(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.avgpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
num_classes = 10
num_epochs = 5
learning_rate = 0.01
model = ResNet(ResidualBlock, [2, 2, 2, 2]).to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, weight_decay = 0.001, momentum = 0.9)
total_step = len(train_loader)
import gc
total_step = len(train_loader)
from tqdm import tqdm
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(tqdm(train_loader)):
# Move tensors to the configured device
images = images.to(device)
labels = labels.to(device)
# Forward pass
outputs = model(images)
loss = criterion(outputs, labels)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
print ('Epoch [{}/{}], Loss: {:.4f}'
.format(epoch+1, num_epochs, loss.item()))
# Validation
with torch.no_grad():
correct = 0
total = 0
for images, labels in valid_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
del images, labels, outputs
print('Accuracy of the network on the {} validation images: {} %'.format(5000, 100 * correct / total))
100%|ββββββββββ| 176/176 [01:15<00:00, 2.35it/s]
Epoch [1/10], Loss: 1.2169
Accuracy of the network on the 5000 validation images: 58.28 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.29it/s]
Epoch [2/10], Loss: 0.8962
Accuracy of the network on the 5000 validation images: 70.36 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.30it/s]
Epoch [3/10], Loss: 0.6691
Accuracy of the network on the 5000 validation images: 75.86 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.29it/s]
Epoch [4/10], Loss: 0.6426
Accuracy of the network on the 5000 validation images: 79.24 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.29it/s]
Epoch [5/10], Loss: 0.2891
Accuracy of the network on the 5000 validation images: 80.4 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.29it/s]
Epoch [6/10], Loss: 0.4245
Accuracy of the network on the 5000 validation images: 81.24 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.29it/s]
Epoch [7/10], Loss: 0.2183
Accuracy of the network on the 5000 validation images: 81.44 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.29it/s]
Epoch [8/10], Loss: 0.1172
Accuracy of the network on the 5000 validation images: 81.06 %
100%|ββββββββββ| 176/176 [01:16<00:00, 2.30it/s]
Epoch [9/10], Loss: 0.1069
Accuracy of the network on the 5000 validation images: 82.14 %
100%|ββββββββββ| 176/176 [01:17<00:00, 2.29it/s]
Epoch [10/10], Loss: 0.0555
Accuracy of the network on the 5000 validation images: 83.12 %
with torch.no_grad():
correct = 0
total = 0
for images, labels in test_loader:
images = images.to(device)
labels = labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
del images, labels, outputs
print('Accuracy of the network on the {} test images: {} %'.format(10000, 100 * correct / total))
model = torch.hub.load("pytorch/vision", "resnet152", weights="IMAGENET1K_V2")
model.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, num_classes)
model = model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=5e-4)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=200)
Using cache found in /root/.cache/torch/hub/pytorch_vision_main
def train(model, trainloader, criterion, optimizer, device):
train_loss = 0.0
train_total = 0
train_correct = 0
# Switch to train mode
model.train()
for inputs, labels in trainloader:
inputs, labels = inputs.to(device), labels.to(device)
# Zero the parameter gradients
optimizer.zero_grad()
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, labels)
# Backward pass and optimize
loss.backward()
optimizer.step()
# Update training loss
train_loss += loss.item() * inputs.size(0)
# Compute training accuracy
_, predicted = torch.max(outputs, 1)
train_total += labels.size(0)
train_correct += (predicted == labels).sum().item()
train_loss = train_loss / len(trainloader.dataset)
train_accuracy = 100.0 * train_correct / train_total
return model, train_loss, train_accuracy
def test(model, testloader, criterion, device):
test_loss = 0.0
test_total = 0
test_correct = 0
# Switch to evaluation mode
model.eval()
with torch.no_grad():
for inputs, labels in testloader:
inputs, labels = inputs.to(device), labels.to(device)
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, labels)
# Update test loss
test_loss += loss.item() * inputs.size(0)
# Compute test accuracy
_, predicted = torch.max(outputs, 1)
test_total += labels.size(0)
test_correct += (predicted == labels).sum().item()
# Compute average test loss and accuracy
test_loss = test_loss / len(testloader.dataset)
test_accuracy = 100.0 * test_correct / test_total
return test_loss, test_accuracy
def train_epochs(model, trainloader, testloader, criterion, optimizer, device, num_epochs, save_interval=5):
train_losses = []
train_accuracies = []
test_losses = []
test_accuracies = []
for epoch in range(num_epochs):
print(f'Epoch {epoch+1}/{num_epochs}')
model, train_loss, train_accuracy = train(model, trainloader, criterion, optimizer, device)
test_loss, test_accuracy = test(model, testloader, criterion, device)
train_losses.append(train_loss)
train_accuracies.append(train_accuracy)
test_losses.append(test_loss)
test_accuracies.append(test_accuracy)
print(f'Train Loss: {train_loss:.4f} - Train Accuracy: {train_accuracy:.2f}%')
print(f'Test Loss: {test_loss:.4f} - Test Accuracy: {test_accuracy:.2f}%')
print()
return model, train_losses, train_accuracies, test_losses, test_accuracies
trainset, trainloader, testset, testloader, classes = load_dataset()
if train_model:
num_epochs = 60
save_interval = 5
model, train_losses, train_accuracies, test_losses, test_accuracies = train_epochs(
model, trainloader, testloader, criterion, optimizer, device,
num_epochs, save_interval)
else:
model.load_state_dict(torch.load('resnet50_cifar10_final_model_epochs_50.pth'))
checkpoint = torch.load("resnet50_cifar10_variables.pth")
epoch = checkpoint['epoch']
train_losses = checkpoint['train_losses']
train_accuracies = checkpoint['train_accuracies']
test_losses = checkpoint['test_losses']
test_accuracies = checkpoint['test_accuracies']
classes = checkpoint['classes']
model.to(device)
model.eval()
Epoch 1/10
----------
100%|ββββββββββ| 704/704 [03:26<00:00, 3.41it/s]
Train Loss: 1.9308 Acc: 0.4630
100%|ββββββββββ| 79/79 [00:22<00:00, 3.52it/s]
Val Loss: 0.1944 Acc: 0.0665
Epoch 2/10
----------
24%|βββ | 166/704 [00:49<02:40, 3.35it/s]
---------------------------------------------------------------------------
KeyboardInterrupt Traceback (most recent call last)
<ipython-input-11-483fc1f8b5af> in <cell line: 51>()
49 num_epochs = 10
50 dataloaders = {'train': train_loader, 'val': valid_loader}
---> 51 trained_model = train_model(combined_model, dataloaders, criterion, optimizer, scheduler, num_epochs=num_epochs, device=device)
<ipython-input-11-483fc1f8b5af> in train_model(model, dataloaders, criterion, optimizer, scheduler, num_epochs, device)
32 optimizer.step()
33
---> 34 running_loss += loss.item() * inputs.size(0)
35 running_corrects += torch.sum(preds == labels.data)
36 del inputs, labels, outputs
KeyboardInterrupt:
- Downloads last month
- 0
Unable to determine this model's library. Check the
docs
.