コード例 #1
0
def train(model, criterion, optimizer, scheduler, epoch, batch_size, use_cuda,
          train_ratings, negatives, n_items, n_neg):
    model.train()
    train_dataset = get_train_instances(train_ratings, negatives, n_items,
                                        n_neg)
    train_loader = DataLoader(dataset=train_dataset,
                              batch_size=batch_size,
                              num_workers=4,
                              shuffle=True)
    train_steps = (len(train_loader.dataset) // train_loader.batch_size) + 1
    running_loss = 0
    for data in train_loader:
        users = data[:, 0]
        items = data[:, 1]
        labels = data[:, 2].float()
        if use_cuda:
            users, items, labels = users.cuda(), items.cuda(), labels.cuda()
        optimizer.zero_grad()
        preds = model(users, items)
        if scheduler:
            scheduler.step()
        loss = criterion(preds.squeeze(1), labels)
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
    return running_loss / train_steps
コード例 #2
0
        model.compile(optimizer=optimizers.SGD(lr=configs.learning_rate),
                      loss='binary_crossentropy')
    """
    # --------------Init performance--------------
    t1 = time()
    (hits, ndcgs) = evaluate_model(model, testRatings, testNegatives, configs.topK)
    hr, ndcg = np.array(hits).mean(), np.array(ndcgs).mean()
    print('Init: HR = %.4f, NDCG = %.4f [%.1f s]' % (hr, ndcg, time() - t1))
    """
    # --------------Train model-----------------
    # best_hr, best_ndcg, best_iter = hr, ndcg, -1
    for epoch in range(configs.epochs):
        t1 = time()

        # Generate training instances
        user_input, item_input, labels = get_train_instances(
            train, configs.num_negatives)
        print('Get_train_instances [%.1f s]' % (time() - t1))
        t1 = time()
        # --------------Fit model----------------
        hist = model.fit(
            [np.array(user_input), np.array(item_input)],
            np.array(labels),
            batch_size=configs.batch_size,
            epochs=1,
            verbose=configs.verbose,
            shuffle=True)
        t2 = time()
        """
        # --------------Evaluation--------------
        if epoch % configs.verbose == 0:
            (hits, ndcgs) = evaluate_model(model, testRatings, testNegatives, configs.topK)