def run():
    device = 0 if torch.cuda.is_available() else -1
    config = BaseConfig()
    logging.info('%s_cross_entropy/ckpt.pth.tar' % config.result_dir)
    if os.path.exists('%s_cross_entropy/ckpt.pth.tar' % config.result_dir):
        return True
    logging.info("Triplet Trainer Not Return")
    create_dirs()
    tr_data_loader, val_data_loader, te_data_loader = loaders.data_loaders(
        shuffle=True)

    model = getattr(models,
                    config.network)(num_classes=len(tr_data_loader.dataset.y))

    model
    criterion = CrossEntropyLoss()

    if device == 0:
        model.cuda()
        criterion.cuda()
    trainer = ModuleTrainer(model)
    epochs = config.epochs

    callbacks = [
        EarlyStopping(monitor='val_acc', patience=20),
        ModelCheckpoint('%s_cross_entropy' % config.result_dir,
                        save_best_only=True,
                        verbose=1),
        CSVLogger("%s_cross_entropy/logger.csv" % config.result_dir)
    ]

    metrics = [CategoricalAccuracy()]

    trainer.compile(loss=criterion, optimizer='adam', metrics=metrics)
    trainer.set_callbacks(callbacks)

    trainer.fit_loader(tr_data_loader,
                       val_loader=val_data_loader,
                       num_epoch=epochs,
                       verbose=2,
                       cuda_device=device)

    tr_loss = trainer.evaluate_loader(tr_data_loader, cuda_device=device)
    logging.info(tr_loss)
    val_loss = trainer.evaluate_loader(val_data_loader, cuda_device=device)
    logging.info(val_loss)
    te_loss = trainer.evaluate_loader(te_data_loader, cuda_device=device)
    logging.info(te_loss)
    with open('%s_cross_entropy' % config.log_path, "a") as f:
        f.write('Train %s\nVal:%s\nTest:%s\n' %
                (str(tr_loss), str(val_loss), te_loss))
Ejemplo n.º 2
0
def run():
    from config import get_config
    config = get_config()

    import losses
    import models
    from utils.make_dirs import create_dirs
    from datasets import loaders
    from torchsample.callbacks import EarlyStopping, ModelCheckpoint, CSVLogger
    from torchsample.metrics import CategoricalAccuracy
    from torchsample.modules import ModuleTrainer
    create_dirs()

    model = getattr(models, config.network).get_network()(
        channel=config.network_channel, embedding_size=config.embedding)
    criterion = getattr(losses, config.loss)()
    if config.cuda:
        model.cuda()
        criterion.cuda()
    trainer = ModuleTrainer(model)

    callbacks = [
        EarlyStopping(monitor='val_loss', patience=50),
        ModelCheckpoint(config.result_dir, save_best_only=True, verbose=1),
        CSVLogger("%s/logger.csv" % config.result_dir)
    ]
    metrics = []
    if config.loader_name == 'data_loaders':
        metrics.append(CategoricalAccuracy(top_k=1))
    trainer.compile(loss=criterion, optimizer='adam', metrics=metrics)
    trainer.set_callbacks(callbacks)

    def get_n_params(model):
        pp = 0
        for p in list(model.parameters()):
            nn = 1
            for s in list(p.size()):
                nn = nn * s
            pp += nn
        return pp

    with open("models.log", mode="a") as f:
        f.write("%s\n" % str(config.__dict__))
        f.write("%s\n" % str(model))
        f.write("%s\n" % str(get_n_params(model)))
        f.write("\n")
            temp.append(h)  # batch, width, 512
        x = torch.stack(temp, dim=3)  # batch, height, 512, width
        x = torch.transpose(x, 1, 2)  # batch, 512, height, width
        x = self.conv(x)
        return x


