【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

相关文章

Conda与Python venv虚拟环境的区别与使用方法详解

《Conda与Pythonvenv虚拟环境的区别与使用方法详解》随着Python社区的成长,虚拟环境的概念和技术也在不断发展,:本文主要介绍Conda与Pythonvenv虚拟环境的区别与使用... 目录前言一、Conda 与 python venv 的核心区别1. Conda 的特点2. Python v

Python使用python-can实现合并BLF文件

《Python使用python-can实现合并BLF文件》python-can库是Python生态中专注于CAN总线通信与数据处理的强大工具,本文将使用python-can为BLF文件合并提供高效灵活... 目录一、python-can 库:CAN 数据处理的利器二、BLF 文件合并核心代码解析1. 基础合

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Python中你不知道的gzip高级用法分享

《Python中你不知道的gzip高级用法分享》在当今大数据时代,数据存储和传输成本已成为每个开发者必须考虑的问题,Python内置的gzip模块提供了一种简单高效的解决方案,下面小编就来和大家详细讲... 目录前言:为什么数据压缩如此重要1. gzip 模块基础介绍2. 基本压缩与解压缩操作2.1 压缩文

Python设置Cookie永不超时的详细指南

《Python设置Cookie永不超时的详细指南》Cookie是一种存储在用户浏览器中的小型数据片段,用于记录用户的登录状态、偏好设置等信息,下面小编就来和大家详细讲讲Python如何设置Cookie... 目录一、Cookie的作用与重要性二、Cookie过期的原因三、实现Cookie永不超时的方法(一)

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

Python实现对阿里云OSS对象存储的操作详解

《Python实现对阿里云OSS对象存储的操作详解》这篇文章主要为大家详细介绍了Python实现对阿里云OSS对象存储的操作相关知识,包括连接,上传,下载,列举等功能,感兴趣的小伙伴可以了解下... 目录一、直接使用代码二、详细使用1. 环境准备2. 初始化配置3. bucket配置创建4. 文件上传到os

使用Python实现可恢复式多线程下载器

《使用Python实现可恢复式多线程下载器》在数字时代,大文件下载已成为日常操作,本文将手把手教你用Python打造专业级下载器,实现断点续传,多线程加速,速度限制等功能,感兴趣的小伙伴可以了解下... 目录一、智能续传:从崩溃边缘抢救进度二、多线程加速:榨干网络带宽三、速度控制:做网络的好邻居四、终端交互

Python中注释使用方法举例详解

《Python中注释使用方法举例详解》在Python编程语言中注释是必不可少的一部分,它有助于提高代码的可读性和维护性,:本文主要介绍Python中注释使用方法的相关资料,需要的朋友可以参考下... 目录一、前言二、什么是注释?示例:三、单行注释语法:以 China编程# 开头,后面的内容为注释内容示例:示例:四