图像分类为图片分配一个标签或类别。与文本或音频分类不同,它的输入是构成图片的像素值。应用包括自然灾害后的损害识别、作物健康监测,以及辅助检查医学影像中的疾病迹象。
本指南介绍:
-
在 Food-101 数据集上微调 ViT,识别图片中的食物。
-
使用微调后的模型进行推理。
要了解兼容此任务的全部模型架构和检查点,可以查看图像分类任务页。
开始之前,需要安装以下库:
pip install transformers datasets evaluate accelerate pillow torchvision scikit-learn trackio
如果希望上传模型并与社区分享,可以登录自己的 Hugging Face 账户。在登录组件提示时输入访问令牌:
>>> from huggingface_hub import notebook_login
>>> notebook_login()
加载 Food-101 数据集
先用 Datasets 加载 Food-101 的一个较小子集。这样可以先验证流程,再投入更多时间训练完整数据集。
>>> from datasets import load_dataset
>>> food = load_dataset("ethz/food101", split="train[:5000]")
用 train_test_split 把原始 train 划分成训练集和测试集:
>>> food = food.train_test_split(test_size=0.2)
查看一个样本。以下对象地址和标签属于原文示例输出:
>>> food["train"][0]
{'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=512x512 at 0x7F52AFC8AC50>,
'label': 79}
每个样本有两个字段:
-
image:食物图片的 PIL 图像对象。 -
label:食物所属类别的标签。
为了能在标签编号和标签名称之间转换,建立双向映射字典。这里代码把编号保存为字符串键或值:
>>> labels = food["train"].features["label"].names
>>> label2id, id2label = dict(), dict()
>>> for i, label in enumerate(labels):
... label2id[label] = str(i)
... id2label[str(i)] = label
现在可以把标签编号转换为名称:
>>> id2label[str(79)]
'prime_rib'
预处理
加载 ViT 图像处理器,把图片处理成张量:
>>> from transformers import AutoImageProcessor
>>> checkpoint = "google/vit-base-patch16-224-in21k"
>>> image_processor = AutoImageProcessor.from_pretrained(checkpoint)
使用图像变换,降低模型过拟合的风险。这里采用 torchvision 的 transforms,也可以使用其他图像库。
随机裁剪图片的一部分、调整尺寸,再根据图像均值和标准差进行归一化:
>>> from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor
>>> normalize = Normalize(mean=image_processor.image_mean, std=image_processor.image_std)
>>> size = (
... image_processor.size["shortest_edge"]
... if "shortest_edge" in image_processor.size
... else (image_processor.size["height"], image_processor.size["width"])
... )
>>> _transforms = Compose([RandomResizedCrop(size), ToTensor(), normalize])
定义预处理函数,应用这些变换,返回模型输入 pixel_values:
>>> def transforms(examples):
... examples["pixel_values"] = [_transforms(img.convert("RGB")) for img in examples["image"]]
... del examples["image"]
... return examples
用 Datasets 的 with_transform 为整个数据集设置预处理。每次读取样本时,变换会即时执行:
>>> food = food.with_transform(transforms)
使用 DefaultDataCollator 把样本组成批次。与其他某些 Transformers 数据整理器不同,它不会额外执行填充等预处理。
>>> from transformers import DefaultDataCollator
>>> data_collator = DefaultDataCollator()
评估
训练中加入评估指标有助于衡量模型表现。用 Evaluate 库加载本任务所需的 accuracy 指标。关于指标的加载与计算,可参考 Evaluate 入门指南:
>>> import evaluate
>>> accuracy = evaluate.load("accuracy")
定义函数,把预测结果与真实标签传给 compute,计算准确率:
>>> import numpy as np
>>> def compute_metrics(eval_pred):
... predictions, labels = eval_pred
... predictions = np.argmax(predictions, axis=1)
... return accuracy.compute(predictions=predictions, references=labels)
compute_metrics 已准备好,设置训练器时会用到它。
训练
如果不熟悉使用 Trainer 微调模型,可以先阅读基础训练教程。
用 AutoModelForImageClassification 加载 ViT,并指定类别数量和双向标签映射:
>>> from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
>>> model = AutoModelForImageClassification.from_pretrained(
... checkpoint,
... num_labels=len(labels),
... id2label=id2label,
... label2id=label2id,
... )
接下来还有三步:
-
在
TrainingArguments中定义训练超参数。必须保留未直接使用的列,否则image会被删除,预处理就无法生成pixel_values。设置remove_unused_columns=False可以避免这一问题。另一个必需参数是output_dir,用于指定模型保存目录。原文示例设置push_to_hub=True,会把模型上传到 Hub,因此需要预先登录。每轮训练结束后,Trainer会评估准确率并保存检查点。 -
把训练参数、模型、数据集、处理组件、数据整理器和
compute_metrics传给Trainer。图像任务在下面的代码中通过processing_class=image_processor提供处理组件。 -
调用
train()微调模型。
>>> training_args = TrainingArguments(
... output_dir="my_awesome_food_model",
... remove_unused_columns=False,
... eval_strategy="epoch",
... save_strategy="epoch",
... learning_rate=5e-5,
... per_device_train_batch_size=16,
... gradient_accumulation_steps=4,
... per_device_eval_batch_size=16,
... num_train_epochs=3,
... warmup_steps=0.1,
... logging_steps=10,
... report_to="trackio",
... run_name="food101",
... load_best_model_at_end=True,
... metric_for_best_model="accuracy",
... push_to_hub=True,
... )
>>> trainer = Trainer(
... model=model,
... args=training_args,
... data_collator=data_collator,
... train_dataset=food["train"],
... eval_dataset=food["test"],
... processing_class=image_processor,
... compute_metrics=compute_metrics,
... )
>>> trainer.train()
训练完成后,可以通过 push_to_hub() 分享模型,供其他人使用:
>>> trainer.push_to_hub()
更详细的图像分类微调案例见对应的 PyTorch notebook。
推理
完成微调后,就可以用模型进行推理。
加载要识别的图片:
>>> ds = load_dataset("ethz/food101", split="validation[:10]")
>>> image = ds["image"][0]
原文用于推理的贝涅饼图片(仅作来源参考,图片独立许可待确认,交付稿不嵌入。)
最方便的方式是使用 pipeline:用自己的模型创建图像分类流水线,再传入图片。下面的分数与类别是原文示例结果,并非本机训练或推理结果:
>>> from transformers import pipeline
>>> classifier = pipeline("image-classification", model="my_awesome_food_model")
>>> classifier(image)
[{'score': 0.31856709718704224, 'label': 'beignets'},
{'score': 0.015232225880026817, 'label': 'bruschetta'},
{'score': 0.01519392803311348, 'label': 'chicken_wings'},
{'score': 0.013022331520915031, 'label': 'pork_chop'},
{'score': 0.012728818692266941, 'label': 'prime_rib'}]
也可以手动重现流水线执行的步骤:
加载图像处理器,预处理图片,并以 PyTorch 张量形式返回输入:
>>> from transformers import AutoImageProcessor
>>> import torch
>>> image_processor = AutoImageProcessor.from_pretrained("my_awesome_food_model")
>>> inputs = image_processor(image, return_tensors="pt")
把输入传给模型,取得 logits:
>>> from transformers import AutoModelForImageClassification
>>> model = AutoModelForImageClassification.from_pretrained("my_awesome_food_model")
>>> with torch.no_grad():
... logits = model(**inputs).logits
选择概率最大的预测类别,再通过模型的 id2label 映射取得标签名称:
>>> predicted_label = logits.argmax(-1).item()
>>> model.config.id2label[predicted_label]
'beignets'
复现时的两个细节
上面的原样代码把 with_transform 应用于整个训练与验证数据集合,因此验证时也使用随机裁剪。若要稳定比较检查点,可为验证集另设确定性的预处理。
当前官方 TrainingArguments 支持把 warmup_steps 写为 [0, 1) 内的小数比例,所以示例中的 0.1 表示总训练步数的 10%。旧版 API 的行为应单独核对。Hub 上传是可选操作;若只在本地训练,应相应调整上传设置。
来源与许可
原文:Image classification。作者或贡献者:Hugging Face Transformers 文档贡献者。本中文版本为翻译;代码、注释和原文示例输出保留原样,必要的技术澄清已在相应段落说明。适用许可:Apache-2.0。
Copyright 2022 The HuggingFace Team. All rights reserved.
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
许可原文
Copyright 2018- The Hugging Face team. All rights reserved.
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
Definitions.
“License” shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
“Licensor” shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
“Legal Entity” shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, “control” means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
“You” (or “Your”) shall mean an individual or Legal Entity exercising permissions granted by this License.
“Source” form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
“Object” form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
“Work” shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
“Derivative Works” shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
“Contribution” shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, “submitted” means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as “Not a Contribution.”
“Contributor” shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
(d) If the Work includes a “NOTICE” text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.











暂无评论内容