张量Tensors
判断是否是张量
torch.is_tensor(obj)
张量个数
torch.numel(a)
a = torch.randn(2,3,4,2)
print(torch.numel(a)) #48
张量的创建
torch.eye
创建2维张量,对角线位置全为1,其它位置全为0
torch.eye(n, m=None, out=None)
参数:
n 行数
m 列数,如果为None,则默认为n
out 结果张量
print(torch.eye(3))
1 0 0
0 1 0
0 0 1
torch.from_numpy
将numpy.ndarray转换为pytorch的Tensor
a = numpy.array([2,3,4])
t = torch.from_numpy(a)
print(t)
tensor([2, 3, 4], dtype=torch.int32)
t[0 = -1
print(a)
[-1 3 4]
torch.linspace
torch.linspace(start, end, steps=100, out=None)
返回一个1维张量
参数:
- start(float)-序列的第一个值
- end(float)-序列的最后一个值
- steps(int)-在start和end间生成的样本数
- out-结果张量
a = torch.linspace(3,10,steps=5)
print(a)
tensor([ 3.0000, 6.5000, 10.0000])
torch.ones
返回一个全为1的张量
a = torch.ones(2,3)
print(a)
tensor([[1., 1., 1.],
[1., 1., 1.]])
torch.rand
返回一个从区间(0,1)的均匀分布中抽取的随机数的张量
torch.randn
返回从标准正态分布(均值为0,方差为 1)的随机数的张量
torch.randperm
返回从0到n-1的随机整数的张量
torch.arange
参数
- start (float) – 序列的起始点
- end (float) – 序列的终止点
- step (float) – 相邻点的间隔大小
- out (Tensor, optional) – 结果张量
a = torch.arange(1,4,0.5)
print(a)
tensor([1.0000, 1.5000, 2.0000, 2.5000, 3.0000, 3.5000])
torch.zeros
返回一个标量0的张量