当前位置:   article > 正文

Hugging Face应用——图像识别_hugging-face的图像识别

hugging-face的图像识别

在这里插入图片描述
利用人工智能解决音频、视觉和语言问题。音频分类、图像分类、物体检测、问答、总结、文本分类、翻译等均有大量模型进行参考。

Eg1: 图像识别

图像分类是为整个图像分配标签或类别的任务。每张图像预计只有一个类别。图像分类模型将图像作为输入并返回有关图像所属类别的预测

在这里插入图片描述

借助该transformers库,可以使用image-classification管道来推断图像分类模型。在不提供模型ID时,默认使用google/vit-base-patch16-224进行初始化pipeline。 调用pipeline管道时,只需要指定路径、http链接或PIL(Python Imaging Library)中加载的图标;还可以提供一个top_k参数来确定应返回多少结果

在这里插入图片描述

使用Transformer微调ViT

如何像对句子标记一样对图像进行标记,以便将其传递到Transformer模型进行训练。

  1. 将图像分割成子图像块的网格
  2. 使用线性投影嵌入每个补丁
  3. 每个嵌入的补丁都会成为一个令牌,嵌入补丁的结果序列就是传递给模型的序列

在这里插入图片描述

  • MLP:Multilayer Perceptron 前向结构的人工神经网络——多层感知器
  • Embedded Patches 嵌入补丁
如何使用datasets下载和处理的图像分类数据集通过微调预训练的ViT transformer
  1. 首先安装软件包

    pip install datasets transformers Pillow
    
    • 1
  2. 加载数据集

    使用beans数据集,是健康和非健康豆叶的图片集合

    from datasets import load_dataset
    
    ds = load_dataset('beans')
    //DatasetDict({
    //    train: Dataset({
    //        features: ['image_file_path', 'image', 'labels'],
    //        num_rows: 1034
    //    })
    //    validation: Dataset({
    //        features: ['image_file_path', 'image', 'labels'],
    //       num_rows: 133
    //    })
    //    test: Dataset({
    //        features: ['image_file_path', 'image', 'labels'],
    //        num_rows: 128
    //    })
    //})
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    每个数据集中每个示例都有3个特征:

    • image: PIL图像
    • image_file_path: str加载的图像文件的路径image
    • labels:一个datasets.CLassLabel特征,是标签的整数表示
    {
      'image': <PIL.JpegImagePlugin ...>,
      'image_file_path': '/root/.cache/.../bean_rust_train.4.jpg',
      'labels': 1
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    ex = ds['train'][400]
    image = ex['image']
    
    • 1
    • 2


    由于'labels'该数据集的特征是 datasets.features.ClassLabel,我们可以使用它来查找本示例的标签 ID 的相应名称

labels = ds['train'].features['labels']

// ClassLabel(num_classes=3, names=['angular_leaf_spot', 'bean_rust', 'healthy'], names_file=None, id=None)
  • 1
  • 2
  • 3

使用int2str 函数来打印示例的类标签

labels.int2str(ex['labels'])

// 'bean_rust'
  • 1
  • 2
  • 3

上面图片叶子感染了“豆锈病”,是一种豆科植物的严重疾病

编写一个函数显示每个类的示例网格:

import random
from PIL import ImageDraw, ImageFont, Image

def show_examples(ds, seed: int = 1234, examples_per_class: int = 3, size=(350, 350)):

    w, h = size
    labels = ds['train'].features['labels'].names
    grid = Image.new('RGB', size=(examples_per_class * w, len(labels) * h))
    draw = ImageDraw.Draw(grid)
    font = ImageFont.truetype("/usr/share/fonts/truetype/liberation/LiberationMono-Bold.ttf", 24)

    for label_id, label in enumerate(labels):

        # Filter the dataset by a single label, shuffle it, and grab a few samples
        ds_slice = ds['train'].filter(lambda ex: ex['labels'] == label_id).shuffle(seed).select(range(examples_per_class))

        # Plot this label's examples along a row
        for i, example in enumerate(ds_slice):
            image = example['image']
            idx = examples_per_class * label_id + i
            box = (idx % examples_per_class * w, idx // examples_per_class * h)
            grid.paste(image.resize(size), box=box)
            draw.text(box, label, (255, 255, 255), font=font)

    return grid

show_examples(ds, seed=random.randint(0, 1337), examples_per_class=3)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

在这里插入图片描述

  • 角叶斑:有不规则的棕色斑块
  • 豆锈病:有圆形棕色斑点,周围有白黄色环
  • 健康:……看起来很健康

加载ViT特征提取器

现在知道图像是什么样子,并且更好地理解我们要解决的问题。让我们看看如何为我们的模型准备这些图像!

当训练 ViT 模型时,特定的转换将应用于输入到其中的图像。对图像使用错误的转换,模型将无法理解它所看到的内容!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/287848
推荐阅读
相关标签