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

问题描述

我试图在一些指定的时期展示 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() 将张量复制到主机内存

标签: pythonplotpytorchgenerative-adversarial-network

解决方案


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

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

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


推荐阅读