gpt4 book ai didi

python - Can't convert cuda :0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory 先

转载 作者:行者123 更新时间:2023-12-05 01:07:55 34 4
gpt4 key购买 nike

我正在尝试展示 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

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

Can't convert cuda:0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first

最佳答案

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

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

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

关于python - Can't convert cuda :0 device type tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory 先,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66752458/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com