Procesamiento del lenguaje natural con Transformers

Procesamiento del lenguaje natural con Transformers#

En este cuaderno, utilizamos la biblioteca Transformers de Hugging Face para el procesamiento del lenguaje natural (NLP). Los modelos de lenguaje más avanzados (como GPT, Llama, etc.) requieren mucha memoria y suelen ser inutilizables en una computadora portátil. Por ello, nos limitamos a modelos más pequeños, aunque menos potentes.

ChatBot#

Actualmente, el uso más común de los modelos de lenguaje (LLM) es el ChatBot, un asistente virtual que responde a nuestras preguntas. Con Hugging Face, puedes crear tu propio ChatBot localmente de la siguiente manera.

Utilizamos una versión simplificada de BlenderBot de Meta (facebook/blenderbot-400M-distill).

Implementación#

from transformers import pipeline
/home/aquilae/anaconda3/envs/dev/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
chatbot = pipeline(task="conversational",model="facebook/blenderbot-400M-distill")

Este ChatBot solo entiende inglés, por lo que debes formularle preguntas en ese idioma.

from transformers import Conversation
user_message = """What is the best french deep learning course?"""
conversation = Conversation(user_message)
conversation = chatbot(conversation)
print(conversation)
No chat template is set for this tokenizer, falling back to a default class-level template. This is very error-prone, because models are often trained with templates different from the class default! Default chat templates are a legacy feature and will be removed in Transformers v4.43, at which point any code depending on them will stop working. We recommend setting a valid chat template before then to ensure that this model continues working without issues.
Conversation id: 44c34bd3-ea1b-44b6-bd54-9127133cc941
user: What is the best  french deep learning course?
assistant:  I'm not sure, but I do know that French is one of the most widely spoken languages in the world.

Como puedes observar, el modelo no está bien entrenado y no sabe que el mejor curso de Deep Learning es este.

Si deseas hacer otra pregunta, el siguiente comando te proporciona la respuesta en una sola línea de código.

conversation=Conversation("What is the most tasty fruit?")
print(chatbot(conversation))
Conversation id: d258da22-78e4-4621-a0e1-90776454a595
user: What is the most tasty fruit?
assistant:  I would have to say watermelon. It is so juicy and juicy.

Si deseas continuar la conversación, utiliza esta función.

# Il faut spécifier le rôle (user) et ajouter votre message dans la conversation déjà existante
conversation.add_message({"role": "user","content": """What else do you recommend?"""})
print(chatbot(conversation))
Conversation id: c3e1a64c-5b40-4808-8632-38d9df14ed9d
user: What is the most tasty fruit?
assistant:  I would have to say watermelon. It is so juicy and juicy.
user: What else do you recommend?
assistant:  I would say mangos are pretty good too. They are sweet and tangy.

Ahora sabes cómo utilizar un ChatBot con la biblioteca Transformers de Hugging Face.

Traducción#

Ahora veremos cómo implementar un traductor. Utilizamos el modelo No Language Left Behind de Meta (facebook/nllb-200-distilled-600M), que permite traducir desde cualquier idioma. Por limitaciones de memoria, empleamos una versión simplificada del modelo.

Implementación#

traducteur = pipeline(task="translation",model="facebook/nllb-200-distilled-600M") 
text = """Le meilleur cours de d'apprentissage profond est celui-ci."""
text_translated = traducteur(text,src_lang="fra_Latn",tgt_lang="eng_Latn")
print("Le texte en anglais : ", text_translated[0]["translation_text"])
text_translated = traducteur(text,src_lang="fra_Latn",tgt_lang="jpn_Jpan")
print("Le texte en japonais : ",text_translated[0]["translation_text"])
Le texte en anglais :  The best course of deep learning is this one.
Le texte en japonais :  深い学習の最高のコースはこれです

La traducción es muy buena (al menos para el inglés; ¡no tengo experiencia con el japonés!). También puedes probar otras combinaciones de idiomas especificando el código adecuado, que encontrarás en esta página.

Resumen de texto#

Otra tarea útil en NLP es el resumen de texto. El modelo debe ser capaz de extraer la información más relevante de un texto. Para ello, utilizamos el modelo BART de Meta (facebook/bart-large-cnn).

resumeur=pipeline(task="summarization",model="facebook/bart-large-cnn")
text= "Troyes is a beautiful city. Troyes is a commune and the capital of the department of Aube in the Grand Est region of north-central France. It is located on the Seine river about 140 km (87 mi) south-east of Paris. Troyes is situated within the Champagne wine region and is near to the Orient Forest Regional Natural Park.Troyes had a population of 61,996 inhabitants in 2018. It is the center of the Communauté d'agglomération Troyes Champagne Métropole, which was home to 170,145 inhabitants."
summary = resumeur(text,min_length=10,max_length=100)
print("Le résumé du texte : ",summary[0]["summary_text"]) #["summary_text"]
Le résumé du texte :  Troyes is a commune and the capital of the department of Aube in the Grand Est region of north-central France. It is located on the Seine river about 140 km (87 mi) south-east of Paris. Troyes had a population of 61,996 inhabitants in 2018.

El resumen no es perfecto, ya que se trata de un modelo pequeño, pero ha logrado extraer la información clave y eliminar los elementos menos relevantes.

Embeddings de frases#

Un aspecto importante del NLP que vimos en el curso es el embedding. Recordemos: esto consiste en proyectar nuestros tokens (palabras o caracteres, por ejemplo) en un espacio latente. Esto permite acercar palabras similares. Por ejemplo, palabras como “perros” y “gatos” estarán cerca en el espacio latente, mientras que “perro” y “es” estarán distantes. Podemos utilizar estos embeddings para calcular la similitud entre dos frases. Para ello, empleamos la biblioteca sentence_transformers, que permite extraer el embedding a partir de un modelo preentrenado.

Utilizamos el modelo all-MiniLM-L6-v2.

from sentence_transformers import SentenceTransformer
from sentence_transformers import util
model = SentenceTransformer("all-MiniLM-L6-v2")

Vamos a analizar la similitud entre diferentes frases.

sentences1 = ['The cat is chasing the mouse','A man is watching the television','The latest movie is awesome']
sentences2 = ['The dog sleeps in the kitchen','A boy watches TV','The new movie is so great']
embeddings1 = model.encode(sentences1, convert_to_tensor=True)
embeddings2 = model.encode(sentences2,convert_to_tensor=True)
cosine_scores = util.cos_sim(embeddings1,embeddings2)
for i in range(len(sentences1)):
  print("{} \t\t {} \t\t Score: {:.4f}".format(sentences1[i],
                                                sentences2[i],
                                                cosine_scores[i][i]))
The cat is chasing the mouse 		 The dog sleep in the kitchen 		 Score: 0.0601
A man is watching the television 		 A boy watches TV 		 Score: 0.7207
The latest movie is awesome 		 The new movie is so great 		 Score: 0.7786

Como puedes ver, las frases con significados similares tienen embeddings bastante parecidos. Por lo tanto, este modelo es útil para extraer embeddings. Contar con un buen modelo para extraer embeddings suele ser un primer paso en un proyecto de NLP.