Pytorch學習筆記2:tensor變量的創(chuàng)建測試代碼
#直接復制到pycharm就能夠運行,這里演示的是常用的tensor創(chuàng)建方式,有注釋可以參考。
import torch
import numpy as np
print('——————————系統(tǒng)環(huán)境——————————')
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('——————————系統(tǒng)環(huán)境——————————')
print()
print('——————————創(chuàng)建變量——————————')
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正態(tài)分布數據,接收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('——————————創(chuàng)建變量——————————')