定州市网站建设_网站建设公司_CSS_seo优化
2025/12/24 16:10:41 网站建设 项目流程

文章目录

  • 多模态
    • 文档问答
    • 可视化问答
    • 零样本可视化问答
    • 特征提取
      • 文本特征提取
      • 音频特征提取
        • 提取特征
        • 提取器支持类
        • 输入预处理
          • 填充
          • 截断
          • 重采样
      • 图像特征提取
    • 图像描述生成
    • 图片转文本
    • 图片文本转文本
    • 蒙版生成

Transformers是一个采用当下技术最新、表现最佳(State-of-the-artSoTA)的模型和技术在预训练自然语言处理计算机视觉音频多模态模型方面提供推理和训练的的开源库;旨在快速易用,以便每个人都可以开始使用transformer模型进行学习或构建。该库不仅包含Transformer模型,还包括用于计算机视觉任务的现代卷积网络等非Transformer模型。

多模态

多模态任务要求模型处理多种数据模态(文本、图像、音频、视频)以解决特定问题。图像描述是一个多模态任务的例子,其中模型将图像作为输入并输出描述图像或图像某些属性的文本序列。

虽然多模态模型处理不同的数据类型或模态,但内部预处理步骤帮助模型将所有数据类型转换为embeddings(向量或数字列表,包含有关数据的有意义信息)。对于像图像描述这样的任务,模型学习图像嵌入和文本嵌入之间的关系。

文档问答

文档问答(Document Question Answering)是从文档中回答“自然语言问题”的任务。与token-level问答任务不同,文档问答根据输入文本(问题)从提供的文档中的图像寻找答案,并返回答案。文档问答可用于解析结构化文档并从中提取关键信息。在下面的例子中,可以从收据中提取总金额和找零金额。

from transformers import pipeline from PIL import Image import requests url = "https://huggingface.co/datasets/hf-internal-testing/example-documents/resolve/main/jpeg_images/2.jpg" image = Image.open(requests.get(url, stream=True).raw) doc_question_answerer = pipeline("document-question-answering", model="magorshunov/layoutlm-invoices") preds = doc_question_answerer( question="What is the total amount?", image=image, ) preds

结果为:

[{'score': 0.8531, 'answer': '17,000', 'start': 4, 'end': 4}]

可视化问答

视觉问答(Visual Question AnsweringVQA)是一个根据图像和开放式问题给出答案的任务。该任务的模型输入通常是一张图像和一个问题的组合,输出是以自然语言表达的答案。

VQA应用案例有:

  • 面向视力障碍个体的辅助应用。
  • 教育:对讲座或教科书中呈现的视觉材料提问。VQA还可以在互动博物馆展示或历史遗址中应用。
  • 客户服务和电子商务:VQA可以通过允许用户提问产品来提升用户体验。
  • 图像检索:VQA模型可以用于检索具有特定特征的图像。如用户通过询问“Is there a dog?”从一组图像中找到所有包含狗的图像等。
from transformers import pipeline pipe = pipeline("visual-question-answering", model="MariaK/vilt_finetuned_200")

然后,准备输入,包括一张图片和一个问题:

example = dataset[0] image = Image.open(example['image_id']) question = example['question'] print(question) pipe(image, question)

以上案例假定有一个数据集并从数据集中提取出第一条记录,然后从iamge_id节点取出图片地址,从question节点取出问题信息,数据集的第一条记录结构如下:

{'question': 'Where is he looking?', 'question_type': 'none of the above', 'question_id': 262148000, 'image_id': '/root/.cache/huggingface/datasets/downloads/extracted/ca733e0e000fb2d7a09fbcc94dbfe7b5a30750681d0e965f8e0a23b1c2f98c75/val2014/COCO_val2014_000000262148.jpg', 'answer_type': 'other', 'label': {'ids': ['at table', 'down', 'skateboard', 'table'], 'weights': [0.30000001192092896, 1.0, 0.30000001192092896, 0.30000001192092896]}}

执行推理得到结果如下:

