Spaces:
Sleeping
Sleeping
Upload src\train_baseline.py with huggingface_hub
Browse files- src//train_baseline.py +102 -0
src//train_baseline.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import pickle
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 6 |
+
from sklearn.linear_model import LogisticRegression
|
| 7 |
+
from sklearn.calibration import CalibratedClassifierCV
|
| 8 |
+
from sklearn.pipeline import Pipeline
|
| 9 |
+
|
| 10 |
+
def train_baseline():
|
| 11 |
+
"""
|
| 12 |
+
Trains a TF-IDF + CalibratedClassifierCV(LogisticRegression) pipeline
|
| 13 |
+
and saves it as models/ticket_classifier/sklearn_router.pkl.
|
| 14 |
+
"""
|
| 15 |
+
print("Training TF-IDF + Logistic Regression baseline pipeline...")
|
| 16 |
+
|
| 17 |
+
# Ensure working directory is project root
|
| 18 |
+
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 19 |
+
os.chdir(project_root)
|
| 20 |
+
|
| 21 |
+
data_path = os.path.join("data", "raw", "support_tickets.csv")
|
| 22 |
+
|
| 23 |
+
categories = [
|
| 24 |
+
'billing', 'technical_support', 'account_management', 'feature_request',
|
| 25 |
+
'compliance_legal', 'onboarding', 'general_inquiry', 'churn_risk'
|
| 26 |
+
]
|
| 27 |
+
cat_to_id = {cat: i for i, cat in enumerate(categories)}
|
| 28 |
+
|
| 29 |
+
# Generate some fallback synthetic data if CSV is not present
|
| 30 |
+
if os.path.exists(data_path):
|
| 31 |
+
print(f"Loading data from {data_path}...")
|
| 32 |
+
try:
|
| 33 |
+
df = pd.read_csv(data_path)
|
| 34 |
+
# Assuming columns 'text' and 'category' exist
|
| 35 |
+
if 'text' in df.columns and 'category' in df.columns:
|
| 36 |
+
# Filter data to only include these categories
|
| 37 |
+
df = df[df['category'].isin(categories)].copy()
|
| 38 |
+
df['label'] = df['category'].map(cat_to_id)
|
| 39 |
+
|
| 40 |
+
texts = df['text'].dropna().astype(str).tolist()
|
| 41 |
+
labels = df['label'].tolist()
|
| 42 |
+
else:
|
| 43 |
+
raise ValueError("CSV missing 'text' or 'category' columns.")
|
| 44 |
+
except Exception as e:
|
| 45 |
+
print(f"Error reading CSV: {e}. Falling back to synthetic data.")
|
| 46 |
+
texts, labels = get_synthetic_data()
|
| 47 |
+
else:
|
| 48 |
+
print(f"{data_path} not found. Generating synthetic baseline data...")
|
| 49 |
+
texts, labels = get_synthetic_data()
|
| 50 |
+
|
| 51 |
+
print(f"Training on {len(texts)} samples across {len(set(labels))} categories...")
|
| 52 |
+
|
| 53 |
+
# Create the pipeline
|
| 54 |
+
pipeline = Pipeline([
|
| 55 |
+
('tfidf', TfidfVectorizer(max_features=5000, stop_words='english', ngram_range=(1, 2))),
|
| 56 |
+
('clf', CalibratedClassifierCV(LogisticRegression(class_weight='balanced', max_iter=1000))),
|
| 57 |
+
])
|
| 58 |
+
|
| 59 |
+
# Fit the pipeline
|
| 60 |
+
pipeline.fit(texts, labels)
|
| 61 |
+
|
| 62 |
+
# Save the model
|
| 63 |
+
out_dir = os.path.join("models", "ticket_classifier")
|
| 64 |
+
os.makedirs(out_dir, exist_ok=True)
|
| 65 |
+
out_path = os.path.join(out_dir, "sklearn_router.pkl")
|
| 66 |
+
|
| 67 |
+
with open(out_path, 'wb') as f:
|
| 68 |
+
pickle.dump(pipeline, f)
|
| 69 |
+
|
| 70 |
+
print(f"Baseline model successfully saved to {out_path}")
|
| 71 |
+
|
| 72 |
+
def get_synthetic_data():
|
| 73 |
+
"""Returns synthetic data for fallback training."""
|
| 74 |
+
categories = [
|
| 75 |
+
'billing', 'technical_support', 'account_management', 'feature_request',
|
| 76 |
+
'compliance_legal', 'onboarding', 'general_inquiry', 'churn_risk'
|
| 77 |
+
]
|
| 78 |
+
base_texts = {
|
| 79 |
+
'billing': ["invoice is wrong", "charge on my card", "cancel subscription", "refund request", "pricing plan"],
|
| 80 |
+
'technical_support': ["server is down", "cannot login", "getting 500 error", "bug in the app", "export failing"],
|
| 81 |
+
'account_management': ["change password", "update email", "delete account", "add user", "role permissions"],
|
| 82 |
+
'feature_request': ["add a feature", "new capability", "implement this", "suggest an improvement"],
|
| 83 |
+
'compliance_legal': ["gdpr report", "data handling documentation", "signed agreement", "privacy policy"],
|
| 84 |
+
'onboarding': ["setup help", "first time user", "getting started", "onboarding walkthrough"],
|
| 85 |
+
'general_inquiry': ["how do I", "question about", "more info", "demo please"],
|
| 86 |
+
'churn_risk': ["I am leaving", "cancel my account", "switching to competitor", "terrible service"]
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
texts = []
|
| 90 |
+
labels = []
|
| 91 |
+
|
| 92 |
+
# Create a reasonably sized synthetic dataset
|
| 93 |
+
for cat in categories:
|
| 94 |
+
for _ in range(50):
|
| 95 |
+
for text in base_texts[cat]:
|
| 96 |
+
texts.append(text)
|
| 97 |
+
labels.append(categories.index(cat))
|
| 98 |
+
|
| 99 |
+
return texts, labels
|
| 100 |
+
|
| 101 |
+
if __name__ == "__main__":
|
| 102 |
+
train_baseline()
|