Files
pytorch-study/05.ipynb

4.9 KiB
Raw Permalink Blame History

In [ ]:
import torch
In [ ]:
# 连接操作
A = torch.ones(3, 3)
B = 2 * torch.ones(3, 3)

C = torch.cat((A, B), 1)
C
In [ ]:
# 堆叠操作
A = torch.arange(0, 4)
B = torch.arange(4, 8)

C = torch.stack((A, B), 1)
C
In [ ]:
# 堆叠操作
A = torch.arange(6).reshape(2, 3)
B = torch.arange(7, 13).reshape(2, 3)
C = torch.stack((A, B), 2)
print(C.shape)
C
In [ ]:
A = torch.tensor([[1, 2], [3, 4]])  # shape = (2, 2)
B = torch.tensor([[5, 6], [7, 8]])  # shape = (2, 2)

S = torch.stack((A, B), dim=0)  # 在最外面添加一个新维度 → shape = (2, 2, 2)
print(S)
S = torch.stack((A, B), dim=1)  # 插入第1维 → shape = (2, 2, 2)
print(S)
S = torch.stack((A, B), dim=2)  # 插入第2维 → shape = (2, 2, 2)
print(S)
In [ ]:
# 切分操作
A = torch.arange(10) + 1
B = torch.chunk(A, 3, 0)
B
In [ ]:
# 切分操作
A = torch.arange(10) + 1
B = torch.split(A, 3, 0)
B
In [36]:
x = torch.arange(10)
torch.chunk(x, 3)
# 输出3个 tensor形状为 [4], [3], [3]
Out[36]:
(tensor([0, 1, 2, 3]), tensor([4, 5, 6, 7]), tensor([8, 9]))
In [53]:
# 索引操作
A = torch.arange(16).view(4, 4)
torch.index_select(A, 1, torch.tensor([1, 3]))
Out[53]:
tensor([[ 1,  3],
        [ 5,  7],
        [ 9, 11],
        [13, 15]])
In [61]:
A = torch.rand(5)
torch.masked_select(A, A > 0.3)
Out[61]:
tensor([0.5685, 0.4049, 0.4695])
In [62]:
# 提取出其中第一行的第一个,第二行的第一、第二个,第三行的最后一个
A = torch.tensor([[4, 5, 7], [3, 9, 8], [2, 3, 4]])
torch.diagonal(A)
Out[62]:
tensor([4, 9, 4])