- Positive
- Negative
- Sometimes Neutral
1. NLP Text Preprocessing
Before a machine learning model can process text, the text needs to be converted into numerical representations. Typical preprocessing includes:- Convert text into tokens
- Convert tokens into token IDs
- Add special tokens
- Create attention masks
- Pad or truncate sequences
- Pass the processed input to the Transformer model
2. HuggingFace Transformers
HuggingFace Transformers provides pre-trained NLP models such as:- BERT
- DistilBERT
- RoBERTa
- ALBERT
- DeBERTa
3. Text Preprocessing with AutoTokenizer
HuggingFace providesAutoTokenizer to automatically load the correct tokenizer for a model.
input_ids
input_ids are numerical representations of the tokens.
attention_mask
attention_mask tells the model which tokens are actual input and which tokens are padding.
4. Tokenization with Padding and Truncation
For multiple sentences, the sentences can have different lengths. We can use:5. Predicting Sentiment
We can load the fine-tuned model usingAutoModelForSequenceClassification.
6. Convert Logits into Probabilities
We can use Softmax to convert logits into probabilities.7. Get the Predicted Class
We can find the class with the highest probability.8. Complete Sentiment Analysis Code
This is a simple version suitable for a beginner coding exercise.9. Using the HuggingFace Pipeline
HuggingFace also provides a much simplerpipeline() API.
Instead of manually performing tokenization, model inference, Softmax, and prediction, we can use:
10. Code by using Pipeline
11. How the Prediction Works
The complete flow is:12. Installing Required Libraries
Install the required packages with:13. Important Concepts
14. pipeline() vs Manual Approach
Pipeline
- You want simple code
- You are learning NLP
- You only need predictions
- You want to quickly test a model
Manual approach
- You want to understand the internal process
- You need custom preprocessing
- You want more control over the model
- You are building a larger NLP application