TUTORIALAI 与数据科学FETCHED
PyTorch torch.atleast_2d 函数
PyTorch torch.atleast_2d 函数 Pytorch torch 参考手册 torch.atleast_2d 是 PyTorch 中用于将输入张量转换为至少 2 维的函数。如果输入维度少于 2 维,会自动添加维度使其变为 2 维。 函数定义 torch.atleast_2d(*tensors) 使用示例 实例 [mycode4 type='python'] import torch #..
更新于 2026/7/16
教程详情页默认 noindex。
PyTorch torch.atleast_2d 函数
torch.atleast_2d 是 PyTorch 中用于将输入张量转换为至少 2 维的函数。如果输入维度少于 2 维,会自动添加维度使其变为 2 维。
函数定义
torch.atleast_2d(*tensors)
使用示例
实例
import torch
# 标量转换为 2 维张量
x = torch.atleast_2d(5)
print("标量转换后:", x, "形状:", x.shape)
# 输出: 标量转换后: tensor([[5]]) 形状: torch.Size([1, 1])
# 1 维张量转换为 2 维
x = torch.tensor([1, 2, 3])
y = torch.atleast_2d(x)
print("1维转2维:", y, "形状:", y.shape)
# 输出: 1维转2维: tensor([[1, 2, 3]]) 形状: torch.Size([1, 3])
# 已经是 2 维的张量保持不变
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_2d(x)
print("2维张量:", y, "形状:", y.shape)
# 标量转换为 2 维张量
x = torch.atleast_2d(5)
print("标量转换后:", x, "形状:", x.shape)
# 输出: 标量转换后: tensor([[5]]) 形状: torch.Size([1, 1])
# 1 维张量转换为 2 维
x = torch.tensor([1, 2, 3])
y = torch.atleast_2d(x)
print("1维转2维:", y, "形状:", y.shape)
# 输出: 1维转2维: tensor([[1, 2, 3]]) 形状: torch.Size([1, 3])
# 已经是 2 维的张量保持不变
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_2d(x)
print("2维张量:", y, "形状:", y.shape)
Pytorch torch 参考手册