Home Topics Hugging Face
šŸ¤—

Hugging Face

The GitHub for Machine Learning

6 hours 15 examples Intermediate
Basics

What is Hugging Face? šŸ¤—

Hugging Face is the most important platform in modern ML. It hosts 500,000+ pre-trained models, datasets, and spaces (demo apps). Think of it as GitHub + npm for AI!

šŸ”§

Transformers

Python library for using BERT, GPT, T5, CLIP, etc.

šŸ“Š

Datasets

60,000+ datasets for training

šŸš€

Spaces

Host ML demos with Gradio/Streamlit

Installation

pip install transformers datasets
Basics

Pipelines: AI in 2 Lines of Code

Pipelines are the easiest way to use pre-trained models. Just specify the task, and Hugging Face handles everything!

pipeline_basics.py
from transformers import pipeline

# Sentiment Analysis - just 2 lines!
classifier = pipeline("sentiment-analysis")
result = classifier("I love learning AI with Hugging Face!")

print("Sentiment Analysis:")
print(result)

# Text Generation
generator = pipeline("text-generation", model="gpt2")
result = generator("Artificial Intelligence will", max_length=30)
print("\nText Generation:")
print(result[0]['generated_text'])
Output
Sentiment Analysis:
[{'label': 'POSITIVE', 'score': 0.9998}]

Text Generation:
Artificial Intelligence will be able to learn from our 
experiences and make decisions based on them.
Tasks

NLP Tasks

nlp_tasks.py
from transformers import pipeline

# 1. Named Entity Recognition (NER)
ner = pipeline("ner", grouped_entities=True)
text = "Elon Musk founded SpaceX in California."
entities = ner(text)
print("šŸ·ļø Named Entities:")
for entity in entities:
    print(f"  {entity['word']}: {entity['entity_group']}")

# 2. Question Answering
qa = pipeline("question-answering")
context = "Hugging Face was founded in 2016. It is based in New York."
question = "When was Hugging Face founded?"
answer = qa(question=question, context=context)
print(f"\nā“ Question: {question}")
print(f"šŸ’” Answer: {answer['answer']} (confidence: {answer['score']:.2f})")

# 3. Summarization
summarizer = pipeline("summarization")
long_text = """
Machine learning is a subset of artificial intelligence that enables 
systems to learn from data. It uses algorithms to identify patterns 
and make predictions without being explicitly programmed for each task.
"""
summary = summarizer(long_text, max_length=30, min_length=10)
print(f"\nšŸ“ Summary: {summary[0]['summary_text']}")
Output
šŸ·ļø Named Entities:
  Elon Musk: PER
  SpaceX: ORG
  California: LOC

ā“ Question: When was Hugging Face founded?
šŸ’” Answer: 2016 (confidence: 0.98)

šŸ“ Summary: Machine learning is a subset of AI that enables 
systems to learn from data.
Tasks

Vision Tasks

vision_tasks.py
from transformers import pipeline

# Image Classification
classifier = pipeline("image-classification")
result = classifier("cat.jpg")  # Local image or URL

print("šŸ–¼ļø Image Classification:")
for pred in result[:3]:
    print(f"  {pred['label']}: {pred['score']*100:.1f}%")

# Object Detection
detector = pipeline("object-detection")
objects = detector("street.jpg")

print("\nšŸŽÆ Objects Detected:")
for obj in objects:
    print(f"  {obj['label']}: {obj['score']*100:.1f}%")
Output
šŸ–¼ļø Image Classification:
  tabby cat: 95.2%
  tiger cat: 3.1%
  Egyptian cat: 1.2%

šŸŽÆ Objects Detected:
  car: 98.5%
  person: 97.2%
  traffic light: 89.4%
Advanced

Fine-Tuning Your Own Model

Pre-trained models are great, but fine-tuning adapts them to your specific data for better performance.

fine_tuning.py
from transformers import (
    AutoTokenizer, 
    AutoModelForSequenceClassification,
    TrainingArguments, 
    Trainer
)
from datasets import load_dataset

# 1. Load dataset
dataset = load_dataset("imdb")  # Movie reviews

# 2. Load pre-trained model and tokenizer
model_name = "distilbert-base-uncased"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(
    model_name, num_labels=2
)

# 3. Tokenize dataset
def tokenize(examples):
    return tokenizer(examples["text"], truncation=True)

tokenized = dataset.map(tokenize, batched=True)

# 4. Set up training
training_args = TrainingArguments(
    output_dir="./results",
    num_train_epochs=3,
    per_device_train_batch_size=16,
    evaluation_strategy="epoch"
)

trainer = Trainer(
    model=model,
    args=training_args,
    train_dataset=tokenized["train"],
    eval_dataset=tokenized["test"]
)

# 5. Train!
trainer.train()
print("āœ“ Fine-tuning complete!")

Popular Models to Fine-Tune

  • • BERT/DistilBERT - Text classification, NER
  • • T5/FLAN-T5 - Any text-to-text task
  • • Whisper - Speech recognition
  • • CLIP - Image-text matching

šŸŽ‰ You've Learned Hugging Face!

Ready to explore the cutting edge? Learn about Diffusion Models next!