Pytorch基础

本文介绍了PyTorch的基础知识,包括张量操作、自动微分、神经网络的构建和训练,以及图像分类器的训练流程。内容涵盖张量的创建、加法和乘法操作、索引和大小调整,以及如何在GPU上运行张量。此外,还讨论了自动微分的工作原理,如何定义和训练神经网络,并给出了训练图像分类器的步骤。
摘要由CSDN通过智能技术生成

Pytorch基础

PyTorch官方文档笔记

PyTorch入门

Tensors(张量)

Tensors类似于Numpy的ndarrays,同时Tensors可以使用GPU进行计算。

import torch

构造一个5×3的矩阵,不初始化。

x = torch.empty(5, 3)
print(x)

构造一个随机初始化的矩阵。

x = torch.rand(5, 3)
print(x)

构造一个数据类型为long的全0矩阵。

x = torch.zeros(5, 3, dtype=torch.long)
print(x)

构造一个张量,直接使用数据:

x = torch.tensor([5, 3])
print(x)

tensor.rand:创建一组均匀分布的随机数
tensor.randn:创建一组正态分布的随机数
tensor.ones:创建一组全为1的数组
tensor.zeros:创建一组全为0的数组

基于一个已经存在的tensor创建tensor。

x = torch.randn_like(x, dtype=torch.float)
print(x)
# 获取维度信息
print(x.size())

操作

加法
方法一:不改变x,y

x = torch.ones(2, 2)
y = torch.ones(2, 2)
print(x + y)
print(x, y)

方法二:不改变x,y,可提供一个输出

x = torch.ones(2, 2)
y = torch.ones(2, 2)
result = torch.empty(2, 2)
print(torch.add(x, y, out=result))
print(x)
print(y)
print(result)

方法三:改变x,y

x = torch.ones(5, 3)
y = torch.ones(5, 3)
y.add_(x)
print(x)
print(y)

任何使张量会发生变化的操作都有一个前缀’_’。

乘法

  1. 元素相乘
    tensor.mul,torch.mul()
x1 = torch.tensor([[2, 2], [2, 2]])
x2 = torch.tensor([[1, 2], [3, 4]])
print(torch.mul(x1, x2))
print(x1.mul(x2))
print(x1*x2)
  1. 矩阵相乘
    torch.matmul(),tensor @ tensor
x1 = torch.tensor([[2, 2], [2, 2]])
x2 = torch.tensor([[1, 2], [3, 4]])
print(torch.matmul(x1, x2))
print(x1 @ x2)

索引
可以使用Numpy类似的索引操作。

x = torch.rand(3,2)
print(x)
print(x[:, 1])

调整大小
可以使用 torch.view改变一个tensor的大小。

x = torch.randn(3, 2)
print(x)
y = x.view(6)
print(y)

取值
使用.item可以获得tensor的value

x = torch.randn(1)
print(x)
print(x.item())

属性
形状、数据类型、tensor位置
tensor.shape:Shape of tensor.
tensor.dtype:Datatype of tensor.
tensor.device:Device tensor is stored on.
GPU
tensor放到GPU上。

tensor = x
if torch.cuda.is_available():
    tensor = tensor.to('cuda')
print(tensor.device)

连接
torch.cat:沿着指定的维度连接tensor,增加现有维度的值 tensor的size必须相同
torch.stack:增加一个维度

a = torch.tensor([[1, 2]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值