加载自己的数据集训练,以VGG和LeNet为例,自己做的笔记,避免忘记

本文介绍了如何使用PyTorch构建VGGNet模型对ImageNet数据集进行训练,包括数据预处理、模型定义、数据加载、训练过程和最终导出为ONNX格式以支持部署。

数据集为imagenet的格式,分为训练和验证两个文件夹,训练文件的子文件夹的名字代表具体的类别。

——ImageNet
  ——train
  	——cls1
  		——cls1_00.jpg
  		——cls1_01.jpg
  		...
  		——cls1_59.jpg
  	——cls2
  	——clsn
  ——test
  	——cls1
  		——cls1_60.jpg
  		——cls1_61.jpg
  		...
  		——cls1_100.jpg
  	——cls2
  	——clsn
import os
from torch.utils.data import Dataset, DataLoader
from PIL import Image
from torch import nn
import torch.optim as optim
from torchvision import transforms, models
import torch

class VGGNet(nn.Module):
    def __init__(self, num_classes=2):
        super(VGGNet, self).__init__()
        net = models.vgg16(pretrained=True)
        net.classifier = nn.Sequential()
        self.features = net
        self.classifier = nn.Sequential(
                nn.Linear(512 * 7 * 7, 512),
                nn.ReLU(True),
                nn.Dropout(),
                nn.Linear(512, 128),
                nn.ReLU(True),
                nn.Dropout(),
                nn.Linear(128, num_classes),
        )

    def forward(self, x):
        print("x.shape =" ,x.shape) #打印这行确定导出为onnx的输入的大小
        x = self.features(x)
        x = x.view(x.size(0), -1)
        x = self.classifier(x) 
        return x

import torch.nn as nn

# 定义LeNet网络结构
# class LeNet(nn.Module):
#     def __init__(self, num_classes=2):
#         super(LeNet, self).__init__()
#         self.features = nn.Sequential(
#             nn.Conv2d(3, 6, kernel_size=5),
#             nn.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值