当前位置:网站首页>【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 是共享内存的;所以数据肯定也是一致的。
边栏推荐
- 牛客 HJ18 识别有效的IP地址和掩码并进行分类统计
- Foreign media right, apple on May be true in inventory
- 多主复制的适用场景(2)-需离线操作的客户端和协作编辑
- The new BMW 3 Series is on the market, with safety and comfort
- ASP.NET Core generates continuous Guid
- 宁波大学NBU IT项目管理期末考试知识点整理
- 上传图片-微信小程序(那些年的坑记录2022.4)
- 使用 Postman 工具高效管理和测试 SAP ABAP OData 服务的试读版
- Codeforces Round #796 (Div. 2) (A-D)
- 6-22漏洞利用-postgresql数据库密码破解
猜你喜欢

How C programs run 01 - the composition of ordinary executable files

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

对话庄表伟:开源第一课

The 2nd China PWA Developer Day

Getting Started with TextBlock Control Basic Tools Usage, Get Started

i.MX6ULL driver development | 33 - NXP original network device driver reading (LAN8720 PHY)

Use of radiobutton

C程序是如何跑起来的01 —— 普通可执行文件的构成

The use of border controls

【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发
随机推荐
MySQL数据库操作
Foreign media right, apple on May be true in inventory
Grafana安装后web打开报错
mysql black window ~ build database and build table
动态规划(一)
Emmet syntax
How to switch remote server in gerrit
type of timer
tensorflow2.0 cnn(layerwise)
Precautions and solutions when SIGABRT error is reported
多主复制下处理写冲突(4)-多主复制拓扑
【7.29】代码源 - 【排列】【石子游戏 II】【Cow and Snacks】【最小生成数】【数列】
Tencent Cloud Deployment----DevOps
Kubernetes common commands
go图书管理系统
C程序是如何跑起来的01 —— 普通可执行文件的构成
C language - function
仿生毛毛虫机器人源码
Implement anti-shake and throttling functions
第二届中国PWA开发者日