PyTorch快速入门

前言

你好,我是醉墨居士,今天分享一下PyTorch的基本使用的快速入门教程,希望能够帮助各位快速掌握PyTorch的使用

简介

PyTorch 是一个开源的深度学习框架,由 Facebook 的人工智能研究团队(FAIR)开发。它在学术界和工业界都被广泛使用,为深度学习的研究和应用提供了强大的支持

软件包导入

本教程中我们使用torch和numpy这两个包
如果是ubuntu系统,可以看这个教程配置环境:https://blog.youkuaiyun.com/qq_67733273/article/details/144787375

import torch
import numpy as np

创建张量

  • form list
print(torch.tensor([1, 2]), torch.tensor([[1, 2], [3, 4]]))
tensor([1, 2]) tensor([[1, 2],
        [3, 4]])
  • form numpy
print(torch.from_numpy(np.array([1, 2])))
tensor([1, 2])
  • 全0填充
print(torch.zeros(2, 3))
tensor([[0., 0., 0.],
        [0., 0., 0.]])
  • 全1填充
print(torch.ones(2, 3))
tensor([[1., 1., 1.],
        [1., 1., 1.]])
  • 自定义数值全部填充
print(torch.full([2, 3], 6))
tensor([[6, 6, 6],
        [6, 6, 6]])
  • 对角矩阵
print(torch.eye(3, 3))
tensor([[1., 0., 0.],
        [0., 1., 0.],
        [0., 0., 1.]])
  • 未初始化
print(torch.empty(2, 3))
tensor([[5.1981e-06, 0.0000e+00, 0.0000e+00],
        [0.0000e+00, 1.5134e-21, 4.2892e-41]])
  • 标准正态分布
print(torch.randn(2, 3))
tensor([[ 0.0711,  0.2728, -0.4199],
        [ 1.0625,  0.9611, -2.0447]])
  • 0 - 1浮点均匀分布
print(torch.rand(2, 3))
tensor([[0.2974, 0.6033, 0.7126],
        [0.1599, 0.5974, 0.8983]])
  • 1 - 9整数均匀分布
print(torch.randint(1, 10, [2, 3]))
tensor([[1, 2, 8],
        [9, 3, 4]])
  • 递增数列, 0 ~ 9,步长是2
print(torch.arange(0, 10, 2))
tensor([0, 2, 4, 6, 8])
  • 等差数列,0 ~ 10, 共计4个数
print(torch.linspace(0, 10, 4))
tensor([ 0.0000,  3.3333,  6.6667, 10.0000])
  • 指定类型创建
print(torch.FloatTensor([1, 2]), torch.LongTensor([1, 2]))
tensor([1., 2.]) tensor([1, 2])

类型操作

  • 获取数据类型
print(torch.randn(2, 3).dtype)
torch.float32
  • 转换数据类型
print(torch.randn(2, 3).to(torch.float64).dtype)
torch.float64
  • 张量形状
print(torch.randn(2, 3).shape
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醉墨居士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值