【PyTorch Tutorial学习笔记】PyTorch代码模板(自用)(一)

这篇博客是PyTorch教程的学习笔记,重点在于提供一个完整的PyTorch代码模板,包括数据加载、模型创建、训练过程以及模型的保存和加载,适用于深度学习和神经网络初学者。
摘要由CSDN通过智能技术生成

QUICKSTART

首先展示一个完整的pytorch代码:

  1. load data
  2. create the model
  3. train the model
  4. save & load the model
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt

### Working with data ###
### step 1: get datasets.
### step 2: get dataloaders. Pass the 'Dataset' as an argument to 'DataLoader'. This supports automatic batching, sampling, shuffling and multiprocess data loading.

# Download training data from open datasets.
training_data = datasets.FashionMNIST(root="data", train=True, download=True, transform=ToTensor())
test_data = datasets.FashionMNIST(root="data", train=False, download=True, transform=ToTensor())

batch_size = 64

# Create data loaders.
train_dataloader = DataLoader(training_data, batch_size=batch_size)
test_dataloader = DataLoader(test_data, batch_size=batch_size)

for X, y in test_dataloader:
    print("Shape of X [N, C, H, W]: ", X.shape)
    print("Shape of y: ", y.shape, y.dtype)
    break

### Creating Models ###
### step 1: create a class that inherits from nn.Module
### step 2: define the layers in '__init__' function
### step 3: define specify the data flow in 'forward' function

# Get cpu or gpu device for training.
device = "cuda" if torch.cuda.is_available(
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值