【Python】科研代码学习:二 dataclass,pipeline

2024-03-09 04:44

本文主要是介绍【Python】科研代码学习:二 dataclass,pipeline,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【Python】科研代码学习:二 dataclass,pipeline

  • 前言
  • dataclass
  • pipeline

前言

  • 后文需要学习一下 transformers 库,必要时会介绍其他相关的重要库和方法。
  • 主要是从源代码、别人的技术文档学习,会更快些。

dataclass

  • Python中的数据类dataclass详解
    python中的dataclasses中的field用法实战
    一文了解 Python3.7 新特性——dataclass装饰器
  • 使用 Tuple 存储数据:data = (1, 2, "abc"),获取:data[0]
  • 使用 Dict 存储数据:data = {"name" : "Alice"},获取:data["Alice"]
  • 使用 namedtuple 存储数据:导入 from collections import namedtuplePlayer = namedtuple('Player', ['name', 'number', 'position', 'age', 'grade'])jordan = Player('Micheal Jordan', 23, 'PG', 29, 'S+'),获取:jordan.name,但数据无法修改
  • 使用自定义类存储数据,但在 __init__ 方法中传参数比较麻烦
  • 使用 dataclass 存储数据:
    导入:from dataclasses import dataclass
    声明:
@dataclass
class Player:name: strnumber: intposition: strage: intgrade: strjames = Player('Lebron James', 23, 'SF', 25, 'S')
  • 它可以支持 Typing.Any, Typying.List 等 ,可以设置默认值,可以数据嵌套,可以传
  • 不可变类型:修改 @dataclass(frozen=True)
    在这里插入图片描述
  • dataclasses.field :数据类的基石
    看一下源码:
# This function is used instead of exposing Field creation directly,
# so that a type checker can be told (via overloads) that this is a
# function whose type depends on its parameters.
def field(*, default=MISSING, default_factory=MISSING, init=True, repr=True,hash=None, compare=True, metadata=None):"""Return an object to identify dataclass fields.default is the default value of the field.  default_factory is a0-argument function called to initialize a field's value.  If initis True, the field will be a parameter to the class's __init__()function.  If repr is True, the field will be included in theobject's repr().  If hash is True, the field will be included inthe object's hash().  If compare is True, the field will be usedin comparison functions.  metadata, if specified, must be amapping which is stored but not otherwise examined by dataclass.It is an error to specify both default and default_factory."""if default is not MISSING and default_factory is not MISSING:raise ValueError('cannot specify both default and default_factory')return Field(default, default_factory, init, repr, hash, compare,metadata)
  • 1)price : float = 0.0 相当于 price : float = field(default = '0.0')
  • 2)default_factory 提供的是一个零参数或全有默认参数的函数,作为初始化。
  • 3)defaultdefault_factory 只能二选一
  • 4)对于可变对象 mutable 类型的(如 list),必须使用 filed(default_factory = list) 等指定
  • 5)metadata 是一个字典,该字典作为额外补充数据,不在 dataclasses 中使用,是给用户去调用额外的信息的。
    其他参数解释:
    在这里插入图片描述
  • 现在再来看一下代码练习(截取了小部分代码)
    应该就能看懂了(asdict 将obj转成dict, fields 相当于一堆 filed)
from dataclasses import asdict, dataclass, field, fields
@dataclass
class TrainingArguments:framework = "pt"output_dir: str = field(metadata={"help": "The output directory where the model predictions and checkpoints will be written."},)overwrite_output_dir: bool = field(default=False,metadata={"help": ("Overwrite the content of the output directory. ""Use this to continue training if output_dir points to a checkpoint directory.")},)do_train: bool = field(default=False, metadata={"help": "Whether to run training."})do_eval: bool = field(default=False, metadata={"help": "Whether to run eval on the dev set."})do_predict: bool = field(default=False, metadata={"help": "Whether to run predictions on the test set."})

pipeline

  • pipeline 主要提供了HF模型的简易接口
    HF官网-Pipelines
    注意:官网左侧修改 transformers 的版本号,不同版本的API文档自然是有出入的
    在这里插入图片描述

  • 怎么学习调用比较好呢,一个推荐是,在上述官网的API中
    我们按照我们需要进行的任务进行索引:
    可以看分类索引
    在这里插入图片描述

或者 task 参数的介绍

task (str) — The task defining which pipeline will be returned. Currently accepted tasks are:"audio-classification": will return a AudioClassificationPipeline.
"automatic-speech-recognition": will return a AutomaticSpeechRecognitionPipeline.
"conversational": will return a ConversationalPipeline.
"depth-estimation": will return a DepthEstimationPipeline.
"document-question-answering": will return a DocumentQuestionAnsweringPipeline.
"feature-extraction": will return a FeatureExtractionPipeline.
"fill-mask": will return a FillMaskPipeline:.
"image-classification": will return a ImageClassificationPipeline.
"image-feature-extraction": will return an ImageFeatureExtractionPipeline.
"image-segmentation": will return a ImageSegmentationPipeline.
"image-to-image": will return a ImageToImagePipeline.
"image-to-text": will return a ImageToTextPipeline.
"mask-generation": will return a MaskGenerationPipeline.
"object-detection": will return a ObjectDetectionPipeline.
"question-answering": will return a QuestionAnsweringPipeline.
"summarization": will return a SummarizationPipeline.
"table-question-answering": will return a TableQuestionAnsweringPipeline.
"text2text-generation": will return a Text2TextGenerationPipeline.
"text-classification" (alias "sentiment-analysis" available): will return a TextClassificationPipeline.
"text-generation": will return a TextGenerationPipeline:.
"text-to-audio" (alias "text-to-speech" available): will return a TextToAudioPipeline:.
"token-classification" (alias "ner" available): will return a TokenClassificationPipeline.
"translation": will return a TranslationPipeline.
"translation_xx_to_yy": will return a TranslationPipeline.
"video-classification": will return a VideoClassificationPipeline.
"visual-question-answering": will return a VisualQuestionAnsweringPipeline.
"zero-shot-classification": will return a ZeroShotClassificationPipeline.
"zero-shot-image-classification": will return a ZeroShotImageClassificationPipeline.
"zero-shot-audio-classification": will return a ZeroShotAudioClassificationPipeline.
"zero-shot-object-detection": will return a ZeroShotObjectDetectionPipeline.
  • 比如说,我需要做文本总结任务,看到有 summarization,然后点击后面的 SummarizationPipeline 去索引它的用法(Usage):
