当前位置:网站首页>【pytorch】1.7 pytorch与numpy,tensor与array的转换
【pytorch】1.7 pytorch与numpy,tensor与array的转换
2022-07-31 16:15:00 【Enzo 想砸电脑】
1、pytorch与numpy 函数对比
2、tensor与ndarray的转换
torch.Tensor(array)torch.tensor(array)torch.as_tensor(array)torch.from_array(array)
import torch
import numpy as np
array = np.array([1,2,3,4])
print(array.dtype) #int64
# 用4种方式 将numpy array转换为torch tensor
tensor = torch.tensor(array)
Tensor = torch.Tensor(array)
as_tensor = torch.as_tensor(array)
from_array = torch.from_numpy(array)
# ====== 对比几种不同方法之间的异同 =========
print(tensor.dtype) #torch.int64
print(Tensor.dtype) #torch.float32
print(as_tensor.dtype) #torch.int64
print(from_array.dtype) #torch.int64
# ========== 判断是否共享内存 ===========
#修改数组的值
array[0] = 10
print(tensor) #tensor([1, 2, 3, 4])
print(Tensor) #tensor([1., 2., 3., 4.])
print(as_tensor) #tensor([10, 2, 3, 4])
print(from_array) #tensor([10, 2, 3, 4])
结论:
1)torch.Tensor() 和 torch.tensor() 在转换的时候,是开辟了新的内存空间来存储tensor的。
- torch.Tensor 在生成tensor的时候,默认生成 float数据类型
- torch.tensor 是根据的情况来推断长生什么样的数据类型。
2)torch.as_tensor() 和 torch.from_array() 转换的tensor,和 numpy array 是共享内存的;所以数据肯定也是一致的。
边栏推荐
- Implementing click on the 3D model in RenderTexture in Unity
- 6-22漏洞利用-postgresql数据库密码破解
- gerrit中如何切换远程服务器
- Visualize GraphQL schemas with GraphiQL
- BGP综合实验(建立对等体、路由反射器、联邦、路由宣告及聚合)
- 2020 WeChat applet decompilation tutorial (can applet decompile source code be used)
- The normal form of the database (first normal form, second normal form, third normal form, BCNF normal form) "recommended collection"
- 2020微信小程序反编译教程(小程序反编译源码能用吗)
- 在资源管理类中提供对原始资源的访问——条款15
- The use of border controls
猜你喜欢
随机推荐
LeetCode_733_Image rendering
2022年必读的12本机器学习书籍推荐
Replication Latency Case (1) - Eventual Consistency
The principle of hough transform detection of straight lines (opencv hough straight line detection)
MySQL multi-table union query
mongo enters error
百度网盘网页版加速播放(有可用的网站吗)
基于Redis(SETNX)实现分布式锁,案例:解决高并发下的订单超卖,秒杀
2022年整理LeetCode最新刷题攻略分享(附中文详细题解)
C language "the third is" upgrade (mode selection + AI chess)
How to switch remote server in gerrit
数据表插入数据insert into
长得很怪的箱图
动态规划之线性dp(上)
牛客网刷题(一)
Implement anti-shake and throttling functions
Replication Latency Case (3) - Monotonic Read
MySQL的相关问题
11 pinia use
外媒所言非虚,苹果降价或许是真的在清库存