if __name__ == '__main__':
    # vgg = torchvision.models.vgg16(pretrained=True)
    vgg = torchvision.models.mobilenet_v2(pretrained=True)

    device = torch.device("cuda")
    batch_size = 1
    noise = torch.randn((batch_size, 3, 224, 224)).type(torch.cuda.FloatTensor)
    target = torch.randn((batch_size, 1, 224, 224)).type(torch.cuda.FloatTensor)

    model = Unet(cfg).cuda()
    model.encoder.seq.load_state_dict(vgg.features.state_dict())
    print(model.parameters)

    opt = torch.optim.Adam(model.parameters(), lr=0.001)
    print('Time: {}'.format(time.clock()))
    _, loss = model(noise, target)
#added for early stopping. The pateience calcualtes the best values of the previous 5 times.
    callbacks = [EarlyStopping(monitor='loss', patience=5)]
    model.set_callbacks(callbacks)
#added
    loss.backward()


Ejemplo n.º 4
0
    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2(x), 2))
        x = x.view(-1, 1600)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return F.log_softmax(x)


model = Network()
trainer = ModuleTrainer(model)

callbacks = [
    EarlyStopping(patience=10),
    ReduceLROnPlateau(factor=0.5, patience=5)
]
regularizers = [
    L1Regularizer(scale=1e-3, module_filter='conv*'),
    L2Regularizer(scale=1e-5, module_filter='fc*')
]
constraints = [UnitNorm(frequency=3, unit='batch', module_filter='fc*')]
initializers = [XavierUniform(bias=False, module_filter='fc*')]
metrics = [CategoricalAccuracy(top_k=3)]

trainer.compile(loss='nll_loss',
                optimizer='adadelta',
                regularizers=regularizers,
                constraints=constraints,
                initializers=initializers,
Ejemplo n.º 5
0
def train(kwargs):
    """
    Training Process

    :return:
    """
    print('[INFO] Loading Settings...')

    parser = None
    config = None

    try:
        parser = NeuralMFConfig()
        # print(kwargs)
        if '-c' in kwargs:
            args = list(enumerate(kwargs))
            for id, arg in args:
                if '-c' == arg and len(args) >= id + 2:
                    config = parser.get_args_from_json(args[id + 1][1])
                    break
                else:
                    raise AssertionError("Corresponding config arg not found")
        else:
            config = parser.parse_args(kwargs)
    except Exception as e:
        print('[Exception] Unavailable Settings, %s' % e)
        if parser:
            help(kwargs)
        if '-c' in kwargs:
            print(
                '[Exception] Please refer formatting: python main.py -c configs/neuralMF_config.json'
            )
        exit(0)

    cuda_device = -1 if not config.cuda else 0
    if config.cuda:
        torch.cuda.set_device(cuda_device)
        config.cuda_device = cuda_device

    print('[INFO] Loading Data...')
    dl = CFDataLoader(config=config, only_test=False)

    print('[INFO] Build Networks...')
    nb_users, nb_items = dl.get_num_user_and_item()
    parser.args.nb_users = nb_users
    parser.args.nb_items = nb_items
    model = implicit_load_model(config.model)(config, nb_users, nb_items)
    print(model)
    callbacks = [
        EarlyStopping(patience=10),
        ReduceLROnPlateau(factor=0.5, patience=5)
    ]
    regularizers = [L2Regularizer(scale=1e-5, module_filter='fc*')]
    constraints = [UnitNorm(frequency=3, unit='batch', module_filter='fc*')]
    initializers = []
    metrics = [HitAccuracy(config.topk), NDCGAccuracy(config.topk)]

    print('[INFO] Begin Training...')
    time_str = _time.strftime('%m%d_%H:%M:%S')

    trainer = RankingModulelTrainer(model=model)
    trainer.compile(loss="binary_cross_entropy_with_logits",
                    optimizer='Adam',
                    regularizers=regularizers,
                    constraints=constraints,
                    initializers=initializers,
                    metrics=metrics,
                    callbacks=callbacks)
    trainer.fit_loader(dl.get_train_data(),
                       dl.get_test_data(),
                       num_epoch=config.epochs,
                       verbose=1,
                       cuda_device=cuda_device)
    print('[INFO] Complete Training...')
    model.save(time_str=time_str, use_onnx=config.onnx)
    parser.save(timestamp=time_str)
    print('[INFO] Saved Model into checkpoint directory')
Ejemplo n.º 6
0
train_loader = data.DataLoader(TGSSaltDataset(train_images, train_masks),
                               batch_size=25,
                               shuffle=True)
val_loader = data.DataLoader(TGSSaltDataset(validate_images, validate_masks),
                             batch_size=50,
                             shuffle=False)

learning_rate = 1e-4
loss_fn = torch.nn.BCELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

trainer = ModuleTrainer(model)

callbacks = [
    EarlyStopping(patience=30),
    ReduceLROnPlateau(factor=0.5, patience=10)
]
regularizers = [
    L1Regularizer(scale=1e-3, module_filter='*'),
    L2Regularizer(scale=1e-5, module_filter='*')
]
constraints = [UnitNorm(frequency=3, unit='batch', module_filter='*')]
initializers = [XavierUniform(bias=False, module_filter='*')]
metrics = [MyIouMetric()]

trainer.compile(
    loss=loss_fn,
    optimizer=optimizer,
    regularizers=None,  #regularizers,
    constraints=None,  #constraints,
Ejemplo n.º 7
0
def run():
    from config import get_config
    config = get_config()

    print('%s/ckpt.pth.tar' % config.result_dir)
    if os.path.exists('%s/ckpt.pth.tar' % config.result_dir):
        return True
    print("Contrastive Trainer Not Return")
    import models
    from utils.make_dirs import create_dirs
    from datasets import loaders
    from torchsample.callbacks import EarlyStopping, ModelCheckpoint, CSVLogger
    from torchsample.metrics import CategoricalAccuracy
    from torchsample.modules import ModuleTrainer
    create_dirs()
    cuda_device = -1
    tr_data_loader, val_data_loader, te_data_loader = loaders.online_pair_loaders()

    model = getattr(models, config.network).get_network()(channel=config.network_channel,
                                                          embedding_size=config.embedding)
    from losses.online_cosine import OnlineCosineLoss
    from datasets.data_utils import AllPositivePairSelector, HardNegativePairSelector

    margin = 0.5

    if args.selector == 'AllPositivePairSelector':
        criterion = OnlineCosineLoss(margin, AllPositivePairSelector())
    elif args.selector == 'HardNegativePairSelector':
        criterion = OnlineCosineLoss(margin, HardNegativePairSelector())

    if config.cuda:
        model.cuda()
        criterion.cuda()
    trainer = ModuleTrainer(model)
    epochs = config.epochs

    callbacks = [EarlyStopping(monitor='val_loss', patience=50),
                 ModelCheckpoint(config.result_dir, save_best_only=True, verbose=1),
                 CSVLogger("%s/logger.csv" % config.result_dir)]

    metrics = []
    if config.loader_name == 'data_loaders' and 'Angle' not in config.loss:
        metrics.append(CategoricalAccuracy(top_k=1))
    trainer.compile(loss=criterion, optimizer='adam', metrics=metrics)
    trainer.set_callbacks(callbacks)
    if config.cuda:
        cuda_device = 0
    start_time = time.time()
    trainer.fit_loader(tr_data_loader, val_loader=val_data_loader, num_epoch=epochs, verbose=2,
                       cuda_device=cuda_device)
    end_time = time.time()

    with open("%s/app.log" % config.result_dir, mode="a") as f:
        f.write("%s\n" % str(model))
        f.write("%s %s\n" % (config.loss, str(end_time - start_time)))
    tr_loss = trainer.evaluate_loader(tr_data_loader, cuda_device=cuda_device)
    print(tr_loss)
    val_loss = trainer.evaluate_loader(val_data_loader, cuda_device=cuda_device)
    te_loss = trainer.evaluate_loader(te_data_loader, cuda_device=cuda_device)
    print(te_loss)
    with open(config.log_path, "a") as f:
        f.write('Train %s\nVal:%s\nTest:%s\n' % (str(tr_loss), str(val_loss), te_loss))

    tr_data_loader, val_data_loader, te_data_loader = loaders.data_loaders(train=False, val=True)

    tr_y_pred = trainer.predict_loader(tr_data_loader, cuda_device=cuda_device)
    save_embeddings(tr_y_pred, '%s/train_embeddings.csv' % config.result_dir)
    save_labels(tr_data_loader, '%s/train_labels.csv' % config.result_dir)

    val_y_pred = trainer.predict_loader(val_data_loader, cuda_device=cuda_device)
    save_embeddings(val_y_pred, '%s/val_embeddings.csv' % config.result_dir)
    save_labels(val_data_loader, '%s/val_labels.csv' % config.result_dir)

    te_y_pred = trainer.predict_loader(te_data_loader, cuda_device=cuda_device)
    save_embeddings(te_y_pred, '%s/test_embeddings.csv' % config.result_dir)
    save_labels(te_data_loader, '%s/test_labels.csv' % config.result_dir)
Ejemplo n.º 8
0
    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2(x), 2))
        x = x.view(-1, 1600)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return F.log_softmax(x, dim=_get_softmax_dim(x.dim()))


