PyTorchの操作方法はNumpyの操作方法と似ています。
そのためNumpyが使用できれば同じような操作方法でPyTrochも扱えるという学習コストの低さが一つのメリットといえます。
しかし、多少の差異はどうしても存在します。
そこで、Numpyの練習に非常に役立つ「100 numpy exercises 」をPyTorchで書き換えることによって、PyTorchの操作方法を学ぶのと同時にNumpyとの類似点や相違点を学んでいきたいと思います。
PyTorchのコードだけでなくNumpyのコードもあわせて紹介していきます。
別記事に他の問題の解法も書いています。
次のリンクにまとめているので、他の問題もあわせて参考にしていただければと思います。
- 26. What is the output of the following script? (★☆☆)
- 27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)
- 28. What are the result of the following expressions?
- 29. How to round away from zero a float array ? (★☆☆)
- 30. How to find common values between two arrays? (★☆☆)
26. What is the output of the following script? (★☆☆)
「次のスクリプトで出力される結果を確認してください」
PyTorch
print(sum(range(5), -1)) print(torch.sum(torch.tensor(range(5)), -1))
# Output 9 tensor(10)
Numpy
print(sum(range(5), -1)) print(np.sum(range(5), -1))
# Output 9 10
27. Consider an integer vector Z, which of these expressions are legal? (★☆☆)
「整数ベクトルZに対して、有効な式は選んでください」
Z ** Z 2 << Z >> 2 Z <- Z 1j * Z Z / 1 / 1 Z < Z > Z
PyTorchの場合は数値比較の際に、Tensor型に変えています。
PyTorch
Z**Z torch.tensor(2) << Z >> torch.tensor(2) Z <- Z 1j * Z Z / 1 / 1 Z < Z > Z
Numpy
Z ** Z 2 << Z >> 2 Z <- Z 1j * Z Z / 1 / 1 Z < Z > Z
28. What are the result of the following expressions?
「次に式の結果を確認してください」
np.array(0) / np.array(0) np.array(0) // np.array(0) np.array([np.nan]).astype(int).astype(float)
PyTorchの場合はTensor型に変更しています。
PyTorch
print(torch.tensor(0) / torch.tensor(0)) print(torch.tensor(0) // torch.tensor(0)) print(torch.tensor([float('nan')]).to(torch.int32).to(torch.float64))
# Output tensor(nan) # 例外発生 RuntimeError: ZeroDivisionError tensor([-2.1475e+09], dtype=torch.float64)
Numpy
print(np.array(0) / np.array(0)) print(np.array(0) // np.array(0)) print(np.array([np.nan]).astype(int).astype(float))
# Output nan 0 [-2.14748365e+09]
29. How to round away from zero a float array ? (★☆☆)
「浮動小数点配列をゼロ以下を丸めてください」
PyTorch
Z = torch.distributions.uniform.Uniform(-10, 10).sample([10]) print(torch.copysign(torch.ceil(torch.abs(Z)), Z)) print(torch.where(Z > 0, torch.ceil(Z), torch.floor(Z)))
# Output tensor([ 3., 8., -2., 10., -8., -10., -10., 1., 2., -6.]) tensor([ 3., 8., -2., 10., -8., -10., -10., 1., 2., -6.])
Numpy
Z = np.random.uniform(-10, +10, 10) print(np.copysign(np.ceil(np.abs(Z)), Z)) print(np.where(Z > 0, np.ceil(Z), np.floor(Z)))
# Output [ -8. -6. -10. 3. 6. -8. -9. 2. -8. 1.] [ -8. -6. -10. 3. 6. -8. -9. 2. -8. 1.]
30. How to find common values between two arrays? (★☆☆)
「二つの配列同士で共通の値を見つけてください」
PyTorch
PyTorchにintersection1d関数
が見つからなかったので、Numpyのintersection1d関数
を使用しています。
Z1 = torch.randint(low=0, high=10, size=(10, )) Z2 = torch.randint(low=0, high=10, size=(10, )) print(torch.tensor(np.intersect1d(Z1, Z2)))
# Output tensor([4, 6, 8])
Numpy
Z1 = np.random.randint(0, 10, 10) Z2 = np.random.randint(0, 10, 10) print(np.intersect1d(Z1, Z2))
# Output [2 3 6 8 9]
リンク