PyTorchの操作方法はNumpyの操作方法と似ています。
そのためNumpyが使用できれば同じような操作方法でPyTrochも扱えるという学習コストの低さが一つのメリットといえます。
しかし、多少の差異はどうしても存在します。
そこで、Numpyの練習に非常に役立つ「100 numpy exercises 」をPyTorchで書き換えることによって、PyTorchの操作方法を学ぶのと同時にNumpyとの類似点や相違点を学んでいきたいと思います。
PyTorchのコードだけでなくNumpyのコードもあわせて紹介していきます。
別記事に他の問題の解法も書いています。
次のリンクにまとめているので、他の問題もあわせて参考にしていただければと思います。
- 31. How to ignore all numpy warnings (not recommended)? (★☆☆)
- 32. Is the following expressions true? (★☆☆)
- 33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
- 34. How to get all the dates corresponding to the month of July 2016? (★★☆)
- 35. How to compute ((A+B)*(-A/2)) in place (without copy)? (★★☆)
31. How to ignore all numpy warnings (not recommended)? (★☆☆)
「すべてのNumpyの警告を無視してください (非推奨)」
PyTorch
PyTorchで警告を無視する方法を見つけることができませんでした。
Numpy
defaults = np.seterr(all="ignore") Z = np.ones(1) / 0 # Back to sanity _ = np.seterr(**defaults) # Equivalently with a context manager with np.errstate(all="ignore"): np.arange(3) / 0
32. Is the following expressions true? (★☆☆)
「次の式がTrueになるか確認してください」
np.sqrt(-1) == np.emath.sqrt(-1)
PyTorch
torch.sqrt(torch.tensor(-1)) == torch.sqrt(torch.tensor(-1, dtype=torch.cfloat))
# Output tensor(False)
Numpy
python
np.sqrt(-1) == np.emath.sqrt(-1)
# Output False
33. How to get the dates of yesterday, today and tomorrow? (★☆☆)
「昨日、今日、明日の日付を取得してください」
PyTorch
PyTorchでdatetime型の操作を見つけることができませんでした。
Numpy
yesterday = np.datetime64('today') - np.timedelta64(1) today = np.datetime64('today') tomorrow = np.datetime64('today') + np.timedelta64(1)
34. How to get all the dates corresponding to the month of July 2016? (★★☆)
「2016年8月のすべての日付を取得してください」
PyTorch
PyTorchでdatetime型の操作を見つけることができませんでした。
Numpy
Z = np.arange('2016-07', '2016-08', dtype='datetime64[D]') print(Z)
# Output ['2016-07-01' '2016-07-02' '2016-07-03' '2016-07-04' '2016-07-05' '2016-07-06' '2016-07-07' '2016-07-08' '2016-07-09' '2016-07-10' '2016-07-11' '2016-07-12' '2016-07-13' '2016-07-14' '2016-07-15' '2016-07-16' '2016-07-17' '2016-07-18' '2016-07-19' '2016-07-20' '2016-07-21' '2016-07-22' '2016-07-23' '2016-07-24' '2016-07-25' '2016-07-26' '2016-07-27' '2016-07-28' '2016-07-29' '2016-07-30' '2016-07-31']
35. How to compute ((A+B)*(-A/2))
in place (without copy)? (★★☆)
「コピーを使用せずに、((A+B)*(-A/2))
を計算してください」
PyTorch
A = torch.ones(3) * 1 B = torch.ones(3) * 2 torch.add(A, B, out=B) torch.divide(A, torch.tensor(2), out=A) torch.negative(A, out=A) torch.multiply(A, B, out=A)
# Output tensor([-1.5000, -1.5000, -1.5000])
Numpy
A = np.ones(3)*1 B = np.ones(3)*2 np.add(A,B,out=B) np.divide(A,2,out=A) np.negative(A,out=A) np.multiply(A,B,out=A)
# Output array([-1.5, -1.5, -1.5])
リンク