import torch import numpy as np x = torch.tensor([[1,2,3], [4,5,6], [7,8,9]]) y = torch.tensor([[3,2,1], [6,5,4], [9,8,7]]) z = x+y print(z) #直接使用加号就能实现加fa #分片操作 a = x[0:2, 0:2] print(a) #resize操作,-1的运用 b = x.view(1, 9) #在numpy中是reshape,在torch中是view c = torch.ones(2,4) print(c) d = c.view(-1, 2) #-1的那个维度,torch会自动计算。例如这里第二个维度是2,共有8个数,那么第一个维数就是8/2=4,输入4*2的矩阵 print(d) #将含有一个元素的Tensor转换为数字 e = torch.tensor([1]) print(e) #输出为tensor([1]) print(e.dtype) #输出为torch.int64 f = e.item() print(f) #输出为1 print(type(f)) #输出为<class 'int'> #numpy和torch的转换, numpy变torch用torch.from_numpy(), torch变numpy用x.numpy() g = np.array([[1,2,3], [4,5,6]]) print(type(g)) #输出为<class 'numpy.ndarray'> h = torch.from_numpy(g) print(h) print(type(h)) #输出为<class 'torch.Tensor'> i = h.numpy() print(type(i)) #输出为<class 'numpy.ndarray'>
输出如下
tensor([[ 4, 4, 4], [10, 10, 10], [16, 16, 16]]) tensor([[1, 2], [4, 5]]) tensor([[1., 1., 1., 1.], [1., 1., 1., 1.]]) tensor([[1., 1.], [1., 1.], [1., 1.], [1., 1.]]) tensor([1]) torch.int64 1 <class 'int'> <class 'numpy.ndarray'> tensor([[1, 2, 3], [4, 5, 6]], dtype=torch.int32) <class 'torch.Tensor'> <class 'numpy.ndarray'>