【问题标题】:Can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first无法将 cuda:0 设备类型张量转换为 numpy。首先使用 Tensor.cpu() 将张量复制到主机内存
【发布时间】:2021-06-19 11:25:44
【问题描述】:

我正在尝试展示 GAN 网络在某些指定时期的结果。打印当前结果的功能以前与 TF 一起使用。我需要换成 pytorch。

def show_result(G_net, z_, num_epoch, show=False, save=False, path='result.png'):


  #test_images = sess.run(G_z, {z: z_, drop_out: 0.0})
  test_images = G_net(z_)

  size_figure_grid = 5
  fig, ax = plt.subplots(size_figure_grid, size_figure_grid, figsize=(5, 5))

  for i, j in itertools.product(range(size_figure_grid), range(size_figure_grid)):
     ax[i, j].get_xaxis().set_visible(False)
     ax[i, j].get_yaxis().set_visible(False)

  for k in range(5*5):
     i = k // 5
     j = k % 5
     ax[i, j].cla()
     ax[i, j].imshow(np.reshape(test_images[k], (28, 28)), cmap='gray')

  label = 'Epoch {0}'.format(num_epoch)
  fig.text(0.5, 0.04, label, ha='center')

  plt.savefig(name)
  file = drive.CreateFile({'title': label, "parents": [{"kind": "https://drive.google.com/drive/u/0/folders/", "id": folder_id}]})
  file.SetContentFile(name)
  file.Upload()

  if num_epoch == 10 or num_epoch == 20 or num_epoch == 50 or num_epoch == 100:
     plt.show()
    
  plt.close()

我需要得到的结果是这样的: result img

我收到此错误,但我不确定我做错了什么

无法将 cuda:0 设备类型张量转换为 numpy。首先使用 Tensor.cpu() 将张量复制到主机内存

【问题讨论】:

    标签: python plot pytorch generative-adversarial-network


    【解决方案1】:

    我假设 G_net 是您的网络。看起来您将网络存储在 GPU 中,因此返回的结果 test_images 也将在 GPU 中。您需要将其移动到 cpu 并转换为 numpy:

    #test_images = G_net(z_)
    test_images = G_net(z_).detach().cpu().numpy()
    

    这将从图中分离张量,移动到 cpu,然后转换为 numpy。

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2019-05-22
      • 2020-07-28
      • 2021-03-09
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      相关资源
      最近更新 更多