Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:666ghj BettaFish SentimentModel train and evaluate

From Leeroopedia
Knowledge Sources
Domains Machine_Learning, Sentiment_Analysis, domain:NLP
Last Updated 2026-10-08 00:00 GMT

Overview

Concrete abstract base class and ML model implementations for Chinese sentiment classification, providing a unified train/evaluate/predict/save/load interface for Bayes, SVM, XGBoost, LSTM, and BERT models.

Description

The BaseModel abstract class defines a unified interface for all traditional ML and deep learning sentiment models in the SentimentAnalysisModel package. Concrete implementations include:

  • BayesModel: Multinomial Naive Bayes with TF-IDF vectorization
  • SVMModel: Support Vector Machine with TF-IDF
  • XGBoostModel: Gradient boosting with TF-IDF
  • LSTMModel: Bidirectional LSTM with embedding layer
  • BertModel_Custom: BERT (Chinese) fine-tuned for sentiment

All models share the same train/evaluate/predict/save/load interface, enabling the SentimentPredictor to load and use any model interchangeably.

Usage

Import the specific model class when you need to train a sentiment classifier. Use BaseModel for the shared interface or SentimentPredictor for unified multi-model prediction.

Code Reference

Source Location

  • Repository: BettaFish
  • Files:
    • `SentimentAnalysisModel/WeiboSentiment_MachineLearning/base_model.py:L14-120` (BaseModel)
    • `SentimentAnalysisModel/WeiboSentiment_MachineLearning/bayes_train.py:L16-95` (BayesModel)
    • `SentimentAnalysisModel/WeiboSentiment_MachineLearning/svm_train.py` (SVMModel)
    • `SentimentAnalysisModel/WeiboSentiment_MachineLearning/xgboost_train.py` (XGBoostModel)
    • `SentimentAnalysisModel/WeiboSentiment_MachineLearning/lstm_train.py` (LSTMModel)
    • `SentimentAnalysisModel/WeiboSentiment_MachineLearning/bert_train.py` (BertModel_Custom)

Signature

class BaseModel(ABC):
    def __init__(self, model_name: str):
        """Initialize with model name."""

    @abstractmethod
    def train(self, train_data: List[Tuple[str, int]], **kwargs) -> None:
        """Train the model on (text, label) pairs."""

    @abstractmethod
    def predict(self, texts: List[str]) -> List[int]:
        """Predict sentiment labels for texts."""

    def predict_single(self, text: str) -> Tuple[int, float]:
        """Predict single text. Returns (label, confidence)."""

    def evaluate(self, test_data: List[Tuple[str, int]]) -> Dict[str, float]:
        """Evaluate on test data. Returns accuracy, f1_score, classification_report."""

    def save_model(self, model_path: str = None) -> None:
        """Save model to pickle file."""

    def load_model(self, model_path: str) -> None:
        """Load model from pickle file."""

    @staticmethod
    def load_data(train_path: str, test_path: str) -> Tuple:
        """Load train/test data from corpus files."""

Import

from SentimentAnalysisModel.WeiboSentiment_MachineLearning.bayes_train import BayesModel
from SentimentAnalysisModel.WeiboSentiment_MachineLearning.svm_train import SVMModel
from SentimentAnalysisModel.WeiboSentiment_MachineLearning.base_model import BaseModel

I/O Contract

Inputs

Name Type Required Description
train_data List[Tuple[str, int]] Yes (processed_text, sentiment_label) pairs
test_data List[Tuple[str, int]] For eval (processed_text, sentiment_label) pairs

Outputs

Name Type Description
model trained model Saved to .pkl or .pth file
evaluate Dict accuracy, f1_score, classification_report

Usage Examples

Train and Evaluate Bayes Model

from SentimentAnalysisModel.WeiboSentiment_MachineLearning.bayes_train import BayesModel
from SentimentAnalysisModel.WeiboSentiment_MachineLearning.utils import load_corpus

# Load data
train_data = load_corpus("data/weibo2018/train.txt")  # (text, label) pairs
test_data = load_corpus("data/weibo2018/test.txt")

# Train
model = BayesModel()
model.train(train_data)

# Evaluate
metrics = model.evaluate(test_data)
print(f"Accuracy: {metrics['accuracy']:.4f}")
print(f"F1: {metrics['f1_score']:.4f}")

# Save
model.save_model("model/bayes_model.pkl")

Related Pages

Implements Principle

Requires Environment

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment