You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
16 Hrs
30 Min
39 Seg

Fine-Tuning de Transformers para Datos Empresariales

13/16
Resources

How to train a model for sentiment analysis?

Sentiment analysis is a powerful tool for understanding opinions expressed in texts. Let's explore how to train a custom model to classify Spanish reviews as positive or negative.

Preparing our data

To begin this process, we need to properly structure our data. The first step is to import a dataset of reviews and prepare it for training:

import pandas as pddf = pd.read_csv('review_dataset.csv')

Once the dataset is loaded, we can verify that it contains the necessary information: the review text (review_body) and the rating (stars). It is essential to condition this data by dividing the dataset into three parts:

  • 70% for training
  • 20% for testing
  • 10% for validation

Transforming the data for the model

To work with natural language processing models, we need to convert our ratings into binary labels:

  • Reviews with more than 3 stars → positive
  • Reviews with 3 or less stars → negative

This step is crucial so that the model can learn to distinguish between positive and negative sentiments in the text.

Using a pre-trained model in Spanish.

For best results, we will use a specialized Spanish base model, such as RoBERTa-BNE, trained with the corpus of the National Library of Spain. This transfer learning approach allows us to take advantage of a model that already understands the structure of the Spanish language.

Tokenization is an essential step in this process:

# we tokenize exclusively the content of the reviewstokenized_data = tokenizer(df['review_body'].tolist())

Training the model

The fine-tuning process allows us to adapt the pre-trained model to our specific binary classification task. Key parameters include:

  • Batch size: 8 (suitable for Google Colab).
  • Epochs: 2 (sufficient for this well-balanced dataset)
  • Learning rate: default values

Importantly, once trained, the model can be uploaded to Hugging Face Hub, allowing anyone in the world to use it.

Evaluating performance

After training, we can test our model with real examples:

  • "I loved the pants" → Positive (99% confidence).
  • "It forces you to buy two units" → Negative (94% confidence).
  • "Worst purchase of my life, do not recommend" → Negative (99% confidence).

This type of personalized sentiment analysis has immediate practical applications for any business that receives customer feedback.

Have you ever trained a natural language processing model? Share your experience or doubts in the comments and don't forget to test this approach with your own data.

Contributions 5

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?

En el contexto de fine-tuning de transformers, cuando imprimes `encoded_dataset`, podrías ver la columna `labels` aunque la hayas removido, porque el dataset podría estar configurado para incluir etiquetas de clasificación automáticamente durante el proceso de tokenización. Asegúrate de que, al crear el dataset, estás eliminando las etiquetas correctamente y revisa la estructura del dataset después de la preparación. Esto asegura que solo las características relevantes estén presentes en el conjunto de entrenamiento.
Weights and Biases (W&B) se utiliza principalmente para el seguimiento de experimentos, gestión de modelos y visualización de métricas durante el entrenamiento de modelos de machine learning. En el contexto del fine-tuning de transformers, como se menciona en la clase, W&B permite monitorear el rendimiento del modelo, registrar hiperparámetros y facilitar la colaboración al compartir resultados. Esto mejora la reproducibilidad y eficiencia en el proceso de desarrollo y ajuste de modelos, haciendo que sea más fácil iterar y optimizar el entrenamiento.
Aquí esta el mío <https://huggingface.co/Edward-117/roberta-base-bne-platzi-project-nlp-con-transformers>
Las redes neuronales convolucionales (CNN) se utilizan principalmente para procesar datos que tienen una estructura en forma de cuadrícula, como imágenes. Estas redes son eficaces en la detección de patrones y características locales en las imágenes, lo que les permite aprender de forma jerárquica. En el contexto de procesamiento de lenguaje natural, aunque las CNN no son tan comunes como las redes recurrentes o Transformers, pueden ser útiles para tareas como análisis de sentimientos al extraer características de secuencias de texto.
jajajaja no, pero como vas a compartir el token.