【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

相关文章

如何将Python彻底卸载的三种方法

《如何将Python彻底卸载的三种方法》通常我们在一些软件的使用上有碰壁,第一反应就是卸载重装,所以有小伙伴就问我Python怎么卸载才能彻底卸载干净,今天这篇文章,小编就来教大家如何彻底卸载Pyth... 目录软件卸载①方法:②方法:③方法:清理相关文件夹软件卸载①方法:首先,在安装python时,下

python uv包管理小结

《pythonuv包管理小结》uv是一个高性能的Python包管理工具,它不仅能够高效地处理包管理和依赖解析,还提供了对Python版本管理的支持,本文主要介绍了pythonuv包管理小结,具有一... 目录安装 uv使用 uv 管理 python 版本安装指定版本的 Python查看已安装的 Python

使用Python开发一个带EPUB转换功能的Markdown编辑器

《使用Python开发一个带EPUB转换功能的Markdown编辑器》Markdown因其简单易用和强大的格式支持,成为了写作者、开发者及内容创作者的首选格式,本文将通过Python开发一个Markd... 目录应用概览代码结构与核心组件1. 初始化与布局 (__init__)2. 工具栏 (setup_t

Python中局部变量和全局变量举例详解

《Python中局部变量和全局变量举例详解》:本文主要介绍如何通过一个简单的Python代码示例来解释命名空间和作用域的概念,它详细说明了内置名称、全局名称、局部名称以及它们之间的查找顺序,文中通... 目录引入例子拆解源码运行结果如下图代码解析 python3命名空间和作用域命名空间命名空间查找顺序命名空

Python如何将大TXT文件分割成4KB小文件

《Python如何将大TXT文件分割成4KB小文件》处理大文本文件是程序员经常遇到的挑战,特别是当我们需要把一个几百MB甚至几个GB的TXT文件分割成小块时,下面我们来聊聊如何用Python自动完成这... 目录为什么需要分割TXT文件基础版:按行分割进阶版:精确控制文件大小完美解决方案:支持UTF-8编码

基于Python打造一个全能文本处理工具

《基于Python打造一个全能文本处理工具》:本文主要介绍一个基于Python+Tkinter开发的全功能本地化文本处理工具,它不仅具备基础的格式转换功能,更集成了中文特色处理等实用功能,有需要的... 目录1. 概述:当文本处理遇上python图形界面2. 功能全景图:六大核心模块解析3.运行效果4. 相

Python中的魔术方法__new__详解

《Python中的魔术方法__new__详解》:本文主要介绍Python中的魔术方法__new__的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、核心意义与机制1.1 构造过程原理1.2 与 __init__ 对比二、核心功能解析2.1 核心能力2.2

Python虚拟环境终极(含PyCharm的使用教程)

《Python虚拟环境终极(含PyCharm的使用教程)》:本文主要介绍Python虚拟环境终极(含PyCharm的使用教程),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录一、为什么需要虚拟环境?二、虚拟环境创建方式对比三、命令行创建虚拟环境(venv)3.1 基础命令3

Python Transformer 库安装配置及使用方法

《PythonTransformer库安装配置及使用方法》HuggingFaceTransformers是自然语言处理(NLP)领域最流行的开源库之一,支持基于Transformer架构的预训练模... 目录python 中的 Transformer 库及使用方法一、库的概述二、安装与配置三、基础使用:Pi

Python 中的 with open文件操作的最佳实践

《Python中的withopen文件操作的最佳实践》在Python中,withopen()提供了一个简洁而安全的方式来处理文件操作,它不仅能确保文件在操作完成后自动关闭,还能处理文件操作中的异... 目录什么是 with open()?为什么使用 with open()?使用 with open() 进行