当前位置:网站首页>【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 是共享内存的;所以数据肯定也是一致的。
边栏推荐
- 网站漏洞修复服务商关于越权漏洞分析
- Kubernetes principle analysis and practical application manual, too complete
- C语言”三子棋“升级版(模式选择+AI下棋)
- Dialogue with Zhuang Biaowei: The first lesson of open source
- arm按键控制led灯闪烁(嵌入式按键实验报告)
- Kubernetes常用命令
- Premiere Pro 2022 for (pr 2022)v22.5.0
- [TypeScript] In-depth study of TypeScript type operations
- 【7.29】Code Source - 【Arrangement】【Stone Game II】【Cow and Snacks】【Minimum Number of Spawns】【Sequence】
- mysql black window ~ build database and build table
猜你喜欢

长得很怪的箱图

仿生毛毛虫机器人源码

After Grafana is installed, the web opens and reports an error

Kubernetes常用命令

The use of border controls

js的toString方法

Internet banking stolen?This article tells you how to use online banking safely

tooltips使用教程(鼠标悬停时显示提示)

【Meetup预告】OpenMLDB+OneFlow:链接特征工程到模型训练,加速机器学习模型开发

【7.29】代码源 - 【排列】【石子游戏 II】【Cow and Snacks】【最小生成数】【数列】
随机推荐
How Redis handles concurrent access
.NET 20th Anniversary Interview - Zhang Shanyou: How .NET technology empowers and changes the world
Kubernetes principle analysis and practical application manual, too complete
go图书管理系统
Kubernetes common commands
贪吃蛇项目(简单)
arm按键控制led灯闪烁(嵌入式按键实验报告)
Qt practical cases (54) - using transparency QPixmap design pictures
Precautions and solutions when SIGABRT error is reported
长得很怪的箱图
TypeError: unhashable type: ‘list‘
js的toString方法
牛客网刷题(三)
Doing things software development - the importance of law and understanding of reasonable conclusions
LeetCode_733_Image rendering
tensorflow2.0 cnn(layerwise)
Delete the disk in good condition (recovery partition)
Tencent Cloud Deployment----DevOps
7. Summary of common interview questions
复杂高维医学数据挖掘与疾病风险分类研究