train_model.py aktualisiert

This commit is contained in:
2025-09-24 14:11:12 +00:00
parent 673fe18347
commit 2b2d25c111

View File

@@ -10,13 +10,22 @@ from thefuzz import fuzz
from collections import Counter from collections import Counter
import logging import logging
import sys import sys
import os
# Importiere deine bestehenden Helfer # Importiere deine bestehenden Helfer
from google_sheet_handler import GoogleSheetHandler from google_sheet_handler import GoogleSheetHandler
from helpers import normalize_company_name from helpers import normalize_company_name
# Logging Setup # --- Detailliertes Logging Setup ---
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Wir stellen sicher, dass wir alles sehen
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)-8s - %(message)s',
handlers=[
logging.StreamHandler(sys.stdout) # Gibt alles in der Konsole aus
]
)
log = logging.getLogger()
# --- Konfiguration --- # --- Konfiguration ---
GOLD_STANDARD_FILE = 'erweitertes_matching.csv' GOLD_STANDARD_FILE = 'erweitertes_matching.csv'
@@ -25,10 +34,8 @@ MODEL_OUTPUT_FILE = 'xgb_model.json'
TERM_WEIGHTS_OUTPUT_FILE = 'term_weights.joblib' TERM_WEIGHTS_OUTPUT_FILE = 'term_weights.joblib'
CRM_PREDICTION_FILE = 'crm_for_prediction.pkl' CRM_PREDICTION_FILE = 'crm_for_prediction.pkl'
# Passe diese Spaltennamen exakt an deine CSV-Datei an!
BEST_MATCH_COL = 'Best Match Option' BEST_MATCH_COL = 'Best Match Option'
# Das Skript findet automatisch alle Spalten, die mit 'V' beginnen und '_Match_Suggestion' enden SUGGESTION_COLS = ['V2_Match_Suggestion', 'V3_Match_Suggestion', 'V4_Match_Suggestion']
SUGGESTION_COLS_PREFIX = 'V'
# --- Stop-/City-Tokens --- # --- Stop-/City-Tokens ---
STOP_TOKENS_BASE = { STOP_TOKENS_BASE = {
@@ -39,7 +46,6 @@ STOP_TOKENS_BASE = {
CITY_TOKENS = set() CITY_TOKENS = set()
# --- Hilfsfunktionen --- # --- Hilfsfunktionen ---
# ... (alle Hilfsfunktionen wie _tokenize, clean_name_for_scoring etc. bleiben unverändert)
def _tokenize(s: str): def _tokenize(s: str):
if not s: return [] if not s: return []
return re.split(r"[^a-z0-9äöüß]+", str(s).lower()) return re.split(r"[^a-z0-9äöüß]+", str(s).lower())
@@ -92,39 +98,49 @@ def create_features(mrec: dict, crec: dict, term_weights: dict):
# --- Haupt-Trainingsskript --- # --- Haupt-Trainingsskript ---
if __name__ == "__main__": if __name__ == "__main__":
logging.info("Starte Trainingsprozess für Duplikats-Checker v5.0") log.info("Starte Trainingsprozess für Duplikats-Checker v5.0")
try: try:
log.info(f"Versuche, Gold-Standard-Datei zu laden: '{GOLD_STANDARD_FILE}'")
if not os.path.exists(GOLD_STANDARD_FILE):
log.critical(f"FEHLER: Die Datei '{GOLD_STANDARD_FILE}' wurde im aktuellen Verzeichnis nicht gefunden.")
sys.exit(1)
gold_df = pd.read_csv(GOLD_STANDARD_FILE, sep=';', encoding='utf-8') gold_df = pd.read_csv(GOLD_STANDARD_FILE, sep=';', encoding='utf-8')
logging.info(f"{len(gold_df)} Zeilen aus Gold-Standard-Datei '{GOLD_STANDARD_FILE}' geladen.") log.info(f"{len(gold_df)} Zeilen aus '{GOLD_STANDARD_FILE}' geladen.")
logging.info("Verbinde mit Google Sheets, um CRM-Daten zu laden...") log.info("Verbinde mit Google Sheets, um CRM-Daten zu laden...")
sheet_handler = GoogleSheetHandler() sheet_handler = GoogleSheetHandler()
crm_df = sheet_handler.get_sheet_as_dataframe(CRM_SHEET_NAME) crm_df = sheet_handler.get_sheet_as_dataframe(CRM_SHEET_NAME)
logging.info(f"{len(crm_df)} CRM Accounts aus Google Sheets geladen.") log.info(f"{len(crm_df)} CRM Accounts aus Google Sheets geladen.")
except Exception as e: except Exception as e:
logging.critical(f"Fehler beim Laden der Daten: {e}") log.critical(f"Fehler beim Laden der Daten: {e}")
sys.exit(1) sys.exit(1)
log.info("Entferne Duplikate aus CRM-Daten für das Training...")
crm_df.drop_duplicates(subset=['CRM Name'], keep='first', inplace=True) crm_df.drop_duplicates(subset=['CRM Name'], keep='first', inplace=True)
logging.info(f"CRM-Daten auf {len(crm_df)} eindeutige Firmennamen reduziert.") log.info(f"CRM-Daten auf {len(crm_df)} eindeutige Firmennamen reduziert.")
log.info("Normalisiere Firmennamen...")
crm_df['normalized_name'] = crm_df['CRM Name'].astype(str).apply(normalize_company_name) crm_df['normalized_name'] = crm_df['CRM Name'].astype(str).apply(normalize_company_name)
gold_df['normalized_CRM Name'] = gold_df['CRM Name'].astype(str).apply(normalize_company_name) gold_df['normalized_CRM Name'] = gold_df['CRM Name'].astype(str).apply(normalize_company_name)
log.info("Berechne Wortgewichte (TF-IDF)...")
term_weights = {token: math.log(len(crm_df) / (count + 1)) for token, count in Counter(t for n in crm_df['normalized_name'] for t in set(clean_name_for_scoring(n)[1])).items()} term_weights = {token: math.log(len(crm_df) / (count + 1)) for token, count in Counter(t for n in crm_df['normalized_name'] for t in set(clean_name_for_scoring(n)[1])).items()}
logging.info(f"{len(term_weights)} Wortgewichte berechnet.") log.info(f"{len(term_weights)} Wortgewichte berechnet.")
logging.info("Erstelle Features für den Trainingsdatensatz...") log.info("Erstelle Features für den Trainingsdatensatz...")
features_list = [] features_list = []
labels = [] labels = []
crm_lookup = crm_df.set_index('CRM Name').to_dict('index') crm_lookup = crm_df.set_index('CRM Name').to_dict('index')
suggestion_cols_found = [col for col in gold_df.columns if col.startswith(SUGGESTION_COLS_PREFIX) and '_Match_Suggestion' in col] # Finde die Spalten mit den alten Vorschlägen dynamisch
logging.info(f"Gefundene Spalten mit alten Vorschlägen: {suggestion_cols_found}") suggestion_cols_found = [col for col in gold_df.columns if col in SUGGESTION_COLS]
if not suggestion_cols_found:
log.warning(f"Keine Spalten für alte Vorschläge in der CSV gefunden (gesucht: {SUGGESTION_COLS}). Training erfolgt nur mit positiven Beispielen.")
for _, row in gold_df.iterrows(): for index, row in gold_df.iterrows():
mrec = row.to_dict() mrec = row.to_dict()
best_match_name = row.get(BEST_MATCH_COL) best_match_name = row.get(BEST_MATCH_COL)
@@ -147,34 +163,41 @@ if __name__ == "__main__":
y = np.array(labels) y = np.array(labels)
if len(X) == 0: if len(X) == 0:
logging.critical("Keine gültigen Trainingsdaten gefunden.") log.critical("FEHLER: Keine gültigen Trainingsdaten-Paare konnten erstellt werden. Überprüfe die Spaltennamen in der CSV und im Skript.")
sys.exit(1) sys.exit(1)
logging.info(f"Trainingsdatensatz erstellt mit {X.shape[0]} Beispielen und {X.shape[1]} Features.") log.info(f"Trainingsdatensatz erfolgreich erstellt mit {X.shape[0]} Beispielen und {X.shape[1]} Features.")
logging.info(f"Verteilung der Klassen: {Counter(y)}") log.info(f"Verteilung der Klassen (0=Falsch, 1=Korrekt): {Counter(y)}")
logging.info("Trainiere das XGBoost-Modell...") log.info("Trainiere das XGBoost-Modell...")
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
scale_pos_weight = (len(y_train) - sum(y_train)) / sum(y_train) if sum(y_train) > 0 else 1 scale_pos_weight = (len(y_train) - sum(y_train)) / sum(y_train) if sum(y_train) > 0 else 1
model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss', scale_pos_weight=scale_pos_weight) model = xgb.XGBClassifier(use_label_encoder=False, eval_metric='logloss', scale_pos_weight=scale_pos_weight)
model.fit(X_train, y_train) model.fit(X_train, y_train)
logging.info("Modell erfolgreich trainiert.") log.info("Modell erfolgreich trainiert.")
log.info("Validiere Modell auf Testdaten...")
y_pred = model.predict(X_test) y_pred = model.predict(X_test)
accuracy = accuracy_score(y_test, y_pred) accuracy = accuracy_score(y_test, y_pred)
logging.info(f"\n--- Validierungsergebnis ---") log.info(f"\n--- Validierungsergebnis ---")
logging.info(f"Genauigkeit auf Testdaten: {accuracy:.2%}") log.info(f"Genauigkeit auf Testdaten: {accuracy:.2%}")
logging.info("Detaillierter Report:") log.info("Detaillierter Report:")
logging.info("\n" + classification_report(y_test, y_pred, zero_division=0)) log.info("\n" + classification_report(y_test, y_pred, zero_division=0))
try: try:
log.info(f"Speichere Modell in '{MODEL_OUTPUT_FILE}'...")
model.save_model(MODEL_OUTPUT_FILE) model.save_model(MODEL_OUTPUT_FILE)
logging.info(f"Modell in '{MODEL_OUTPUT_FILE}' erfolgreich gespeichert.") log.info("...erfolgreich.")
log.info(f"Speichere Wortgewichte in '{TERM_WEIGHTS_OUTPUT_FILE}'...")
joblib.dump(term_weights, TERM_WEIGHTS_OUTPUT_FILE) joblib.dump(term_weights, TERM_WEIGHTS_OUTPUT_FILE)
logging.info(f"Wortgewichte in '{TERM_WEIGHTS_OUTPUT_FILE}' erfolgreich gespeichert.") log.info("...erfolgreich.")
log.info(f"Speichere CRM-Daten in '{CRM_PREDICTION_FILE}'...")
crm_df.to_pickle(CRM_PREDICTION_FILE) crm_df.to_pickle(CRM_PREDICTION_FILE)
logging.info(f"CRM-Daten in '{CRM_PREDICTION_FILE}' erfolgreich gespeichert.") log.info("...erfolgreich.")
log.info("Alle Dateien wurden erfolgreich erstellt.")
except Exception as e: except Exception as e:
logging.critical(f"FEHLER BEIM SPEICHERN DER DATEIEN: {e}") log.critical(f"FEHLER BEIM SPEICHERN DER DATEIEN: {e}")