import pandas as pd import os import json from tqdm import tqdm import fasttext import multiprocessing import tempfile # ---------------------------------------- # 1. 설정 # ---------------------------------------- # 전처리된 데이터 파일 경로 input_file_path = '/chosun_pos_tagged_parallel.jsonl' # 10년 단위 모델 저장 디렉토리 output_dir = '/koselleck_analysis_results' model_dir = os.path.join(output_dir, 'fasttext_models_decade') os.makedirs(model_dir, exist_ok=True) # fastText 모델 학습 파라미터 VECTOR_SIZE = 100 WINDOW = 5 MIN_COUNT = 5 MODEL_TYPE = 'skipgram' WORKERS = max(1, multiprocessing.cpu_count() - 1) # ---------------------------------------- # 2. 데이터 로드 및 그룹화 # ---------------------------------------- print("--- 10년 단위 fastText 모델 학습 시작 ---") print("\n1. 전처리된 데이터를 로드하여 10년 단위로 그룹화합니다.") try: df = pd.read_json(input_file_path, lines=True) df = df[df['type'] == 'article'].copy() df['decade'] = (df['year'] // 10) * 10 print("파일 로드 및 그룹화 완료.") except FileNotFoundError: print(f"오류: '{input_file_path}'를 찾을 수 없습니다.") exit() # ---------------------------------------- # 3. 10년 단위 모델 학습 # ---------------------------------------- print(f"\n2. 10년 단위 fastText 모델을 순차적으로 학습합니다.") for decade, group in tqdm(df.groupby('decade'), desc="10년 단위 모델 학습"): model_path = os.path.join(model_dir, f'fasttext_{decade}.bin') if os.path.exists(model_path): print(f"{decade}년대 모델이 이미 존재하여 건너뜁니다.") continue temp_filename = '' try: with tempfile.NamedTemporaryFile(mode='w+', delete=False, encoding='utf-8') as temp_f: temp_filename = temp_f.name for doc in group['pos_tagged_body']: nouns = [word for word, pos in doc if pos == 'Noun'] if nouns: temp_f.write(" ".join(nouns) + "\n") model = fasttext.train_unsupervised( temp_filename, model=MODEL_TYPE, dim=VECTOR_SIZE, ws=WINDOW, minCount=MIN_COUNT, thread=WORKERS ) model.save_model(model_path) print(f"{decade}년대 모델 학습 및 저장 완료.") except Exception as e: print(f"{decade}년대 모델 학습 중 오류 발생: {e}") finally: if temp_filename and os.path.exists(temp_filename): os.remove(temp_filename) print(f"\n> 모든 10년 단위 모델 학습이 완료되었습니다. 결과 저장 경로: {model_dir}")