書中(pytorch入門實戰)講:index_select(input, dim, index),指定維度dim上選取,未有示例。
查到相關資料后,
import torch as t # 導入torch模塊
c = t.randn(3, 6) # 定義tensor
print(c)
b = t.index_select(c, 0, t.tensor([0, 2]))
"""
第一個參數c為被引用tensor,
第二個參數0表示按行索引,1表示按列索引
第三個參數是一個tensor,表示tensor索引的序號,eg:b里面tensor[0, 2]表示第0行和第2行
"""
print(b)
print(c.index_select(0, t.tensor([0, 2]))) # 從輸出結果看,此用法與b中方法等價
c = t.index_select(c, 1, t.tensor([1, 3])) # 按列索引,第1列到第3列
print(c)
輸出:
tensor([[-1.3710, 0.0348, -0.0733, 0.1358, 1.2035, -0.5978],
[ 0.4770, -0.0906, -0.7095, 0.3073, 0.2640, 1.9909],
[-1.3719, -0.4406, 1.3095, -0.4160, 0.0700, 1.2667]])
tensor([[-1.3710, 0.0348, -0.0733, 0.1358, 1.2035, -0.5978],
[-1.3719, -0.4406, 1.3095, -0.4160, 0.0700, 1.2667]])
tensor([[-1.3710, 0.0348, -0.0733, 0.1358, 1.2035, -0.5978],
[-1.3719, -0.4406, 1.3095, -0.4160, 0.0700, 1.2667]])
tensor([[ 0.0348, 0.1358],
[-0.0906, 0.3073],
[-0.4406, -0.4160]])