这是《动手学深度学习》(PyTorch版)(Dive-into-DL-PyTorch)的学习笔记,里面有一些代码是我自己拓展的。

其他笔记在专栏 深度学习 中。

1.5 Tensor和NumPy相互转换

1.5.1 Tensor转NumPy

a = torch.ones(5)
b = a.numpy()
print(type(a), type(b))  #a是Tensor,b是numpy
print(a, b)

a += 1
print(a, b)

b += 1
print(a, b)
<class 'torch.Tensor'> <class 'numpy.ndarray'>
tensor([1., 1., 1., 1., 1.]) [1. 1. 1. 1. 1.]
tensor([2., 2., 2., 2., 2.]) [2. 2. 2. 2. 2.]
tensor([3., 3., 3., 3., 3.]) [3. 3. 3. 3. 3.]

1.5.2 Numpy转Tensor

c = torch.from_numpy(b)
print(b, c)

b += 1
print(b, c)

c += 1
print(b, c)
[3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.])
[4. 4. 4. 4. 4.] tensor([4., 4., 4., 4., 4.])
[5. 5. 5. 5. 5.] tensor([5., 5., 5., 5., 5.])
import numpy as np
a = np.ones(5)
b = torch.from_numpy(a)
print(a, b)

a += 1
print(a, b)

b += 1
print(a, b)
[1. 1. 1. 1. 1.] tensor([1., 1., 1., 1., 1.], dtype=torch.float64)
[2. 2. 2. 2. 2.] tensor([2., 2., 2., 2., 2.], dtype=torch.float64)
[3. 3. 3. 3. 3.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)
  • 所有在CPU上的Tensor(除了CharTensor)都支持与NumPy数组相互转换。
  • 用numpy()和from_numpy()将Tensor和NumPy中的数组相互转换。
  • 但是需要注意的一点是:这两个函数所产生的的Tensor和NumPy中的数组共享相同的内存(所以他们之间的转换很快),改变其中一个时另一个也会改变!!!

1.5.3 直接用torch.tensor()将NumPy数组转换成Tensor

该方法总是会进行数据拷贝,返回的Tensor和原来的数据不再共享内存。

c = torch.tensor(a)
a += 1
print(a, c)
[4. 4. 4. 4. 4.] tensor([3., 3., 3., 3., 3.], dtype=torch.float64)

1.6 将大小为1的张量转换为Python标量

x = torch.tensor([3.5])
print(x, x.item(), float(a))
tensor([3.5000]) 3.5 3.5 3
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