异常:IndexError: tensors used as indices must be long, byte or bool tensors

异常:IndexError: tensors used as indices must be long, byte or bool tensors

详细异常

Traceback (most recent call last):
  File "D:/PythonCode/pytorch131/UltraGCN-main/main.py", line 624, in <module>
    train(ultragcn, optimizer, train_loader, test_loader, mask, test_ground_truth_list, interacted_items, params)
  File "D:/PythonCode/pytorch131/UltraGCN-main/main.py", line 410, in train
    loss = model(users, pos_items, neg_items)
  File "C:\anaconda3\envs\pytorch131\lib\site-packages\torch\nn\modules\module.py", line 532, in __call__
    result = self.forward(*input, **kwargs)
  File "D:/PythonCode/pytorch131/UltraGCN-main/main.py", line 359, in forward
    omega_weight = self.get_omegas(users, pos_items, neg_items)
  File "D:/PythonCode/pytorch131/UltraGCN-main/main.py", line 300, in get_omegas
    pos_weight = self.constraint_mat[users * self.item_num + pos_items].to(device)
IndexError: tensors used as indices must be long, byte or bool tensors
# 错误语句
pos_weight = self.constraint_mat[users * self.item_num + pos_items].to(device)

这个异常不是一个单一异常,后面所有用的 user, pos_items, neg_items 等等语句都可能报这个异常。

所以要找到根源的 user, pos_items, neg_items 变量。

说明,每个代码的异常变量都不一样,要测试好是那个变量的问题。可以通过逐一改变变量的类型(.long())测试。

我的根源语句是

users = users.to(device)
pos_items = pos_items.to(device)
neg_items = neg_items.to(device)

改正后

users = users.long().to(device)
pos_items = pos_items.long().to(device)
neg_items = neg_items.long().to(device)

看的其他的解答,pytorch框架 下long() 也可以换为.type(torch.long)

猜你喜欢

转载自blog.csdn.net/qq_38463737/article/details/121742453