Exemple #1
0
 def print_output_stats(self, output_stats):
     table = OrderedDict()
     for name, stats in six.iteritems(output_stats):
         table.setdefault('name', []).append(name)
         for key in stats:
             table.setdefault(key, []).append(stats[key])
     print('Output statistics:')
     print(format_table(table))
     print()
Exemple #2
0
 def print_output_stats(self, output_stats):
     table = OrderedDict()
     for name, stats in six.iteritems(output_stats):
         table.setdefault('name', []).append(name)
         for key in stats:
             table.setdefault(key, []).append(stats[key])
     print('Output statistics:')
     print(format_table(table))
     print()
Exemple #3
0
 def print_class_weights(self, class_weights):
     table = OrderedDict()
     for name, class_weight in six.iteritems(class_weights):
         if not class_weight:
             continue
         column = []
         for cla, weight in six.iteritems(class_weight):
             column.append('%s=%.2f' % (cla, weight))
             table[name] = column
     if table:
         print('Class weights:')
         print(format_table(table))
         print()
Exemple #4
0
 def print_class_weights(self, class_weights):
     table = OrderedDict()
     for name, class_weight in six.iteritems(class_weights):
         if not class_weight:
             continue
         column = []
         for cla, weight in six.iteritems(class_weight):
             column.append('%s=%.2f' % (cla, weight))
             table[name] = column
     if table:
         print('Class weights:')
         print(format_table(table))
         print()
Exemple #5
0
    def set_trainability(self, model):
        opts = self.opts
        trainable = []
        not_trainable = []
        if opts.fine_tune:
            not_trainable.append('.*')
        elif opts.train_models:
            not_trainable.append('.*')
            for name in opts.train_models:
                trainable.append('%s/' % name)
        if opts.freeze_filter:
            not_trainable.append(mod.get_first_conv_layer(model.layers).name)
        if not trainable and opts.trainable:
            trainable = opts.trainable
        if not not_trainable and opts.not_trainable:
            not_trainable = opts.not_trainable

        if not trainable and not not_trainable:
            return

        table = OrderedDict()
        table['layer'] = []
        table['trainable'] = []
        for layer in model.layers:
            if is_input_layer(layer) or is_output_layer(layer, model):
                continue
            if not hasattr(layer, 'trainable'):
                continue
            for regex in not_trainable:
                if re.match(regex, layer.name):
                    layer.trainable = False
            for regex in trainable:
                if re.match(regex, layer.name):
                    layer.trainable = True
            table['layer'].append(layer.name)
            table['trainable'].append(layer.trainable)
        print('Layer trainability:')
        print(format_table(table))
        print()
Exemple #6
0
    def set_trainability(self, model):
        opts = self.opts
        trainable = []
        not_trainable = []
        if opts.fine_tune:
            not_trainable.append('.*')
        elif opts.train_models:
            not_trainable.append('.*')
            for name in opts.train_models:
                trainable.append('%s/' % name)
        if opts.freeze_filter:
            not_trainable.append(mod.get_first_conv_layer(model.layers).name)
        if not trainable and opts.trainable:
            trainable = opts.trainable
        if not not_trainable and opts.not_trainable:
            not_trainable = opts.not_trainable

        if not trainable and not not_trainable:
            return

        table = OrderedDict()
        table['layer'] = []
        table['trainable'] = []
        for layer in model.layers:
            if is_input_layer(layer) or is_output_layer(layer, model):
                continue
            if not hasattr(layer, 'trainable'):
                continue
            for regex in not_trainable:
                if re.match(regex, layer.name):
                    layer.trainable = False
            for regex in trainable:
                if re.match(regex, layer.name):
                    layer.trainable = True
            table['layer'].append(layer.name)
            table['trainable'].append(layer.trainable)
        print('Layer trainability:')
        print(format_table(table))
        print()
Exemple #7
0
    def set_trainability(self, model):
        opts = self.opts
        trainable = []  #create a list
        not_trainable = []  #create a list
        if opts.fine_tune: #only train output layers
            not_trainable.append('.*')
        elif opts.train_models:  #only train the specified model, including dna, cpg, and joint
            not_trainable.append('.*')
            for name in opts.train_models:
                trainable.append('%s/' % name)
        if opts.freeze_filter:  #Exclude filter weights of first convolutional layer from training
            not_trainable.append(mod.get_first_conv_layer(model.layers).name)
        if not trainable and opts.trainable:
            trainable = opts.trainable
        if not not_trainable and opts.not_trainable:
            not_trainable = opts.not_trainable

        if not trainable and not not_trainable:
            return

        table = OrderedDict() #dictionary which remember the order
        table['layer'] = []
        table['trainable'] = []
        for layer in model.layers:
            if layer not in model.input_layers + model.output_layers:
                if not hasattr(layer, 'trainable'):
                    continue
                for regex in not_trainable:
                    if re.match(regex, layer.name):
                        layer.trainable = False
                for regex in trainable:
                    if re.match(regex, layer.name):
                        layer.trainable = True
                table['layer'].append(layer.name)
                table['trainable'].append(layer.trainable)
        print('Layer trainability:')
        print(format_table(table))
        print()
