{"slug": "classify-text-in-10-lines-with-a-hugging-face-transformers-pipeline", "title": "Classify Text in 10 Lines with a Hugging Face Transformers Pipeline", "summary": "A tutorial by Mariana Souza demonstrates how to classify text sentiment in 10 lines of Python using a Hugging Face Transformers pipeline with a pretrained DistilBERT model, running entirely on CPU with no GPU or training required. The script, built with transformers 5.14.1 and PyTorch 2.13.0, labels text as POSITIVE or NEGATIVE using the 67M-parameter distilbert-base-uncased-finetuned-sst-2-english model, achieving scores above 0.99 on example reviews.", "body_md": "# Classify Text in 10 Lines with a Hugging Face Transformers Pipeline\n\nInstall Transformers, load a pretrained DistilBERT model, and classify sentiment locally with no GPU or training.\n\n[Mariana Souza](https://sourcefeed.dev/u/mariana_souza)\n\n## What you'll build\n\nA Python script that labels any text as `POSITIVE`\n\nor `NEGATIVE`\n\nsentiment using a pretrained DistilBERT model from the Hugging Face Hub — running entirely on your CPU. The core logic is 10 lines. No training, no GPU, no API key.\n\n## Prerequisites\n\n**Python 3.10+**—[Transformers](https://huggingface.co/docs/transformers)v5 requires it. Verified here with Python 3.13.5.** Verified library versions:**transformers 5.14.1,[PyTorch](https://pytorch.org)2.13.0 (CPU build).**~1.5 GB free disk**— the CPU PyTorch wheel plus a ~270 MB model download.** Internet access on first run**— the model downloads once, then loads from the local cache at`~/.cache/huggingface/hub`\n\n.- No Hugging Face account or token needed; the model is public.\n\nCommands below are for macOS/Linux. On Windows, activate the virtual environment with `.venv\\Scripts\\activate`\n\ninstead.\n\n## 1. Create a project and virtual environment\n\nKeep this isolated from your system Python — Transformers pulls in a dozen dependencies you don't want globally.\n\n```\nmkdir first-pipeline && cd first-pipeline\npython3 -m venv .venv\nsource .venv/bin/activate\n```\n\nYour prompt should now show `(.venv)`\n\n.\n\n## 2. Install PyTorch and Transformers\n\nTransformers v5 is PyTorch-only (TensorFlow and Flax backends were dropped in 5.0). Install the CPU build of torch explicitly — on Linux this skips several gigabytes of CUDA libraries you don't need for this tutorial:\n\n```\npip install torch --index-url https://download.pytorch.org/whl/cpu\npip install transformers\n```\n\nConfirm both landed:\n\n``` python\npython -c \"import torch, transformers; print(torch.__version__, transformers.__version__)\"\n```\n\nExpected: `2.13.0+cpu 5.14.1`\n\n(plain `2.13.0`\n\non macOS) or newer.\n\n## 3. Write the classifier\n\nCreate `classify.py`\n\n:\n\n``` python\nfrom transformers import pipeline\n\nclassifier = pipeline(\n    \"text-classification\",\n    model=\"distilbert/distilbert-base-uncased-finetuned-sst-2-english\",\n)\n\nreviews = [\n    \"The battery life on this laptop is incredible.\",\n    \"Shipping took three weeks and the box arrived crushed.\",\n]\n\nfor review, result in zip(reviews, classifier(reviews)):\n    print(f\"{result['label']:<8} {result['score']:.4f}  {review}\")\n```\n\nTwo things worth knowing. `pipeline()`\n\nbundles the tokenizer, model, and post-processing into one callable — you pass raw strings, it returns dicts with a `label`\n\nand a `score`\n\n(the model's probability for that label). And the model is pinned explicitly: `pipeline(\"text-classification\")`\n\nalone works, but it logs a \"No model was supplied\" warning and leaves you at the mercy of whatever default Hugging Face picks later. The pinned checkpoint, [distilbert-base-uncased-finetuned-sst-2-english](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english), is a 67M-parameter DistilBERT fine-tuned on Stanford Sentiment Treebank movie reviews — small enough to run comfortably on any laptop CPU.\n\n## 4. Run it\n\n```\npython classify.py\n```\n\nThe first run downloads the model (~268 MB) and tokenizer files, then caches them. Subsequent runs load from disk and classify both sentences in well under a second.\n\n## Verify it works\n\nYou should see exactly this (scores may differ in the last decimal places across platforms):\n\n```\nPOSITIVE 0.9998  The battery life on this laptop is incredible.\nNEGATIVE 0.9997  Shipping took three weeks and the box arrived crushed.\n```\n\nIf both labels match with scores above 0.99, everything works. Swap in your own sentences and rerun — no re-download happens.\n\n## Troubleshooting\n\n** ModuleNotFoundError: No module named 'transformers'** — you're running a Python outside the virtual environment. Check that your prompt shows\n\n`(.venv)`\n\n, re-run `source .venv/bin/activate`\n\n, and confirm with `which python`\n\nthat it points into `.venv`\n\n.** OSError: We couldn't connect to 'https://huggingface.co' to load the files, and couldn't find them in the cached files.** — the Hub is unreachable on first download. Check your connection and proxy settings, and make sure\n\n`HF_HUB_OFFLINE`\n\nisn't set in your shell (`echo $HF_HUB_OFFLINE`\n\nshould print nothing).** Warning: You are sending unauthenticated requests to the HF Hub. Please set a HF_TOKEN to enable higher rate limits and faster downloads.** — informational, not an error; the download still works. To silence it, create a free token at huggingface.co/settings/tokens and export it as\n\n`HF_TOKEN`\n\n.** ERROR: Could not find a version that satisfies the requirement transformers** — pip found no compatible wheel, which almost always means Python older than 3.10. Run\n\n`python3 --version`\n\nand install a current Python before recreating the venv.## Next steps\n\n- Pass\n`top_k=None`\n\nto`pipeline()`\n\nto get scores for every label instead of just the winner — useful for confidence thresholds. - Swap the model string for\n[cardiffnlp/twitter-roberta-base-sentiment-latest](https://huggingface.co/cardiffnlp/twitter-roberta-base-sentiment-latest)(adds a`neutral`\n\nclass, tuned for social media) — nothing else in the code changes. That interchangeability is the pipeline API's whole point. - Try\n`pipeline(\"zero-shot-classification\")`\n\nto classify against your own arbitrary labels with no fine-tuning. - Got an NVIDIA GPU? Install the CUDA build of torch and pass\n`device=\"cuda\"`\n\nto`pipeline()`\n\n. - The\n[Pipeline API reference](https://huggingface.co/docs/transformers/main_classes/pipelines)lists every supported task, and the free[Hugging Face LLM Course](https://huggingface.co/learn/llm-course)goes from here to fine-tuning your own models.\n\n## Sources & further reading\n\n-\n[Transformers Installation](https://huggingface.co/docs/transformers/en/installation)— huggingface.co -\n[Pipelines API Reference](https://huggingface.co/docs/transformers/en/main_classes/pipelines)— huggingface.co -\n[Transformers Quickstart](https://huggingface.co/docs/transformers/en/quicktour)— huggingface.co -\n[DistilBERT base uncased finetuned SST-2 model card](https://huggingface.co/distilbert/distilbert-base-uncased-finetuned-sst-2-english)— huggingface.co -\n[PyTorch Get Started Locally](https://pytorch.org/get-started/locally/)— pytorch.org\n\n[Mariana Souza](https://sourcefeed.dev/u/mariana_souza)· Senior Editor\n\nMariana covers the fast-moving world of machine learning and generative AI, with a particular focus on how these technologies are reshaping development workflows. When she isn't stress-testing the latest foundation models, she's usually at a local hackathon.\n\n## Discussion 0\n\nNo comments yet\n\nBe the first to weigh in.", "url": "https://wpnews.pro/news/classify-text-in-10-lines-with-a-hugging-face-transformers-pipeline", "canonical_source": "https://sourcefeed.dev/a/classify-text-in-10-lines-with-a-hugging-face-transformers-pipeline", "published_at": "2026-07-24 11:40:52+00:00", "updated_at": "2026-07-24 11:59:07.380044+00:00", "lang": "en", "topics": ["natural-language-processing", "developer-tools"], "entities": ["Hugging Face", "DistilBERT", "PyTorch", "Mariana Souza", "Stanford Sentiment Treebank"], "alternates": {"html": "https://wpnews.pro/news/classify-text-in-10-lines-with-a-hugging-face-transformers-pipeline", "markdown": "https://wpnews.pro/news/classify-text-in-10-lines-with-a-hugging-face-transformers-pipeline.md", "text": "https://wpnews.pro/news/classify-text-in-10-lines-with-a-hugging-face-transformers-pipeline.txt", "jsonld": "https://wpnews.pro/news/classify-text-in-10-lines-with-a-hugging-face-transformers-pipeline.jsonld"}}