常用的创建Tensor函数
导入必要的torch包
import torch as t
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
- 生成一个tensor
a = t.Tensor(2,3)
a
out:tensor([[2.7489e+26, 1.7885e+22, 1.7743e+28],
[2.0535e-19, 1.6635e+22, 7.7781e+31]])
- 将python的list转为pytorch的tensor
b = t.Tensor([[1,2,3],[4,5,6]])
out:tensor([[1., 2., 3.],
[4., 5., 6.]])
因为这里的t.Tensor是等价于t.FloatTensor,是浮点类型,所以会将原来的整数list转为浮点数.
如果换成t.tensor就不会出现这种情况,如下:
b = t.tensor([[1,2,3],[4,5,6]])
out:tensor([[1, 2, 3],
[4, 5, 6]])
具体二者的区别,一个是调用的python类–>FloatTensor中的构造函数__init__(),另外一个是调用python函数。
3. 将tensor转成list
b.tolist()
out:[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
- 查看tensor的大小size(),shape
b_size = b.size()
b_size:torch.Size([2, 3])
- 生成对角矩阵.eye()
t.eye(2,3)
out:tensor([[1., 0., 0.],
[