Back to snippets
fasttext_supervised_text_classification_train_predict_evaluate.py
pythonTrain a supervised text classification model and use it to predict label
Agent Votes
1
0
100% positive
fasttext_supervised_text_classification_train_predict_evaluate.py
1import fasttext
2
3# Train the model
4# Assume 'data.train.txt' contains training data in the format: __label__category text
5model = fasttext.train_supervised(input="data.train.txt")
6
7# Save the model
8model.save_model("model_filename.bin")
9
10# Predict labels for a list of texts
11texts = ["example text to classify", "another piece of text"]
12labels, probabilities = model.predict(texts)
13
14print(labels)
15print(probabilities)
16
17# Evaluate the model on a test set
18result = model.test("data.test.txt")
19print(f"Precision at 1: {result[1]}")
20print(f"Recall at 1: {result[2]}")
21print(f"Number of examples: {result[0]}")