train_model.py aktualisiert
This commit is contained in:
@@ -10,13 +10,22 @@ from thefuzz import fuzz
|
||||
from collections import Counter
|
||||
import logging
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Importiere deine bestehenden Helfer
|
||||
from google_sheet_handler import GoogleSheetHandler
|
||||
from helpers import normalize_company_name
|
||||
|
||||
# Logging Setup
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
|
||||
# --- Detailliertes Logging Setup ---
|
||||
# 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 ---
|
||||
GOLD_STANDARD_FILE = 'erweitertes_matching.csv'
|
||||
@@ -25,10 +34,8 @@ MODEL_OUTPUT_FILE = 'xgb_model.json'
|
||||
TERM_WEIGHTS_OUTPUT_FILE = 'term_weights.joblib'
|
||||
CRM_PREDICTION_FILE = 'crm_for_prediction.pkl'
|
||||
|
||||
# Passe diese Spaltennamen exakt an deine CSV-Datei an!
|
||||
BEST_MATCH_COL = 'Best Match Option'
|
||||
# Das Skript findet automatisch alle Spalten, die mit 'V' beginnen und '_Match_Suggestion' enden
|
||||
SUGGESTION_COLS_PREFIX = 'V'
|
||||
SUGGESTION_COLS = ['V2_Match_Suggestion', 'V3_Match_Suggestion', 'V4_Match_Suggestion']
|
||||
|
||||
# --- Stop-/City-Tokens ---
|
||||
STOP_TOKENS_BASE = {
|
||||
@@ -39,7 +46,6 @@ STOP_TOKENS_BASE = {
|
||||
CITY_TOKENS = set()
|
||||
|
||||
# --- Hilfsfunktionen ---
|
||||
# ... (alle Hilfsfunktionen wie _tokenize, clean_name_for_scoring etc. bleiben unverändert)
|
||||
def _tokenize(s: str):
|
||||
if not s: return []
|
||||
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 ---
|
||||
if __name__ == "__main__":
|
||||
logging.info("Starte Trainingsprozess für Duplikats-Checker v5.0")
|
||||
log.info("Starte Trainingsprozess für Duplikats-Checker v5.0")
|
||||
|
||||
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')
|
||||
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()
|
||||
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:
|
||||
logging.critical(f"Fehler beim Laden der Daten: {e}")
|
||||
log.critical(f"Fehler beim Laden der Daten: {e}")
|
||||
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)
|
||||
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)
|
||||
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()}
|
||||
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 = []
|
||||
labels = []
|
||||
|
||||
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]
|
||||
logging.info(f"Gefundene Spalten mit alten Vorschlägen: {suggestion_cols_found}")
|
||||
# Finde die Spalten mit den alten Vorschlägen dynamisch
|
||||
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()
|
||||
best_match_name = row.get(BEST_MATCH_COL)
|
||||
|
||||
@@ -147,34 +163,41 @@ if __name__ == "__main__":
|
||||
y = np.array(labels)
|
||||
|
||||
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)
|
||||
|
||||
logging.info(f"Trainingsdatensatz erstellt mit {X.shape[0]} Beispielen und {X.shape[1]} Features.")
|
||||
logging.info(f"Verteilung der Klassen: {Counter(y)}")
|
||||
log.info(f"Trainingsdatensatz erfolgreich erstellt mit {X.shape[0]} Beispielen und {X.shape[1]} Features.")
|
||||
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)
|
||||
|
||||
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.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)
|
||||
accuracy = accuracy_score(y_test, y_pred)
|
||||
logging.info(f"\n--- Validierungsergebnis ---")
|
||||
logging.info(f"Genauigkeit auf Testdaten: {accuracy:.2%}")
|
||||
logging.info("Detaillierter Report:")
|
||||
logging.info("\n" + classification_report(y_test, y_pred, zero_division=0))
|
||||
log.info(f"\n--- Validierungsergebnis ---")
|
||||
log.info(f"Genauigkeit auf Testdaten: {accuracy:.2%}")
|
||||
log.info("Detaillierter Report:")
|
||||
log.info("\n" + classification_report(y_test, y_pred, zero_division=0))
|
||||
|
||||
try:
|
||||
log.info(f"Speichere Modell in '{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)
|
||||
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)
|
||||
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:
|
||||
logging.critical(f"FEHLER BEIM SPEICHERN DER DATEIEN: {e}")
|
||||
log.critical(f"FEHLER BEIM SPEICHERN DER DATEIEN: {e}")
|
||||
Reference in New Issue
Block a user