PyTorch torch.narrow 関数


Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

torch.narrowPyTorch でテンソルのスライスを返すための関数です。指定された次元で開始位置から指定された長さまでのスライスビューを返します。

関数定義

torch.narrow(input, dim, start, length)

引数:

  • input(Tensor): 入力テンソル。
  • dim(int): スライスする次元。
  • start(int): 開始インデックス。
  • length(int): スライスの長さ。

戻り値:

  • torch.Tensor: 指定されたスライス後のテンソルビューを返します。

使用例

例

import torch

# テンソルを作成する
x = torch.tensor([[1, 2, 3, 4],
                  [5, 6, 7, 8],
                  [9, 10, 11, 12]])

# 最初の次元(行)で、インデックス0から2行を取得する
y = torch.narrow(x, dim=0, start=0, length=2)

print("元のテンソル:")
print(x)
print("nスライス結果:")
print(y)

出力結果は:

原始张量:
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]])

切片结果:
tensor([[1, 2, 3, 4],
        [5, 6, 7, 8]])

例

import torch

# テンソルを作成する
x = torch.tensor([[1, 2, 3, 4],
                  [5, 6, 7, 8],
                  [9, 10, 11, 12]])

# 2番目の次元(列)で、インデックス1から2列を取得する
y = torch.narrow(x, dim=1, start=1, length=2)

print("元のテンソル:")
print(x)
print("nスライス結果:")
print(y)

出力結果は:

原始张量:
tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12]])

切片结果:
tensor([[ 2,  3],
        [ 6,  7],
        [10, 11]])

例

import torch

# 3Dテンソルを作成する
x = torch.randn(5, 6, 7)

# 最初の次元で、インデックス2から3つの要素を取得する
y = torch.narrow(x, dim=0, start=2, length=3)

print("元の形状:", x.shape)
print("スライス後の形状:", y.shape)

出力結果は:

原始形状: torch.Size([5, 6, 7])
切片后形状: torch.Size([3, 6, 7])

注意:torch.narrow返されるのは元のテンソルのビューであり、コピーではありません。コピーが必要な場合は、次を使用できます。torch.narrow_copy。


Pytorch torch 参考手册Pytorch torch リファレンスマニュアル

その他の拡張