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.FloatTensor
    64位浮点型:torch.float64
    16位浮点型:torch.float16
    64位整型:torch.in64/torch.long(常用),相当于torch.LongTensor
    32位整型:torch.int32
    16位整型:torch.int16
    8位整型: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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值