一、创建二、运算三、改变形状四、Torch Tensor和Numpy array之间的相互转换
一、创建
import torch x = torch.empty(2, 3) # tensor([[ 0.0000e+00, -2.5244e-29, 0.0000e+00], [-2.5244e-29, 1.6816e-44, 0.0000e+00]]) # 生成 2*3 的张量,服从 [0, 1) 标准正态分布 x = torch.rand(2, 3) # tensor([[0.9694, 0.3158, 0.6500], [0.0295, 0.8634, 0.6159]]) x = torch.zeros(2, 3, dtype=torch.long) # tensor([[0, 0, 0], [0, 0, 0]]) x = torch.ones(2, 3, dtype=torch.long) # tensor([[1, 1, 1], [1, 1, 1]]) x = torch.tensor([2.5, 3.5]) # tensor([2.5000, 3.5000]) # 利用news_methods方法得到一个张量 x = x.new_ones(2, 3, dtype=torch.double) # tensor([[1., 1., 1.], [1., 1., 1.]], dtype=torch.float64) # 利用randn_like方法得到 相同张量尺寸 的一个新张量, 并且采用随机初始化来对其赋值 y = torch.randn_like(x, dtype=torch.float) # tensor([[ 0.2930, 1.1197, 1.8780], [-1.1264, -1.2930, -0.1120]]) x.size() # torch.Size函数本质上返回的是一个tuple, 因此它支持一切元组的 *** 作. # torch.Size([2, 3]) # x.shape() 没有这个函数二、运算
x = torch.randn(2, 3) # tensor([[-0.4300, -0.8063, 1.4317], [ 0.8179, 0.5675, -2.0124]]) y = torch.ones(2, 3) # tensor([[1., 1., 1.], [1., 1., 1.]]) # 加法方式 1 x + y # tensor([[ 0.5700, 0.1937, 2.4317], [ 1.8179, 1.5675, -1.0124]]) # 加法方式 2 torch.add(x, y) # tensor([[ 0.5700, 0.1937, 2.4317], [ 1.8179, 1.5675, -1.0124]]) # 加法方式 3 # 提前设定一个空的张量 result = torch.empty(2, 3) # 将空的张量作为加法的结果存储张量 torch.add(x, y, out=result) # tensor([[ 0.5700, 0.1937, 2.4317], [ 1.8179, 1.5675, -1.0124]]) # 加法方式 4 - in-place (原地置换) # 注意: 所有in-place的 *** 作函数都有一个下划线的后缀. # 比如x.copy_(y), x.add_(y), 都会直接改变x的值. y.add_(x) # tensor([[ 0.5700, 0.1937, 2.4317], [ 1.8179, 1.5675, -1.0124]]) x[:, 1] tensor([-0.8063, 0.5675]) # tensor([[-0.4300, -0.8063, 1.4317], [ 0.8179, 0.5675, -2.0124]])三、改变形状
x = torch.randn(2, 3) # tensor([[ 0.3722, 0.3018, -0.8382], [-0.6036, -0.6115, 1.2695]]) # tensor.view() *** 作需要保证数据元素的总数量不变 y = x.view(6) # tensor([ 0.3722, 0.3018, -0.8382, -0.6036, -0.6115, 1.2695]) # -1代表自动匹配个数 z = x.view(-1, 2) ''' tensor([[ 0.3722, 0.3018], [-0.8382, -0.6036], [-0.6115, 1.2695]]) ''' z1 = x.view(2, -1) ''' tensor([[ 0.3722, 0.3018, -0.8382], [-0.6036, -0.6115, 1.2695]]) ''' print(x.size(), y.size(), z.size(), z1.size()) # torch.Size([2, 3]) torch.Size([6]) torch.Size([3, 2]) torch.Size([2, 3]) x = torch.randn(1) # tensor([-0.2878]) x.item() # -0.28781047463417053
四、Torch Tensor和Numpy array之间的相互转换
a = torch.ones(5) # tensor([1., 1., 1., 1., 1.]) b = a.numpy() # array([1., 1., 1., 1., 1.], dtype=float32) a.add_(1) # tensor([2., 2., 2., 2., 2.]) b # 同时被改变 # array([2., 2., 2., 2., 2.], dtype=float32) import numpy as np a = np.ones(5) # array([1., 1., 1., 1., 1.]) b = torch.from_numpy(a) # tensor([1., 1., 1., 1., 1.], dtype=torch.float64) np.add(a, 1, out=a) # array([2., 2., 2., 2., 2.])
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)