当前位置:网站首页>【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 是共享内存的;所以数据肯定也是一致的。
边栏推荐
- Character pointer assignment [easy to understand]
- 上传图片-微信小程序(那些年的坑记录2022.4)
- MySQL database operations
- 牛客网刷题(四)
- ML.NET相关资源整理
- jeecg master-slave database read-write separation configuration "recommended collection"
- 仿生毛毛虫机器人源码
- 【7.28】代码源 - 【Fence Painting】【合适数对(数据加强版)】
- 6. 使用 Postman 工具高效管理和测试 SAP ABAP OData 服务
- Kubernetes principle analysis and practical application manual, too complete
猜你喜欢

EF Core 2.2中将ORM框架生成的SQL语句输出到控制台

Kubernetes common commands

动态规划(一)

Unity 之 图集属性详解和代码示例 -- 拓展一键自动打包图集工具

C language "the third is" upgrade (mode selection + AI chess)

mysql black window ~ build database and build table
![[TypeScript] In-depth study of TypeScript type operations](/img/d9/ee240ccba72e8d3114ee5c52ed0c8f.png)
[TypeScript] In-depth study of TypeScript type operations

【C语言】LeetCode27.移除元素

第05章 存储引擎【1.MySQL架构篇】【MySQL高级】

.NET 20周年专访 - 张善友:.NET 技术是如何赋能并改变世界的
随机推荐
苹果官网样式调整 结账时产品图片“巨大化”
t-sne 数据可视化网络中的部分参数+
LeetCode_733_Image rendering
百度网盘网页版加速播放(有可用的网站吗)
深度学习机器学习理论及应用实战-必备知识点整理分享
研发过程中的文档管理与工具
go图书管理系统
Stuck in sill idealTree buildDeps during npm installation, npm installation is slow, npm installation is stuck in one place
The use of border controls
研发过程中的文档管理与工具
update data table update
Applicable Scenarios of Multi-Master Replication (1) - Multi-IDC
type of timer
牛客 HJ18 识别有效的IP地址和掩码并进行分类统计
Matlab matrix basic operations (definition, operation)
Oracle动态注册非1521端口
mysql黑窗口~建库建表
i.MX6ULL驱动开发 | 33 - NXP原厂网络设备驱动浅读(LAN8720 PHY)
数据表插入数据insert into
牛客网刷题(一)