transformers
БесплатноЗапускает вложенные скриптыНе проверенWork with state-of-the-art machine learning models for NLP, computer vision, audio, and multimodal tasks using HuggingFace Transformers. This skill should be…
от lifangda★ 43 звезды на GitHubОб этом скилле
Transformers
Overview
The Transformers library provides state-of-the-art machine learning models for NLP, computer vision, audio, and multimodal tasks. Apply this skill for quick inference through pipelines, comprehensive training via the Trainer API, and flexible text generation with various decoding strategies.
Core Capabilities
1. Quick Inference with Pipelines
For rapid inference without complex setup, use the pipeline() API. Pipelines abstract away tokenization, model invocation, and post-processing.
from transformers import pipeline
# Text classification
classifier = pipeline("text-classification")
result = classifier("This product is amazing!")
# Named entity recognition
ner = pipeline("token-classification")
entities = ner("Sarah works at Microsoft in Seattle")
# Question answering
qa = pipeline("question-answering")
answer = qa(question="What is the capital?", context="Paris is the capital of France.")
# Text generation
generator = pipeline("text-generation", model="gpt2")
text = generator("Once upon a time", max_length=50)
# Image classification
image_classifier = pipeline("image-classification")
predictions = image_classifier("image.jpg")
When to use pipelines:
- Quick prototyping and testing
- Simple inference tasks without custom logic
- Demonstrations and examples
- Production inference for standard tasks
Available pipeline tasks:
- NLP: text-classification, token-classification, question-answering, summarization, translation, text-generation, fill-mask, zero-shot-classification
- Vision: image-classification, object-detection, image-segmentation, depth-estimation, zero-shot-image-classification
- Audio: automatic-speech-recognition, audio-classification, text-to-audio
- Multimodal: image-to-text, visual-question-answering, image-text-to-text
For comprehensive pipeline documentation, see references/pipelines.md.
2. Model Training and Fine-Tuning
Use the Trainer API for comprehensive model training with support for distributed training, mixed precision, and advanced optimization.
Basic training workflow:
from transformers import (
AutoTokenizer,
AutoModelForSequenceClassification,
TrainingArguments,
Trainer
)
from datasets import load_dataset
# 1. Load and tokenize data
dataset = load_dataset("imdb")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
def tokenize_function(examples):
return tokenizer(examples["text"], padding="max_length", truncation=True)
tokenized_datasets = dataset.map(tokenize_function, batched=True)
# 2. Load model
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-uncased",
num_labels=2
)
# 3. Configure training
training_args = TrainingArguments(
output_dir="./results",
num_train_epochs=3,
per_device_train_batch_size=16,
eval_strategy="epoch",
save_strategy="epoch",
load_best_model_at_end=True,
)
# 4. Create trainer and train
trainer = Trainer(
model=model,
args=training_args,
train_dataset=tokenized_datasets["train"],
eval_dataset=tokenized_datasets["test"],
)
trainer.train()
Key training features:
- Mixed precision training (fp16/bf16)
- Distributed training (multi-GPU, multi-node)
- Gradient accumulation
- Learning rate scheduling with warmup
- Checkpoint management
- Hyperparameter search
- Push to Hugging Face Hub
For detailed training documentation, see references/training.md.
3. Text Generation
Generate text using various decoding strategies including greedy decoding, beam search, sampling, and more.
Generation strategies:
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained("gpt2")
tokenizer = AutoTokenizer.from_pretrained("gpt2")
inputs = tokenizer("Once upon a time", return_tensors="pt")
# Greedy decoding (deterministic)
outputs = model.generate(**inputs, max_new_tokens=50)
# Beam search (explores multiple hypotheses)
outputs = model.generate(
**inputs,
max_new_tokens=50,
num_beams=5,
early_stopping=True
)
# Sampling (creative, diverse)
outputs = model.generate(
**inputs,
max_new_tokens=50,
do_sample=True,
temperature=0.7,
top_p=0.9,
top_k=50
)
Generation parameters:
temperature: Controls randomness (0.1-2.0)top_k: Sample from top-k tokenstop_p: Nucleus sampling thresholdnum_beams: Number of beams for beam searchrepetition_penalty: Discourage repetitionno_repeat_ngram_size: Prevent repeating n-grams
For comprehensive generation documentation, see references/generation_strategies.md.
4. Task-Specific Patterns
Common task patterns with appropriate model classes:
Text Classification:
from transformers import AutoModelForSequenceClassification
model = AutoModelForSequenceClassification.from_pretrained(
"bert-base-uncased",
num_labels=3,
id2label={0: "negative", 1: "neutra
Установить transformers в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл transformers?
Work with state-of-the-art machine learning models for NLP, computer vision, audio, and multimodal tasks using HuggingFace Transformers. This skill should be used when fine-tuning pre-trained models, performing inference with pipelines, generating text, training sequence models, or working with BERT, GPT, T5, ViT, and other transformer architectures. Covers model loading, tokenization, training with Trainer API, text generation strategies, and task-specific patterns for classification, NER, QA, summarization, translation, and image tasks. (plugin:scientific-packages@claude-scientific-skills)
Как установить скилл transformers?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл transformers запускает скрипты?
Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic