PyTorchの操作方法はNumpyの操作方法と似ています。
そのためNumpyが使用できれば同じような操作方法でPyTrochも扱えるという学習コストの低さが一つのメリットといえます。
しかし、多少の差異はどうしても存在します。
そこで、Numpyの練習に非常に役立つ「100 numpy exercises 」をPyTorchで書き換えることによって、PyTorchの操作方法を学ぶのと同時にNumpyとの類似点や相違点を学んでいきたいと思います。
PyTorchのコードだけでなくNumpyのコードもあわせて紹介していきます。
別記事に他の問題の解法も書いています。
次のリンクにまとめているので、他の問題もあわせて参考にしていただければと思います。
- 41. How to sum a small array faster than np.sum? (★★☆)
- 42. Consider two random array A and B, check if they are equal (★★☆)
- 43. Make an array immutable (read-only) (★★☆)
- 44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
- 45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
41. How to sum a small array faster than np.sum? (★★☆)
「np.sum
よりも高速に小さい配列の合計を求めてください」
PyTorch
PyTorchでの方法を見つけることができませんでした。
Numpy
Z = np.arange(10)
np.add.reduce(Z)
# Output 45
42. Consider two random array A and B, check if they are equal (★★☆)
「2つのランダムな配列AとBを生成し、それらが等しいかどうかを確認してください」
PyTorch
A = torch.randint(0, 2, (5, )) B = torch.randint(0, 2, (5, )) equal = torch.allclose(A, B) print(equal) equal = torch.equal(A, B) print(equal)
# Output False False
Numpy
A = np.random.randint(0,2,5) B = np.random.randint(0,2,5) equal = np.allclose(A,B) print(equal) equal = np.array_equal(A,B) print(equal)
# Output False False
43. Make an array immutable (read-only) (★★☆)
「配列をイミュータブルにしてください (読み取り専用)」
PyTorch
PyTorchでの方法を見つけることができませんでした。
Numpy
Z = np.zeros(10) Z.flags.writeable = False Z[0] = 1
# Output ValueError Traceback (most recent call last) <ipython-input-27-dcc5e7f145b5> in <module> 1 Z = np.zeros(10) 2 Z.flags.writeable = False ----> 3 Z[0] = 1 ValueError: assignment destination is read-only
44. Consider a random 10x2 matrix representing cartesian coordinates, convert them to polar coordinates (★★☆)
「ランダムな10×2のデカルト座標をを、極座標に変換してください」
PyTorch
Z = torch.rand((10, 2)) X, Y = Z[:, 0], Z[:, 1] R = torch.sqrt(X ** 2 + Y ** 2) T = torch.atan2(Y, X) print(R) print(T)
# Output tensor([1.1982, 0.9687, 0.9823, 0.6827, 0.8931, 0.5745, 0.3249, 0.2551, 0.9058, 0.6270]) tensor([0.9306, 1.0158, 0.8575, 0.1896, 0.6822, 0.2025, 0.0669, 1.5393, 1.0571, 1.4041])
Numpy
Z = np.random.random((10,2)) X, Y = Z[:, 0], Z[:, 1] R = np.sqrt(X ** 2 + Y ** 2) T = np.arctan2(Y, X) print(R) print(T)
[0.90070354 1.01800321 0.78441702 0.95049752 1.11017192 0.27065243 0.79427736 0.99211086 0.5668249 0.11723197] [0.58831358 1.31460146 0.96513677 0.33565787 0.54408958 0.61816405 0.24312103 1.19447296 0.07146238 0.50700983]# Output
45. Create random vector of size 10 and replace the maximum value by 0 (★★☆)
「サイズが10のランダムなベクトルを作成し、最大値を0に置き換えてください」
PyTorch
Z = torch.rand(10) Z[Z.argmax()] = 0 print(Z)
# Output tensor([0.5895, 0.6495, 0.3585, 0.2356, 0.4506, 0.3121, 0.9188, 0.2343, 0.0000, 0.3912])
Numpy
Z = np.random.random(10) Z[Z.argmax()] = 0 print(Z)
# Output [0.10059966 0.98373062 0. 0.10486769 0.44599612 0.47102902 0.10372803 0.48582492 0.50050563 0.49439192]
リンク