pytorch tensor與numpy轉換

tensor to numpy

a = torch.ones(5)
print(a)

輸出

tensor([1., 1., 1., 1., 1.])

進行轉換

b = a.numpy()
print(b)

輸出

[1. 1. 1. 1. 1.]

注意,轉換後的tensor與numpy指向同一地址,所以,對一方的值改變另一方也隨之改變

a.add_(1)
print(a)
print(b)

numpy to tensor

import numpy as np a = np.ones(5) b = torch.from_numpy(a) np.add(a, 1, out=a) print(a) print(b)

輸出

[2. 2. 2. 2. 2.]
tensor([2., 2., 2., 2., 2.], dtype=torch.float64)

除chartensor外所有tensor都可以轉換爲numpy

轉載自:https://www.cnblogs.com/wzyuan/p/9733433.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章