首页 > 其他分享 >PyTorchStepByStep - Chapter 2.1: Going Classy

PyTorchStepByStep - Chapter 2.1: Going Classy

时间:2024-10-13 17:43:45浏览次数:1  
标签:Chapter None self loader Going cuda device 2.1 model

 

class StepByStep():
    def __init__(self, model, loss_fn, optimizer):
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.model = model.to(self.device)
        self.loss_fn = loss_fn
        self.optimizer = optimizer

    def to(self, device):
        # This method allows the user to specify a different device
        # It sets the corresponding attribute (to be used later in
        # the mini-batches) and sends the model to the device
        try:
            self.device = device
            self.model.to(self.device)
        except RuntimeError:
            self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
            print(f"Couldn't send it to {device}, sending it to {self.device} instead.")
            self.model.to(self.device)

 

class StepByStep():
    def __init__(self, model, loss_fn, optimizer):
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.model = model.to(self.device)
        self.loss_fn = loss_fn
        self.optimizer = optimizer

        # These attributes are defined here, but since they are
        # not available at the moment of creation, we keep them None
        self.train_loader = None
        self.val_loader = None
        self.writer = None

    def to(self, device):
        # This method allows the user to specify a different device
        # It sets the corresponding attribute (to be used later in
        # the mini-batches) and sends the model to the device
        try:
            self.device = device
            self.model.to(self.device)
        except RuntimeError:
            self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
            print(f"Couldn't send it to {device}, sending it to {self.device} instead.")
            self.model.to(self.device)

    def set_loaders(self, train_loader, val_loader=None):
        self.train_loader = train_loader
        self.val_loader = val_loader

    def set_tensorboard(self, name, folder='runs'):
        # This method allows the user to create a SummaryWriter to interface with TensorBoard
        suffix = datetime.now().strftime('%Y%m%d%H%M%S')
        self.writer = SummaryWriter(f'{folder}/{name}_{suffix}')

 

class StepByStep():
    def __init__(self, model, loss_fn, optimizer):
        self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
        self.model = model.to(self.device)
        self.loss_fn = loss_fn
        self.optimizer = optimizer

        # These attributes are defined here, but since they are
        # not available at the moment of creation, we keep them None
        self.train_loader = None
        self.val_loader = None
        self.writer = None

        # These attributes are going to be computed internally
        self.losses = []
        self.val_losses = []
        self.total_epochs = 0

    def to(self, device):
        # This method allows the user to specify a different device
        # It sets the corresponding attribute (to be used later in
        # the mini-batches) and sends the model to the device
        try:
            self.device = device
            self.model.to(self.device)
        except RuntimeError:
            self.device = 'cuda' if torch.cuda.is_available() else 'cpu'
            print(f"Couldn't send it to {device}, sending it to {self.device} instead.")
            self.model.to(self.device)

    def set_loaders(self, train_loader, val_loader=None):
        self.train_loader = train_loader
        self.val_loader = val_loader

    def set_tensorboard(self, name, folder='runs'):
        # This method allows the user to create a SummaryWriter to interface with TensorBoard
        suffix = datetime.now().strftime('%Y%m%d%H%M%S')
        self.writer = SummaryWriter(f'{folder}/{name}_{suffix}')

 

标签:Chapter,None,self,loader,Going,cuda,device,2.1,model
From: https://www.cnblogs.com/zhangzhihui/p/18462649

相关文章

  • 如何学习VBA_3.2.12:工作表函数也是可以利用的
    我给VBA的定义:VBA是个人小型自动化处理的有效工具。利用好了,可以大大提高自己的劳动效率,而且可以提高数据处理的准确度。我推出的VBA系列教程共九套和一部VBA汉英手册,现在已经全部完成,希望大家利用、学习。如果您只是一般的职场VBA需求,可以打包选择7.1.3.9教程+汉英手册,第7套教程是......
  • PyTorchStepByStep - Chapter 2: Rethinking the Training Loop
      defmake_train_step_fn(model,loss_fn,optimizer):defperform_train_step_fn(x,y):#SetmodeltoTRAINmodemodel.train()#Step1-Computemodel'spredictions-forwardpassyhat=model(x)......
  • YoloDotNet v2.1:实时物体检测的利器oX
    项目介绍YoloDotNetv2.1是一个基于C#和.NET8的实时物体检测框架,专为图像和视频中的物体检测而设计。它集成了Yolov8~Yolov11模型,通过ML.NET和ONNX运行时实现高效的物体检测,并支持GPU加速(使用CUDA)。YoloDotNet不仅支持传统的物体检测,还涵盖了分类、OBB检测、......
  • 2018-8-10-win10-uwp-商业游戏-1.2.1
    titleauthordateCreateTimecategorieswin10uwp商业游戏1.2.1lindexi2018-08-1019:16:50+08002018-2-1317:23:3+0800Win10UWP上一个游戏已经告诉大家如何写多个游戏,现在继续写这个无聊的游戏。希望大家在看这篇文章之前先看win10uwp商业游戏,在这个文章告诉了大家如何创建......
  • YoloDotNet v2.1:实时物体检测的利器
    项目介绍YoloDotNetv2.1是一个基于C#和.NET8的实时物体检测框架,专为图像和视频中的物体检测而设计。它集成了Yolov8~Yolov11模型,通过ML.NET和ONNX运行时实现高效的物体检测,并支持GPU加速(使用CUDA)。YoloDotNet不仅支持传统的物体检测,还涵盖了分类、OBB检测、分......
  • Cornell cs3110 - Chapter9 Lessons
    使用Menhir构建SimPL的编译器LexerandParser语法分析模块Lexer,Parser,AST是三个依次耦合的模块,可以这么描述三者的关系:Lexer---tokens-->Parser---nodes-->AST相对于上面的图像化描述,cs3110反过来构建整个Lexer和Parser的结构在ast.ml中,定义了AST上......
  • 【RAG论文精读3】RAG论文综述1(2312.10997)-第1部分
    收录于我的专栏:AI修炼之路简介论文中英文名Retrieval-AugmentedGenerationforLargeLanguageModels:ASurvey面向大型语言模型的检索增强生成:综述论文地址arxiv地址:https://arxiv.org/abs/2312.10997精读理由这篇综述论文对RAG在大型语言模型中的应用进行了......
  • Html批量转word工具2.1
    2024年10月7日记录:有客户反馈,2.0刚运行就提示转换完成有问题就解决。正好国庆假期这几天有空,2.1版就出炉了。2.1更新记录:修复了1个bug:刚运行就提示转换完成下载地址:Html转word批量处理工具(独家原创工具)-精品资源小站资源包包含:html转word工具1.0版html转wor......
  • foobar2000 v2.1.6 汉化版
    foobar2000v2.1.6汉化版-----------------------【软件截图】----------------------   -----------------------【软件介绍】----------------------foobar2000是一个Windows平台下的高级音频播放器.包含完全支持unicode及支持播放增益的高级标签功能.特色:*支......
  • Cisco Firepower 9300 Series FTD Software 7.6.0 & ASA Software 9.22.1
    CiscoFirepower9300SeriesFTDSoftware7.6.0&ASASoftware9.22.1FirepowerThreatDefense(FTD)Software-思科防火墙系统软件请访问原文链接:https://sysin.org/blog/cisco-firepower-9300/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgCiscoSecure防......