chosunilbo-analysis / scripts /02a_train_word2vec_yearly.py
ddokbaro's picture
Create 02a_train_word2vec_yearly.py
7f27d41 verified
import os
import json
import time
import multiprocessing
from tqdm import tqdm
from gensim.models import Word2Vec
# ----------------------------------------
# 1. 설정
# ----------------------------------------
# 전처리된 데이터 파일 경로
input_file_path = '/chosun_pos_tagged_parallel.jsonl'
# 연도별 모델 저장 디렉토리
output_dir = '/koselleck_analysis_results'
model_dir = os.path.join(output_dir, 'word2vec_models_yearly')
os.makedirs(model_dir, exist_ok=True)
# Word2Vec 모델 학습 파라미터
VECTOR_SIZE = 100
WINDOW = 5
MIN_COUNT = 5
MINIMUM_DOCS_THRESHOLD = 100
NUM_PROCESSES = max(1, multiprocessing.cpu_count() - 1)
# ----------------------------------------
# 2. 병렬 처리를 위한 작업 함수
# ----------------------------------------
def train_model_for_year(args):
"""단일 연도 Word2Vec 모델 학습을 위한 작업 함수 (독립 작업자 모델)"""
year, input_path, model_dir_path = args
model_path = os.path.join(model_dir_path, f'word2vec_{year}.model')
if os.path.exists(model_path):
return year, "skipped_existing"
sentences = []
doc_count = 0
with open(input_path, 'r', encoding='utf-8') as f:
for line in f:
record = json.loads(line)
if record.get('type') == 'article' and record.get('year') == year:
sentences.append([word for word, pos in record['pos_tagged_body'] if pos == 'Noun'])
doc_count += 1
if doc_count < MINIMUM_DOCS_THRESHOLD:
return year, "skipped_insufficient_data"
try:
model = Word2Vec(sentences, vector_size=VECTOR_SIZE, window=WINDOW, min_count=MIN_COUNT, workers=4)
model.save(model_path)
return year, "success"
except Exception as e:
return year, f"error: {e}"
# ----------------------------------------
# 3. 메인 실행 로직
# ----------------------------------------
if __name__ == "__main__":
print("--- 연도별 Word2Vec 모델 병렬 학습 시작 ---")
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}")