X-Git-Url: https://fleuret.org/cgi-bin/gitweb/gitweb.cgi?a=blobdiff_plain;f=cnn-svrt.py;h=f3d350eb9ea9203f408a0603e7c0458b88801e95;hb=8c709c982d64948ab1c8949930dc0468f91039aa;hp=283f02ba22ac7b3ad9825fea05f699db82e70bda;hpb=c5660d2adc37f116088867ae71f66a89b34c94f1;p=pysvrt.git
diff --git a/cnn-svrt.py b/cnn-svrt.py
index 283f02b..f3d350e 100755
--- a/cnn-svrt.py
+++ b/cnn-svrt.py
@@ -19,11 +19,12 @@
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
-# along with selector. If not, see .
+# along with svrt. If not, see .
import time
import argparse
import math
+import distutils.util
from colorama import Fore, Back, Style
@@ -40,61 +41,80 @@ from torchvision import datasets, transforms, utils
# SVRT
-from vignette_set import VignetteSet, CompressedVignetteSet
+import svrtset
######################################################################
parser = argparse.ArgumentParser(
- description = 'Simple convnet test on the SVRT.',
+ description = "Convolutional networks for the SVRT. Written by Francois Fleuret, (C) Idiap research institute.",
formatter_class = argparse.ArgumentDefaultsHelpFormatter
)
-parser.add_argument('--nb_train_batches',
- type = int, default = 1000,
- help = 'How many samples for train')
+parser.add_argument('--nb_train_samples',
+ type = int, default = 100000)
-parser.add_argument('--nb_test_batches',
- type = int, default = 100,
- help = 'How many samples for test')
+parser.add_argument('--nb_test_samples',
+ type = int, default = 10000)
+
+parser.add_argument('--nb_validation_samples',
+ type = int, default = 10000)
+
+parser.add_argument('--validation_error_threshold',
+ type = float, default = 0.0,
+ help = 'Early training termination criterion')
parser.add_argument('--nb_epochs',
- type = int, default = 50,
- help = 'How many training epochs')
+ type = int, default = 50)
parser.add_argument('--batch_size',
- type = int, default = 100,
- help = 'Mini-batch size')
+ type = int, default = 100)
parser.add_argument('--log_file',
- type = str, default = 'cnn-svrt.log',
- help = 'Log file name')
+ type = str, default = 'default.log')
parser.add_argument('--compress_vignettes',
- action='store_true', default = False,
+ type = distutils.util.strtobool, default = 'True',
help = 'Use lossless compression to reduce the memory footprint')
+parser.add_argument('--deep_model',
+ type = distutils.util.strtobool, default = 'True',
+ help = 'Use Afroze\'s Alexnet-like deep model')
+
+parser.add_argument('--test_loaded_models',
+ type = distutils.util.strtobool, default = 'False',
+ help = 'Should we compute the test errors of loaded models')
+
+parser.add_argument('--problems',
+ type = str, default = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23',
+ help = 'What problems to process')
+
args = parser.parse_args()
######################################################################
-log_file = open(args.log_file, 'w')
+log_file = open(args.log_file, 'a')
pred_log_t = None
print(Fore.RED + 'Logging into ' + args.log_file + Style.RESET_ALL)
-def log_string(s):
+# 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
- s = Fore.BLUE + time.ctime() + ' ' + Fore.GREEN + elapsed + Style.RESET_ALL + ' ' + s
- log_file.write(s + '\n')
+
+ log_file.write('[' + time.ctime() + '] ' + elapsed + ' ' + s + '\n')
log_file.flush()
- print(s)
+
+ print(Fore.BLUE + '[' + time.ctime() + '] ' + Fore.GREEN + elapsed + Style.RESET_ALL + ' ' + s + Fore.CYAN + remark + Style.RESET_ALL)
######################################################################
@@ -133,7 +153,70 @@ class AfrozeShallowNet(nn.Module):
######################################################################
-def train_model(model, train_set):
+# Afroze's DeepNet
+
+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 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 i in range(0, data_set.batch_size):
+ if wta_prediction[i] != target[i]:
+ ne = ne + 1
+
+ return ne
+
+######################################################################
+
+def train_model(model, train_set, validation_set):
batch_size = args.batch_size
criterion = nn.CrossEntropyLoss()
@@ -142,6 +225,8 @@ def train_model(model, train_set):
optimizer = optim.SGD(model.parameters(), lr = 1e-2)
+ start_t = time.time()
+
for e in range(0, args.nb_epochs):
acc_loss = 0.0
for b in range(0, train_set.nb_batches):
@@ -152,24 +237,25 @@ def train_model(model, train_set):
model.zero_grad()
loss.backward()
optimizer.step()
- log_string('train_loss {:d} {:f}'.format(e + 1, acc_loss))
+ dt = (time.time() - start_t) / (e + 1)
- return model
+ log_string('train_loss {:d} {:f}'.format(e + 1, acc_loss),
+ ' [ETA ' + time.ctime(time.time() + dt * (args.nb_epochs - e)) + ']')
-######################################################################
+ if validation_set is not None:
+ nb_validation_errors = nb_errors(model, validation_set)
-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)
+ log_string('validation_error {:.02f}% {:d} {:d}'.format(
+ 100 * nb_validation_errors / validation_set.nb_samples,
+ nb_validation_errors,
+ validation_set.nb_samples)
+ )
- for i in range(0, data_set.batch_size):
- if wta_prediction[i] != target[i]:
- ne = ne + 1
+ if nb_validation_errors / validation_set.nb_samples <= args.validation_error_threshold:
+ log_string('below validation_error_threshold')
+ break
- return ne
+ return model
######################################################################
@@ -178,23 +264,67 @@ for arg in vars(args):
######################################################################
-for problem_number in range(1, 24):
+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)
- log_string('**** problem ' + str(problem_number) + ' ****')
+class vignette_logger():
+ def __init__(self, delay_min = 60):
+ self.start_t = time.time()
+ self.last_t = self.start_t
+ self.delay_min = delay_min
- model = AfrozeShallowNet()
+ def __call__(self, n, m):
+ t = time.time()
+ if t > self.last_t + self.delay_min:
+ dt = (t - self.start_t) / m
+ log_string('sample_generation {:d} / {:d}'.format(
+ m,
+ n), ' [ETA ' + time.ctime(time.time() + dt * (n - m)) + ']'
+ )
+ self.last_t = t
- if torch.cuda.is_available():
- model.cuda()
+######################################################################
+
+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
- model_filename = model.name + '_' + \
- str(problem_number) + '_' + \
- str(args.nb_train_batches) + '.param'
+log_string('############### start ###############')
+
+if args.compress_vignettes:
+ log_string('using_compressed_vignettes')
+ VignetteSet = svrtset.CompressedVignetteSet
+else:
+ log_string('using_uncompressed_vignettes')
+ VignetteSet = svrtset.VignetteSet
+
+for problem_number in map(int, args.problems.split(',')):
+
+ log_string('############### problem ' + str(problem_number) + ' ###############')
+
+ if args.deep_model:
+ model = AfrozeDeepNet()
+ else:
+ model = AfrozeShallowNet()
+
+ if torch.cuda.is_available(): model.cuda()
+
+ model_filename = model.name + '_pb:' + \
+ str(problem_number) + '_ns:' + \
+ 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))
+ ##################################################
+ # Tries to load the model
+
need_to_train = False
try:
model.load_state_dict(torch.load(model_filename))
@@ -202,26 +332,33 @@ for problem_number in range(1, 24):
except:
need_to_train = True
+ ##################################################
+ # Train if necessary
+
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_batches, args.batch_size,
- cuda=torch.cuda.is_available())
- else:
- train_set = VignetteSet(problem_number,
- args.nb_train_batches, args.batch_size,
- cuda=torch.cuda.is_available())
+ train_set = VignetteSet(problem_number,
+ args.nb_train_samples, args.batch_size,
+ cuda = torch.cuda.is_available(),
+ logger = vignette_logger())
log_string('data_generation {:0.2f} samples / s'.format(
- (train_set.nb_samples + test_set.nb_samples) / (time.time() - t))
+ train_set.nb_samples / (time.time() - t))
)
- train_model(model, train_set)
+ if args.validation_error_threshold > 0.0:
+ validation_set = VignetteSet(problem_number,
+ args.nb_validation_samples, args.batch_size,
+ cuda = torch.cuda.is_available(),
+ logger = vignette_logger())
+ else:
+ validation_set = None
+
+ train_model(model, train_set, validation_set)
torch.save(model.state_dict(), model_filename)
log_string('saved_model ' + model_filename)
@@ -234,23 +371,24 @@ for problem_number in range(1, 24):
train_set.nb_samples)
)
- if args.compress_vignettes:
- test_set = CompressedVignetteSet(problem_number,
- args.nb_test_batches, args.batch_size,
- cuda=torch.cuda.is_available())
- else:
- test_set = VignetteSet(problem_number,
- args.nb_test_batches, args.batch_size,
- cuda=torch.cuda.is_available())
+ ##################################################
+ # Test if necessary
+
+ if need_to_train or args.test_loaded_models:
- nb_test_errors = nb_errors(model, test_set)
+ t = time.time()
+
+ test_set = VignetteSet(problem_number,
+ args.nb_test_samples, args.batch_size,
+ cuda = torch.cuda.is_available())
- 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)
- )
+ nb_test_errors = nb_errors(model, test_set)
+ 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)
+ )
######################################################################