"Where is he looking?" [{'score': 0.5498199462890625, 'answer': 'down'}]

零样本可视化问答

前一模型将VQA视为分类任务进行处理。近期的一些模型,如BLIPBLIP-2InstructBLIP,则将VQA视为生成任务。以BLIP-2为例。它引入了一种支持预训练视觉编码器和LLM的任意组合的新的视觉语言(visual-language)预训练范式。这使得在多个视觉语言任务中实现了最先进的结果,包括视觉问答。

下面开始讲解如何在VQA任务上使用这个模型。

首先先加载模型。如果设备支持GPU,则将加载的模型指给GPU。之前在训练时不需要这样做,训练器会自动处理:

from transformers import AutoProcessor, Blip2ForConditionalGeneration import torch processor = AutoProcessor.from_pretrained("Salesforce/blip2-opt-2.7b") model = Blip2ForConditionalGeneration.from_pretrained("Salesforce/blip2-opt-2.7b", torch_dtype=torch.float16) device = "cuda" if torch.cuda.is_available() else "cpu" model.to(device)

然后准备输入包括一张图像和一段文本:

example = dataset[0] image = Image.open(example['image_id']) question = example['question']

以上案例假定有一个数据集并从数据集中提取出第一条记录,然后从iamge_id节点取出图片地址,从question节点取出问题信息,数据集的第一条记录结构如下:

{'question': 'Where is he looking?', 'question_type': 'none of the above', 'question_id': 262148000, 'image_id': '/root/.cache/huggingface/datasets/downloads/extracted/ca733e0e000fb2d7a09fbcc94dbfe7b5a30750681d0e965f8e0a23b1c2f98c75/val2014/COCO_val2014_000000262148.jpg', 'answer_type': 'other', 'label': {'ids': ['at table', 'down', 'skateboard', 'table'], 'weights': [0.30000001192092896, 1.0, 0.30000001192092896, 0.30000001192092896]}}

要使用BLIP-2进行视觉问答任务,文本提示必须遵循特定的格式:Question: {} Answer:.

prompt = f"Question: {question} Answer:"

现在使用processor预处理图像/提示,并将处理过的输入传给实例model,然后解码输出:

inputs = processor(image, text=prompt, return_tensors="pt").to(device, torch.float16) generated_ids = model.generate(**inputs, max_new_tokens=10) generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0].strip() print(generated_text)

结果:

"He is looking at the crowd"

正如你所见,模型识别了人群和面部的朝向(向下看),但它似乎忽略了人群在滑冰者后面的事实。尽管如此,在无法获取人工注释数据集的情况下,这种方法可以快速产生有用的结果。

特征提取

特征抽取(feature-extraction)用途非常广泛,指将文本、语音、图片、视频抽帧等多模态内容向量化,在内容相似比对、推荐模型、迁移学习、检索排序、RAG等场景非常常用。

文本特征提取

首先将Pipeline实例化,并在实例化时指定任务feature-extraction和所使用的模型facebook/bart-base:

from transformers import pipeline feature_extractor = pipeline(model="google-bert/bert-base-uncased", task="feature-extraction")

然后调用实例feature_extractor并传入要处理的文本得到预测的结果并打印输出:

text = "Transformers is an awesome library!" output=feature_extractor(text,return_tensors = "pt") print(output)

音频特征提取

特征提取器将音频数据预处理成给定模型所需的正确格式。它接受原始音频信号并将其转换为可以馈送到模型中的张量。张量的形状取决于模型,但是特征提取器会根据你使用的模型正确地预处理音频数据。特征提取器还包括填充、截断和重采样的方法。

提取特征

调用 [~AutoFeatureExtractor.from_pretrained] 从Hugging Face Hub站点或本地目录加载特征提取器及其预处理器配置。特征提取器和预处理器配置保存在preprocessor_config.json文件中。

将音频信号(通常保存在array中)传递给特征提取器,并设置sampling_rate参数为预训练音频模型的采样率。注意:音频数据的采样率与预训练音频模型所训练的数据的采样率要相匹配。

