当前位置: 首页 > news >正文

1-Pytorch初始化张量和张量的类型

1-Pytorch初始化张量和张量的类型

1 导入必备库

import torch
import numpy as np

2 初始化张量

# 初始化张量
t = torch.tensor([1,2])#.type(torch.FloatTensor)
print(t)
print(t.dtype)

输出:

tensor([1, 2])
torch.int64

3 创建float型张量

# 创建float型张量
t = torch.FloatTensor([1,2])
print(t)
print(t.dtype)t = torch.LongTensor([1,2])#int型
print(t)
print(t.dtype)

输出:

tensor([1., 2.])
torch.float32
tensor([1, 2])
torch.int64

4 从Numpy数组ndarray创建张量

# 从Numpy数组ndarray创建张量
np_array = np.array([[1,2],[3,4]])
t_np = torch.from_numpy(np_array)#.type(torch.int32)
print(t_np)'''张量的ndarray类型主要包含:32位浮点型:torch.float32/torh.float(常用),相当于torch.FloatTensor64位浮点型:torch.float6416位浮点型:torch.float1664位整型:torch.in64/torch.long(常用),相当于torch.LongTensor32位整型:torch.int3216位整型:torch.int168位整型:torch.int8
'''
print(torch.float == torch.float32)
print(torch.long == torch.int64)

输出:

tensor([[1, 2],[3, 4]], dtype=torch.int32)
True
True

5 构建张量时用dtype明确其类型,或者用type

# 构建张量时用dtype明确其类型,或者用type
t = torch.tensor([[1, 2],[3, 4]], dtype=torch.int32)
print(t)
print(t.dtype)t = torch.tensor([[1, 2],[3, 4]]).type(torch.int32)
print(t)
print(t.dtype)

输出:

tensor([[1, 2],[3, 4]], dtype=torch.int32)
torch.int32
tensor([[1, 2],[3, 4]], dtype=torch.int32)
torch.int32

6 等价转换int64和float32

t = torch.tensor([[1, 2],[3, 4]]).type(torch.int32)
print(t)
print(t.dtype)t = t.long()    #等同int64
print(t)
print(t.dtype)t = t.float()   #等同float32
print(t)
print(t.dtype)

输出:

tensor([[1, 2],[3, 4]], dtype=torch.int32)
torch.int32
tensor([[1, 2],[3, 4]])
torch.int64
tensor([[1., 2.],[3., 4.]])
torch.float32
http://www.lryc.cn/news/160566.html

相关文章:

  • 诊断网络卡的原因
  • 100万级连接,爱奇艺WebSocket网关如何架构
  • 当电脑遇到msvcp110.dll丢失怎么办?最新解决方法分享
  • 微信小程序自动化测试pytest版工具使用方法
  • React 与 TS 结合使用时的技巧总结
  • 【深入解析spring cloud gateway】07 自定义异常返回报文
  • 如何写一个sh脚本将一个本地文件通过 scp命令上传到远程的 centos服务器?
  • 【CMake工具】工具CMake编译轻度使用(C/C++)
  • 用Navicat备份Mysql演示系统数据库的时候出:Too Many Connections
  • 知识储备--基础算法篇-矩阵
  • Zabbix -- QQ邮箱报警
  • eclipse链接MySQL数据库
  • ansible 使用roles简单部署LAMP平台
  • 如何使用Web Storage对页面中数据进行监听?
  • GO语言网络编程(并发编程)runtime包
  • MR源码解析和join案例
  • ML+LLMs:利用LLMs大语言模型赋能或者结合ML机器学习算法进行具体应用的简介、具体案例之详细攻略
  • python GIL锁
  • git打tag和版本控制规范
  • php版 短信跳转微信小程序
  • leetcode127单词接龙刷题打卡
  • 基于SSM的物流管理系统
  • EagleSDR USB HAT FT600
  • Java多线程(四)锁策略(CAS,死锁)和多线程对集合类的使用
  • 基于spring boot+ vue+ mysql开发的UWB室内外定位系统源码
  • 第2章_瑞萨MCU零基础入门系列教程之面向过程与面向对象
  • 数字图像处理:亮度对比度-几何变换-噪声处理
  • maven报错:[ERROR] 不再支持源选项 7。请使用 8 或更高版本。
  • MySQL基础3-约束
  • OJ练习第166题——课程表(拓扑排序问题)