How to convert Pytorch autograd.Variable to Numpy?(如何将 Pytorch autograd.Variable 转换为 Numpy?)
问题描述
标题说明了一切.我想将 PyTorch autograd.Variable
转换为其等效的 numpy
数组.在他们的官方文档中,他们提倡使用a.numpy()
获取等效的 numpy
数组(用于 PyTorch 张量
).但这给了我以下错误:
回溯(最近一次调用最后一次):文件stdin",第 1 行,在模块中文件"/home/bishwajit/anaconda3/lib/python3.6/site-packages/torch/autograd/variable.py",第 63 行,在 getattr 中引发 AttributeError(name) AttributeError:麻木
有什么办法可以绕过这个吗?
两种可能的情况
使用 GPU:如果您尝试将 cuda 浮点张量直接转换为 numpy,如下所示,它将引发错误.
<块引用>x.data.numpy()
运行时错误:不支持 FloatTensor 的 numpy 转换
因此,您不能将 cuda 浮点张量直接转换为 numpy,相反,您必须先将其转换为 cpu 浮点张量,然后尝试转换为 numpy,如下所示.><块引用>
x.data.cpu().numpy()
使用 CPU: 转换 CPU 张量很简单.
<块引用>x.data.numpy()
The title says it all. I want to convert a PyTorch autograd.Variable
to its equivalent numpy
array. In their official documentation they advocated using a.numpy()
to get the equivalent numpy
array (for PyTorch tensor
). But this gives me the following error:
Traceback (most recent call last): File "stdin", line 1, in module File "/home/bishwajit/anaconda3/lib/python3.6/site-packages/torch/autograd/variable.py", line 63, in getattr raise AttributeError(name) AttributeError: numpy
Is there any way I can circumvent this?
Two possible case
Using GPU: If you try to convert a cuda float-tensor directly to numpy like shown below,it will throw an error.
x.data.numpy()
RuntimeError: numpy conversion for FloatTensor is not supported
So, you cant covert a cuda float-tensor directly to numpy, instead you have to convert it into a cpu float-tensor first, and try converting into numpy, like shown below.
x.data.cpu().numpy()
Using CPU: Converting a CPU tensor is straight forward.
x.data.numpy()
这篇关于如何将 Pytorch autograd.Variable 转换为 Numpy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 Pytorch autograd.Variable 转换为 Numpy?


基础教程推荐
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01