这段代码是合法的,但是报错信息显示了一个类型错误。根据报错信息,只有整数标量数组可以转换为标量索引。这意味着 top5_indices[i][j] 不是整数标量数组。

可能的原因是 top5_indices 列表中的元素类型不正确。您可以在使用 top5_indices.append(top5_indice.cpu().numpy()) 之前,将 top5_indice 转换为整数类型。例如,您可以使用 top5_indice.cpu().numpy().astype(int) 来确保 top5_indice 是整数类型的数组。

修改后的代码如下所示:

top5_probs, top5_indice = torch.topk(torch.softmax(output, dim=1), k=5)
top5_predictions.append(top5_probs.cpu().numpy())
top5_indices.append(top5_indice.cpu().numpy().astype(int))

这样修改后,您应该能够使用 top5_indices[i][j] 来访问元素。

PyTorch Top-K 错误:TypeError: only integer scalar arrays can be converted to a scalar index

原文地址: https://www.cveoy.top/t/topic/qfKG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录