当前位置:网站首页>【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 是共享内存的;所以数据肯定也是一致的。
边栏推荐
- The new BMW 3 Series is on the market, with safety and comfort
- Implement anti-shake and throttling functions
- 基于ABP实现DDD
- MySQL database operations
- Bilateral filtering acceleration "recommended collection"
- 【TypeScript】深入学习TypeScript类型操作
- Precautions and solutions when SIGABRT error is reported
- Visualize GraphQL schemas with GraphiQL
- 6-22 Vulnerability exploit - postgresql database password cracking
- form 表单提交后,使页面不跳转[通俗易懂]
猜你喜欢
i.MX6ULL driver development | 33 - NXP original network device driver reading (LAN8720 PHY)
二分查找的细节坑
Implementing distributed locks based on Redis (SETNX), case: Solving oversold orders under high concurrency
6-22漏洞利用-postgresql数据库密码破解
mysql black window ~ build database and build table
Unity 之 图集属性详解和代码示例 -- 拓展一键自动打包图集工具
mysql黑窗口~建库建表
The 2nd China PWA Developer Day
Why is the field of hacking almost filled with boys?
Graham‘s Scan法求解凸包问题
随机推荐
Single-cell sequencing workflow (single-cell RNA sequencing)
全新宝马3系上市,安全、舒适一个不落
复制延迟案例(3)-单调读
长得很怪的箱图
研发过程中的文档管理与工具
贪吃蛇项目(简单)
"Autumn Recruitment Series" MySQL Interview Core 25 Questions (with answers)
LevelSequence源码分析
TypeError: unhashable type: ‘list‘
MySQL常用语句整理
Design and Implementation of Compiler Based on C Language
How C programs run 01 - the composition of ordinary executable files
Kubernetes常用命令
利用PHP开发具有注册、登陆、文件上传、发布动态功能的网站
npm安装时卡在sill idealTree buildDeps,npm安装速度慢,npm安装卡在一个地方不动
动态规划之线性dp(下)
【7.29】Code Source - 【Arrangement】【Stone Game II】【Cow and Snacks】【Minimum Number of Spawns】【Sequence】
[Meetup Preview] OpenMLDB+OneFlow: Link feature engineering to model training to accelerate machine learning model development
【C语言】LeetCode27.移除元素
Character pointer assignment [easy to understand]