pytorch tensor
![]()
import torch import numpy as np dd=[[1,2,3],[4,5,6],[7,8,9]] t=torch.tensor(dd) print(type(dd),type(t)) print(t.shape) t=t.reshape(1,9) print(t) print(t.shape) print(t.dtype,t.device,t.layout,sep='分隔')
<class 'list'> <class 'torch.Tensor'>
torch.Size([3, 3])
tensor([[1, 2, 3, 4, 5, 6, 7, 8, 9]])
torch.Size([1, 9])
torch.int64分隔cpu分隔torch.strided
张量的数据类型有如下几种:

![]()

















![]()




但是pytorch 1.8版本中上述的两种tensor类型之间可以互相加减了。
t1=torch.tensor([1,2,3])
t2=torch.tensor([1.,2.,3.])
print(t1.dtype,t2.dtype)
print(t1+t2)
结果:
torch.int64 torch.float32
tensor([2., 4., 6.])
下图为不同设备之间的运算出错:
import torch import numpy as np t3=torch.tensor([1,2,3]) t4=t3.cuda() print(t3.device,t4.device) print(t3+t4) 结果为: cpu cuda:0 Traceback (most recent call last): File "E:/code/python/DLT/data/deeplizard.py", line 7, in <module> print(t3+t4) RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cuda:0 and cpu!

在pytorch中创建张量的方法主要有四种,
1.torch.Tensor(data);
2.torch.tensor(data);
3.torch.as_tensor(data);
4.torch.from_numpy(data);
下面用numpy数组来创建一些数据:
import torch import numpy as np data=np.array([1,2,3]) t5=torch.tensor(data) t6=torch.Tensor(data) t7=torch.as_tensor(data) t8=torch.from_numpy(data) print("data: ",data,'data type: ',type(data)) print('t5: ',t5,'t5 type: ',type(t5)) print('t6: ',t6,'t6 type: ',type(t6)) print('t7: ',t7,'t7 type: ',type(t7)) print('t8: ',t8,'t8 type: ',type(t8)) 结果如下: data: [1 2 3] data type: <class 'numpy.ndarray'> t5: tensor([1, 2, 3], dtype=torch.int32) t5 type: <class 'torch.Tensor'> t6: tensor([1., 2., 3.]) t6 type: <class 'torch.Tensor'> t7: tensor([1, 2, 3], dtype=torch.int32) t7 type: <class 'torch.Tensor'> t8: tensor([1, 2, 3], dtype=torch.int32) t8 type: <class 'torch.Tensor'>
可看到,t6内数据后有小数点,表明其是浮点数。
上述代码中t5,t6的区别在于,t6是类构造函数,t5那个小写的tensor表示的张量函数是我们所说的为我们构建张量对象的工厂函数。
torch.Tensor()是python类,更明确地说,是默认张量类型torch.FloatTensor()的别名,torch.Tensor([1,2])会调用Tensor类的构造函数init,生成单精度浮点类型的张量。






浙公网安备 33010602011771号