现在位置: 首页 > PyTorch 教程 > 正文

PyTorch torch.atleast_1d 函数


Pytorch torch 参考手册 Pytorch torch 参考手册

torch.atleast_1d 是 PyTorch 中用于将输入张量转换为至少 1 维的函数。如果输入已经是至少 1 维的,则返回原始张量的视图;否则会添加一个新的维度。

函数定义

torch.atleast_1d(*tensors)

使用示例

实例

import torch

# 标量转换为 1 维张量
x = torch.atleast_1d(5)
print("标量转换后:", x, "形状:", x.shape)

# 已经是 1 维的张量
x = torch.tensor([1, 2, 3])
y = torch.atleast_1d(x)
print("1维张量:", y, "形状:", y.shape)

# 2 维张量保持不变
x = torch.tensor([[1, 2], [3, 4]])
y = torch.atleast_1d(x)
print("2维张量:", y, "形状:", y.shape)

# 多个输入
a = 1
b = torch.tensor([2, 3])
c = torch.tensor([[4, 5]])
result = torch.atleast_1d(a, b, c)
for i, t in enumerate(result):
    print(f"输入{i}形状: {t.shape}")

Pytorch torch 参考手册 Pytorch torch 参考手册