プリンキピア

第2章準備

2.1.6. Conversion to Other Python Objects2.1.6 ほかのPythonオブジェクトへの変換

Converting to a NumPy tensor (ndarray), or vice versa, is easy. The torch tensor and NumPy array will share their underlying memory, and changing one through an in-place operation will also change the other.
英語のヒント
NumPyのテンソル(ndarray)への変換や、その逆は簡単である。torchのテンソルとNumPyの配列は、元のメモリを共有するので、その場での演算で一方を変えると、もう一方も変わる。
A = X.numpy()
B = torch.from_numpy(A)
type(A), type(B)
(numpy.ndarray, torch.Tensor)
To convert a size-1 tensor to a Python scalar, we can invoke the item function or Python’s built-in functions.
英語のヒント
大きさ1のテンソルをPythonのスカラーに変換するには、item関数か、Pythonの組み込み関数を呼び出せばよい。
a = torch.tensor([3.5])
a, a.item(), float(a), int(a)
(tensor([3.5000]), 3.5, 3.5, 3)