PyTorch torch.atleast_3d 函数
torch.atleast_3d 是 PyTorch 中用于将输入张量转换为至少 3 维的函数。如果输入维度少于 3 维,会自动添加维度使其变为 3 维。
函数定义
torch.atleast_3d(*tensors)
使用示例
实例
import torch
# 标量转换为 3 维张量
x = torch.atleast_3d(5)
print("标量转换后:", x, "形状:", x.shape)
# 输出: 标量转换后: tensor([[[5]]]) 形状: torch.Size([1, 1, 1])
# 1 维张量转换为 3 维
x = torch.tensor([1, 2, 3])
y = torch.atleast_3d(x)
print("1维转3维:", y, "形状:", y.shape)
# 输出: 1维转3维: tensor([[[1], [2], [3]]]) 形状: torch.Size([3, 1, 1])
# 2 维张量转换为 3 维
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_3d(x)
print("2维转3维:", y, "形状:", y.shape)
# 输出: 2维转3维: tensor([[[1, 2], [3, 4]]]) 形状: torch.Size([1, 2, 2])
# 已经是 3 维的张量保持不变
x = torch.tensor([[[1, 2], [3, 4]]])
y = torch.atleast_3d(x)
print("3维张量:", y, "形状:", y.shape)
# 标量转换为 3 维张量
x = torch.atleast_3d(5)
print("标量转换后:", x, "形状:", x.shape)
# 输出: 标量转换后: tensor([[[5]]]) 形状: torch.Size([1, 1, 1])
# 1 维张量转换为 3 维
x = torch.tensor([1, 2, 3])
y = torch.atleast_3d(x)
print("1维转3维:", y, "形状:", y.shape)
# 输出: 1维转3维: tensor([[[1], [2], [3]]]) 形状: torch.Size([3, 1, 1])
# 2 维张量转换为 3 维
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_3d(x)
print("2维转3维:", y, "形状:", y.shape)
# 输出: 2维转3维: tensor([[[1, 2], [3, 4]]]) 形状: torch.Size([1, 2, 2])
# 已经是 3 维的张量保持不变
x = torch.tensor([[[1, 2], [3, 4]]])
y = torch.atleast_3d(x)
print("3维张量:", y, "形状:", y.shape)

Pytorch torch 参考手册