Exemple #8
0
    def main(self, name, opts):
        logging.basicConfig(filename=opts.log_file,
                            format='%(levelname)s (%(asctime)s): %(message)s')
        log = logging.getLogger(name)
        if opts.verbose:
            log.setLevel(logging.DEBUG)
        else:
            log.setLevel(logging.INFO)

        if opts.seed is not None:
            np.random.seed(opts.seed)
            random.seed(opts.seed)

        self.log = log
        self.opts = opts

        make_dir(opts.out_dir)

        log.info('Building model ...')
        model = self.build_model()

        model.summary()
        self.set_trainability(model)
        if opts.filter_weights:
            conv_layer = mod.get_first_conv_layer(model.layers)
            log.info('Initializing filters of %s ...' % conv_layer.name)
            self.init_filter_weights(opts.filter_weights, conv_layer)
        mod.save_model(model, os.path.join(opts.out_dir, 'model.json'))

        log.info('Computing output statistics ...')
        output_names = []
        for output_layer in model.output_layers:
            output_names.append(output_layer.name)

        output_stats = OrderedDict()

        if opts.no_class_weights:
            class_weights = None
        else:
            class_weights = OrderedDict()

        for name in output_names:
            output = hdf.read(opts.train_files,
                              'outputs/%s' % name,
                              nb_sample=opts.nb_train_sample)
            output = list(output.values())[0]
            output_stats[name] = get_output_stats(output)
            if class_weights is not None:
                class_weights[name] = get_output_class_weights(name, output)

        self.print_output_stats(output_stats)
        if class_weights:
            self.print_class_weights(class_weights)

        output_weights = None
        if opts.output_weights:
            log.info('Initializing output weights ...')
            output_weights = get_output_weights(output_names,
                                                opts.output_weights)
            print('Output weights:')
            for output_name in output_names:
                if output_name in output_weights:
                    print('%s: %.2f' %
                          (output_name, output_weights[output_name]))
            print()

        self.metrics = dict()
        for output_name in output_names:
            self.metrics[output_name] = get_metrics(output_name)

        optimizer = Adam(lr=opts.learning_rate)
        model.compile(optimizer=optimizer,
                      loss=mod.get_objectives(output_names),
                      loss_weights=output_weights,
                      metrics=self.metrics)

        log.info('Loading data ...')
        replicate_names = dat.get_replicate_names(opts.train_files[0],
                                                  regex=opts.replicate_names,
                                                  nb_key=opts.nb_replicate)
        data_reader = mod.data_reader_from_model(
            model, replicate_names=replicate_names)
        nb_train_sample = dat.get_nb_sample(opts.train_files,
                                            opts.nb_train_sample)
        train_data = data_reader(opts.train_files,
                                 class_weights=class_weights,
                                 batch_size=opts.batch_size,
                                 nb_sample=nb_train_sample,
                                 shuffle=True,
                                 loop=True)

        if opts.val_files:
            nb_val_sample = dat.get_nb_sample(opts.val_files,
                                              opts.nb_val_sample)
            val_data = data_reader(opts.val_files,
                                   batch_size=opts.batch_size,
                                   nb_sample=nb_val_sample,
                                   shuffle=False,
                                   loop=True)
        else:
            val_data = None
            nb_val_sample = None

        log.info('Initializing callbacks ...')
        callbacks = self.get_callbacks()

        log.info('Training model ...')
        print()
        print('Training samples: %d' % nb_train_sample)
        if nb_val_sample:
            print('Validation samples: %d' % nb_val_sample)
        model.fit_generator(train_data,
                            nb_train_sample,
                            opts.nb_epoch,
                            callbacks=callbacks,
                            validation_data=val_data,
                            nb_val_samples=nb_val_sample,
                            max_q_size=opts.data_q_size,
                            nb_worker=opts.data_nb_worker,
                            verbose=0)

        print('\nTraining set performance:')
        print(
            format_table(self.perf_logger.epoch_logs, precision=LOG_PRECISION))

        if self.perf_logger.val_epoch_logs:
            print('\nValidation set performance:')
            print(
                format_table(self.perf_logger.val_epoch_logs,
                             precision=LOG_PRECISION))

        # Restore model with highest validation performance
        filename = os.path.join(opts.out_dir, 'model_weights_val.h5')
        if os.path.isfile(filename):
            model.load_weights(filename)

        # Delete metrics since they cause problems when loading the model
        # from HDF5 file. Metrics can be loaded from json + weights file.
        model.metrics = None
        model.metrics_names = None
        model.metrics_tensors = None
        model.save(os.path.join(opts.out_dir, 'model.h5'))

        log.info('Done!')

        return 0
