tensor转成numpy的几种情况

下面将将tensor转成numpy的几种情况

  1. GPU中的Variable变量:

a.cuda().data.cpu().numpy()

  1. GPU中的tensor变量:

a.cuda().cpu().numpy()

  1. CPU中的Variable变量:
    a.data.numpy()

  2. CPU中的tensor变量:

a.numpy()

总结:

.cuda()是读取GPU中的数据

.data是读取Variable中的tensor

.cpu是把数据转移到cpu上

.numpy()把tensor变成numpy

转自:[https://www.jianshu.com/p/e9074a6f408d]

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在PyTorch中,将Tensor转换为NumPy数组有几种方法。一种常用的方法是使用`.numpy()`方法。这个方法将Tensor对象转换为NumPy数组,但是需要注意的是,只有当Tensor对象在CPU上时才能进行转换。因此,如果你的Tensor对象在GPU上,需要先将其转移到CPU上,然后再使用`.numpy()`方法进行转换。具体代码如下所示: ```python import torch import numpy as np # 创建一个Tensor对象 a = torch.tensor([1, 2, 3]) # 将Tensor对象转换为NumPy数组 b = a.cpu().numpy() # 打印转换后的结果 print(type(a)) print(type(b)) print(a) print(b) ``` 输出结果为: ``` <class 'torch.Tensor'> <class 'numpy.ndarray'> tensor([1, 2, 3]) <span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [TensorNumpy互相转换](https://blog.csdn.net/m0_56676881/article/details/126912457)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [tensornumpy转换资源合集](https://download.csdn.net/download/Rocky006/87842415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [pytorch 实现tensornumpy数组转换](https://download.csdn.net/download/weixin_38668225/13762306)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值