Home Technology peripherals AI Hugging Face Image Classification: A Comprehensive Guide With Examples

Hugging Face Image Classification: A Comprehensive Guide With Examples

Mar 07, 2025 am 09:34 AM

Harnessing Hugging Face for Image Classification: A Comprehensive Guide

Image classification, a cornerstone of AI and machine learning, finds applications across diverse fields, from facial recognition to medical imaging. Hugging Face emerges as a powerful platform for this task, particularly for those familiar with natural language processing (NLP) and increasingly, computer vision. This guide details using Hugging Face for image classification, catering to both beginners and experienced practitioners.

Understanding Image Classification and Hugging Face's Advantages

Image classification involves categorizing images into predefined classes using algorithms that analyze visual content and predict categories based on learned patterns. Convolutional Neural Networks (CNNs) are the standard approach due to their pattern-recognition capabilities. For a deeper dive into CNNs, refer to our article "An Introduction to Convolutional Neural Networks (CNNs)." Our "Classification in Machine Learning: An Introduction" article provides a broader understanding of classification algorithms.

Hugging Face offers several advantages:

Hugging Face Image Classification: A Comprehensive Guide With Examples

Key benefits of using Hugging Face for image classification

  • Accessibility: Intuitive APIs and comprehensive documentation cater to all skill levels.
  • Pre-trained Models: A vast repository of pre-trained models allows for efficient fine-tuning on custom datasets, minimizing training time and computational resources. Users can train and deploy their own models.
  • Community & Support: A vibrant community provides invaluable support and troubleshooting assistance.

Hugging Face also simplifies model deployment across major cloud platforms (AWS, Azure, Google Cloud Platform) with various inference options.

Hugging Face Image Classification: A Comprehensive Guide With Examples

Model deployment options across cloud platforms

Data Preparation and Preprocessing

This guide uses the Hugging Face "beans" dataset for demonstration. After loading, we'll visualize the data before preprocessing. The accompanying Google Colab notebook provides the code. The code is inspired by Hugging Face's official documentation.

Library Requirements:

Install necessary libraries using pip:

pip -q install datasets
pip -q install transformers=='4.29.0'
pip -q install tensorflow=='2.15' 
pip -q install evaluate
pip -q install --upgrade accelerate
Copy after login
Copy after login

Restart the kernel after installation. Import required libraries:

import torch
import torchvision
import numpy as np
import evaluate
from datasets import load_dataset
from huggingface_hub import notebook_login
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from transformers import DefaultDataCollator
from transformers import AutoImageProcessor
from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor
from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
import matplotlib.pyplot as plt
Copy after login
Copy after login

Data Loading and Organization:

Load the dataset:

pip -q install datasets
pip -q install transformers=='4.29.0'
pip -q install tensorflow=='2.15' 
pip -q install evaluate
pip -q install --upgrade accelerate
Copy after login
Copy after login

The dataset contains 1034 images, each with 'image_file_path', 'image' (PIL object), and 'labels' (0: angular_leaf_spot, 1: bean_rust, 2: healthy).

A helper function visualizes random images:

import torch
import torchvision
import numpy as np
import evaluate
from datasets import load_dataset
from huggingface_hub import notebook_login
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from transformers import DefaultDataCollator
from transformers import AutoImageProcessor
from torchvision.transforms import RandomResizedCrop, Compose, Normalize, ToTensor
from transformers import AutoModelForImageClassification, TrainingArguments, Trainer
import matplotlib.pyplot as plt
Copy after login
Copy after login

Visualize six random images:

beans_train = load_dataset("beans", split="train")
Copy after login

Hugging Face Image Classification: A Comprehensive Guide With Examples

Sample images from the beans dataset

Data Preprocessing:

Split the dataset (80% train, 20% validation):

labels_names = {0: "angular_leaf_spot", 1: "bean_rust", 2: "healthy"}

def display_random_images(dataset, num_images=4):
   # ... (function code as in original input) ...
Copy after login

Create label mappings:

display_random_images(beans_train, num_images=6)
Copy after login

Model Loading and Fine-tuning

Load the pre-trained ViT model:

beans_train = beans_train.train_test_split(test_size=0.2)
Copy after login

The code loads the pre-trained model, defines transformations (resizing, normalization), and prepares the dataset for training. The accuracy metric is defined for evaluation.

Log in to Hugging Face:

labels = beans_train["train"].features["labels"].names
label2id, id2label = dict(), dict()
for i, label in enumerate(labels):
   label2id[label] = str(i)
   id2label[str(i)] = label
Copy after login

(Follow on-screen instructions)

Configure and initiate training:

checkpoint = "google/vit-base-patch16-224-in21k"
image_processor = AutoImageProcessor.from_pretrained(checkpoint)
# ... (rest of the preprocessing code as in original input) ...
Copy after login