from transformers import AutoFeatureExtractor feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base") processed_sample = feature_extractor(dataset[0]["audio"]["array"], sampling_rate=16000) processed_sample

结果:

{'input_values': [array([ 9.4472744e-05, 3.0777880e-03, -2.8888427e-03, ..., -2.8888427e-03, 9.4472744e-05, 9.4472744e-05], dtype=float32)]}

从输出的结果可知,特征提取器预处理的结果保存在input_values属性节点中。

提取器支持类

Transformers提供的所有特征提取器都继承自 [SequenceFeatureExtractor] 类; [SequenceFeatureExtractor] 类是 [FeatureExtractionMixin] 的子类。

  • [SequenceFeatureExtractor] 需要提供一个填充方法设置到 [~SequenceFeatureExtractor.pad] 属性上,整个方法用来处理序列的长度,以避免序列长度不均匀;
  • [FeatureExtractionMixin] 提供[~FeatureExtractionMixin.from_pretrained]来载入配置和特征提取器; 提供[~FeatureExtractionMixin.save_pretrained]来保存更改的配置和特征提取器.

有两种方式可以载入特征提取器:一种是通过[AutoFeatureExtractor] ;使用[AutoFeatureExtractor] 会从给定的模型自动装配上正确的特征提取器,如:

from transformers import AutoFeatureExtractor feature_extractor = AutoFeatureExtractor.from_pretrained("openai/whisper-tiny")

另外一种是直接使用特定模型提供的专有特征提取器。每个预训练模型都会有一个对应的特征提取器以便能够正确的处理音频数据。在载入特征提取器的时候,它会从preprocessor_config.json文件中载入特征提取配置项(如特征大小、块大小等)。

from transformers import WhisperFeatureExtractor feature_extractor = WhisperFeatureExtractor.from_pretrained("openai/whisper-tiny")
输入预处理

特征提取器期望输入为特定形状的PyTorch张量。输入形状则会因为所使用的特定音频模型的不同而有所不同。例如,[Whisper] 期望input_features是包含batch_size,feature_size,sequence_length) 在内的形状张量,但[Wav2Vec2]期望input_values’是包含batch_size,sequence_length的形状张量。

特征提取器会根据所使用的音频模型生成正确的输入形状;特征提取器还设置音频文件的采样率(每秒获取的音频信号值的数量)。音频数据的采样率必须与预训练模型所训练的数据集的采样率相匹配。这个值通常在模型卡中给出。

使用特征提取器的 [~FeatureExtractionMixin.from_pretrained]方法加载一个数据集:

from datasets import load_dataset, Audio from transformers import AutoFeatureExtractor dataset = load_dataset("PolyAI/minds14", name="en-US", split="train") feature_extractor = AutoFeatureExtractor.from_pretrained("facebook/wav2vec2-base")

从给定的数据集的音频子集audio中的array中检出原始音频信号:

dataset[0]["audio"]["array"] array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, 0. , 0. ])
填充

不同的音频序列长度不一定相同,但Transformers希望所有序列都具有相同的长度,这样它们就可以批量处理。不均匀的序列长度不能成批处理。如:

dataset[0]["audio"]["array"].shape (86699,) dataset[1]["audio"]["array"].shape (53248,)

为了保证批处理中的每个序列拥有相同的长度,需要为每个序列添加特殊的“填充标识”。实际处理中,特征提取器以批处理中的最长序列为基准,为其他序列添加0 00至和最长的序列等长。可以设置padding=True来启用填充操作。

def preprocess_function(examples): audio_arrays = [x["array"] for x in examples["audio"]] inputs = feature_extractor( audio_arrays, sampling_rate=16000, padding=True, ) return inputs processed_dataset = preprocess_function(dataset[:5]) processed_dataset["input_values"][0].shape # (86699,) processed_dataset["input_values"][1].shape # (86699,)
截断

在崩溃之前,模型只能处理确定长度的序列。

