Ejemplo n.º 1
0
def train(epochs=10, batchSize=1024, lr=0.001, dim=128, eva_per_epochs=1):
    #读取数据
    train, test, allItems = dp.getTrainAndTestSeqs(fp.Ml_latest_small.SEQS)
    #初始化模型
    net = RNN_ALS_rec(max(allItems) + 1, dim)
    #定义损失函数
    criterion = torch.nn.BCELoss()
    #初始化优化器
    optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=5e-3)
    #开始训练
    for e in range(epochs):
        all_lose = 0
        for seq in DataLoader(
                train,
                batch_size=batchSize,
                shuffle=True,
        ):
            x = torch.LongTensor(seq[:, :-2].detach().numpy())
            item = torch.LongTensor(seq[:, -2].detach().numpy())
            y = torch.FloatTensor(seq[:, -1].detach().numpy())
            optimizer.zero_grad()
            logits = net(x, item)
            loss = criterion(logits, y)
            all_lose += loss
            loss.backward()
            optimizer.step()
        print('epoch {},avg_loss={:.4f}'.format(
            e, all_lose / (len(train) // batchSize)))

        #评估模型
        if e % eva_per_epochs == 0:
            p, r, acc = doEva(net, train)
            print('train:p:{:.4f}, r:{:.4f}, acc:{:.4f}'.format(p, r, acc))
            p, r, acc = doEva(net, test)
            print('test:p:{:.4f}, r:{:.4f}, acc:{:.4f}'.format(p, r, acc))
Ejemplo n.º 2
0
def train(epochs=10, batchSize=1024, lr=0.001, dim=128, eva_per_epochs=1):
    #读取数据
    train, test, allItems = dp.getTrainAndTestSeqs(fp.Ml_latest_small.SEQS)

    all_seq_lens = len(train[0]) - 1
    #初始化模型
    net = Transformer4Rec(max(allItems) + 1, all_seq_lens, dim)
    #初始化优化器
    optimizer = torch.optim.AdamW(net.parameters(), lr=lr, weight_decay=5e-3)
    #开始训练
    for e in range(epochs):
        all_lose = 0
        for seq in tqdm(DataLoader(train, batch_size=batchSize, shuffle=True)):
            x = torch.LongTensor(seq[:, :-2].detach().numpy())
            history_seqs = torch.LongTensor(seq[:, 1:-1].detach().numpy())
            target_item = torch.LongTensor(seq[:, -2].detach().numpy())
            target_label = torch.FloatTensor(seq[:, -1].detach().numpy())

            optimizer.zero_grad()
            loss = net(x, history_seqs, target_item, target_label)
            all_lose += loss
            loss.backward()
            optimizer.step()
        print('epoch {},avg_loss={:.4f}'.format(
            e, all_lose / (len(train) // batchSize)))

        #评估模型
        if e % eva_per_epochs == 0:
            p, r, acc = doEva(net, train)
            print('train:p:{:.4f}, r:{:.4f}, acc:{:.4f}'.format(p, r, acc))
            p, r, acc = doEva(net, test)
            print('test:p:{:.4f}, r:{:.4f}, acc:{:.4f}'.format(p, r, acc))