if __name__ == "__main__":
    model = Network()
    trainer = ModuleTrainer(model)

    callbacks = [EarlyStopping(patience=10),
                 ReduceLROnPlateau(factor=0.5, patience=5)]
    regularizers = [L1Regularizer(scale=1e-3, module_filter='conv*'),
                    L2Regularizer(scale=1e-5, module_filter='fc*')]
    constraints = [UnitNorm(frequency=3, unit='batch', module_filter='fc*')]
    initializers = [XavierUniform(bias=False, module_filter='fc*')]
    metrics = [CategoricalAccuracy(top_k=3)]

    trainer.compile(loss='nll_loss',
                    optimizer='adadelta',
                    regularizers=regularizers,
                    constraints=constraints,
                    initializers=initializers,
                    metrics=metrics,
                    callbacks=callbacks)
Ejemplo n.º 9
0
def main(args):
    """Simply redirrcts to the correct function."""
    start = default_timer()

    args.cuda = not args.no_cuda and torch.cuda.is_available()

    np.random.seed(args.seed)
    torch.manual_seed(args.seed)

    print("-------------------------------------------------")
    if args.verbose > 0:
        print("Ran on {}".format(time.strftime("%Y-%m-%d %H:%M")))
        print()

    print('Parameters: {}'.format(vars(args)))
    print()

    # PREPARES DATA
    if args.verbose > 1:
        print('Prepares data ...')
    train, valid, test = train_valid_test_datasets(
        args.dataset,
        validSize=args.validation_size,
        isHashingTrick=not args.dictionnary,
        nFeaturesRange=args.num_features_range,
        ngramRange=args.ngrams_range,
        seed=args.seed,
        num_words=args.num_embeding,
        specificArgs={'dictionnary': ['num_words']})

    num_classes = len(train.classes)
    train = DataLoader(dataset=train,
                       batch_size=args.batch_size,
                       shuffle=not args.no_shuffle)
    valid = DataLoader(dataset=valid,
                       batch_size=args.batch_size,
                       shuffle=not args.no_shuffle)
    test = DataLoader(dataset=test,
                      batch_size=args.batch_size,
                      shuffle=not args.no_shuffle)

    # PREPARES MODEL
    if args.verbose > 1:
        print('Prepares model ...')

    Model = ModelNoDict if args.model == 'embed-softmax' else ModelDict
    model = Model(args.num_embeding,
                  args.dim,
                  num_classes,
                  isHash=not args.no_hashembed,
                  seed=args.seed,
                  num_buckets=args.num_buckets,
                  append_weight=not args.no_append_weight,
                  aggregation_mode=args.agg_mode,
                  oldAlgorithm=args.old_hashembed)
    if args.cuda:
        model.cuda()

    if args.verbose > 1:
        model_parameters = filter(lambda p: p.requires_grad,
                                  model.parameters())
        nParams = sum([np.prod(p.size()) for p in model_parameters])
        print('Num parameters in model: {}'.format(nParams))
        print("Train on {} samples, validate on {} samples".format(
            len(train), len(valid)))

    # COMPILES
    trainer = ModuleTrainer(model)
    loss = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters())

    callbacks = []
    callbackMetric = "val_loss" if args.val_loss_callback else "val_acc_metric"
    if args.patience is not None:
        callbacks.append(
            EarlyStopping(patience=args.patience, monitor=callbackMetric))
    if args.plateau_reduce_lr is not None:
        callbacks.append(
            ReduceLROnPlateau(factor=args.plateau_reduce_lr[1],
                              patience=args.plateau_reduce_lr[0],
                              monitor=callbackMetric))
    if not args.no_checkpoint:
        modelDir = os.path.join(parentddir, 'models')
        filename = "{}.pth.tar".format(args.dataset)
        callbacks.append(
            ModelCheckpoint(modelDir,
                            filename=filename,
                            save_best_only=True,
                            max_save=1,
                            monitor=callbackMetric))

    metrics = [CategoricalAccuracy()]

    trainer.compile(loss=loss,
                    optimizer=optimizer,
                    callbacks=callbacks,
                    metrics=metrics)

    # TRAINS
    if args.verbose > 1:
        print('Trains ...')
    trainer.fit_loader(train,
                       val_loader=valid,
                       num_epoch=args.epochs,
                       verbose=args.verbose,
                       cuda_device=0 if args.cuda else -1)

    # EVALUATES
    print()
    evalTest = trainer.evaluate_loader(test,
                                       verbose=args.verbose,
                                       cuda_device=0 if args.cuda else -1)
    evalValid = trainer.evaluate_loader(valid,
                                        verbose=args.verbose,
                                        cuda_device=0 if args.cuda else -1)
    print("Last Model. Validation - Loss: {}, Accuracy: {}".format(
        evalValid['val_loss'], evalValid['val_acc_metric']))
    print("Last Model. Test - Loss: {}, Accuracy: {}".format(
        evalTest['val_loss'], evalTest['val_acc_metric']))

    if not args.no_checkpoint:
        checkpoint = torch.load(os.path.join(modelDir, filename))
        model.load_state_dict(checkpoint["state_dict"])
        evalTest = trainer.evaluate_loader(test,
                                           verbose=args.verbose,
                                           cuda_device=0 if args.cuda else -1)
        evalValid = trainer.evaluate_loader(valid,
                                            verbose=args.verbose,
                                            cuda_device=0 if args.cuda else -1)
        print("Best Model. Validation - Loss: {}, Accuracy: {}".format(
            evalValid['val_loss'], evalValid['val_acc_metric']))
        print("Best Model. Test - Loss: {}, Accuracy: {}".format(
            evalTest['val_loss'], evalTest['val_acc_metric']))

    if args.verbose > 1:
        print('Finished after {:.1f} min.'.format(
            (default_timer() - start) / 60))
Ejemplo n.º 10
0
    def forward(self, x):
        x = F.relu(F.max_pool2d(self.conv1(x), 2))
        x = F.relu(F.max_pool2d(self.conv2(x), 2))
        x = x.view(-1, 1600)
        x = F.relu(self.fc1(x))
        x = F.dropout(x, training=self.training)
        x = self.fc2(x)
        return F.log_softmax(x)


model = Network()
trainer = ModuleTrainer(model)

callbacks = [
    EarlyStopping(patience=20),
    ReduceLROnPlateau(factor=0.5, patience=5),
    CSVLogger('logs.csv')
]
regularizers = [
    L1Regularizer(scale=1e-3, module_filter='conv*'),
    L2Regularizer(scale=1e-5, module_filter='fc*')
]
constraints = [UnitNorm(frequency=3, unit='batch', module_filter='fc*')]
initializers = [XavierUniform(bias=False, module_filter='fc*')]
metrics = [CategoricalAccuracy(top_k=1)]

trainer.compile(loss='nll_loss',
                optimizer='adadelta',
                metrics=metrics,
                callbacks=callbacks)