Exemple #9
0
    def main(self, name, opts):
        logging.basicConfig(filename=opts.log_file,
                            format='%(levelname)s (%(asctime)s): %(message)s')
        log = logging.getLogger(name)
        if opts.verbose:
            log.setLevel(logging.DEBUG)
        else:
            log.setLevel(logging.INFO)

        if opts.seed is not None:
            np.random.seed(opts.seed)
            random.seed(opts.seed)

        self.log = log
        self.opts = opts

        make_dir(opts.out_dir)

        log.info('Building model ...')
        model = self.build_model()

        model.summary()
        self.set_trainability(model)
        if opts.filter_weights:
            conv_layer = mod.get_first_conv_layer(model.layers)
            log.info('Initializing filters of %s ...' % conv_layer.name)
            self.init_filter_weights(opts.filter_weights, conv_layer)
        mod.save_model(model, os.path.join(opts.out_dir, 'model.json'))

        log.info('Computing output statistics ...')
        output_names = model.output_names

        output_stats = OrderedDict()

        if opts.no_class_weights:
            class_weights = None
        else:
            class_weights = OrderedDict()

        for name in output_names:
            output = hdf.read(opts.train_files, 'outputs/%s' % name,
                              nb_sample=opts.nb_train_sample)
            output = list(output.values())[0]
            output_stats[name] = get_output_stats(output)
            if class_weights is not None:
                class_weights[name] = get_output_class_weights(name, output)

        self.print_output_stats(output_stats)
        if class_weights:
            self.print_class_weights(class_weights)

        output_weights = None
        if opts.output_weights:
            log.info('Initializing output weights ...')
            output_weights = get_output_weights(output_names,
                                                opts.output_weights)
            print('Output weights:')
            for output_name in output_names:
                if output_name in output_weights:
                    print('%s: %.2f' % (output_name,
                                        output_weights[output_name]))
            print()

        self.metrics = dict()
        for output_name in output_names:
            self.metrics[output_name] = get_metrics(output_name)

        optimizer = Adam(lr=opts.learning_rate)
        model.compile(optimizer=optimizer,
                      loss=mod.get_objectives(output_names),
                      loss_weights=output_weights,
                      metrics=self.metrics)

        log.info('Loading data ...')
        replicate_names = dat.get_replicate_names(
            opts.train_files[0],
            regex=opts.replicate_names,
            nb_key=opts.nb_replicate)
        data_reader = mod.data_reader_from_model(
            model, replicate_names=replicate_names)
        nb_train_sample = dat.get_nb_sample(opts.train_files,
                                            opts.nb_train_sample)
        train_data = data_reader(opts.train_files,
                                 class_weights=class_weights,
                                 batch_size=opts.batch_size,
                                 nb_sample=nb_train_sample,
                                 shuffle=True,
                                 loop=True)

        if opts.val_files:
            nb_val_sample = dat.get_nb_sample(opts.val_files,
                                              opts.nb_val_sample)
            val_data = data_reader(opts.val_files,
                                   batch_size=opts.batch_size,
                                   nb_sample=nb_val_sample,
                                   shuffle=False,
                                   loop=True)
        else:
            val_data = None
            nb_val_sample = None

        log.info('Initializing callbacks ...')
        callbacks = self.get_callbacks()

        log.info('Training model ...')
        print()
        print('Training samples: %d' % nb_train_sample)
        if nb_val_sample:
            print('Validation samples: %d' % nb_val_sample)
        model.fit_generator(
            train_data,
            steps_per_epoch=nb_train_sample // opts.batch_size,
            epochs=opts.nb_epoch,
            callbacks=callbacks,
            validation_data=val_data,
            validation_steps=nb_val_sample // opts.batch_size,
            max_queue_size=opts.data_q_size,
            workers=opts.data_nb_worker,
            verbose=0)

        print('\nTraining set performance:')
        print(format_table(self.perf_logger.epoch_logs,
                           precision=LOG_PRECISION))

        if self.perf_logger.val_epoch_logs:
            print('\nValidation set performance:')
            print(format_table(self.perf_logger.val_epoch_logs,
                               precision=LOG_PRECISION))

        # Restore model with highest validation performance
        filename = os.path.join(opts.out_dir, 'model_weights_val.h5')
        if os.path.isfile(filename):
            model.load_weights(filename)

        # Delete metrics since they cause problems when loading the model
        # from HDF5 file. Metrics can be loaded from json + weights file.
        model.metrics = None
        model.metrics_names = None
        model.metrics_tensors = None
        model.save(os.path.join(opts.out_dir, 'model.h5'))

        log.info('Done!')

        return 0