ddokbaro commited on
Commit
d4b52e4
·
verified ·
1 Parent(s): 45f58ce

Create 03c_analyze_semantic_axis_fasttext.py

Browse files
scripts/03c_analyze_semantic_axis_fasttext.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import os
3
+ import json
4
+ from tqdm import tqdm
5
+ import numpy as np
6
+ from huggingface_hub import hf_hub_download, list_repo_files
7
+
8
+ # ----------------------------------------
9
+ # 1. 분석 설정 (이곳을 수정하여 분석 대상을 변경할 수 있습니다)
10
+ # ----------------------------------------
11
+ # 분석할 모델 타입을 선택하세요: 'word2vec' 또는 'fasttext'
12
+ MODEL_TYPE = 'fasttext'
13
+
14
+ # 분석할 시간 단위를 선택하세요: 'yearly' 또는 'decade'
15
+ TIME_UNIT = 'yearly'
16
+
17
+ # 결과 저장 디렉토리
18
+ output_dir = '/home/work/baro/koselleck_analysis_results'
19
+ # Hugging Face 모델 저장소 ID
20
+ MODEL_REPO_ID = "ddokbaro/chosunilbo-LMs"
21
+
22
+ # 의미 축 정의를 위한 핵심어
23
+ PAST_SEEDS = ['과거', '역사', '어제', '전통', '기억']
24
+ FUTURE_SEEDS = ['미래', '계획', '내일', '발전', '희망']
25
+
26
+ # ----------------------------------------
27
+ # 2. 라이브러리 동적 임포트
28
+ # ----------------------------------------
29
+ # 설정에 따라 필요한 라이브러리만 불러옵니다.
30
+ if MODEL_TYPE == 'word2vec':
31
+ from gensim.models import Word2Vec
32
+ elif MODEL_TYPE == 'fasttext':
33
+ import fasttext
34
+ else:
35
+ raise ValueError("MODEL_TYPE은 'word2vec' 또는 'fasttext'여야 합니다.")
36
+
37
+ # ----------------------------------------
38
+ # 3. 연도별 의미 축 계산 및 점수 산출
39
+ # ----------------------------------------
40
+ print(f"1. Hugging Face Hub에서 [{MODEL_TYPE} / {TIME_UNIT}] 모델을 불러와 '의미 방향성 점수'를 계산합니다.")
41
+
42
+ def get_semantic_axis(model, past_seeds, future_seeds):
43
+ """주어진 모델과 핵심어들로 '과거-미래' 의미 축 벡터를 계산합니다."""
44
+ if MODEL_TYPE == 'word2vec':
45
+ past_vectors = [model.wv[word] for word in past_seeds if word in model.wv]
46
+ future_vectors = [model.wv[word] for word in future_seeds if word in model.wv]
47
+ else: # fasttext
48
+ past_vectors = [model.get_word_vector(word) for word in past_seeds if word in model.words]
49
+ future_vectors = [model.get_word_vector(word) for word in future_seeds if word in model.words]
50
+
51
+ if not past_vectors or not future_vectors: return None
52
+ past_vec = np.mean(past_vectors, axis=0)
53
+ future_vec = np.mean(future_vectors, axis=0)
54
+ axis = future_vec - past_vec
55
+ return axis / np.linalg.norm(axis)
56
+
57
+ def calculate_orientation_score(model, axis):
58
+ """모델의 전체 어휘집을 사용하여 의미 방향성 점수를 계산합니다."""
59
+ if MODEL_TYPE == 'word2vec':
60
+ all_vectors = model.wv.vectors
61
+ if all_vectors is None or len(all_vectors) == 0: return 0
62
+ else: # fasttext
63
+ all_words = model.words
64
+ if not all_words: return 0
65
+ all_vectors = np.array([model.get_word_vector(word) for word in all_words])
66
+
67
+ projections = np.dot(all_vectors, axis)
68
+ return np.mean(projections)
69
+
70
+ yearly_scores = []
71
+
72
+ try:
73
+ path_prefix = f"{MODEL_TYPE}/{TIME_UNIT}/"
74
+ print(f"'{MODEL_REPO_ID}' 저장소의 '{path_prefix}' 경로에서 모델 목록을 가져옵니다...")
75
+ model_files = [f for f in list_repo_files(MODEL_REPO_ID) if f.startswith(path_prefix)]
76
+
77
+ if TIME_UNIT == 'yearly':
78
+ units_to_process = sorted([int(f.split('_')[-1].split('.')[0]) for f in model_files])
79
+ else: # decade
80
+ units_to_process = sorted([int(f.split('_')[-1].split('.')[0]) for f in model_files])
81
+
82
+ print(f"총 {len(units_to_process)}개의 모델을 대상으로 분석을 시작합니다.")
83
+ except Exception as e:
84
+ print(f"Hugging Face Hub에서 파일 목록을 가져오는 데 실패했습니다: {e}")
85
+ exit()
86
+
87
+ for unit in tqdm(units_to_process, desc=f"{TIME_UNIT}별 점수 계산"):
88
+ try:
89
+ if MODEL_TYPE == 'word2vec':
90
+ filename = f"{path_prefix}word2vec_{unit}.model"
91
+ else: # fasttext
92
+ filename = f"{path_prefix}fasttext_{unit}.bin"
93
+
94
+ model_path = hf_hub_download(repo_id=MODEL_REPO_ID, filename=filename)
95
+
96
+ if MODEL_TYPE == 'word2vec':
97
+ model = Word2Vec.load(model_path)
98
+ else: # fasttext
99
+ model = fasttext.load_model(model_path)
100
+
101
+ axis = get_semantic_axis(model, PAST_SEEDS, FUTURE_SEEDS)
102
+ if axis is None: continue
103
+
104
+ score = calculate_orientation_score(model, axis)
105
+ yearly_scores.append({'unit': unit, 'orientation_score': score})
106
+
107
+ except Exception as e:
108
+ # print(f"{unit} 처리 중 오류 발생: {e}")
109
+ continue
110
+
111
+ score_df = pd.DataFrame(yearly_scores)
112
+ score_df.rename(columns={'unit': TIME_UNIT}, inplace=True)
113
+ print(f"\n[{TIME_UNIT}별 의미 방향성 점수 (상위 5개)]")
114
+ print(score_df.head())
115
+
116
+ # ----------------------------------------
117
+ # 4. 분석 결과 저장
118
+ # ----------------------------------------
119
+ print("\n2. '의미 방향성 점수'를 파일로 저장합니다.")
120
+ os.makedirs(output_dir, exist_ok=True)
121
+ output_filename = f"{TIME_UNIT}_semantic_orientation_scores_{MODEL_TYPE}.csv"
122
+ score_data_path = os.path.join(output_dir, output_filename)
123
+ score_df.to_csv(score_data_path, index=False, encoding='utf-8-sig')
124
+ print(f"생성된 결과가 다음 경로에 저장되었습니다: {score_data_path}")