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