pythainlp.classify

class pythainlp.classify.GzipModel(training_data: list[tuple[str, str]] | None = None, model_path: str = '')[source]

Parameter-free text classifier using a gzip compressor.

This class is a re-implementation of “Low-Resource” Text Classification: A Parameter-Free Classification Method with Compressors (Jiang et al., Findings 2023).

Parameters:
  • training_data (Optional[list[tuple[str, str]]]) – list of (text, label) tuples (default: None)

  • model_path (str) – path to load a saved model from (default: empty string, which trains from training_data)

__init__(training_data: list[tuple[str, str]] | None = None, model_path: str = '') → None[source]

Initialize the model.

Parameters:
  • training_data (Optional[list[tuple[str, str]]]) – list of (text, label) tuples

  • model_path (str) – path to load a saved model from

training_data: NDArray[Any]
cx2_list: list[int]
train() → list[int][source]

Compute the compressed length of each training text.

Returns:

compressed length of each training text

Return type:

list[int]

predict(x1: str, k: int = 1) → str[source]

Predict the label for the given text.

Parameters:
  • x1 (str) – text to predict the label of

  • k (int) – number of nearest neighbors to consider (default: 1)

Returns:

predicted label

Return type:

str

Example:
>>>     from pythainlp.classify import GzipModel
>>>     training_data = [
...         ("รายละเอียดตามนี้เลยค่าา ^^", "Neutral"),
...         ("กลัวพวกมึงหาย อดกินบาบิก้อน", "Neutral"),
...         ("บริการแย่มากก เป็นหมอได้ไง😤", "Negative"),
...         ("ขับรถแย่มาก", "Negative"),
...         ("ดีนะครับ", "Positive"),
...         ("ลองแล้วรสนี้อร่อย... ชอบๆ", "Positive"),
...         ("ฉันรู้สึกโกรธ เวลามือถือแบตหมด", "Negative"),
...         ("เธอภูมิใจที่ได้ทำสิ่งดี ๆ และดีใจกับเด็ก ๆ", "Positive"),
...         ("นี่เป็นบทความหนึ่ง", "Neutral"),
...     ]
>>>     model = GzipModel(training_data)
>>>     print(model.predict("ฉันดีใจ", k=1))
    Positive
save(path: str) → None[source]

Save the model to a file.

Parameters:

path (str) – path to save the model to

load(path: str) → None[source]

Load the model from a file.

Parameters:

path (str) – path to load the model from

class pythainlp.classify.LayaModel(model_path: str | None = None, providers: list[str] | None = None, revision: str | None = None, batch_size: int = 16, max_length: int | None = None, head_max_length: int | None = None)[source]

Laya Multilingual model for zero-shot text classification and decision making.

Laya is a non-autoregressive decision model designed for fast, calibrated, and reliable decision making. It supports over 100 languages including Thai, allowing zero-shot classification using an instruction prompt and candidate choices without any task-specific fine-tuning.

Parameters:
  • model_path (Optional[str]) – Hugging Face model repository ID or local directory path containing the ONNX model files. Default is "pythainlp/laya-multilingual-onnx".

  • providers (Optional[list[str]]) – List of ONNX Runtime execution providers (e.g. ["CPUExecutionProvider"], ["CUDAExecutionProvider"]). Default is ["CPUExecutionProvider"].

  • revision (Optional[str]) – Git revision (branch, tag, or commit hash) on Hugging Face Hub (optional).

  • batch_size (int) – Batch size for batched inference (default: 16).

  • max_length (Optional[int]) – Maximum sequence length in tokens (default from configuration, typically 1024).

  • head_max_length (Optional[int]) – Maximum token length for the question header and candidate options (default from configuration, typically 256).

Example:
>>> from pythainlp.classify import LayaModel
>>> model = LayaModel()
>>> model.classify(
...     "อาหารอร่อยมาก บรรยากาศดี พนักงานบริการยอดเยี่ยม",
...     choices=["Positive", "Negative", "Neutral"],
...     prompt="What is the sentiment of the text?",
... )
'Positive'
__init__(model_path: str | None = None, providers: list[str] | None = None, revision: str | None = None, batch_size: int = 16, max_length: int | None = None, head_max_length: int | None = None) → None[source]

Initialize the Laya ONNX model and tokenizer.

batch_size: int
providers: list[str]
model_path: str
system_one(state: str | dict[str, Any] | list[Any], questions: dict[str, Any]) → dict[str, Any][source]

Execute typed-decision questions over state (upstream Laya System 1 interface).

Supports question types: - choice: Select best option among criteria. - score: Ordinal evaluation across score criteria. - noul: Binary yes/no statement evaluation.

Parameters:
  • state (Union[str, dict[str, Any], list[Any]]) – Context or document to evaluate.

  • questions (dict[str, Any]) – Dictionary of question definitions keyed by question ID.

Returns:

Dictionary containing "model", "answers", and token "usage".

Return type:

dict[str, Any]

classify(text: str | dict[str, Any] | list[Any], choices: list[str] | dict[str, Any], prompt: str = 'Select the best choice for the given text.', return_details: bool = False) → str | dict[str, Any][source]

Classify text into one of candidate choices using prompt guidance.

Parameters:
  • text (Union[str, dict[str, Any], list[Any]]) – Input text or structured state.

  • choices (Union[list[str], dict[str, Any]]) – List of candidate choice labels or dictionary mapping each choice label to its description.

  • prompt (str) – Instruction prompt guiding the classification task. Default is "Select the best choice for the given text.".

  • return_details (bool) – If True, returns full details dictionary including choice, confidence, probabilities, and action probability. If False (default), returns the selected choice label string.

Returns:

Selected choice string or detailed answer dictionary.

Return type:

Union[str, dict[str, Any]]

classify_batch(texts: list[str | dict[str, Any] | list[Any]], choices: list[str] | dict[str, Any], prompt: str = 'Select the best choice for the given text.', return_details: bool = False) → list[str | dict[str, Any]][source]

Classify multiple texts in batches.

Parameters:
  • texts (list[Union[str, dict[str, Any], list[Any]]]) – List of texts or states.

  • choices (Union[list[str], dict[str, Any]]) – Candidate choices.

  • prompt (str) – Instruction prompt.

  • return_details (bool) – Whether to return full details.

Returns:

List of predicted choices or detailed dictionaries.

Return type:

list[Union[str, dict[str, Any]]]

predict(text: str | dict[str, Any] | list[Any], choices: list[str] | dict[str, Any] | None = None, prompt: str = 'Select the best choice for the given text.', questions: dict[str, Any] | None = None, return_details: bool = False) → Any[source]

Predict classification choice or structured decisions.

If choices is provided, executes choice classification. If questions is provided, executes structured decision tasks.

Parameters:
  • text (Union[str, dict[str, Any], list[Any]]) – Input text or state.

  • choices (Optional[Union[list[str], dict[str, Any]]]) – Candidate choices.

  • prompt (str) – Instruction prompt when using choices.

  • questions (Optional[dict[str, Any]]) – Question dictionary.

  • return_details (bool) – Whether to return detailed output.

Returns:

Predicted choice or questions output.

Return type:

Any