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

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