chosunilbo-analysis / scripts /03b_analyze_semantic_axis_word2vec.py
ddokbaro's picture
Update scripts/03b_analyze_semantic_axis_word2vec.py
8c1aeef verified
import pandas as pd
import os
import json
from tqdm import tqdm
import numpy as np
from huggingface_hub import hf_hub_download, list_repo_files
# ----------------------------------------
# 1. 분석 설정 (이곳을 수정하여 분석 대상을 변경할 수 있습니다)
# ----------------------------------------
# 분석할 모델 타입을 선택하세요: 'word2vec' 또는 'fasttext'
MODEL_TYPE = 'word2vec'
# 분석할 시간 단위를 선택하세요: 'yearly' 또는 'decade'
TIME_UNIT = 'yearly'
# 결과 저장 디렉토리
output_dir = '/koselleck_analysis_results'
# Hugging Face 모델 저장소 ID
MODEL_REPO_ID = "ddokbaro/chosunilbo-LMs"
# 의미 축 정의를 위한 핵심어
PAST_SEEDS = ['과거', '역사', '어제', '전통', '기억']
FUTURE_SEEDS = ['미래', '계획', '내일', '발전', '희망']
# ----------------------------------------
# 2. 라이브러리 동적 임포트
# ----------------------------------------
# 설정에 따라 필요한 라이브러리만 불러옵니다.
if MODEL_TYPE == 'word2vec':
from gensim.models import Word2Vec
elif MODEL_TYPE == 'fasttext':
import fasttext
else:
raise ValueError("MODEL_TYPE은 'word2vec' 또는 'fasttext'여야 합니다.")
# ----------------------------------------
# 3. 연도별 의미 축 계산 및 점수 산출
# ----------------------------------------
print(f"1. Hugging Face Hub에서 [{MODEL_TYPE} / {TIME_UNIT}] 모델을 불러와 '의미 방향성 점수'를 계산합니다.")
def get_semantic_axis(model, past_seeds, future_seeds):
"""주어진 모델과 핵심어들로 '과거-미래' 의미 축 벡터를 계산합니다."""
if MODEL_TYPE == 'word2vec':
past_vectors = [model.wv[word] for word in past_seeds if word in model.wv]
future_vectors = [model.wv[word] for word in future_seeds if word in model.wv]
else: # fasttext
past_vectors = [model.get_word_vector(word) for word in past_seeds if word in model.words]
future_vectors = [model.get_word_vector(word) for word in future_seeds if word in model.words]
if not past_vectors or not future_vectors: return None
past_vec = np.mean(past_vectors, axis=0)
future_vec = np.mean(future_vectors, axis=0)
axis = future_vec - past_vec
return axis / np.linalg.norm(axis)
def calculate_orientation_score(model, axis):
"""모델의 전체 어휘집을 사용하여 의미 방향성 점수를 계산합니다."""
if MODEL_TYPE == 'word2vec':
all_vectors = model.wv.vectors
if all_vectors is None or len(all_vectors) == 0: return 0
else: # fasttext
all_words = model.words
if not all_words: return 0
all_vectors = np.array([model.get_word_vector(word) for word in all_words])
projections = np.dot(all_vectors, axis)
return np.mean(projections)
yearly_scores = []
try:
path_prefix = f"{MODEL_TYPE}/{TIME_UNIT}/"
print(f"'{MODEL_REPO_ID}' 저장소의 '{path_prefix}' 경로에서 모델 목록을 가져옵니다...")
model_files = [f for f in list_repo_files(MODEL_REPO_ID) if f.startswith(path_prefix)]
if TIME_UNIT == 'yearly':
units_to_process = sorted([int(f.split('_')[-1].split('.')[0]) for f in model_files])
else: # decade
units_to_process = sorted([int(f.split('_')[-1].split('.')[0]) for f in model_files])
print(f"총 {len(units_to_process)}개의 모델을 대상으로 분석을 시작합니다.")
except Exception as e:
print(f"Hugging Face Hub에서 파일 목록을 가져오는 데 실패했습니다: {e}")
exit()
for unit in tqdm(units_to_process, desc=f"{TIME_UNIT}별 점수 계산"):
try:
if MODEL_TYPE == 'word2vec':
filename = f"{path_prefix}word2vec_{unit}.model"
else: # fasttext
filename = f"{path_prefix}fasttext_{unit}.bin"
model_path = hf_hub_download(repo_id=MODEL_REPO_ID, filename=filename)
if MODEL_TYPE == 'word2vec':
model = Word2Vec.load(model_path)
else: # fasttext
model = fasttext.load_model(model_path)
axis = get_semantic_axis(model, PAST_SEEDS, FUTURE_SEEDS)
if axis is None: continue
score = calculate_orientation_score(model, axis)
yearly_scores.append({'unit': unit, 'orientation_score': score})
except Exception as e:
# print(f"{unit} 처리 중 오류 발생: {e}")
continue
score_df = pd.DataFrame(yearly_scores)
score_df.rename(columns={'unit': TIME_UNIT}, inplace=True)
print(f"\n[{TIME_UNIT}별 의미 방향성 점수 (상위 5개)]")
print(score_df.head())
# ----------------------------------------
# 4. 분석 결과 저장
# ----------------------------------------
print("\n2. '의미 방향성 점수'를 파일로 저장합니다.")
os.makedirs(output_dir, exist_ok=True)
output_filename = f"{TIME_UNIT}_semantic_orientation_scores_{MODEL_TYPE}.csv"
score_data_path = os.path.join(output_dir, output_filename)
score_df.to_csv(score_data_path, index=False, encoding='utf-8-sig')
print(f"생성된 결과가 다음 경로에 저장되었습니다: {score_data_path}")