from __future__ import print_function import torch
1.1 创建矩阵
1 2 3 4 5 6 7 8 9 10
#API x = torch.empty(5,3)#没有初始化的5x3矩阵 x = torch.rand(5,3)#随机初始化的矩阵 x = torch.zeros(5,3, dtype=torch.long)#初始化为类型为long值为0的矩阵 #数据 x = torch.tensor([5.5, 4]) x = torch.from_numpy(np.array([5.5,4])) #已经存在的tensor x = x.new_ones(2,2,dtype=torch.double)#new_* x = torch.randn_like(x, dtype=torch.float)#*_like
1.2 矩阵操作
add的三种方式
A+B:
1 2 3
x = torch.ones(5,3) y = torch.rand(5, 3) print("x+y:n", x+y)
torch.add(A,B):
可以指定输出变量
1 2 3 4
print("torch.add(x,y):n", torch.add(x,y)) result = torch.empty(5,3) torch.add(x,y, out=result) print("通过形参指定输出变量:n", result)
print("Converting a Torch Tensor to a NumPy Array:n") a = torch.ones(5) b = a.numpy() print("使用torch.numpy(), 把tensor转换为numpy类型的数据:n",a, b) print("来看看numpy数组的值怎么变换的") a.add_(1) print("a.add_(1):n", a, b) np.add(b, 1, out=b) print("np.add(b, 1, out=b):n", a, b)
numpy ndarray => torch tensor
1 2 3 4 5 6 7 8
print("Converting NumPy array to Torch Tensor:n") a = np.ones(4) b = torch.from_numpy(a) print("使用torch.from_numpy()将numpy数组转换为tensor:n",a,b) np.add(a, 1, out=a) print("np.add(a,1,out=a):n",a,b) b.add_(1) print("b.add_(1):n", a,b)
近期评论