Skip to content

Instantly share code, notes, and snippets.

@colesbury
Last active May 8, 2018 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colesbury/2b786128f4409dbd07eef44839f0b3ce to your computer and use it in GitHub Desktop.
Save colesbury/2b786128f4409dbd07eef44839f0b3ce to your computer and use it in GitHub Desktop.
from __future__ import print_function
import time
import math
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
from torchvision import datasets, transforms
#import matplotlib.pyplot as plt
#from large_margin_softmax_linear import LargeMarginSoftmaxLinear
#from experiment import LargeMarginSoftmaxLinear
torch.set_printoptions(precision=20)
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
(44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
(148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
(227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
(188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]
for i in range(len(tableau20)):
r, g, b = tableau20[i]
tableau20[i] = (r / 255., g / 255., b / 255.)
# Training settings
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=256, metavar='N',
help='input batch size for training (default: 256)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=30, metavar='N',
help='number of epochs to train (default: 30)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.9, metavar='M',
help='SGD momentum (default: 0.9)')
parser.add_argument('--weight_decay', type=float, default=0.0005, metavar='W',
help='SGD weight decay (default: 0.0005)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=50, metavar='N',
help='how many batches to wait before logging training status')
parser.add_argument('--vis_path', type=str, default="visualizations/color6", metavar='S',
help='path to save your visualization figures')
args = parser.parse_args()
#use_cuda = False
use_cuda = not args.no_cuda and torch.cuda.is_available()
print(use_cuda)
torch.manual_seed(args.seed)
device = torch.device("cuda" if use_cuda else "cpu")
torch.backends.cudnn.benchmark = True if use_cuda else False
print(device)
kwargs = {'num_workers': 6, 'pin_memory': True} if use_cuda else {}
train_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=True, download=True,
transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=args.batch_size, shuffle=True, **kwargs)
test_loader = torch.utils.data.DataLoader(
datasets.MNIST('../data', train=False, transform=transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])),
batch_size=args.test_batch_size, shuffle=True, **kwargs)
def weights_init(m):
if isinstance(m, nn.Conv2d):
n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
m.weight.data.normal_(0, math.sqrt(2. / n))
#nn.init.xavier_uniform(m.weight.batch_data)
#elif isinstance(m, nn.BatchNorm2d):
# m.weight.batch_data.fill_(1)
# m.bias.batch_data.zero_()
#elif isinstance(m, nn.BatchNorm1d):
# m.weight.batch_data.fill_(1)
# m.bias.batch_data.zero_()
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 32, kernel_size=5, padding=2)
#self.bn1 = nn.BatchNorm2d(32)
self.prelu1 = nn.PReLU()
self.conv2 = nn.Conv2d(32, 32, kernel_size=5, padding=2)
#self.bn2 = nn.BatchNorm2d(32)
self.prelu2 = nn.PReLU()
self.conv3 = nn.Conv2d(32, 64, kernel_size=5, padding=2)
#self.bn3 = nn.BatchNorm2d(64)
self.prelu3 = nn.PReLU()
self.conv4 = nn.Conv2d(64, 64, kernel_size=5, padding=2)
#self.bn4 = nn.BatchNorm2d(64)
self.prelu4 = nn.PReLU()
self.conv5 = nn.Conv2d(64, 128, kernel_size=5, padding=2)
#self.bn5 = nn.BatchNorm2d(128)
self.prelu5 = nn.PReLU()
self.conv6 = nn.Conv2d(128, 128, kernel_size=5, padding=2)
#self.bn6 = nn.BatchNorm2d(128)
self.prelu6 = nn.PReLU()
self.fc1 = nn.Linear(1152, 2)
#self.bn7 = nn.BatchNorm1d(2)
self.prelu7 = nn.PReLU()
self.fc2 = nn.Linear(2, 10)
self.loss = nn.CrossEntropyLoss()
#self.fc2 = LargeMarginSoftmaxLinear(2, 10, 2, 0)
#self.fc2 = LargeMarginSoftmaxLinear(2, 10, 2, 0, use_cuda, device)
def forward(self, x, y):
x = self.prelu1(self.conv1(x))
x = F.max_pool2d(self.prelu2(self.conv2(x)), 2, stride=2)
x = self.prelu3(self.conv3(x))
x = F.max_pool2d(self.prelu4(self.conv4(x)), 2, stride=2)
x = self.prelu5(self.conv5(x))
x = F.max_pool2d(self.prelu6(self.conv6(x)), 2, stride=2)
#x = F.relu(self.bn1(self.conv1(x)))
#x = F.max_pool2d(F.relu(self.bn2(self.conv2(x))), 2, stride=2)
#x = F.relu(self.bn3(self.conv3(x)))
#x = F.max_pool2d(F.relu(self.bn4(self.conv4(x))), 2, stride=2)
#x = F.relu(self.bn5(self.conv5(x)))
#x = F.max_pool2d(F.relu(self.bn6(self.conv6(x))), 2, stride=2)
x = x.view(-1, 1152)
#print(x.shape)
features = self.fc1(x)
x = self.prelu7(features)
#x = F.relu(self.bn7(self.fc1(x)))
#x = self.fc2(x, y)
x = self.fc2(x)
#print(x)
return self.loss(x, y)
model = Net().to(device)
model.apply(weights_init)
optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay)
def visualize(features, labels, epoch, vis_path):
plt.clf()
for i in range(10):
plt.scatter(features[(labels == i), 0], features[(labels == i), 1], s=3, c=tableau20[i], alpha=0.8)
plt.savefig(vis_path + "/epoch_" + str(epoch) + ".jpg")
return
def train(epoch):
model.train()
#features = []
#predictions = []
#labels = []
for batch_idx, (batch_data, batch_labels) in enumerate(train_loader):
batch_data, batch_labels = batch_data.to(device), batch_labels.to(device)
#print(batch_data.dtype)
#print(batch_labels.dtype)
#print(batch_data.size())
#print(batch_labels.size())
optimizer.zero_grad()
enabled = batch_idx == 10
with torch.autograd.profiler.profile(enabled=enabled, use_cuda=True) as prof:
loss = model(batch_data, batch_labels)
#loss = F.nll_loss(batch_scores, batch_labels)
#print(loss)
loss.backward()
optimizer.step()
if enabled:
print(prof.key_averages().table(sort_by='cuda_time_total'))
import pdb
pdb.set_trace()
if batch_idx % args.log_interval == 0:
print('Train Epoch: {} [{}/{} ({:.2f}%)]\tLoss: {:.6f}'.format(
epoch, batch_idx * len(batch_data), len(train_loader.dataset),
100. * batch_idx / len(train_loader), loss.item()))
#features.append(batch_features)
#batch_predictions = batch_scores.max(1, keepdim=True)[1]
#predictions.append(batch_predictions)
#labels.append(batch_labels)
#features = torch.cat(features, 0).data.to('cpu').numpy()
#predictions = torch.cat(predictions, 0).data.cpu().numpy()
#labels = torch.cat(labels, 0).data.to('cpu').numpy()
#visualize(features, labels, epoch, args.vis_path)
def test():
model.eval()
test_loss = 0
correct = 0
with torch.no_grad():
for batch_data, batch_labels in test_loader:
batch_data, batch_labels = batch_data.to(device), batch_labels.to(device)
batch_scores, batch_features = model(batch_data)
test_loss += F.nll_loss(batch_scores, batch_labels, size_average=False).item() # sum up batch loss
pred = batch_scores.max(1, keepdim=True)[1] # get the index of the max log-probability
correct += pred.eq(batch_labels.view_as(pred)).sum().item()
test_loss /= len(test_loader.dataset)
print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
test_loss, correct, len(test_loader.dataset),
100. * correct / len(test_loader.dataset)))
scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=10, gamma=0.1)
for epoch in range(1, args.epochs + 1):
scheduler.step()
#lr = []
#for param_group in optimizer.param_groups:
# lr += [param_group['lr']]
#print(lr)
torch.cuda.synchronize()
start = time.perf_counter()
train(epoch)
torch.cuda.synchronize()
end = time.perf_counter()
#print(end-start)
print('Total time taken: {:.2f}s\n'.format(end-start))
#test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment