AYUDA DE PYTHON

fastText Python (Cómo Funciona: Una Guía para Desarrolladores)

Publicado en 5 de marzo, 2025
Compartir:

Introducción a FastText

FastTextes una biblioteca de Python desarrollada inicialmente por el laboratorio de investigación de IA de Facebook(FERIA)que proporciona una clasificación de texto eficiente y un aprendizaje de representación de Word. Ofrece un enfoque innovador para la representación de palabras, abordando algunas de las limitaciones de modelos anteriores como Word2Vec. Su capacidad para comprender vectores o elementos de subpalabras y manejar diversos desafíos lingüísticos lo convierte en una herramienta poderosa en el conjunto de herramientas de PLN. FastText se basa en distribuciones modernas de macOS y Linux. En este artículo, aprenderemos sobre el paquete de Python FastText y también sobre una versátil biblioteca de generación de PDF,IronPDF deIron Software.

Características

  1. Modelo de Representación de Palabras:

    • Aprende a calcular vectores de Word, utiliza fasttext.train_unsupervised con el modelo skip-gram o CBOW con un uso de memoria reducido:
import fasttext
        model = fasttext.train_unsupervised('data.txt', model='skipgram')
        # data.txt is the training file
import fasttext
        model = fasttext.train_unsupervised('data.txt', model='skipgram')
        # data.txt is the training file
import fasttext model = fasttext.train_unsupervised( 'data.txt', model='skipgram')
		#data.txt is the training file
$vbLabelText   $csharpLabel
  • Recuperar vectores de Word:
print(model.words)  # List of words in the dictionary
        print(model['king'])  # Vector for the word 'king'
print(model.words)  # List of words in the dictionary
        print(model['king'])  # Vector for the word 'king'
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.words) # List @of words in the dictionary print(model['king']) # Vector for the word 'king'
$vbLabelText   $csharpLabel
  • Guardar y cargar modelos entrenados:
model.save_model("model_filename.bin")
        loaded_model = fasttext.load_model("model_filename.bin")
model.save_model("model_filename.bin")
        loaded_model = fasttext.load_model("model_filename.bin")
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'model.save_model("model_filename.bin") loaded_model = fasttext.load_model("model_filename.bin")
$vbLabelText   $csharpLabel
  1. Modelo de Clasificación de Texto:

    • Entrena clasificadores de texto supervisados utilizando fasttext.train_supervised o usa un modelo previamente entrenado:
model = fasttext.train_supervised('data.train.txt')
model = fasttext.train_supervised('data.train.txt')
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'model = fasttext.train_supervised('data.train.txt')
$vbLabelText   $csharpLabel
  • Evalúe el modelo dentro de la ventana de contexto:
print(model.test('data.test.txt'))  # Precision and recall
print(model.test('data.test.txt'))  # Precision and recall
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.test('data.test.txt')) # Precision @and recall
$vbLabelText   $csharpLabel
  • Predecir etiquetas para texto específico:
print(model.predict("Which baking dish is best for banana bread?"))
print(model.predict("Which baking dish is best for banana bread?"))
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'print(model.predict("Which baking dish is best for banana bread?"))
$vbLabelText   $csharpLabel

Ejemplos de código

El código demuestra cómo entrenar un modelo de clasificación de texto utilizando FastText:

import fasttext
# Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
import fasttext
# Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
#Training data file format: '__label__<label> <text>' with vocabulary words and out of vocabulary words
#Write the training data to a text file with enriching word vectors
#Train a supervised model with training sentence file input
#Testing the model
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fasttext train_data = ["__label__positive I love this!", "__label__negative This movie is terrible.", "__label__positive Great job!", "__label__neutral The weather is okay."] @with TryCast(open('train.txt', "w"c, encoding='utf-8'), f): for item in train_data: f.write("%s" + vbLf % item) model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0) texts = ["I like it.", "Not good.", "Awesome!"] for text in texts: print(f"Input text: '{text}'") print("Predicted label:", model.predict(text)) print()
$vbLabelText   $csharpLabel

Explicación del Resultado

  • Entrenamiento: El ejemplo entrena un modelo de FastText utilizando un conjunto de datos pequeño(datos_de_entrenamiento). Cada entrada en train_data comienza con una etiqueta seguida de una etiqueta(positivo, negativo, neutral)y el texto correspondiente.
  • Predicción: Después del entrenamiento, el modelo predice etiquetas(positivo, negativo, neutral)para nuevos textos de entrada(textos). Cada texto se clasifica en una de las etiquetas según el modelo entrenado.

Salida

fastText Python(Cómo funciona: una guía para desarrolladores): Figura 1 - Salida del modelo de clasificación de texto

Presentación de IronPDF

fastText Python(Cómo funciona: una guía para desarrolladores): Figura 2 - IronPDF: La biblioteca de PDF para Python

IronPDF es una robusta biblioteca de Python diseñada para crear, editar y firmar digitalmente documentos PDF utilizando HTML, CSS, imágenes y JavaScript. Sobresale en rendimiento al tiempo que mantiene una huella de memoria mínima. Las características clave incluyen:

  • Conversión de HTML a PDF: Convierte archivos HTML, cadenas HTML y URLs en documentos PDF, junto con la capacidad de renderizar páginas web utilizando el renderizador PDF de Chrome.
  • Compatibilidad Multiplataforma: Compatible con Python 3+ en Windows, Mac, Linux y varias plataformas en la nube. IronPDF también está disponible para entornos .NET, Java, Python y Node.js.
  • Edición y Firma: Personaliza las propiedades de PDF, refuerza la seguridad con contraseñas y permisos, y aplica firmas digitales a los documentos.
  • Plantillas y configuraciones de página: Personalice los PDFs con encabezados, pies de página, números de página, márgenes ajustables, tamaños de papel personalizados y diseños adaptativos.
  • Cumplimiento de los estándares: Garantiza la adherencia a los estándares PDF como PDF/A y PDF/UA, admite la codificación de caracteres UTF-8 y gestiona sin problemas activos como imágenes, hojas de estilo CSS y fuentes.

Instalación

pip install fastText
pip install fastText
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastText
$vbLabelText   $csharpLabel

Generar documentos PDF utilizando IronPDF y FastText

Requisitos previos

  1. Asegúrate de que Visual Studio Code esté instalado como editor de código

  2. Python versión 3 está instalado

    Para empezar, creemos un archivo Python para añadir nuestros scripts.

    Abre Visual Studio Code y crea un archivo, fastTextDemo.py.

    Instale las bibliotecas necesarias:

pip install fastText
pip install ironpdf
pip install fastText
pip install ironpdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'pip install fastText pip install ironpdf
$vbLabelText   $csharpLabel

A continuación, agregue el siguiente código para demostrar el uso de los paquetes de Python IronPDF y FastText.

import fasttext
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with Fasttext</h1>"
# Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words,  rare words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
content += "<h2>Training data</h2>"
for data in train_data:
    print(data)
    content += f"<p>{data}</p>"
content += "<h2>Train a supervised model</h2>"
content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>"
content += "<h2>Testing the model</h2>"
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
    content += f"<p>----------------------------------------------</p>"
    content += f"<p>Input text: '{text}</p>"
    content += f"<p>Predicted label:{model.predict(text)}</p>"
pdf = renderer.RenderHtmlAsPdf(content) 
    # Export to a file or Stream
pdf.SaveAs("DemoIronPDF-FastText.pdf")
import fasttext
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
# Create a PDF from a HTML string using Python
content = "<h1>Awesome Iron PDF with Fasttext</h1>"
# Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words,  rare words and out of vocabulary words
train_data = [
    "__label__positive I love this!",
    "__label__negative This movie is terrible.",
    "__label__positive Great job!",
    "__label__neutral The weather is okay."
]
# Write the training data to a text file with enriching word vectors
with open('train.txt', 'w', encoding='utf-8') as f:
    for item in train_data:
        f.write("%s\n" % item)
# Train a supervised model with training sentence file input
model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)
# Testing the model
texts = [
    "I like it.",
    "Not good.",
    "Awesome!"
]
content += "<h2>Training data</h2>"
for data in train_data:
    print(data)
    content += f"<p>{data}</p>"
content += "<h2>Train a supervised model</h2>"
content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>"
content += "<h2>Testing the model</h2>"
for text in texts:
    print(f"Input text: '{text}'")
    print("Predicted label:", model.predict(text))
    print()
    content += f"<p>----------------------------------------------</p>"
    content += f"<p>Input text: '{text}</p>"
    content += f"<p>Predicted label:{model.predict(text)}</p>"
pdf = renderer.RenderHtmlAsPdf(content) 
    # Export to a file or Stream
pdf.SaveAs("DemoIronPDF-FastText.pdf")
#Apply your license key
#Create a PDF from a HTML string using Python
#Training data file format to learn word vectors: '__label__<label> <text>' with vocabulary words, rare words and out of vocabulary words
#Write the training data to a text file with enriching word vectors
#Train a supervised model with training sentence file input
#Testing the model
	#Export to a file or Stream
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'import fasttext from ironpdf import * License.LicenseKey = "key" content = "<h1>Awesome Iron PDF with Fasttext</h1>" train_data = ["__label__positive I love this!", "__label__negative This movie is terrible.", "__label__positive Great job!", "__label__neutral The weather is okay."] @with TryCast(open('train.txt', "w"c, encoding='utf-8'), f): for item in train_data: f.write("%s" + vbLf % item) model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0) texts = ["I like it.", "Not good.", "Awesome!"] content += "<h2>Training data</h2>" for data in train_data: print(data) content += f"<p>{data}</p>" content += "<h2>Train a supervised model</h2>" content += f"<p>model = fasttext.train_supervised(input='train.txt', epoch=10, lr=1.0)</p>" content += "<h2>Testing the model</h2>" for text in texts: print(f"Input text: '{text}'") print("Predicted label:", model.predict(text)) print() content += f"<p>----------------------------------------------</p>" content += f"<p>Input text: '{text}</p>" content += f"<p>Predicted label:{model.predict(text)}</p>" pdf = renderer.RenderHtmlAsPdf(content) pdf.SaveAs("DemoIronPDF-FastText.pdf")
$vbLabelText   $csharpLabel

Salida

fastText Python(Cómo funciona: una guía para desarrolladores): Figura 3 - Salida de Consola

PDF

fastText Python(Cómo funciona: Una guía para desarrolladores): Figura 4 - Salida en PDF

Licencia IronPDF

IronPDF funciona con una clave de licencia para Python. IronPDF for Python ofrece unprueba gratuitaclave de licencia para permitir que los usuarios comiencen de forma gratuita.

Coloque la clave de licencia al inicio del script antes de usarloPaquete IronPDF:

from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
from ironpdf import * 
# Apply your license key
License.LicenseKey = "key"
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Conclusión

FastText es una biblioteca ligera y eficiente para la representación y clasificación de texto. Destaca en el aprendizaje de incrustaciones de palabras utilizando información de subpalabras, respaldando tareas de clasificación de texto con alta velocidad y escalabilidad, ofreciendo modelos preentrenados para múltiples idiomas y proporcionando una interfaz de Python fácil de usar para una integración sencilla en proyectos. IronPDF es una biblioteca integral de Python para crear, editar y renderizar documentos PDF de forma programática. Simplifica tareas como convertir HTML a PDF, agregar contenido y anotaciones a PDFs, gestionar propiedades y seguridad de documentos, y es compatible con diferentes sistemas operativos y entornos de programación. Ideal para generar y manipular PDFs de manera eficiente dentro de aplicaciones Python.

Junto con ambas bibliotecas, podemos entrenar modelos de texto y documentar los resultados de salida en formato PDF para fines de archivo.

Kannaopat Udonpant

Kannapat Udonpant

Ingeniero de software

 LinkedIn

Antes de convertirse en ingeniero de software, Kannapat realizó un doctorado en Recursos Medioambientales en la Universidad de Hokkaido (Japón). Mientras cursaba su licenciatura, Kannapat también se convirtió en miembro del Laboratorio de Robótica Vehicular, que forma parte del Departamento de Ingeniería de Bioproducción. En 2022, aprovechó sus conocimientos de C# para unirse al equipo de ingeniería de Iron Software, donde se centra en IronPDF. Kannapat valora su trabajo porque aprende directamente del desarrollador que escribe la mayor parte del código utilizado en IronPDF. Además del aprendizaje entre iguales, Kannapat disfruta del aspecto social de trabajar en Iron Software. Cuando no está escribiendo código o documentación, Kannapat suele jugar con su PS5 o volver a ver The Last of Us.
< ANTERIOR
Folium Python (Cómo funciona: una guía para desarrolladores)
SIGUIENTE >
Botella Python ((Cómo funciona: una guía para desarrolladores))