File size: 5,191 Bytes
45f58ce
 
 
 
 
 
 
 
09f2bc6
45f58ce
09f2bc6
 
 
 
 
 
45f58ce
8c1aeef
45f58ce
 
 
 
 
 
 
 
09f2bc6
 
 
 
 
 
 
 
 
 
 
 
45f58ce
09f2bc6
45f58ce
 
09f2bc6
 
 
 
 
 
 
 
45f58ce
 
 
 
 
 
 
09f2bc6
 
 
 
 
 
 
 
 
45f58ce
 
 
 
 
 
09f2bc6
 
 
 
 
 
 
 
 
 
45f58ce
 
 
 
09f2bc6
45f58ce
09f2bc6
 
 
 
 
 
 
 
 
 
 
45f58ce
 
 
 
 
09f2bc6
45f58ce
 
09f2bc6
45f58ce
 
 
09f2bc6
 
45f58ce
 
 
09f2bc6
45f58ce
 
 
09f2bc6
 
45f58ce
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
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}")