截断是一种策略,用于从序列中删除多余的token,以确保它不超过最大长度。设置truncation=True启用截断功能,将序列截断为max_length参数中设定的长度值。

def preprocess_function(examples): audio_arrays = [x["array"] for x in examples["audio"]] inputs = feature_extractor( audio_arrays, sampling_rate=16000, max_length=50000, truncation=True, ) return inputs processed_dataset = preprocess_function(dataset[:5]) processed_dataset["input_values"][0].shape #(50000,) processed_dataset["input_values"][1].shape #(50000,)
重采样

[Datassets]库也可以重新采样音频数据,以匹配音频模型的预期采样率。这种方法只针对加载的音频数据对其进行重新采样,这比对整个数据集进行重新采样要快得多。

下面用的音频数据集的采样率为8 k H z 8kHz8kHz,但预训练模型的采样率为16 k H z 16kHz16kHz

dataset[0]["audio"] {'path': '/root/.cache/huggingface/datasets/downloads/extracted/f507fdca7f475d961f5bb7093bcc9d544f16f8cab8608e772a2ed4fbeb4d6f50/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'array': array([ 0. , 0.00024414, -0.00024414, ..., -0.00024414, 0. , 0. ]), 'sampling_rate': 8000}

调用 [~datasets.Dataset.cast_column] 将audio列的采样率转换到16 k H z 16kHz16kHz

dataset = dataset.cast_column("audio", Audio(sampling_rate=16000))

现在再看样例数据集,采样率已经变成了16 k H z 16kHz16kHz

dataset[0]["audio"] {'path': '/root/.cache/huggingface/datasets/downloads/extracted/f507fdca7f475d961f5bb7093bcc9d544f16f8cab8608e772a2ed4fbeb4d6f50/en-US~JOINT_ACCOUNT/602ba55abb1e6d0fbce92065.wav', 'array': array([ 1.70562416e-05, 2.18727451e-04, 2.28099874e-04, ..., 3.43842403e-05, -5.96364771e-06, -1.76846661e-05]), 'sampling_rate': 16000}

图像特征提取

图像特征提取(Image feature extraction)是对给定图像提取语义上有意义的特征。它有许多用例,包括图像相似度和图像检索等。此外,大多数计算机视觉模型都可以用于图像特征提取如去除特定任务的头部(如图像分类,目标检测等)并获得特征。这些特征在更高的层次上的视觉处理如边缘检测,角点检测等是非常有用的。它们也可能包含关于现实世界的信息(例如,猫的样子),这取决于模型的深度。因此,这些输出可用于在特定数据集上训练新的分类器。

假定现在有两张猫坐在渔网上图片,其中一张是生成的:

from PIL import Image import requests img_urls = ["https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.jpeg"] image_real = Image.open(requests.get(img_urls[0], stream=True).raw).convert("RGB") image_gen = Image.open(requests.get(img_urls[1], stream=True).raw).convert("RGB")

现在开始使用Pipeline来演示如何提取特征的。首先通过初始化Pipeline实例加载google/vit-base-patch16-224模型(如果想计算相似度,需设置参数poolTrue):

import torch from transformers import pipeline from accelerate.test_utils.testing import get_backend # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) DEVICE, _, _ = get_backend() pipe = pipeline(task="image-feature-extraction", model_name="google/vit-base-patch16-384", device=DEVICE, pool=True)

然后对输入进行推理并打印结果:

outputs = pipe([image_real, image_gen]) # get the length of a single output print(len(outputs[0][0])) # show outputs print(outputs)

结果:

# 768 # [[[-0.03909236937761307, 0.43381670117378235, -0.06913255900144577,...

获取相似度得分后,需要将结果作为参数传给cosine_similarity

from torch.nn.functional import cosine_similarity similarity_score = cosine_similarity(torch.Tensor(outputs[0]), torch.Tensor(outputs[1]), dim=1) print(similarity_score)

结果:

# tensor([0.6043])

如果想在池化前获取最后的隐藏状态,切记不要设置pool=True

pipe = pipeline(task="image-feature-extraction", model_name="google/vit-base-patch16-224", device=DEVICE) outputs = pipe(image_real)

既然不需要对输出做池化处理,那么输出的结果的第一个维度表示批数,后两个值为形状的隐藏状态值。

import numpy as np print(np.array(outputs).shape)

结果:

# (1, 197, 768)

图像描述生成

图像描述生成(Image captioning)是为给定图像预测出一段描述的任务;可以看作“开图说话”。它在现实世界中的常见应用包括帮助视力受损的人在不同的情况下导航。因此,图像字幕通过识别给定图片向人们描述图像。

首先,我们先加载微调的模型(假定模型名为microsoft/git-base):

from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained(checkpoint)

然后加载要分析的图片:

from PIL import Image import requests url = "https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/pokemon.png" image = Image.open(requests.get(url, stream=True).raw) image

接下来将分析的图片传入到模型中:

from accelerate.test_utils.testing import get_backend # automatically detects the underlying device type (CUDA, CPU, XPU, MPS, etc.) device, _, _ = get_backend() inputs = processor(images=image, return_tensors="pt").to(device) pixel_values = inputs.pixel_values

最后,调用[~AutoModelForCausalLM.generate]来解码预测结果:

generated_ids = model.generate(pixel_values=pixel_values, max_length=50) generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0] print(generated_caption)

