python - 无法将 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() 将张量复制到主机内存
解决方案
我假设 G_net 是您的网络。看起来您将网络存储在 GPU 中,因此返回的结果 test_images 也将在 GPU 中。您需要将其移动到 cpu 并转换为 numpy:
#test_images = G_net(z_)
test_images = G_net(z_).detach().cpu().numpy()
这将从图中分离张量,移动到 cpu,然后转换为 numpy。
推荐阅读
- html - `form` 和 `:hover` 之间的分隔符(空格)如何在 CSS 中的“form :hover { property:value }”中将样式应用于表单的所有元素?
- nginx - access_by_lua 和 content_by_lua 引用 nginx.conf 中的 lua 脚本有什么区别?
- paypal - Paypal:抱歉,我们无法使用您选择的付款方式设置您的订阅。请尝试其他付款方式
- animation - 是否有可能在现代浏览器中获得一致的 apng 支持?
- javascript - 使用 plotly-js 绘制多个支持 extendTrace 的变量
- c++ - CRC4 INTERLAKEN 和 ITU 查找表生成
- vuejs2 - v-text-field 中的多个验证规则
- typescript - 对象的 TypeScript 类型,指定了一个属性类型,而所有其他属性类型都是不同的类型
- flutter - 无法在 VS Code 中调试颤振飞镖代码,未验证断点错误
- material-ui - 有条件地在 MUI 上添加样式属性