PyTorchの操作方法はNumpyの操作方法と似ています。
そのためNumpyが使用できれば同じような操作方法でPyTrochも扱えるという学習コストの低さが一つのメリットといえます。
しかし、多少の差異はどうしても存在します。
そこで、Numpyの練習に非常に役立つ「100 numpy exercises 」をPyTorchで書き換えることによって、PyTorchの操作方法を学ぶのと同時にNumpyとの類似点や相違点を学んでいきたいと思います。
PyTorchのコードだけでなくNumpyのコードもあわせて紹介していきます。
別記事に他の問題の解法も書いています。
次のリンクにまとめているので、他の問題もあわせて参考にしていただければと思います。
- 6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
- 7. Create a vector with values ranging from 10 to 49 (★☆☆)
- 8. Reverse a vector (first element becomes last) (★☆☆)
- 9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
- 10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
6. Create a null vector of size 10 but the fifth value which is 1 (★☆☆)
「サイズが10の要素がすべて0で、5つ目の要素が1の配列を作成してください」
PyTorch
Z = torch.zeros(10) Z[4] = 1 print(Z)
# Output tensor([0., 0., 0., 0., 1., 0., 0., 0., 0., 0.])
Numpy
Z = np.zeros(10) Z[4] = 1 print(Z)
# Output [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
7. Create a vector with values ranging from 10 to 49 (★☆☆)
「10から49の範囲の値を持つベクトルを作成してください」
PyTorch
Z = torch.arange(10, 50) print(Z)
# Output tensor([10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49])
Numpy
Z = np.arange(10,50) print(Z)
# Output [10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49]
8. Reverse a vector (first element becomes last) (★☆☆)
「配列を逆順にしてください (最初の要素が最後になるように)」
PyTorch
Z = torch.arange(50) Z = torch.flip(Z, (-1, )) print(Z)
# Output tensor([49, 48, 47, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
Numpy
Z = np.arange(50) Z = Z[::-1] print(Z)
# Output [49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0]
9. Create a 3x3 matrix with values ranging from 0 to 8 (★☆☆)
「要素が0~8の3行3列の配列を作成してください」
PyTorch
Z = torch.arange(9).view(3, 3) print(Z)
# Output tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
Numpy
Z = np.arange(9).reshape(3, 3) print(Z)
# Output [[0 1 2] [3 4 5] [6 7 8]]
10. Find indices of non-zero elements from [1,2,0,0,4,0] (★☆☆)
「[1,2,0,0,4,0]という配列から0でない要素のインデックスを取得してください」
PyTorch
Z = torch.nonzero(torch.tensor([1, 2, 0, 0, 4, 0]), as_tuple=True) print(Z)
# Output (tensor([0, 1, 4]),)
Numpy
nz = np.nonzero([1, 2, 0, 0, 4, 0]) print(nz)
# Output (array([0, 1, 4], dtype=int64),)
リンク