tensor 和 numpy 的互相转换

要对tensor进行操作,需要先启动一个Session,否则,我们无法对一个tensor比如一个tensor常量重新赋值或是做一些判断操作,所以如果将它转化为numpy数组就好处理了。下面一个小程序讲述了将tensor转化为numpy数组,以及又重新还原为tensor:

import tensorflow as tf
img1 = tf.constant(value=[[[[1],[2],[3],[4]],[[1],[2],[3],[4]],[[1],[2],[3],[4]],[[1],[2],[3],[4]]]],dtype=tf.float32)
img2 = tf.constant(value=[[[[1],[1],[1],[1]],[[1],[1],[1],[1]],[[1],[1],[1],[1]],[[1],[1],[1],[1]]]],dtype=tf.float32)
img = tf.concat(values=[img1,img2],axis=3)
sess=tf.Session()
#sess.run(tf.initialize_all_variables())
sess.run(tf.global_variables_initializer())
print("out1=",type(img))
#转化为numpy数组
img_numpy=img.eval(session=sess)
print("out2=",type(img_numpy))
#转化为tensor
img_tensor= tf.convert_to_tensor(img_numpy)
print("out2=",type(img_tensor))

输出:

out1= <class 'tensorflow.python.framework.ops.Tensor'>
out2= <class 'numpy.ndarray'>
out2= <class 'tensorflow.python.framework.ops.Tensor'>

参考资料:好的博客

在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 ]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值