# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

import torch

# +
#----------------------------张量的一些常见操作------------------------------
# -

#torch.trunk可以将一个张量在dim维度（默认为0）上分割成多个张量
b = torch.rand([3,2])
b

c,d = torch.chunk(b, chunks=2)
c,d

c,d = torch.chunk(b, chunks=2, dim=1)
c,d

b, torch.reshape(b,[2,3]), torch.reshape(b,[-1])

#torch.scatter: 根据dim和index将src张量中填充到结果张量相应位置中
#self[index[i][j][k]][j][k] = src[i][j][k]  # if dim == 0
#self[i][index[i][j][k]][k] = src[i][j][k]  # if dim == 1
#self[i][j][index[i][j][k]] = src[i][j][k]  # if dim == 2
src = torch.arange(1, 11).reshape((2, 5))
index = torch.tensor([[0, 1, 2, 0]])
src,torch.zeros(3, 5, dtype=src.dtype).scatter_(0, index, src)

index = torch.tensor([[0, 1, 2], [0, 1, 4]])
src,torch.zeros(3, 5, dtype=src.dtype).scatter_(1, index, src)

#torch.split(tensor, split_size_or_sections, dim=0)，其和trunk不同之处是可以传入列表
a = torch.arange(10).reshape(5,2)
a,torch.split(a, 2)

torch.split(a, [1,4])

# torch.squeeze(input, dim=None, *, out=None) → Tensor:将input所有维度为1的维度移除
# When dim is given, a squeeze operation is done only in the given dimension. 
a = torch.rand([3,2])
a,a.shape

torch.reshape(a,[3,1,2])

torch.squeeze(torch.reshape(a,[3,1,2]))

b = torch.reshape(a, [3,1,2,1,1])
b

torch.squeeze(b,dim=1).shape   # dim不能为元组和列表

#torch.stack(tensors, dim=0, *, out=None) → Tensor
#Concatenates a sequence of tensors along a new dimension.
#All tensors need to be of the same size.
b = torch.rand([3,2])
a,b

torch.stack([a,b]),torch.stack([a,b]).shape

torch.stack([a,b], dim=1),torch.stack([a,b], dim=1).shape

torch.stack([a,b], dim=2),torch.stack([a,b], dim=1).shape



StarcoderdataJupyterScriptsDedupFiltered