1.创建一个未初始化矩阵
from __future__ import print_function import torch x = torch.empty(2,3)#uninitialized matrix print(x)
2.均匀分布
x = torch.rand(2,3) print(x)
3.创建一个零矩阵
x = torch.zeros(5,3,dtype = torch.long) print(x)
4.自定义初始化矩阵,覆盖并改变dtype
x = torch.tensor([5.5,3])#初始化 x = torch.randn_like(x,dtype=torch.float)#override dtype print(x)
5.产生单位矩阵
x = torch.eye(4,4,dtype = torch.float) print(x)
6.将已有矩阵的元素都变成1
x = torch.eye(4,4,dtype = torch.float) x= x.new_ones(5,3) print(x)
7.加
from __future__ import print_function import torch x = torch.eye(5,3,dtype = torch.float) y= x.new_ones(5,3) print(x+y) print(torch.add(x,y)) result = torch.empty(5,3) torch.add(x,y,out = result) print(result) y.add_(x) print(y)
8.打印第一列
print(x[:,0])
9.view
x = torch.randn(4,5) y = x.view(20) z = x.view(-1,10) print(x.size(),y.size(),z.size()) print(x) print(y) print(z)
10.item (单元素矩阵转数字)
x = torch.randn(1) print(x) print(x.item())
11.tensor转numpy
a=torch.ones(5) print(a) b=a.numpy() print(b)
12.numpy转tensor
import numpy as np a = np.ones(5) b=torch.from_numpy(a) np.add(a,1,out=a) print(a) print(b)
13.numpy转PIL
Image.fromarray(np.uint8(img))
14.PIL转numpy
img = Image.open('1.png') a = np.asarray(img)
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:pytorch基础 - Python技术站