结果:

a drawing of a pink and blue pokemon

除了这种方式外,采用图片转文本或图片文本转文本也可以实现图像描述生成的功能。

图片转文本

作为可视化语言模型(vision language models,VLMs)的一种,图片转文本(Image-to-text)是一个接受一张图像,分析图像中的文字并将其提取出来的任务。它不依赖于OCR引擎。

应用场景包括:

  • 文档扫描与数字化:将纸质文档快速转化为电子版;
  • 自动字幕生成:对视频进行实时字幕提取,适用于听觉障碍的人群;
  • 社交媒体分析:提取图像中的文字喜喜,用于新闻摘要、情感分析等大数据应用;
  • 智能办公:自动识别表格数据,提升工作效率。

首先将Pipeline实例化,并在实例化时指定任务为image-to-text和传入nlpconnect/vit-gpt2-image-captioning模型:

from transformers import pipeline ''' # 设置镜像地址(如果能访问Huging Face Hub或者通过其他方式已把模型下载,则可省略 import os os.environ["HF_ENDPOINT"] = "https://hf-mirror.com" os.environ["CUDA_VISIBLE_DEVICES"] = "2" ''' image_to_text = pipeline("image-to-text", model="nlpconnect/vit-gpt2-image-captioning")

然后,调用实例进行预测并将结果打印:

output=image_to_text("./parrots.png") print(output)

结果(图像中的文本):

[{"generated_text": "two birds are standing next to each other"}]

图片文本转文本

作为可视化语言模型(vision language models,VLMs)的一种,图片文本转文本(Image-text-to-text)是一个接受图像和文本输入的语言模型。该模型可以解决从视觉问答到图像分割等不同的任务;它与image-to-text有一些相似之处如图像描述生成(Image captioning),但image-to-text模型仅接受图像输入,提取图像中的文字信息,而Image-text-to-text接受开放式的文本和图像输入,是更通用的模型。

在本节中,我们简要概述VLMs,并展示了如何将它们与transformer一起使用来进行推理。

首先,有多种类型的VLMs可选:

  • 用于微调的基础模型
  • 用于会话的调整好的对话模型
  • 指令微调模型

首先通过 实例化Pipeline指定任务image-text-to-text并传入llava-hf/llava-interleave-qwen-0.5b-hf模型:

from transformers import pipeline pipe = pipeline("image-text-to-text", model="llava-hf/llava-interleave-qwen-0.5b-hf")

下面使用聊天模板格式化文本输入作为案例:

