Spaces:
Runtime error
Runtime error
Create train_spam_model.py
Browse files- train_spam_model.py +96 -0
train_spam_model.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -----------------------------
|
| 2 |
+
# 1️⃣ Import des librairies
|
| 3 |
+
# -----------------------------
|
| 4 |
+
import pandas as pd
|
| 5 |
+
import re
|
| 6 |
+
import joblib
|
| 7 |
+
import nltk
|
| 8 |
+
from nltk.corpus import stopwords
|
| 9 |
+
from nltk.stem import PorterStemmer
|
| 10 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 11 |
+
from sklearn.model_selection import train_test_split
|
| 12 |
+
from sklearn.linear_model import LogisticRegression
|
| 13 |
+
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, roc_auc_score
|
| 14 |
+
from imblearn.over_sampling import SMOTE
|
| 15 |
+
|
| 16 |
+
# Télécharger stopwords si nécessaire
|
| 17 |
+
nltk.download('stopwords')
|
| 18 |
+
|
| 19 |
+
# -----------------------------
|
| 20 |
+
# 2️⃣ Prétraitement des messages
|
| 21 |
+
# -----------------------------
|
| 22 |
+
stop_words = set(stopwords.words('english'))
|
| 23 |
+
stemmer = PorterStemmer()
|
| 24 |
+
|
| 25 |
+
def preprocess_message(text):
|
| 26 |
+
if pd.isna(text):
|
| 27 |
+
return ""
|
| 28 |
+
text = text.lower()
|
| 29 |
+
text = re.sub(r'http\S+|www\S+', '', text) # supprimer URLs
|
| 30 |
+
text = re.sub(r'\S+@\S+', '', text) # supprimer emails
|
| 31 |
+
text = re.sub(r'\+?\d[\d -]{8,}\d', '', text) # supprimer numéros
|
| 32 |
+
text = re.sub(r'\d+', '', text) # supprimer chiffres
|
| 33 |
+
text = re.sub(r'[^a-z\s!/+>]', '', text) # garder ponctuation utile spam
|
| 34 |
+
words = [stemmer.stem(word) for word in text.split() if word not in stop_words]
|
| 35 |
+
return " ".join(words)
|
| 36 |
+
|
| 37 |
+
# -----------------------------
|
| 38 |
+
# 3️⃣ Charger les données
|
| 39 |
+
# -----------------------------
|
| 40 |
+
# data doit avoir les colonnes "Message" et "Category" ('spam'/'ham')
|
| 41 |
+
data = pd.read_csv("data.csv")
|
| 42 |
+
data['cleaned'] = data['Message'].apply(preprocess_message)
|
| 43 |
+
|
| 44 |
+
X = data['cleaned']
|
| 45 |
+
y = data['Category']
|
| 46 |
+
|
| 47 |
+
# Split train/test stratifié
|
| 48 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 49 |
+
X, y, test_size=0.2, random_state=42, stratify=y
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# -----------------------------
|
| 53 |
+
# 4️⃣ Vectorisation TF-IDF
|
| 54 |
+
# -----------------------------
|
| 55 |
+
tfidf = TfidfVectorizer(
|
| 56 |
+
max_features=5000,
|
| 57 |
+
min_df=2,
|
| 58 |
+
max_df=0.95,
|
| 59 |
+
ngram_range=(1,2),
|
| 60 |
+
token_pattern=r'(?u)\b\w+\b|[!/+>]' # capture mots et ponctuations importantes
|
| 61 |
+
)
|
| 62 |
+
X_train_tfidf = tfidf.fit_transform(X_train)
|
| 63 |
+
X_test_tfidf = tfidf.transform(X_test)
|
| 64 |
+
|
| 65 |
+
# -----------------------------
|
| 66 |
+
# 5️⃣ Équilibrage des classes avec SMOTE
|
| 67 |
+
# -----------------------------
|
| 68 |
+
smote = SMOTE(random_state=42)
|
| 69 |
+
X_train_balanced, y_train_balanced = smote.fit_resample(X_train_tfidf, y_train)
|
| 70 |
+
|
| 71 |
+
# -----------------------------
|
| 72 |
+
# 6️⃣ Entraînement du modèle Logistic Regression
|
| 73 |
+
# -----------------------------
|
| 74 |
+
model = LogisticRegression(random_state=42, max_iter=1000)
|
| 75 |
+
model.fit(X_train_balanced, y_train_balanced)
|
| 76 |
+
|
| 77 |
+
# -----------------------------
|
| 78 |
+
# 7️⃣ Évaluation rapide
|
| 79 |
+
# -----------------------------
|
| 80 |
+
y_pred = model.predict(X_test_tfidf)
|
| 81 |
+
print("Classification Report:\n", classification_report(y_test, y_pred))
|
| 82 |
+
print("Matrice de confusion:\n", confusion_matrix(y_test, y_pred))
|
| 83 |
+
accuracy = accuracy_score(y_test, y_pred)
|
| 84 |
+
print(f"Accuracy: {accuracy:.4f}")
|
| 85 |
+
|
| 86 |
+
if hasattr(model, 'predict_proba'):
|
| 87 |
+
y_test_binary = (y_test == 'spam').astype(int)
|
| 88 |
+
auc = roc_auc_score(y_test_binary, model.predict_proba(X_test_tfidf)[:,1])
|
| 89 |
+
print(f"AUC-ROC: {auc:.4f}")
|
| 90 |
+
|
| 91 |
+
# -----------------------------
|
| 92 |
+
# 8️⃣ Sauvegarder modèle et TF-IDF
|
| 93 |
+
# -----------------------------
|
| 94 |
+
joblib.dump(model, "spam_model.pkl")
|
| 95 |
+
joblib.dump(tfidf, "tfidf_vectorizer.pkl")
|
| 96 |
+
print("✅ Modèle Logistic Regression et TF-IDF vectorizer sauvegardés avec succès !")
|