chosunilbo-analysis / scripts /02b_train_word2vec_decade.py
ddokbaro's picture
Create 02b_train_word2vec_decade.py
cc9afbf verified
import pandas as pd
import os
import json
from tqdm import tqdm
from gensim.models import Word2Vec
import multiprocessing
# ----------------------------------------
# 1. 설정
# ----------------------------------------
# 전처리된 데이터 파일 경로
input_file_path = '/chosun_pos_tagged_parallel.jsonl'
# 10년 단위 모델 저장 디렉토리
output_dir = '/koselleck_analysis_results'
model_dir = os.path.join(output_dir, 'word2vec_models_decade')
os.makedirs(model_dir, exist_ok=True)
# Word2Vec 모델 학습 파라미터
VECTOR_SIZE = 100
WINDOW = 5
MIN_COUNT = 5
WORKERS = max(1, multiprocessing.cpu_count() - 1)
# ----------------------------------------
# 2. 데이터 로드 및 그룹화
# ----------------------------------------
print("--- 10년 단위 Word2Vec 모델 학습 시작 ---")
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년 단위 Word2Vec 모델을 순차적으로 학습합니다.")
for decade, group in tqdm(df.groupby('decade'), desc="10년 단위 모델 학습"):
model_path = os.path.join(model_dir, f'word2vec_{decade}.model')
if os.path.exists(model_path):
print(f"{decade}년대 모델이 이미 존재하여 건너뜁니다.")
continue
try:
sentences = [[word for word, pos in doc if pos == 'Noun'] for doc in group['pos_tagged_body']]
model = Word2Vec(sentences, vector_size=VECTOR_SIZE, window=WINDOW, min_count=MIN_COUNT, workers=WORKERS)
model.save(model_path)
print(f"{decade}년대 모델 학습 및 저장 완료.")
except Exception as e:
print(f"{decade}년대 모델 학습 중 오류 발생: {e}")
print(f"\n> 모든 10년 단위 모델 학습이 완료되었습니다. 결과 저장 경로: {model_dir}")