fastText Predict

0.9.2.4 · active · verified Mon Apr 13

fasttext-predict is a Python package that provides a lightweight, standalone implementation of fastText's prediction functionality. It is specifically designed to include only the `predict` method, making it compact (<1MB) and free of external dependencies, including NumPy. This library aims to provide pre-built wheels for various architectures, ensuring easy installation for deployment scenarios where a full fastText installation is not desired. It is actively maintained with frequent minor updates, offering a stable solution for inference.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to load a pre-trained fastText model (e.g., for language identification) and use its `predict` method to classify a given text. It also shows how to retrieve multiple top-k predictions and their associated probabilities. A fastText model file must be downloaded and accessible for this example to run correctly.

# A fastText model file (e.g., for language identification) needs to be downloaded separately.
# Example model: lid.176.ftz from https://fasttext.cc/docs/en/language-identification.html

import fasttext
import os

# Ensure the model file is accessible, e.g., placed in the current directory
model_path = os.environ.get('FASTTEXT_MODEL_PATH', 'lid.176.ftz')

try:
    model = fasttext.load_model(model_path)
    text_to_predict = 'Fondant au chocolat et tarte aux myrtilles'
    predictions = model.predict(text_to_predict)
    
    print(f"Text: '{text_to_predict}'")
    print(f"Predicted label(s): {predictions[0]}")
    print(f"Probabilities: {predictions[1]}")

    # To get top-k predictions with probabilities
    top_k_predictions = model.predict(text_to_predict, k=2)
    print(f"\nTop 2 Predicted label(s): {top_k_predictions[0]}")
    print(f"Top 2 Probabilities: {top_k_predictions[1]}")

except ValueError as e:
    print(f"Error loading model or making prediction: {e}")
    print("Please ensure the model file is downloaded and the path is correct.")
except FileNotFoundError:
    print(f"Error: Model file not found at '{model_path}'.")
    print("Please download 'lid.176.ftz' (or your target model) and place it correctly, or set FASTTEXT_MODEL_PATH environment variable.")

view raw JSON →