红圈圈 里的数据类型比较重要 瞎贴一波: 一、数据类型 a = torch.randn(2,3 ) print (a) print (type(a)) print (isinstance(a, torch.FloatTensor)) # 合法化检验 print (isinstance(a, torch.cuda.FloatTensor)) # 合法化检
红圈圈里的数据类型比较重要
瞎贴一波:
一、数据类型
a = torch.randn(2,3) print(a) print(type(a)) print(isinstance(a, torch.FloatTensor))#合法化检验 print(isinstance(a, torch.cuda.FloatTensor))#合法化检验 a = a.cuda()#返回一个GPU上的引用 print(isinstance(a, torch.cuda.FloatTensor))#合法化检验 >>> tensor([[ 1.0300, -0.7234, -0.5679], [-0.7928, -0.2508, -0.9085]]) <class ‘torch.Tensor‘> True False True
torch.tensor(1.) >>>tensor(1.) torch.tensor(1.3) >>>tensor(1.3000) torch.tensor([1.]) #torch.tensor([1.]) >>>tensor([1.]) a = torch.tensor(2.2) a.shape >>>torch.Size([]) len(a.shape) >>>0 a.size() >>>torch.Size([]) torch.tensor([1.1]) >>>tensor([1.1000]) torch.tensor([1.1,2.2]) >>>tensor([1.1000, 2.2000]) torch.FloatTensor(1) >>>tensor([1.4574e-43]) torch.FloatTensor(2) >>>tensor([0., 0.]) data = np.ones(2) data >>>array([1., 1.]) torch.from_numpy(data) >>>tensor([1., 1.], dtype=torch.float64) a = torch.ones(2) a.shape >>>torch.Size([2])
a = torch.randn(2,3) a >>>tensor([[ 0.5736, 0.4078, -0.8879], [-0.0126, 0.4756, -0.0214]]) a.shape >>>torch.Size([2, 3]) a.size(0) >>>2 a.size(1) >>>3
a = torch.rand(2,1,4,4) a >>>tensor([[[[0.4224, 0.5601, 0.3603, 0.7440], [0.2749, 0.4182, 0.5837, 0.1956], [0.9536, 0.9231, 0.6720, 0.4501], [0.0255, 0.0731, 0.7247, 0.3907]]], [[[0.0651, 0.7923, 0.1018, 0.3250], [0.7650, 0.5583, 0.5320, 0.9807], [0.2130, 0.2525, 0.7932, 0.0258], [0.7981, 0.6380, 0.1390, 0.2147]]]]) a.numel() #元素个数 >>>32 a.dim() #维度 >>>4
二、创建Tensor
1.import from numpy,从numpy数据中载入
a = np.array([2,3.3]) torch.from_numpy(a) >>>tensor([2.0000, 3.3000], dtype=torch.float64) a = np.ones([2,3]) torch.from_numpy(a) >>>tensor([[1., 1., 1.], [1., 1., 1.]], dtype=torch.float64)
2.import from List,从列表类型数据中载入
torch.tensor([2., 3.2]) #直接接受数据,经常使用,注意是小写 >>>tensor([2.0000, 3.2000]) torch.FloatTensor(4,3)#设定维度,经常使用 >>>tensor([[0., 0., 0.], [0., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) torch.FloatTensor([2.,3.2]) #不轻易用,容易和小写的tensor混淆 >>>tensor([2.0000, 3.2000]) torch.IntTensor(2,3) #未初始化,数据分布差异太大 >>>tensor([[0, 0, 1], [0, 1, 0]], dtype=torch.int32) torch.FloatTensor(2,3) #未初始化 >>>tensor([[7.4715e+37, 6.6001e-43, 8.4078e-45], [0.0000e+00, 1.4013e-45, 0.0000e+00]]) torch.tensor([1.2, 3]).type() >>>‘torch.FloatTensor‘ #默认情况是FloatTensor torch.set_default_tensor_type(torch.DoubleTensor) #修改默认情况 torch.tensor([1.2, 3]).type() >>>‘torch.DoubleTensor‘