|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
MODEL_TYPE = 'word2vec' |
|
|
|
|
|
|
|
|
TIME_UNIT = 'yearly' |
|
|
|
|
|
|
|
|
output_dir = '/koselleck_analysis_results' |
|
|
|
|
|
MODEL_REPO_ID = "ddokbaro/chosunilbo-LMs" |
|
|
|
|
|
|
|
|
PAST_SEEDS = ['과거', '역사', '어제', '전통', '기억'] |
|
|
FUTURE_SEEDS = ['미래', '계획', '내일', '발전', '희망'] |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if MODEL_TYPE == 'word2vec': |
|
|
from gensim.models import Word2Vec |
|
|
elif MODEL_TYPE == 'fasttext': |
|
|
import fasttext |
|
|
else: |
|
|
raise ValueError("MODEL_TYPE은 'word2vec' 또는 'fasttext'여야 합니다.") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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: |
|
|
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: |
|
|
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: |
|
|
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: |
|
|
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: |
|
|
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: |
|
|
|
|
|
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()) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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}") |
|
|
|