1. 32位浮点型:torch.FloatTensor
a=torch.Tensor( [[2,3],[4,8],[7,9]], )
print "a:",a
print "a.size():",a.size()
print "a.dtype:",a.dtype
b=torch.FloatTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype
可以看出 torch.FloatTensor 是32位float类型,并且torch.Tensor默认的数据类型是32位float类型。
2. 64位浮点型:torch.DoubleTensor
b=torch.DoubleTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype
3. 16位整型:torch.ShortTensor
b=torch.ShortTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype
4. 32位整型:torch.IntTensor
b=torch.IntTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype
5. 64位整型:torch.LongTensor
b=torch.LongTensor( [[2,3],[4,8],[7,9]] )
print "b:",b
print "b.shape:",b.shape
print "b.dtype:",b.dtype
6. 快速创建Tensor
(1) torch.zeros()
a=torch.zeros( size=(4,5),dtype=torch.float32 )
print a
print a.shape
print a.dtype
(2) torch.randn()
a=torch.randn( size=(4,5),dtype=torch.float32 )
print a
print a.shape
print a.dtype
7. Tensor索引方式,参考numpy
8. Tensor和numpy数组转换:
(1) Tensor转numpy,
a=torch.randn( size=(4,5),dtype=torch.float32 )
print a
print a.shape
print a.dtype
b= a.numpy()
print b
print b.shape
print b.dtype
(2) numpy转Tensor,
a=np.random.randn(4,3)
print a
print a.shape
print a.dtype
b=torch.from_numpy( a )
print b
print b.shape
print b.dtype
9.更改Tensor的数据类型,
a=torch.FloatTensor( (3,2) )
print a
print a.shape
print a.dtype
a.int()
print a
print a.shape
print a.dtype
10. GPU加速,如果pytorch支持GPU加速,可以加Tensor放到GPU执行,
if torch.cuda.is_available():
a_cuda = a.cuda()