【问题标题】:Can't call numpy() on Tensor that requires grad无法在需要 grad 的张量上调用 numpy()
【发布时间】:2021-07-01 12:58:32
【问题描述】:

我有一个变量losses_all = [],我想将其转换为 np.array。我尝试使用代码这样做并收到以下错误:

# convert to numpy array
losses = np.array(losses_all)

# ERROR MESSAGE
RuntimeError: Can't call numpy() on Tensor that requires grad. Use tensor.detach().numpy() instead.

我也试过了,但出现以下错误:

# using code from error message above
losses=losses_all.detach().numpy()

# NEW ERROR MESSAGE
AttributeError: 'list' object has no attribute 'detach'

还有其他方法可以将此变量转换为数组吗?

【问题讨论】:

    标签: python list numpy tensor


    【解决方案1】:

    您正在列表变量上调用 numpy 数组。如果你的列表 loss_all 有不同的张量值,那么

    这样调用:

    losses= [ loss.detach().numpy() for loss in losses_all]
    

    【讨论】:

      猜你喜欢
      • 2021-11-11
      • 2023-04-09
      • 2019-08-23
      • 1970-01-01
      • 2019-07-17
      • 2020-03-26
      • 2021-07-23
      • 2020-08-31
      • 2020-06-25
      相关资源
      最近更新 更多