『PyTorch』第五弹_深入理解Tensor对象_上:初始化以及尺寸调整

一、创建Tensor

特殊方法:

t.arange(1,6,2)
t.linspace(1,10,3)
t.randn(2,3) # 标准分布,*size
t.randperm(5) # 随机排序,从0到n
t.normal(means=t.arange(0, 11), std=t.arange(1, 0, -0.1))

概览:

"""创建空Tensor"""
a = t.Tensor(2, 3)
# 创建和b大小一致的Tensor
c = t.Tensor(a.size())
print(a,c) # 数值取决于内存空间状态
-9.6609e+30  7.9594e-43 -4.1334e+27
7.9594e-43 -4.1170e+27 7.9594e-43
[torch.FloatTensor of size 2x3] -9.6412e+30 7.9594e-43 -9.6150e+30
7.9594e-43 -4.1170e+27 7.9594e-43
[torch.FloatTensor of size 2x3]
"""由list/tuple创建Tensor"""
b = t.Tensor([[1,2,3],[4,5,6]])
print(b) # 根据list初始化Tensor print(b.tolist())
print(b) # 并非inplace转换
 1  2  3
4 5 6
[torch.FloatTensor of size 2x3] [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] 1 2 3
4 5 6
[torch.FloatTensor of size 2x3]
# 等价写法,查看元素个数(2*3=6)
print(b.numel())
print(b.nelement())
6
6
# 传入tuple等价于传入list
d = t.Tensor((2,3))
print(d)
 2
3
[torch.FloatTensor of size 2]
"""创建特定Tensor"""
print(t.eye(2,3))
print(t.ones(2,3))
print(t.zeros(2,3))
print(t.arange(1,6,2))
print(t.linspace(1,10,3))
# 几个特殊初始化方法
print(t.randn(2,3)) # 标准分布,*size
print(t.randperm(5)) # 随机排序,从0到n
print(t.normal(means=t.arange(0, 11), std=t.arange(1, 0, -0.1)))
 1  0  0
0 1 0
[torch.FloatTensor of size 2x3] 1 1 1
1 1 1
[torch.FloatTensor of size 2x3] 0 0 0
0 0 0
[torch.FloatTensor of size 2x3] 1
3
5
[torch.FloatTensor of size 3] 1.0000
5.5000
10.0000
[torch.FloatTensor of size 3] -0.9959 -0.8446 0.7241
3.0315 -0.5367 1.0722
[torch.FloatTensor of size 2x3] 4
3
2
1
0
[torch.LongTensor of size 5] -0.5880
1.2708
1.5530
3.2490
4.7693
4.9497
6.0663
6.1482
7.9109
8.9492
10.0000
[torch.FloatTensor of size 11]

二、尺度调整

特殊方法:

a.view(-1,3)
b.unsqueeze_(0)
b.resize_(3,3)

概览:

a = t.arange(0,6)
print(a.view(2,3)) # 非inplace
print(a.view(-1,3)) # -1为自动计算大小
 0  1  2
3 4 5
[torch.FloatTensor of size 2x3] 0 1 2
3 4 5
[torch.FloatTensor of size 2x3]
b = a.view(-1,3)
b.unsqueeze_(0)
print(b)
print(b.size())
(0 ,.,.) =
0 1 2
3 4 5
[torch.FloatTensor of size 1x2x3] torch.Size([1, 2, 3])
c = b.view(1,1,1,2,3)
print(c.squeeze_(0)) # 压缩第0个1
print(c.squeeze_()) # 压缩全部的1
(0 ,0 ,.,.) =
0 1 2
3 4 5
[torch.FloatTensor of size 1x1x2x3] 0 1 2
3 4 5
[torch.FloatTensor of size 2x3]
# view要求前后元素数相同,resize_没有这个要求
# resize_没有对应的非inplace操作版本
print(b.resize_(1,3))
print(b.resize_(3,3))
print(b)
 0  1  2
[torch.FloatTensor of size 1x3] 0.0000e+00 1.0000e+00 2.0000e+00
3.0000e+00 4.0000e+00 5.0000e+00
3.3845e+15 0.0000e+00 0.0000e+00
[torch.FloatTensor of size 3x3] 0.0000e+00 1.0000e+00 2.0000e+00
3.0000e+00 4.0000e+00 5.0000e+00
3.3845e+15 0.0000e+00 0.0000e+00
[torch.FloatTensor of size 3x3]
上一篇:打造强大的BaseModel(2):让Model实现自动映射,将字典转化成Model


下一篇:[原创]java WEB学习笔记36:Java Bean 概述,及在JSP 中的使用,原理