Tensor和Numpy互相转换

常用的API例子

1 tensor转为numpy

ps:  gpu下的tensor不能直接转numpy,需要先转到cpu tensor后再转为numpy.cpu().numpy()

1.1 tensor.numpy()

x = torch.rand(6).view(2,3).type(torch.float32)

print(type(x))

x_array = x.numpy()

print(x_array,type(x_array))

output:

<class 'torch.Tensor'>

[[0.9542696  0.8235684  0.6300868 ]

[0.16127479 0.40761203 0.22885096]] <class 'numpy.ndarray'>

2 numpy转为tensor

2.1 torch.tensor(x)

x = np.array(3)

print(type(x))

x = torch.tensor(x)

print(type(x))

output:

<class 'numpy.ndarray'>

<class 'torch.Tensor'>

2.2 torch.as_tensor()

x = np.ones(5)

print(type(x))

x = torch.as_tensor(x,dtype=torch.float32)

print(x,type(x))

output:

&l

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在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 ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值