messages = [ { "role": "user", "content": [ { "type": "image", "image": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg", }, {"type": "text", "text": "Describe this image."}, ], }, { "role": "assistant", "content": [ {"type": "text", "text": "There's a pink flower"}, ], }, ]

将格式化的文本和图像传给Pipeline,并设置参数’return_full_text=False,表示要从生成的输出中删除输入。

outputs = pipe(text=messages, max_new_tokens=20, return_full_text=False) outputs[0]["generated_text"]

结果:

# with a yellow center in the foreground. The flower is surrounded by red and white flowers with green stems

如果需要,也可以单独加载图像,并将它们传给pipeline,如下所示:

pipe = pipeline("image-text-to-text", model="HuggingFaceTB/SmolVLM-256M-Instruct") img_urls = [ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png", "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg", ] images = [ Image.open(requests.get(img_urls[0], stream=True).raw), Image.open(requests.get(img_urls[1], stream=True).raw), ] messages = [ { "role": "user", "content": [ {"type": "image"}, {"type": "image"}, {"type": "text", "text": "What do you see in these images?"}, ], } ] outputs = pipe(text=messages, images=images, max_new_tokens=50, return_full_text=False) outputs[0]["generated_text"]

结果:

" In the first image, there are two cats sitting on a plant. In the second image, there are flowers with a pinkish hue."

此时,图像仍然会被包含在输出的input_text字段中:

outputs[0]['input_text']

结果:

[{'role': 'user', 'content': [{'type': 'image', 'image': <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=622x412>}, {'type': 'image', 'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=5184x3456>}, {'type': 'text', 'text': 'What do you see in these images?'}]}]

蒙版生成

蒙版生成(Mask generation)是一个为图像生成语义上有意义的蒙版任务。

该任务与“图像分割”非常相似,但存在许多不同之处。“图像分割”模型在标记过的数据集上进行训练且仅限于在训练期间看到的分类;并返回给定图像的一组掩码和相应的分类。

掩码生成模型在大量数据上进行训练,并在两种模式下运行。

  • 提示模式:该模式下,模型输入接受一张图像和一组提示,提示是图像中物体或者物体周围的边界框的平面坐标(直角坐标)。在提示模式下,模型只返回提示所指向的对象的掩码。
  • 分割模式:在给定一个图像可以分割任意的内容,模型生成图像中的每个遮罩。为此,生成一个点网格并覆盖在图像上进行推理。

掩码生成任务由SAMSegment Anything Model)] 提供支持。它是一个由一个基于视觉转换器的图像编码器、一个提示编码器和一个双向转换掩码解码器组成的功能强大的模型。图像和提示被编码,解码器接受这些嵌入并生成有效的掩码。

💡小提示

SAMSegment Anything Model)是一个强大的分割基础模型,拥有很大的数据覆盖。它是在一个拥有100万张图像和11亿个掩模的数据集[SA-1B]上训练的。

首先,我们通过实例化Pipeline并在实例化时指定mask-generation任务和预训练模型facebook/sam-vit-base

from transformers import pipeline checkpoint = "facebook/sam-vit-base" mask_generator = pipeline(model=checkpoint, task="mask-generation")

然后准备一张图片:

from PIL import Image import requests img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/bee.jpg" image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")

在分割模式下设置参数points-per-batch可以启用并行对图像点进行推理,这样可以实现更快的推理,但会消耗更多的内存。此外,SAM只支持对点而不是图像进行批处理。pred_iou_threshIoU置信度阈值,其中只返回高于该阈值的掩码。

masks = mask_generator(image, points_per_batch=128, pred_iou_thresh=0.88)

输出结果:

{'masks': [array([[False, False, False, ..., True, True, True], [False, False, False, ..., True, True, True], [False, False, False, ..., True, True, True], ..., [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False]]), array([[False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], [False, False, False, ..., False, False, False], ..., 'scores': tensor([0.9972, 0.9917, ..., }

如果愿意,可以使用以下代码可视化:

import matplotlib.pyplot as plt plt.imshow(image, cmap='gray') for i, mask in enumerate(masks["masks"]): plt.imshow(mask, cmap='viridis', alpha=0.1, vmin=0, vmax=1) plt.axis('off') plt.show()

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询