Pytorch的基本操作

本文主要讲解pytorch上的一些重要操作:

创建、查看形状、创建指定形式的张量、操作方法(加减乘除)以及操作设备(cpu/gpu)

1)torch.tesor([])创建张量

2)torch.view()对张量进行降维

3)torch.size()查看张量的形状

4)torch.ones() torch.zeros()创建指定形式的张量

5)torch.to(device)

在使用torch之前,要对其进行导入

import torch

创建一个torch

1 x = torch.tensor([12, 5])
2 print(x)

得到torch的维度

print(x.size())

torch的resize

1 # resizing
2 x = torch.ones(3, 3)
3 print(x)
4 y = x.view(9)
5 print(y)
6 z = x.view(-1)
7 print(z)
1 tensor([[1., 1., 1.],
2         [1., 1., 1.],
3         [1., 1., 1.]])
4 tensor([1., 1., 1., 1., 1., 1., 1., 1., 1.])
5 tensor([1., 1., 1., 1., 1., 1., 1., 1., 1.])

同样也可以使用x.size(-1)实现

使用GPU进行运算

1 device = torch.device('cuda')
1 x = torch.ones(5, 5, device=device)

或者将定义好的torch迁移到GPU上

1 y = torch.ones(5, 5, dtype=torch.float)
2 y = y.to(device)

同样的,也可以迁移回CPU

1 x = x.to('cpu')
2 y = y.to('cpu')

 

posted @ 2021-05-19 19:32  hi_mxd  阅读(210)  评论(0编辑  收藏  举报