TUTORIALAI 与数据科学FETCHED

PyTorch torch.triu 函数

PyTorch torch.triu 函数 Pytorch torch 参考手册 torch.triu 是 PyTorch 中用于提取矩阵上三角部分(包括主对角线)的函数。下三角部分会被设为0。 函数定义 torch.triu(input, diagonal=0, out=None) 参数说明: input: 输入张量 diagonal: 对角线索引,0 表示主对角线 out: 输出张量 使用示例 实例 [my..

更新于 2026/7/16

教程详情页默认 noindex。

PyTorch torch.triu 函数


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

torch.triu 是 PyTorch 中用于提取矩阵上三角部分(包括主对角线)的函数。下三角部分会被设为0。

函数定义

torch.triu(input, diagonal=0, out=None)

参数说明:

  • input: 输入张量
  • diagonal: 对角线索引,0 表示主对角线
  • out: 输出张量

使用示例

实例

import torch

# 创建矩阵
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# 提取上三角部分
y = torch.triu(a)
print(y)

输出结果为:

tensor([[1, 2, 3],
        [0, 5, 6],
        [0, 0, 9]])

实例

import torch

# 创建矩阵
a = torch.tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# 提取主对角线以上第一对角线的上三角
y = torch.triu(a, diagonal=1)
print(y)

输出结果为:

tensor([[0, 2, 3],
        [0, 0, 6],
        [0, 0, 0]])

实例

import torch

# 创建非方阵
a = torch.tensor([[1, 2, 3], [4, 5, 6]])

# 提取上三角部分
y = torch.triu(a)
print(y)

输出结果为:

tensor([[1, 2, 3],
        [0, 5, 6]])

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