ddokbaro commited on
Commit
7f27d41
·
verified ·
1 Parent(s): e022aed

Create 02a_train_word2vec_yearly.py

Browse files
scripts/02a_train_word2vec_yearly.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import time
4
+ import multiprocessing
5
+ from tqdm import tqdm
6
+ from gensim.models import Word2Vec
7
+
8
+ # ----------------------------------------
9
+ # 1. 설정
10
+ # ----------------------------------------
11
+ # 전처리된 데이터 파일 경로
12
+ input_file_path = '/chosun_pos_tagged_parallel.jsonl'
13
+
14
+ # 연도별 모델 저장 디렉토리
15
+ output_dir = '/koselleck_analysis_results'
16
+ model_dir = os.path.join(output_dir, 'word2vec_models_yearly')
17
+ os.makedirs(model_dir, exist_ok=True)
18
+
19
+ # Word2Vec 모델 학습 파라미터
20
+ VECTOR_SIZE = 100
21
+ WINDOW = 5
22
+ MIN_COUNT = 5
23
+ MINIMUM_DOCS_THRESHOLD = 100
24
+ NUM_PROCESSES = max(1, multiprocessing.cpu_count() - 1)
25
+
26
+ # ----------------------------------------
27
+ # 2. 병렬 처리를 위한 작업 함수
28
+ # ----------------------------------------
29
+ def train_model_for_year(args):
30
+ """단일 연도 Word2Vec 모델 학습을 위한 작업 함수 (독립 작업자 모델)"""
31
+ year, input_path, model_dir_path = args
32
+ model_path = os.path.join(model_dir_path, f'word2vec_{year}.model')
33
+
34
+ if os.path.exists(model_path):
35
+ return year, "skipped_existing"
36
+
37
+ sentences = []
38
+ doc_count = 0
39
+ with open(input_path, 'r', encoding='utf-8') as f:
40
+ for line in f:
41
+ record = json.loads(line)
42
+ if record.get('type') == 'article' and record.get('year') == year:
43
+ sentences.append([word for word, pos in record['pos_tagged_body'] if pos == 'Noun'])
44
+ doc_count += 1
45
+
46
+ if doc_count < MINIMUM_DOCS_THRESHOLD:
47
+ return year, "skipped_insufficient_data"
48
+
49
+ try:
50
+ model = Word2Vec(sentences, vector_size=VECTOR_SIZE, window=WINDOW, min_count=MIN_COUNT, workers=4)
51
+ model.save(model_path)
52
+ return year, "success"
53
+ except Exception as e:
54
+ return year, f"error: {e}"
55
+
56
+ # ----------------------------------------
57
+ # 3. 메인 실행 로직
58
+ # ----------------------------------------
59
+ if __name__ == "__main__":
60
+ print("--- 연도별 Word2Vec 모델 병렬 학습 시작 ---")
61
+
62
+ print("\n1. 처리할 연도 목록을 추출합니다.")
63
+ try:
64
+ years_to_process = set()
65
+ with open(input_file_path, 'r', encoding='utf-8') as f:
66
+ for line in tqdm(f, desc="처리 대상 연도 스캔"):
67
+ record = json.loads(line)
68
+ if record.get('type') == 'article' and record.get('year'):
69
+ years_to_process.add(record.get('year'))
70
+
71
+ tasks = [(year, input_file_path, model_dir) for year in sorted(list(years_to_process))]
72
+ print(f"총 {len(tasks)}개의 연도에 대한 작업을 생성했습니다.")
73
+ except FileNotFoundError:
74
+ print(f"오류: '{input_file_path}'를 찾을 수 없습니다.")
75
+ exit()
76
+
77
+ print(f"\n2. 총 {NUM_PROCESSES}개의 프로세스로 병렬 처리를 시작합니다.")
78
+ start_time = time.time()
79
+
80
+ with multiprocessing.Pool(processes=NUM_PROCESSES) as pool:
81
+ results = list(tqdm(pool.imap_unordered(train_model_for_year, tasks), total=len(tasks), desc="전체 연도 모델 학습"))
82
+
83
+ end_time = time.time()
84
+ print(f"\n> 병렬 학습 완료 (총 소요 시간: {end_time - start_time:.2f}초)")
85
+
86
+ success_count = sum(1 for res in results if res[1] == "success")
87
+ skipped_existing_count = sum(1 for res in results if res[1] == "skipped_existing")
88
+ skipped_data_count = sum(1 for res in results if res[1] == "skipped_insufficient_data")
89
+ error_count = sum(1 for res in results if "error" in res[1])
90
+
91
+ print("\n--- 최종 결과 요약 ---")
92
+ print(f" - 신규 학습 성공: {success_count} 개 연도")
93
+ print(f" - 기존 모델 스킵: {skipped_existing_count} 개 연도")
94
+ print(f" - 데이터 부족으로 건너뜀: {skipped_data_count} 개 연도")
95
+ print(f" - 오류 발생: {error_count} 개 연도")
96
+ print(f"> 연도별 모델은 다음 경로에 저장되었습니다: {model_dir}")