File size: 2,515 Bytes
a677f92 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
import joblib
import os # تم إضافة هذه المكتبة لفحص الملفات
# اسم ملف البيانات الذي سيبحث عنه الكود في نفس المجلد
DATA_FILE = "clickbait_data.csv"
def train_model():
"""
الدالة الرئيسية لتدريب النموذج وحفظه
"""
print("Starting model training...")
# 1. تحميل البيانات
# التأكد من وجود الملف في نفس المجلد قبل محاولة قراءته
if not os.path.exists(DATA_FILE):
print(f"Error: '{DATA_FILE}' not found in the current directory.")
print("Please make sure the dataset is present before running the training.")
print("You can download it from Kaggle: https://www.kaggle.com/datasets/amananandrai/clickbait-dataset")
exit()
try:
df = pd.read_csv(DATA_FILE)
except Exception as e:
print(f"Error reading {DATA_FILE}: {e}")
exit()
print(f"Dataset loaded: {len(df)} headlines.")
# 2. تحديد المدخلات والمخرجات
X = df['headline']
y = df['clickbait']
# 3. تقسيم البيانات
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 4. بناء "الخط" (Pipeline)
# هذا يدمج خطوتين: تحويل النص لأرقام (TfidfVectorizer) والتصنيف (LogisticRegression)
model_pipeline = Pipeline([
('vectorizer', TfidfVectorizer(max_features=5000)), # نأخذ أهم 5000 كلمة
('classifier', LogisticRegression(max_iter=1000))
])
# 5. التدريب
print("Training the model... (This may take a minute)")
model_pipeline.fit(X_train, y_train)
# 6. التقييم
accuracy = model_pipeline.score(X_test, y_test)
print(f"Training complete. Model accuracy: {accuracy * 100:.2f}%")
# 7. حفظ النموذج
joblib.dump(model_pipeline, "clickbait_model.pkl")
print("Model saved successfully as 'clickbait_model.pkl'")
# --- تشغيل الكود ---
# هذا السطر يضمن أن الكود سيعمل فقط عند تشغيل الملف مباشرة
if __name__ == "__main__":
train_model() |