プリンキピア

第2章準備

2.1.2. Indexing and Slicing2.1.2 インデックス指定とスライス

As with Python lists, we can access tensor elements by indexing (starting with 0). To access an element based on its position relative to the end of the list, we can use negative indexing. Finally, we can access whole ranges of indices via slicing (e.g., X[start:stop]), where the returned value includes the first index (start) but not the last (stop). Finally, when only one index (or slice) is specified for a kth-order tensor, it is applied along axis 0. Thus, in the following code, [-1] selects the last row and [1:3] selects the second and third rows.
英語のヒント
Pythonのリストと同じように、テンソルの要素にはインデックス(0から始まる)で取り出せる。リストの末尾からの相対的な位置にもとづいて要素を取り出すには、負のインデックスを使えばよい。また、スライス(たとえばX[start:stop])で、インデックスの範囲全体を取り出せる。返される値は最初のインデックス(start)を含むが、最後のインデックス(stop)は含まない。最後に、kth階のテンソルにインデックス(またはスライス)を一つだけ指定すると、それは軸0に沿って適用される。したがって次のコードでは、[-1]は最後の行を選び、[1:3]は2行目と3行目を選ぶ。
X[-1], X[1:3]
(tensor([ 8.,  9., 10., 11.]),
 tensor([[ 4.,  5.,  6.,  7.],
         [ 8.,  9., 10., 11.]]))
Beyond reading them, we can also write elements of a matrix by specifying indices.
英語のヒント
読み取るだけでなく、インデックスを指定して行列の要素に書き込むこともできる。
X[1, 2] = 17
X
tensor([[ 0.,  1.,  2.,  3.],
        [ 4.,  5., 17.,  7.],
        [ 8.,  9., 10., 11.]])
If we want to assign multiple elements the same value, we apply the indexing on the left-hand side of the assignment operation. For instance, [:2, :] accesses the first and second rows, where : takes all the elements along axis 1 (column). While we discussed indexing for matrices, this also works for vectors and for tensors of more than two dimensions.
英語のヒント
複数の要素に同じ値を代入したいときは、代入演算の左辺でインデックスを指定する。たとえば[:2, :]は1行目と2行目を取り出す。ここで:は軸1(列)に沿ったすべての要素をとる。行列のインデックス指定を論じたが、これはベクトルや3次元以上のテンソルでも使える。
X[:2, :] = 12
X
tensor([[12., 12., 12., 12.],
        [12., 12., 12., 12.],
        [ 8.,  9., 10., 11.]])