tensor.view(shape): 返回给定形状的张量视图
返回一个具有指定形状的新张量,原始张量的形状必须与新形状兼容。
import torch
tensor = torch.tensor([[1, 2], [3, 4]])
reshaped_tensor = tensor.view(1, 4) # Reshapes the tensor to a 1x4 tensor
print(reshaped_tensor)
tensor.reshape(shape): 改变张量的形状
返回一个具有指定形状的新张量,原始张量的元素数量必须与新形状一致
import torch
tensor = torch.tensor([[1, 2], [3, 4]])
reshaped_tensor = tensor.reshape(1, 4) # Reshapes the tensor to a 1x4 tensor
print(reshaped_tensor)
tensor.transpose(dim0, dim1): 交换两个维度
交换张量中两个维度的位置
import torch
tensor = torch.tensor([[1, 2], [3, 4]])
transposed_tensor = tensor.transpose(0, 1) # Swaps the first and second dimensions
print(transposed_tensor)
tensor.permute(*dims): 按照指定顺序排列张量的维度
按照给定顺序重新排列张量的维度
import torch
tensor = torch.tensor([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
permuted_tensor = tensor.permute(1, 0, 2) # Permutes the dimensions to (1, 0, 2)
print(permuted_tensor)
tensor.squeeze(): 删除所有长度为1的维度
删除张量中所有长度为1的维度
import torch
tensor = torch.tensor([[[1, 2], [3, 4]]])
squeezed_tensor = tensor.squeeze() # Removes the single-dimensional entries
print(squeezed_tensor)
tensor.unsqueeze(dim): 在指定位置增加一个维度
在指定位置增加一个长度为1的新维度
import torch
tensor = torch.tensor([[1, 2], [3, 4]])
unsqueezed_tensor = tensor.unsqueeze(0) # Adds a dimension at index 0
print(unsqueezed_tensor)