(Training results as shown in the original input)

Model Deployment and Integration

Push the trained model to the Hugging Face Hub:

notebook_login()
Copy after login

The model can then be accessed and used via:

  1. Hugging Face Portal: Directly upload images for prediction.
  2. Transformers Library: Use the model within your Python code.
  3. REST API: Utilize the provided API endpoint for predictions. Example using the API:
training_args = TrainingArguments(
    # ... (training arguments as in original input) ...
)

trainer = Trainer(
    # ... (trainer configuration as in original input) ...
)

trainer.train()
Copy after login

Conclusion and Further Resources

This guide provides a comprehensive walkthrough of image classification using Hugging Face. Further learning resources include:

  • "An Introduction to Using Transformers and Hugging Face"
  • "Image Processing with Python" skill track
  • "What is Image Recognition?" article

This guide empowers users of all levels to leverage Hugging Face for their image classification projects.

The above is the detailed content of Hugging Face Image Classification: A Comprehensive Guide With Examples. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
Getting Started With Meta Llama 3.2 - Analytics Vidhya Getting Started With Meta Llama 3.2 - Analytics Vidhya Apr 11, 2025 pm 12:04 PM

Meta's Llama 3.2: A Leap Forward in Multimodal and Mobile AI Meta recently unveiled Llama 3.2, a significant advancement in AI featuring powerful vision capabilities and lightweight text models optimized for mobile devices. Building on the success o

10 Generative AI Coding Extensions in VS Code You Must Explore 10 Generative AI Coding Extensions in VS Code You Must Explore Apr 13, 2025 am 01:14 AM

Hey there, Coding ninja! What coding-related tasks do you have planned for the day? Before you dive further into this blog, I want you to think about all your coding-related woes—better list those down. Done? – Let&#8217

Selling AI Strategy To Employees: Shopify CEO's Manifesto Selling AI Strategy To Employees: Shopify CEO's Manifesto Apr 10, 2025 am 11:19 AM

Shopify CEO Tobi Lütke's recent memo boldly declares AI proficiency a fundamental expectation for every employee, marking a significant cultural shift within the company. This isn't a fleeting trend; it's a new operational paradigm integrated into p

AV Bytes: Meta's Llama 3.2, Google's Gemini 1.5, and More AV Bytes: Meta's Llama 3.2, Google's Gemini 1.5, and More Apr 11, 2025 pm 12:01 PM

This week's AI landscape: A whirlwind of advancements, ethical considerations, and regulatory debates. Major players like OpenAI, Google, Meta, and Microsoft have unleashed a torrent of updates, from groundbreaking new models to crucial shifts in le

GPT-4o vs OpenAI o1: Is the New OpenAI Model Worth the Hype? GPT-4o vs OpenAI o1: Is the New OpenAI Model Worth the Hype? Apr 13, 2025 am 10:18 AM

Introduction OpenAI has released its new model based on the much-anticipated “strawberry” architecture. This innovative model, known as o1, enhances reasoning capabilities, allowing it to think through problems mor

A Comprehensive Guide to Vision Language Models (VLMs) A Comprehensive Guide to Vision Language Models (VLMs) Apr 12, 2025 am 11:58 AM

Introduction Imagine walking through an art gallery, surrounded by vivid paintings and sculptures. Now, what if you could ask each piece a question and get a meaningful answer? You might ask, “What story are you telling?

How to Add a Column in SQL? - Analytics Vidhya How to Add a Column in SQL? - Analytics Vidhya Apr 17, 2025 am 11:43 AM

SQL's ALTER TABLE Statement: Dynamically Adding Columns to Your Database In data management, SQL's adaptability is crucial. Need to adjust your database structure on the fly? The ALTER TABLE statement is your solution. This guide details adding colu

Reading The AI Index 2025: Is AI Your Friend, Foe, Or Co-Pilot? Reading The AI Index 2025: Is AI Your Friend, Foe, Or Co-Pilot? Apr 11, 2025 pm 12:13 PM

The 2025 Artificial Intelligence Index Report released by the Stanford University Institute for Human-Oriented Artificial Intelligence provides a good overview of the ongoing artificial intelligence revolution. Let’s interpret it in four simple concepts: cognition (understand what is happening), appreciation (seeing benefits), acceptance (face challenges), and responsibility (find our responsibilities). Cognition: Artificial intelligence is everywhere and is developing rapidly We need to be keenly aware of how quickly artificial intelligence is developing and spreading. Artificial intelligence systems are constantly improving, achieving excellent results in math and complex thinking tests, and just a year ago they failed miserably in these tests. Imagine AI solving complex coding problems or graduate-level scientific problems – since 2023

See all articles