pytorch基础

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
    原文地址: https://www.cnblogs.com/alilliam/p/9984850.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