Getting Started with Hugging Face Transformers
The Transformers library is the easiest way to use pre-trained AI models.
Installation
```bash
pip install transformers torch
```
Text Generation (LLM)
```python
from transformers import pipeline
generator = pipeline("text-generation", model="meta-llama/Llama-3.2-3B-Instruct")
result = generator("Explain quantum computing in simple terms:", max_new_tokens=200)
print(result[0]["generated_text"])
```
Sentiment Analysis
```python
classifier = pipeline("sentiment-analysis")
result = classifier("I love using AI for coding!")
print(result) # [{'label': 'POSITIVE', 'score': 0.9998}]
```
Image Classification
```python
classifier = pipeline("image-classification", model="google/vit-base-patch16-224")
result = classifier("https://example.com/cat.jpg")
print(result) # [{'label': 'tabby cat', 'score': 0.95}]
```
Zero-Shot Classification
```python
classifier = pipeline("zero-shot-classification")
result = classifier(
"This is a tutorial about machine learning",
candidate_labels=["education", "politics", "technology"]
)
print(result["labels"][0]) # 'technology'
```
Key Concepts
| Concept | Description |
|---------|-------------|
| **Pipeline** | High-level API — one line to load model + tokenizer |
| **AutoModel** | Lower-level — more control over model architecture |
| **AutoTokenizer** | Handles text → tokens → text conversion |
| **Trainer** | Fine-tuning API with logging, checkpointing, evaluation |
| **Hub** | Central repository for sharing models and datasets |