X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?p=pysvrt.git;a=blobdiff_plain;f=cnn-svrt.py;h=5dc91c82e66e99322ee77ec95e6e8c4b337dcdff;hp=f731c2b7f0210ff3146fa88c49c16f85f8758344;hb=15f2d2cf0a655234cfa435789e26238b95f5a371;hpb=2760d7e70c1a93cd122f1857cc6f6393a6b549a8 diff --git a/cnn-svrt.py b/cnn-svrt.py index f731c2b..5dc91c8 100755 --- a/cnn-svrt.py +++ b/cnn-svrt.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python-for-pytorch +#!/usr/bin/env python # svrt is the ``Synthetic Visual Reasoning Test'', an image # generator for evaluating classification performance of machine @@ -22,6 +22,12 @@ # along with selector. If not, see . import time +import argparse +import math + +from colorama import Fore, Back, Style + +# Pytorch import torch @@ -32,106 +38,319 @@ from torch import nn from torch.nn import functional as fn from torchvision import datasets, transforms, utils -import svrt +# SVRT + +from vignette_set import VignetteSet, CompressedVignetteSet ###################################################################### -def generate_set(p, n): - target = torch.LongTensor(n).bernoulli_(0.5) - input = svrt.generate_vignettes(p, target) - input = input.view(input.size(0), 1, input.size(1), input.size(2)).float() - return Variable(input), Variable(target) +parser = argparse.ArgumentParser( + description = "Convolutional networks for the SVRT. Written by Francois Fleuret, (C) Idiap research institute.", + formatter_class = argparse.ArgumentDefaultsHelpFormatter +) + +parser.add_argument('--nb_train_samples', + type = int, default = 100000) + +parser.add_argument('--nb_test_samples', + type = int, default = 10000) + +parser.add_argument('--nb_epochs', + type = int, default = 50) + +parser.add_argument('--batch_size', + type = int, default = 100) + +parser.add_argument('--log_file', + type = str, default = 'default.log') + +parser.add_argument('--compress_vignettes', + action='store_true', default = True, + help = 'Use lossless compression to reduce the memory footprint') + +parser.add_argument('--deep_model', + action='store_true', default = True, + help = 'Use Afroze\'s Alexnet-like deep model') + +parser.add_argument('--test_loaded_models', + action='store_true', default = False, + help = 'Should we compute the test errors of loaded models') + +args = parser.parse_args() + +###################################################################### + +log_file = open(args.log_file, 'w') +pred_log_t = None + +print(Fore.RED + 'Logging into ' + args.log_file + Style.RESET_ALL) + +# Log and prints the string, with a time stamp. Does not log the +# remark +def log_string(s, remark = ''): + global pred_log_t + + t = time.time() + + if pred_log_t is None: + elapsed = 'start' + else: + elapsed = '+{:.02f}s'.format(t - pred_log_t) + + pred_log_t = t + + log_file.write('[' + time.ctime() + '] ' + elapsed + ' ' + s + '\n') + log_file.flush() + + print(Fore.BLUE + '[' + time.ctime() + '] ' + Fore.GREEN + elapsed + Style.RESET_ALL + ' ' + s + Fore.CYAN + remark + Style.RESET_ALL) ###################################################################### -# 128x128 --conv(9)-> 120x120 --max(4)-> 30x30 --conv(6)-> 25x25 --max(5)-> 5x5 +# Afroze's ShallowNet -class Net(nn.Module): +# map size nb. maps +# ---------------------- +# input 128x128 1 +# -- conv(21x21 x 6) -> 108x108 6 +# -- max(2x2) -> 54x54 6 +# -- conv(19x19 x 16) -> 36x36 16 +# -- max(2x2) -> 18x18 16 +# -- conv(18x18 x 120) -> 1x1 120 +# -- reshape -> 120 1 +# -- full(120x84) -> 84 1 +# -- full(84x2) -> 2 1 + +class AfrozeShallowNet(nn.Module): def __init__(self): - super(Net, self).__init__() - self.conv1 = nn.Conv2d(1, 10, kernel_size=9) - self.conv2 = nn.Conv2d(10, 20, kernel_size=6) - self.fc1 = nn.Linear(500, 100) - self.fc2 = nn.Linear(100, 2) + super(AfrozeShallowNet, self).__init__() + self.conv1 = nn.Conv2d(1, 6, kernel_size=21) + self.conv2 = nn.Conv2d(6, 16, kernel_size=19) + self.conv3 = nn.Conv2d(16, 120, kernel_size=18) + self.fc1 = nn.Linear(120, 84) + self.fc2 = nn.Linear(84, 2) + self.name = 'shallownet' def forward(self, x): - x = fn.relu(fn.max_pool2d(self.conv1(x), kernel_size=4, stride=4)) - x = fn.relu(fn.max_pool2d(self.conv2(x), kernel_size=5, stride=5)) - x = x.view(-1, 500) + x = fn.relu(fn.max_pool2d(self.conv1(x), kernel_size=2)) + x = fn.relu(fn.max_pool2d(self.conv2(x), kernel_size=2)) + x = fn.relu(self.conv3(x)) + x = x.view(-1, 120) x = fn.relu(self.fc1(x)) x = self.fc2(x) return x -def train_model(train_input, train_target): - model, criterion = Net(), nn.CrossEntropyLoss() +###################################################################### + +# Afroze's DeepNet + +# map size nb. maps +# ---------------------- +# input 128x128 1 +# -- conv(21x21 x 32 stride=4) -> 28x28 32 +# -- max(2x2) -> 14x14 6 +# -- conv(7x7 x 96) -> 8x8 16 +# -- max(2x2) -> 4x4 16 +# -- conv(5x5 x 96) -> 26x36 16 +# -- conv(3x3 x 128) -> 36x36 16 +# -- conv(3x3 x 128) -> 36x36 16 + +# -- conv(5x5 x 120) -> 1x1 120 +# -- reshape -> 120 1 +# -- full(3x84) -> 84 1 +# -- full(84x2) -> 2 1 + +class AfrozeDeepNet(nn.Module): + def __init__(self): + super(AfrozeDeepNet, self).__init__() + self.conv1 = nn.Conv2d( 1, 32, kernel_size=7, stride=4, padding=3) + self.conv2 = nn.Conv2d( 32, 96, kernel_size=5, padding=2) + self.conv3 = nn.Conv2d( 96, 128, kernel_size=3, padding=1) + self.conv4 = nn.Conv2d(128, 128, kernel_size=3, padding=1) + self.conv5 = nn.Conv2d(128, 96, kernel_size=3, padding=1) + self.fc1 = nn.Linear(1536, 256) + self.fc2 = nn.Linear(256, 256) + self.fc3 = nn.Linear(256, 2) + self.name = 'deepnet' + + def forward(self, x): + x = self.conv1(x) + x = fn.max_pool2d(x, kernel_size=2) + x = fn.relu(x) + + x = self.conv2(x) + x = fn.max_pool2d(x, kernel_size=2) + x = fn.relu(x) + + x = self.conv3(x) + x = fn.relu(x) + + x = self.conv4(x) + x = fn.relu(x) + + x = self.conv5(x) + x = fn.max_pool2d(x, kernel_size=2) + x = fn.relu(x) + + x = x.view(-1, 1536) + + x = self.fc1(x) + x = fn.relu(x) + + x = self.fc2(x) + x = fn.relu(x) + + x = self.fc3(x) + + return x + +###################################################################### + +def train_model(model, train_set): + batch_size = args.batch_size + criterion = nn.CrossEntropyLoss() if torch.cuda.is_available(): - model.cuda() criterion.cuda() - nb_epochs = 25 - optimizer, bs = optim.SGD(model.parameters(), lr = 1e-1), 100 + optimizer = optim.SGD(model.parameters(), lr = 1e-2) + + start_t = time.time() - for k in range(0, nb_epochs): - for b in range(0, nb_train_samples, bs): - output = model.forward(train_input.narrow(0, b, bs)) - loss = criterion(output, train_target.narrow(0, b, bs)) + for e in range(0, args.nb_epochs): + acc_loss = 0.0 + for b in range(0, train_set.nb_batches): + input, target = train_set.get_batch(b) + output = model.forward(Variable(input)) + loss = criterion(output, Variable(target)) + acc_loss = acc_loss + loss.data[0] model.zero_grad() loss.backward() optimizer.step() + dt = (time.time() - start_t) / (e + 1) + log_string('train_loss {:d} {:f}'.format(e + 1, acc_loss), + ' [ETA ' + time.ctime(time.time() + dt * (args.nb_epochs - e)) + ']') return model ###################################################################### -def print_test_error(model, test_input, test_target): - bs = 100 - nb_test_errors = 0 +def nb_errors(model, data_set): + ne = 0 + for b in range(0, data_set.nb_batches): + input, target = data_set.get_batch(b) + output = model.forward(Variable(input)) + wta_prediction = output.data.max(1)[1].view(-1) - for b in range(0, nb_test_samples, bs): - output = model.forward(test_input.narrow(0, b, bs)) - _, wta = torch.max(output.data, 1) + for i in range(0, data_set.batch_size): + if wta_prediction[i] != target[i]: + ne = ne + 1 - for i in range(0, bs): - if wta[i][0] != test_target.narrow(0, b, bs).data[i]: - nb_test_errors = nb_test_errors + 1 + return ne - print('TEST_ERROR {:.02f}% ({:d}/{:d})'.format( - 100 * nb_test_errors / nb_test_samples, - nb_test_errors, - nb_test_samples) - ) +###################################################################### + +for arg in vars(args): + log_string('argument ' + str(arg) + ' ' + str(getattr(args, arg))) ###################################################################### -nb_train_samples = 100000 -nb_test_samples = 10000 +def int_to_suffix(n): + if n > 1000000 and n%1000000 == 0: + return str(n//1000000) + 'M' + elif n > 1000 and n%1000 == 0: + return str(n//1000) + 'K' + else: + return str(n) + +###################################################################### -for p in range(1, 24): - print('-- PROBLEM #{:d} --'.format(p)) +if args.nb_train_samples%args.batch_size > 0 or args.nb_test_samples%args.batch_size > 0: + print('The number of samples must be a multiple of the batch size.') + raise + +for problem_number in range(1, 24): + + log_string('**** problem ' + str(problem_number) + ' ****') + + if args.deep_model: + model = AfrozeDeepNet() + else: + model = AfrozeShallowNet() - t1 = time.time() - train_input, train_target = generate_set(p, nb_train_samples) - test_input, test_target = generate_set(p, nb_test_samples) if torch.cuda.is_available(): - train_input, train_target = train_input.cuda(), train_target.cuda() - test_input, test_target = test_input.cuda(), test_target.cuda() + model.cuda() + + model_filename = model.name + '_' + \ + str(problem_number) + '_' + \ + int_to_suffix(args.nb_train_samples) + '.param' + + nb_parameters = 0 + for p in model.parameters(): nb_parameters += p.numel() + log_string('nb_parameters {:d}'.format(nb_parameters)) + + need_to_train = False + try: + model.load_state_dict(torch.load(model_filename)) + log_string('loaded_model ' + model_filename) + except: + need_to_train = True + + if need_to_train: + + log_string('training_model ' + model_filename) + + t = time.time() + + if args.compress_vignettes: + train_set = CompressedVignetteSet(problem_number, + args.nb_train_samples, args.batch_size, + cuda = torch.cuda.is_available()) + else: + train_set = VignetteSet(problem_number, + args.nb_train_samples, args.batch_size, + cuda = torch.cuda.is_available()) + + log_string('data_generation {:0.2f} samples / s'.format( + train_set.nb_samples / (time.time() - t)) + ) + + train_model(model, train_set) + torch.save(model.state_dict(), model_filename) + log_string('saved_model ' + model_filename) + + nb_train_errors = nb_errors(model, train_set) + + log_string('train_error {:d} {:.02f}% {:d} {:d}'.format( + problem_number, + 100 * nb_train_errors / train_set.nb_samples, + nb_train_errors, + train_set.nb_samples) + ) + + if need_to_train or args.test_loaded_models: - mu, std = train_input.data.mean(), train_input.data.std() - train_input.data.sub_(mu).div_(std) - test_input.data.sub_(mu).div_(std) + t = time.time() - t2 = time.time() - print('[data generation {:.02f}s]'.format(t2 - t1)) - model = train_model(train_input, train_target) + if args.compress_vignettes: + test_set = CompressedVignetteSet(problem_number, + args.nb_test_samples, args.batch_size, + cuda = torch.cuda.is_available()) + else: + test_set = VignetteSet(problem_number, + args.nb_test_samples, args.batch_size, + cuda = torch.cuda.is_available()) - t3 = time.time() - print('[train {:.02f}s]'.format(t3 - t2)) - print_test_error(model, test_input, test_target) + log_string('data_generation {:0.2f} samples / s'.format( + test_set.nb_samples / (time.time() - t)) + ) - t4 = time.time() + nb_test_errors = nb_errors(model, test_set) - print('[test {:.02f}s]'.format(t4 - t3)) - print() + log_string('test_error {:d} {:.02f}% {:d} {:d}'.format( + problem_number, + 100 * nb_test_errors / test_set.nb_samples, + nb_test_errors, + test_set.nb_samples) + ) ######################################################################