pytorch基本数据类型

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2020/3/11 13:57
# @Author  : zhoujianwen
# @Email   : [email protected]
# @File    : typecheck.py
# @Describe: pytorch基本数据类型
import torch
import numpy as np

# 随机正态分布生成二行三列的tensor数据,第一维是2,第二维是3,其dim是2
a = torch.randn(2,3)
print("shape:",a.shape,"\nsize:",a.size())
shape: torch.Size([2, 3]) 
size: torch.Size([2, 3])
print("第二个维度的信息:",a.size(1))
第二个维度的信息: 3
print("dim:",a.dim())
dim: 2
k = torch.rand(1,2,3)  # 使用随机均匀分布,数据分布范围在[0,1]
print("k:",k)
k: tensor([[[0.0964, 0.8898, 0.1816],
         [0.7350, 0.5357, 0.1356]]])
print("k[0]:",k[0])
k[0]: tensor([[0.0964, 0.8898, 0.1816],
        [0.7350, 0.5357, 0.1356]])
print(list(k.shape))
[1, 2, 3]
print(torch.tensor(1.))
tensor(1.)
print(torch.tensor(1.3))
tensor(1.3000)
print(isinstance(a,torch.FloatTensor))
True
print(isinstance(a,torch.cuda.FloatTensor))
False
a = a.cuda()
print(isinstance(a,torch.cuda.FloatTensor))
True
b = torch.randn(2,3)
print(b)
tensor([[ 0.4233,  0.7711, -0.6087],
        [ 1.4722,  1.3866, -0.4094]])
print(len(b.shape))
2
print(b.shape)
torch.Size([2, 3])
print(b.size())
torch.Size([2, 3])
print("dim:",b.dim())
dim: 2
print(len(torch.tensor(1.).shape))
0
print(torch.tensor(1.).size())
torch.Size([])
c = torch.FloatTensor(3)
print(c)
tensor([1.4013e-45, 0.0000e+00, 2.8399e-29])
print(c.shape)  # size/shape表达tensor具体的形状
torch.Size([3])
print(c.dim())  # dim表达size/shape的长度
1
print(len(c.shape))
1
print(torch.tensor([1.2,2,2]))
tensor([1.2000, 2.0000, 2.0000])
print(torch.tensor([1.2,2,2]).shape)
torch.Size([3])
print(len(torch.tensor([1.2,2,2])))
3
print("torch.version:",torch.__version__)
torch.version: 1.3.1
data = np.ones(2)
print(data)
[1. 1.]
d = torch.rand(2,3,28,28)
print("size:",d.shape)
size: torch.Size([2, 3, 28, 28])
print("dim:",d.dim())
dim: 4
print("numel:",d.numel())  # numel是指tensor占用内存的数量 d.numel() = 2*3*28*28
numel: 4704
print("numel = 2*3*28*28 = ",d.size(0)*d.size(1)*d.size(2)*d.size(3))
numel = 2*3*28*28 =  4704
print("len:",len(d.shape))
len: 4
发布了40 篇原创文章 · 获赞 0 · 访问量 1531

猜你喜欢

转载自blog.csdn.net/zhoumoon/article/details/104888027
今日推荐