Pytorch学习笔记2:tensor变量的创建测试代码
#直接复制到pycharm就能够运行,这里演示的是常用的tensor创建方式,有注释可以参考。
import torch
import numpy as np
print('——————————系统环境——————————')
import torch
print('Torch Version:',torch.__version__)
print('CUDA GPU check:',torch.cuda.is_available())
if(torch.cuda.is_available()):
print('CUDA GPU num:', torch.cuda.device_count())
n=torch.cuda.device_count()
while n > 0:
print('CUDA GPU name:', torch.cuda.get_device_name(n-1))
print('CUDA GPU capability:', torch.cuda.get_device_capability(n-1))
print('CUDA GPU properties:', torch.cuda.get_device_properties(n-1))
n -= 1
print('CUDA GPU index:', torch.cuda.current_device())
print('——————————系统环境——————————')
print()
print('——————————创建变量——————————')
a=torch.tensor([2.,3.3])#接受数字的tensor方法
print('variable created:',a.type())
print(a)
print()
b=torch.FloatTensor(2,3,3)#接受shape的Tensor方法,两行三列,每个位置有三个元素
print('variable created:',b.type())
print(b)
print()
n=np.array([[2.2,3.3,4.4],[2.2,3.3,4.4],[2.2,3.3,4.4]])#导入numpy数据
m=torch.from_numpy(n)
print('variable created:',m.type())
print(m)
print()
torch.set_default_tensor_type(torch.DoubleTensor)#改变生成的tensor类型
torch.set_default_tensor_type(torch.FloatTensor)#改变生成的tensor类型
c=torch.tensor([[[2.,3.],[4.,5.5],[5.6,5.]],[[2.,3.],[4.,5.5],[5.6,5.]]])
print('variable created:',c.type())
print(c)
print()
d=torch.rand(3,3)#0-1均匀分布
print('variable created:',d.type())
print(d)
print()
e=torch.rand_like(b)#根据一个tensor的shape填入0-1均匀分布的数据
print('variable created:',e.type())
print(e)
print()
f=torch.randint(1,10,[3,3])#在3x3的tensor内生成1-10均匀分布的整数
print('variable created:',f.type())
print(f)
print()
g=torch.randn(4,4)#生成0-1正态分布数据,接收tensor的shape
print('variable created:',g.type())
print(g)
print()
h=torch.full([4,4],6,dtype=torch.int16)#生成3x3的tensor,里面填充4.pytorch1.6要求指定dtype,否则会报错
#https://pytorch.org/docs/stable/tensor_attributes.html#torch.torch.dtype
print('variable created:',h.type())
print(h)
print()
i=torch.arange(0,16,1)#生成等差数列,这里差为1
print('variable created:',i.type())
print(i)
print()
j=torch.linspace(0,10,5)#0-10等分切割
print('variable created:',j.type())
print(j)
print()
k=torch.logspace(0,-1,steps=10)#log的指数序列,指数为0到-1的等差数列
print('variable created:',k.type())
print(k)
print()
o=torch.ones(3,3,dtype=torch.int16)#生成3x3全部是1的tensor
print('variable created:',o.type())
print(o)
print()
p=torch.zeros(3,3)#生成3x3全部是0的tensor
print('variable created:',p.type())
print(p)
print()
q=torch.eye(3,3)#生成对角矩阵
print('variable created:',q.type())
print(q)
print()
r=torch.randperm(10)#随机种子
print('variable created:',r.type())
print(r)
print()
print('——————————创建变量——————————')