from transformers import pipeline# use bart in pytorch
summarizer = pipeline("summarization")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)# use t5 in tf
summarizer = pipeline("summarization", model="google-t5/t5-base", tokenizer="google-t5/t5-base", framework="tf")
summarizer("An apple a day, keeps the doctor away", min_length=5, max_length=20)
  • 一个问题是,model 是一个可选参数嘛,有时候默认的模型只能做英文任务,这个时候我可以去 HF 官网,查找需要的模型,传入 model 参数即可。
  • 一个比较重要的参数是 device,设置运行的单卡

device (int, optional, defaults to -1) — Device ordinal for CPU/GPU supports. Setting this to -1 will leverage CPU, a positive will run the model on the associated CUDA device id. You can pass native torch.device or a str too

  • 如果想要多卡,那么需要使用 device_map,注意不能和 device 同时用

device_map (str or Dict[str, Union[int, str, torch.device], optional) — Sent directly as model_kwargs (just a simpler shortcut). When accelerate library is present, set device_map=“auto” to compute the most optimized

  • 再看一下源码:
    在这里插入图片描述

  • 所以后续可能要详细看一下:

PreTrainedModel : model 的参数类型
PretrainedConfig : config 的参数类型
PreTrainedTokenizer : tokenizer 的参数类型
以及训练时必用的
Trainer
TrainingArguments
Data Collator

这篇关于【Python】科研代码学习:二 dataclass,pipeline的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/789542

相关文章

JAVA调用Deepseek的api完成基本对话简单代码示例

《JAVA调用Deepseek的api完成基本对话简单代码示例》:本文主要介绍JAVA调用Deepseek的api完成基本对话的相关资料,文中详细讲解了如何获取DeepSeekAPI密钥、添加H... 获取API密钥首先,从DeepSeek平台获取API密钥,用于身份验证。添加HTTP客户端依赖使用Jav

Java实现状态模式的示例代码

《Java实现状态模式的示例代码》状态模式是一种行为型设计模式,允许对象根据其内部状态改变行为,本文主要介绍了Java实现状态模式的示例代码,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来... 目录一、简介1、定义2、状态模式的结构二、Java实现案例1、电灯开关状态案例2、番茄工作法状态案例

一文教你使用Python实现本地分页

《一文教你使用Python实现本地分页》这篇文章主要为大家详细介绍了Python如何实现本地分页的算法,主要针对二级数据结构,文中的示例代码简洁易懂,有需要的小伙伴可以了解下... 在项目开发的过程中,遇到分页的第一页就展示大量的数据,导致前端列表加载展示的速度慢,所以需要在本地加入分页处理,把所有数据先放

树莓派启动python的实现方法

《树莓派启动python的实现方法》本文主要介绍了树莓派启动python的实现方法,文中通过图文介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录一、RASPBerry系统设置二、使用sandroidsh连接上开发板Raspberry Pi三、运

Python给Excel写入数据的四种方法小结

《Python给Excel写入数据的四种方法小结》本文主要介绍了Python给Excel写入数据的四种方法小结,包含openpyxl库、xlsxwriter库、pandas库和win32com库,具有... 目录1. 使用 openpyxl 库2. 使用 xlsxwriter 库3. 使用 pandas 库

python实现简易SSL的项目实践

《python实现简易SSL的项目实践》本文主要介绍了python实现简易SSL的项目实践,包括CA.py、server.py和client.py三个模块,文中通过示例代码介绍的非常详细,对大家的学习... 目录运行环境运行前准备程序实现与流程说明运行截图代码CA.pyclient.pyserver.py参

使用Python实现批量分割PDF文件

《使用Python实现批量分割PDF文件》这篇文章主要为大家详细介绍了如何使用Python进行批量分割PDF文件功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、架构设计二、代码实现三、批量分割PDF文件四、总结本文将介绍如何使用python进js行批量分割PDF文件的方法

Python实现多路视频多窗口播放功能

《Python实现多路视频多窗口播放功能》这篇文章主要为大家详细介绍了Python实现多路视频多窗口播放功能的相关知识,文中的示例代码讲解详细,有需要的小伙伴可以跟随小编一起学习一下... 目录一、python实现多路视频播放功能二、代码实现三、打包代码实现总结一、python实现多路视频播放功能服务端开

使用Python在Excel中创建和取消数据分组

《使用Python在Excel中创建和取消数据分组》Excel中的分组是一种通过添加层级结构将相邻行或列组织在一起的功能,当分组完成后,用户可以通过折叠或展开数据组来简化数据视图,这篇博客将介绍如何使... 目录引言使用工具python在Excel中创建行和列分组Python在Excel中创建嵌套分组Pyt

Python实现视频转换为音频的方法详解

《Python实现视频转换为音频的方法详解》这篇文章主要为大家详细Python如何将视频转换为音频并将音频文件保存到特定文件夹下,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. python需求的任务2. Python代码的实现3. 代码修改的位置4. 运行结果5. 注意事项