chosunilbo-analysis / scripts /02c_train_fasttext_yearly.py
ddokbaro's picture
Create 02c_train_fasttext_yearly.py
97d471b verified
import os
import json
import time
import multiprocessing
import tempfile
from tqdm import tqdm
import fasttext
# ----------------------------------------
# 1. 설정
# ----------------------------------------
# 전처리된 데이터 파일 경로
input_file_path = '/chosun_pos_tagged_parallel.jsonl'
# 연도별 모델 저장 디렉토리
output_dir = '/koselleck_analysis_results'
model_dir = os.path.join(output_dir, 'fasttext_models_yearly')
os.makedirs(model_dir, exist_ok=True)
# fastText 모델 학습 파라미터
VECTOR_SIZE = 100
WINDOW = 5
MIN_COUNT = 5
MODEL_TYPE = 'skipgram'
MINIMUM_DOCS_THRESHOLD = 100
NUM_PROCESSES = max(1, multiprocessing.cpu_count() - 1)
# ----------------------------------------
# 2. 병렬 처리를 위한 작업 함수
# ----------------------------------------
def train_model_for_year(args):
"""단일 연도 fastText 모델 학습을 위한 작업 함수 (독립 작업자 모델)"""
year, input_path, model_dir_path = args
model_path = os.path.join(model_dir_path, f'fasttext_{year}.bin')
if os.path.exists(model_path):
return year, "skipped_existing"
doc_count = 0
temp_filename = ''
try:
with tempfile.NamedTemporaryFile(mode='w+', delete=False, encoding='utf-8') as temp_f:
temp_filename = temp_f.name
with open(input_path, 'r', encoding='utf-8') as f_in:
for line in f_in:
record = json.loads(line)
if record.get('type') == 'article' and record.get('year') == year:
nouns = [word for word, pos in record['pos_tagged_body'] if pos == 'Noun']
if nouns:
temp_f.write(" ".join(nouns) + "\n")
doc_count += 1
if doc_count < MINIMUM_DOCS_THRESHOLD:
return year, "skipped_insufficient_data"
model = fasttext.train_unsupervised(
temp_filename, model=MODEL_TYPE, dim=VECTOR_SIZE, ws=WINDOW,
minCount=MIN_COUNT, thread=4
)
model.save_model(model_path)
return year, "success"
except Exception as e:
return year, f"error: {e}"
finally:
if temp_filename and os.path.exists(temp_filename):
os.remove(temp_filename)
# ----------------------------------------
# 3. 메인 실행 로직
# ----------------------------------------
if __name__ == "__main__":
print("--- 연도별 fastText 모델 병렬 학습 시작 ---")
print("\n1. 처리할 연도 목록을 추출합니다.")
try:
years_to_process = set()
with open(input_file_path, 'r', encoding='utf-8') as f:
for line in tqdm(f, desc="처리 대상 연도 스캔"):
record = json.loads(line)
if record.get('type') == 'article' and record.get('year'):
years_to_process.add(record.get('year'))
tasks = [(year, input_file_path, model_dir) for year in sorted(list(years_to_process))]
print(f"총 {len(tasks)}개의 연도에 대한 작업을 생성했습니다.")
except FileNotFoundError:
print(f"오류: '{input_file_path}'를 찾을 수 없습니다.")
exit()
print(f"\n2. 총 {NUM_PROCESSES}개의 프로세스로 병렬 처리를 시작합니다.")
start_time = time.time()
with multiprocessing.Pool(processes=NUM_PROCESSES) as pool:
results = list(tqdm(pool.imap_unordered(train_model_for_year, tasks), total=len(tasks), desc="전체 연도 모델 학습"))
end_time = time.time()
print(f"\n> 병렬 학습 완료 (총 소요 시간: {end_time - start_time:.2f}초)")
success_count = sum(1 for res in results if res[1] == "success")
skipped_existing_count = sum(1 for res in results if res[1] == "skipped_existing")
skipped_data_count = sum(1 for res in results if res[1] == "skipped_insufficient_data")
error_count = sum(1 for res in results if "error" in res[1])
print("\n--- 최종 결과 요약 ---")
print(f" - 신규 학습 성공: {success_count} 개 연도")
print(f" - 기존 모델 스킵: {skipped_existing_count} 개 연도")
print(f" - 데이터 부족으로 건너뜀: {skipped_data_count} 개 연도")
print(f" - 오류 발생: {error_count} 개 연도")
print(f"> 연도별 모델은 다음 경로에 저장되었습니다: {model_dir}")