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
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!
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'])
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.
NLP Tasks
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']}")
š·ļø 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.
Vision Tasks
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}%")
š¼ļø 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%
Fine-Tuning Your Own Model
Pre-trained models are great, but fine-tuning adapts them to your specific data for better performance.
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!