首页 > 其他 > 详细

Pytorch的基本操作

时间:2021-05-19 23:46:12      阅读:26      评论:0      收藏:0      [点我收藏+]

本文主要讲解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)

 

Pytorch的基本操作

原文:https://www.cnblogs.com/xmd-home/p/14787037.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!