pytorch基础知识

本文介绍了PyTorch的安装,包括CPU和GPU版本,并展示了基本使用方法,如创建和操作矩阵,以及与NumPy的转换。接着详细解释了autograd的求导机制,探讨了不同类型的tensor数据形式。最后,通过线性回归实例展示了模型训练、预测、保存和GPU加速训练的过程。
摘要由CSDN通过智能技术生成


源码地址:https://gitee.com/leecj2020/python.git

一、pytorch安装

(1)使用anaconda进行安装
(2)CUP版本:pip install torch1.5.1+cpu torchvision0.4.1+cpu -f https:download.pytorch.org/whl/torch_stable.html
GUP版本:pip install torch1.5.1 torchvision0.4.1 -f https:download.pytorch.org/whl/torch_stable.html
安装完成后进行检验是否安装成功:

import torch
print(torch.__version__)

显示结果如下:

1.5.1+cpu

说明安装成功。

二、pytorch基本使用方法

2.1 创建空矩阵、随机矩阵、全零矩阵,全1矩阵(5行3列)

import torch
#创建一个空矩阵 5行3列
x=torch.empty(5,3)
print(x)
#创建随机矩阵 5行3列
x=torch.rand(5,3)
print(x)
#全零矩阵 5行3列
x=torch.zeros(5,3,dtype=torch.long)
print(x)
#全1矩阵 5行3列
x=torch.ones(5,3,dtype=torch.long)
print(x)

显示结果:

tensor([[-8.2241e+07,  9.4588e-43, -8.2233e+07],
        [ 9.4588e-43, -8.2241e+07,  9.4588e-43],
        [-8.2241e+07,  9.4588e-43, -8.2236e+07],
        [ 9.4588e-43, -8.2236e+07,  9.4588e-43],
        [-8.2232e+07,  9.4588e-43, -8.2232e+07]])
tensor([[0.4545, 0.8451, 0.4694],
        [0.7477, 0.6897, 0.3975],
        [0.2023, 0.0432, 0.2775],
        [0.0717, 0.9505, 0.4091],
        [0.8665, 0.1950, 0.0786]])
tensor([[0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0],
        [0, 0, 0]])
tensor([[1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1],
        [1, 1, 1]])

矩阵大小:

x=x.size()
print(x)

显示大小:

torch.Size([5, 3])

2.2 矩阵基本计算(5行3列)

基本的加减乘除以及求余

x=torch.ones(5,3)
y=torch.rand(5,3)
#加法
z=x+y
print(z)
#乘法
z=x*y
print(z)
#减法
z=x-y
print(z)
#除法
z=x/y
print(z)
#求余
z=x%y
print(z)

结果如下:

tensor([[1.4779, 1.2724, 1.3372],
        [1.8216, 1.6517, 1.4438],
        [1.5118, 1.2189, 1.5068],
        [1.8231, 1.4565, 1.4452],
        [1.9011, 1.3671, 1.3393]])
tensor([[0.4779, 0.2724, 0.3372],
        [0.8216, 0.6517, 0.4438],
        [0.5118, 0.2189, 0.5068],
        [0.8231, 0.4565, 0.4452],
        [0.9011, 0.3671, 0.3393]])
tensor([[0.5221, 0.7276, 0.6628],
        [0.1784, 0.3483, 0.5562],
        [0.4882, 0.7811, 0.4932
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值