일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- bloc
- FastAPI
- 백준
- BFS
- system hacking
- Kaggle
- Computer Architecture
- 파이토치 트랜스포머를 활용한 자연어 처리와 컴퓨터비전 심층학습
- fastapi를 사용한 파이썬 웹 개발
- llm을 활용 단어장 앱 개발일지
- Widget
- C++
- Flutter
- Got
- study book
- Stream
- MDP
- ARM
- rao
- Image Processing
- 영상처리
- MATLAB
- BOF
- PCA
- BAEKJOON
- pytorch
- Dreamhack
- ML
- Algorithm
- DART
- Today
- Total
Bull
[kaggle] Gensim Word2Vec Tutorial - Review하기 본문
[kaggle] Gensim Word2Vec Tutorial - Review하기
Bull_ 2024. 7. 21. 00:52이 글은 친구와 kaggle에 익숙해지기 위해 스터디하는 걸 정리해봤습니다.
목적으로 코드도 중요하지만 데이터를 어떻게 다루고 왜 다루고 전처리는 어떤 방식으로 하는 지 궁금해기 때문에 하나하나 관찰하며 혜안을 얻고자 하는 목적입니다.
Dataset
https://www.kaggle.com/datasets/pierremegret/dialogue-lines-of-the-simpsons
Dialogue Lines of The Simpsons
Dialogues from all 27 seasons
www.kaggle.com
Motivation
작성자가 이 데이터셋을 통해 분석을 하게 된 이유
Supportiv에서 일하기 시작하면서 Gensim의 Word2Vec 구현에 집중하게 되었다. 여러 온라인 튜토리얼을 시도했지만, 결과에 만족하지 못하고 오히려 혼란스러웠다. 특히 모델 훈련 관리와 데이터 준비 단계에서 많은 문제가 있었다. 많은 튜토리얼이 기존의 전처리된 데이터셋을 사용하거나, 데이터 준비 과정을 생략하는 경우가 많아, 전처리가 중요한 Word2Vec 모델의 핵심 단계를 놓치게 만들었다. 이러한 경험을 바탕으로, 데이터 준비 단계부터 자세히 다루는 자신만의 튜토리얼을 작성하게 되었다. 이를 통해 다른 사람들도 비슷한 문제를 겪지 않도록 돕고자 한다.
Purpose
이 튜토리얼은 Gensim 라이브러리의 Word2Vec 패키지를 올바르게 사용하는 것에 초점을 맞추고 있다.
Word2Vec는 2013년 9월과 10월 사이에 구글 연구팀에 의해 두 개의 논문으로 소개되었으며, 연구팀은 C 언어로 구현을 발표했다. 첫 번째 논문 후, Gensim에서 파이썬 구현이 이루어졌다.
Word2Vec의 기본 가정은 비슷한 맥락에서 사용되는 두 단어가 유사한 의미와 벡터 표현을 가진다는 것이다. 예를 들어, "dog", "puppy", "pup"은 "good", "fluffy", "cute"와 같은 유사한 주변 단어들과 함께 자주 사용되므로 유사한 벡터 표현을 공유하게 된다.
이 가정을 통해 Word2Vec는 데이터셋 내 단어들 간의 관계를 발견하고, 유사성을 계산하며, 이러한 단어들의 벡터 표현을 텍스트 분류나 군집화와 같은 다른 응용 프로그램의 입력으로 사용할 수 있다.
Getting Started
environment
python==3.6.3
Libraries used:xlrd==1.1.0
: xlrdspaCy==2.0.12
: spaCygensim==3.4.0
: gensimscikit-learn==0.19.1
: scikit-learnseaborn==0.8
: seaborn
import re # For preprocessing
import pandas as pd # For data handling
from time import time # To time our operations
from collections import defaultdict # For word frequency
import spacy # For preprocessing
import logging # Setting up the loggings to monitor gensim
logging.basicConfig(format="%(levelname)s - %(asctime)s: %(message)s", datefmt= '%H:%M:%S', level=logging.INFO)
Preprocessing
raw_character_text
: 누가 말했는 지 말한 사람spoken_words
: 대사 내용
우리는 normalized_text
를 사용하지 않습니다. 왜냐하면 작성자는 직접 전처리를 진행하고 싶어합니다.
데이터 프레임에 넣기
In
df = pd.read_csv('../input/simpsons_dataset.csv')
df.shape
Out
(158314, 2)
상단 5개 보기
In
df.head()
Out
raw_character_text | spoken_words | |
---|---|---|
0 | Miss Hoover | No, actually, it was a little of both. Sometim... |
1 | Lisa Simpson | Where's Mr. Bergstrom? |
2 | Miss Hoover | I don't know. Although I'd sure like to talk t... |
3 | Lisa Simpson | That life is worth living. |
4 | Edna Krabappel-Flanders | The polls will be open from now until the end ... |
비어 있는 값은 대사 없이 어떤 일이 발생하는 스크립트의 일부에서 비롯됩니다. 예를 들어, "(Springfield Elementary School: EXT. ELEMENTARY - SCHOOL PLAYGROUND - AFTERNOON)"와 같은 경우입니다.
null이 담긴 열의 개수
In
df.isnull().sum()
out
raw_character_text 17814
spoken_words 26459
dtype: int64
Cleaning
우리는 각 대사 줄에서 표제어 추출을 하고 불용어와 비알파벳 문자를 제거하고 있습니다.
In
nlp = spacy.load('en', disable=['ner', 'parser']) # 명명된 개체 인식 비활성화로 속도 향상
def cleaning(doc):
# 표제어 추출 및 불용어 제거
# doc는 spacy Doc 객체여야 함
txt = [token.lemma_ for token in doc if not token.is_stop]
# Word2Vec는 문맥 단어를 사용하여 대상 단어의 벡터 표현을 학습함
# 문장이 한두 단어로만 구성된 경우, 학습에 대한 이점이 매우 작음
if len(txt) > 2:
return ' '.join(txt)
Removes non-alphabetic characters.
In
brief_cleaning = (re.sub("[^A-Za-z']+", ' ', str(row)).lower() for row in df['spoken_words'])
spaCy.pipe()로 전처리 속도를 올립니다.
In
t = time()
txt = [cleaning(doc) for doc in nlp.pipe(brief_cleaning, batch_size=5000, n_threads=-1)]
print('Time to clean up everything: {} mins'.format(round((time() - t) / 60, 2)))
Out
Time to clean up everything: 1.91 mins
결측값과 중복을 제거하기 위해 DataFrame에 결과를 넣습니다.
In
df_clean = pd.DataFrame({'clean': txt})
df_clean = df_clean.dropna().drop_duplicates()
df_clean.shape
Out
(92412, 1)
Bigrams
We are using Gensim Phrases package to automatically detect common phrases (bigrams) from a list of sentences. The main reason we do this is to catch words like "mr_burns" or "bart_simpson" !
바이그램(bigram)은 연속된 두 단어로 구성된 단어 쌍을 의미합니다. 예를 들어, "machine learning"이라는 구문에서 "machine"과 "learning"이 함께 나타나는 경우, 이를 하나의 바이그램으로 취급하여 "machine_learning"처럼 연결하여 처리할 수 있습니다. 바이그램을 사용하면 문맥을 더 잘 이해할 수 있고, 특정 단어 쌍의 의미를 보존할 수 있습니다. Gensim Phrases 패키지를 사용하면 자동으로 이러한 일반적인 단어 쌍을 감지하여 "mr_burns"나 "bart_simpson" 같은 표현을 효과적으로 잡아낼 수 있습니다.
In
from gensim.models.phrases import Phrases, Phraser
# Phrases()는 단어 리스트의 리스트를 입력으로 받습니다:
sent = [row.split() for row in df_clean['clean']]
# 문장 목록에서 관련 구문을 생성합니다:
phrases = Phrases(sent, min_count=30, progress_per=10000)
# Phrases()의 메모리 소비를 줄이기 위해 Phraser()를 사용합니다:
bigram = Phraser(phrases)
# 감지된 바이그램을 기반으로 코퍼스를 변환합니다:
sentences = bigram[sent]
Out
INFO - 01:16:12: 'pattern' package not found; tag filters are not available for English
INFO - 01:16:13: collecting all words and their counts
INFO - 01:16:13: PROGRESS: at sentence #0, processed 0 words and 0 word types
INFO - 01:16:13: PROGRESS: at sentence #10000, processed 67396 words and 50551 word types
INFO - 01:16:13: PROGRESS: at sentence #20000, processed 140465 words and 95808 word types
INFO - 01:16:13: PROGRESS: at sentence #30000, processed 207950 words and 132011 word types
INFO - 01:16:13: PROGRESS: at sentence #40000, processed 270207 words and 164407 word types
INFO - 01:16:13: PROGRESS: at sentence #50000, processed 334085 words and 196195 word types
INFO - 01:16:13: PROGRESS: at sentence #60000, processed 400877 words and 228659 word types
INFO - 01:16:14: PROGRESS: at sentence #70000, processed 467802 words and 260712 word types
INFO - 01:16:14: PROGRESS: at sentence #80000, processed 534361 words and 292095 word types
INFO - 01:16:14: PROGRESS: at sentence #90000, processed 602037 words and 321944 word types
INFO - 01:16:14: collected 328658 word types from a corpus of 618920 words (unigram + bigrams) and 92412 sentences
INFO - 01:16:14: using 328658 counts as vocab in Phrases<0 vocab, min_count=30, threshold=10.0, max_vocab_size=40000000>
INFO - 01:16:14: source_vocab length 328658
INFO - 01:16:17: Phraser built with 127 phrasegrams
가장 빈번한 단어
이 작업은 주로 표제어 추출, 불용어 제거 및 바이그램 추가의 효과를 확인하는 것입니다.
from collections import defaultdict
word_freq = defaultdict(int)
for sent in sentences:
for i in sent:
word_freq[i] += 1
# 단어 빈도 수
len(word_freq) # 29673
# 가장 빈번한 상위 10개 단어
sorted(word_freq, key=word_freq.get, reverse=True)[:10]
# ['be', 'not', 'oh', 'will', 'like', "'s", 'know', 'think', 'hey', 'good']
모델 훈련
Gensim의 Word2Vec 구현을 사용합니다: Gensim Word2Vec Documentation
python코드 복사
import multiprocessing
from gensim.models import Word2Vec
모델 훈련을 3단계로 분리하는 이유:
명확성과 모니터링을 위해 모델 훈련을 3개의 구별된 단계로 나누는 것을 선호합니다.
- Word2Vec():
첫 번째 단계에서는 모델의 매개변수를 하나씩 설정합니다. 이 단계에서는sentences
매개변수를 제공하지 않아 모델을 초기화하지 않습니다. - .build_vocab():
이 단계에서는 문장 시퀀스로부터 어휘를 구축하여 모델을 초기화합니다. 로깅을 통해 진행 상황을 확인하고, 특히min_count
와sample
매개변수가 말뭉치에 미치는 영향을 모니터링할 수 있습니다. 이 두 매개변수, 특히sample
은 모델 성능에 큰 영향을 미칩니다. - .train():
마지막으로, 모델을 훈련합니다. 이 단계의 로깅은 주로 모니터링을 위해 사용되며, 실행 중에 쓰레드가 즉시 실행되지 않도록 합니다.
cores = multiprocessing.cpu_count() # 컴퓨터의 코어 수 계산
w2v_model = Word2Vec(
min_count=20,
window=2,
size=300,
sample=6e-5,
alpha=0.03,
min_alpha=0.0007,
negative=20,
workers=cores-1
)
어휘 테이블 구축:
Word2Vec는 어휘 테이블을 구축해야 합니다(모든 단어를 소화하고 고유 단어를 필터링하여 기본적인 카운트를 수행).
import time
t = time.time()
w2v_model.build_vocab(sentences, progress_per=10000)
print('Time to build vocab: {} mins'.format(round((time.time() - t) / 60, 2)))
로그 메시지:
INFO - 01:16:19: collecting all words and their counts
INFO - 01:16:19: PROGRESS: at sentence #0, processed 0 words, keeping 0 word types
INFO - 01:16:20: PROGRESS: at sentence #10000, processed 65193 words, keeping 9096 word types
INFO - 01:16:20: PROGRESS: at sentence #20000, processed 136024 words, keeping 13916 word types
INFO - 01:16:20: PROGRESS: at sentence #30000, processed 201577 words, keeping 16865 word types
INFO - 01:16:20: PROGRESS: at sentence #40000, processed 262082 words, keeping 19506 word types
INFO - 01:16:21: PROGRESS: at sentence #50000, processed 324069 words, keeping 21758 word types
INFO - 01:16:21: PROGRESS: at sentence #60000, processed 388895 words, keeping 23910 word types
INFO - 01:16:21: PROGRESS: at sentence #70000, processed 454042 words, keeping 25876 word types
INFO - 01:16:21: PROGRESS: at sentence #80000, processed 518929 words, keeping 27769 word types
INFO - 01:16:22: PROGRESS: at sentence #90000, processed 584755 words, keeping 29345 word types
INFO - 01:16:22: collected 29673 word types from a corpus of 601119 raw words and 92412 sentences
INFO - 01:16:22: Loading a fresh vocabulary
INFO - 01:16:22: effective_min_count=20 retains 3375 unique words (11% of original 29673, drops 26298)
INFO - 01:16:22: effective_min_count=20 leaves 515089 word corpus (85% of original 601119, drops 86030)
INFO - 01:16:22: deleting the raw counts dictionary of 29673 items
INFO - 01:16:22: sample=6e-05 downsamples 1080 most-common words
INFO - 01:16:22: downsampling leaves estimated 219321 word corpus (42.6% of prior 515089)
INFO - 01:16:22: estimated required memory for 3375 words and 300 dimensions: 9787500 bytes
INFO - 01:16:22: resetting layer weights
Time to build vocab: 0.04 mins
파라미터 설명:
min_count
(int): 절대 빈도가 이 값보다 낮은 모든 단어를 무시합니다. (예: 2, 100)window
(int): 문장에서 현재 단어와 예측된 단어 사이의 최대 거리입니다. (예: 2, 10)size
(int): 피처 벡터의 차원 수입니다. (예: 50, 300)sample
(float): 더 높은 빈도의 단어를 무작위로 다운샘플링하는 임계값입니다. 매우 영향력이 큽니다. (예: 0, 1e-5)alpha
(float): 초기 학습률입니다. (예: 0.01, 0.05)min_alpha
(float): 학습이 진행됨에 따라 학습률이 선형적으로 이 값으로 떨어집니다. 설정 방법: alpha - (min_alpha * epochs) ~ 0.00
negative
(int): 0보다 큰 경우, 네거티브 샘플링을 사용하며, 몇 개의 "노이즈 단어"를 뽑을지 지정합니다. 0으로 설정하면 네거티브 샘플링을 사용하지 않습니다. (예: 5, 20)workers
(int): 모델을 훈련하는 데 사용할 워커 스레드 수입니다. 멀티코어 머신에서 더 빠른 훈련이 가능합니다.
모델 훈련
훈련 매개변수:
total_examples
(int): 문장 수epochs
(int): 말뭉치를 반복하는 횟수 (에포크) - [10, 20, 30]
import time
t = time.time()
w2v_model.train(sentences, total_examples=w2v_model.corpus_count, epochs=30, report_delay=1)
print('Time to train the model: {} mins'.format(round((time.time() - t) / 60, 2)))
로그 메시지:
INFO - 01:16:22: training model with 3 workers on 3375 vocabulary and 300 features, using sg=0 hs=0 sample=6e-05 negative=20 window=2
INFO - 01:16:23: EPOCH 1 - PROGRESS: at 37.39% examples, 83477 words/s, in_qsize 0, out_qsize 0
INFO - 01:16:24: EPOCH 1 - PROGRESS: at 80.01% examples, 86297 words/s, in_qsize 0, out_qsize 0
INFO - 01:16:24: worker thread finished; awaiting finish of 2 more threads
.
.
.
INFO - 01:17:32: worker thread finished; awaiting finish of 1 more threads
INFO - 01:17:32: worker thread finished; awaiting finish of 0 more threads
INFO - 01:17:32: EPOCH - 28 : training on 601119 raw words (219753 effective words) took 2.4s, 91317 effective words/s
INFO - 01:17:33: EPOCH 29 - PROGRESS: at 40.98% examples, 87482 words/s, in_qsize 0, out_qsize 0
INFO - 01:17:34: EPOCH 29 - PROGRESS: at 76.68% examples, 81469 words/s, in_qsize 0, out_qsize 0
INFO - 01:17:35: worker thread finished; awaiting finish of 2 more threads
INFO - 01:17:35: worker thread finished; awaiting finish of 1 more threads
INFO - 01:17:35: worker thread finished; awaiting finish of 0 more threads
INFO - 01:17:35: EPOCH - 29 : training on 601119 raw words (219058 effective words) took 2.6s, 84528 effective words/s
INFO - 01:17:36: EPOCH 30 - PROGRESS: at 42.87% examples, 91994 words/s, in_qsize 0, out_qsize 0
INFO - 01:17:37: EPOCH 30 - PROGRESS: at 84.97% examples, 91028 words/s, in_qsize 0, out_qsize 0
INFO - 01:17:37: worker thread finished; awaiting finish of 2 more threads
INFO - 01:17:37: worker thread finished; awaiting finish of 1 more threads
INFO - 01:17:37: worker thread finished; awaiting finish of 0 more threads
INFO - 01:17:37: EPOCH - 30 : training on 601119 raw words (219783 effective words) took 2.4s, 92438 effective words/s
INFO - 01:17:37: training on a 18033570 raw words (6581170 effective words) took 75.5s, 87111 effective words/s
Time to train the model: 1.26 mins
훈련 최적화:
추가 훈련을 계획하지 않기 때문에, init_sims()
를 호출하여 모델을 더 메모리 효율적으로 만듭니다.init_sims
메서드의 역할
- L2 노름 계산: 각 단어 벡터의 L2 노름을 미리 계산합니다.
- 메모리 최적화: 모델의 상태를 업데이트하여 메모리를 덜 사용하게 합니다.
- 추가 훈련 불가: 이 메서드를 호출하면 모델은 더 이상 훈련할 수 없습니다. 따라서 모델 훈련이 완료된 후에만 호출해야 합니다.
w2v_model.init_sims(replace=True)
로그 메시지:
INFO - 01:17:37: precomputing L2-norms of word weight vectors
요약:
- 모델의 매개변수를 설정하고 어휘를 구축합니다.
- 설정된 매개변수를 바탕으로 모델을 훈련합니다.
- 추가 훈련 계획이 없으면
init_sims()
를 호출하여 모델을 메모리 효율적으로 만듭니다.모델 탐색
가장 유사한 단어 찾기:
시뮬레이션 캐릭터의 유사한 단어를 찾아보겠습니다.
호머 심슨의 유사한 단어:
w2v_model.wv.most_similar(positive=["homer"])
[('depressed', 0.7399601936340332),
('marge', 0.6840592622756958),
('terrific', 0.6683255434036255),
('hammock', 0.6648209095001221),
('bongo', 0.6537353992462158),
('suspicious', 0.650877833366394),
('brad', 0.6480956077575684),
('dr_hibbert', 0.6459894180297852),
('crummy', 0.6455820798873901),
('tab', 0.6413768529891968)]
호머 심슨 바이그램의 유사한 단어:
w2v_model.wv.most_similar(positive=["homer_simpson"])
[('pleased', 0.6995885372161865),
('governor', 0.6765384078025818),
('congratulation', 0.673900842666626),
('select', 0.670538604259491),
('client', 0.6673898696899414),
('council', 0.6545040011405945),
('sir', 0.6534280776977539),
('easily', 0.652005672454834),
('montgomery_burn', 0.646706223487854),
('waylon', 0.6452118754386902)]
마지 심슨의 유사한 단어:
w2v_model.wv.most_similar(positive=["marge"])
[('homie', 0.691033124923706),
('grownup', 0.6905738115310669),
('anyhoo', 0.689124584197998),
('badly', 0.6851314306259155),
('homer', 0.6840591430664062),
('fault', 0.6757026314735413),
('rude', 0.6737008094787598),
('arrange', 0.6706920266151428),
('becky', 0.6677480936050415),
('depressed', 0.6599912643432617)]
바트 심슨의 유사한 단어:
w2v_model.wv.most_similar(positive=["bart"])
[('lisa', 0.8355059623718262),
('homework', 0.748320996761322),
('dr_hibbert', 0.7391160726547241),
('hearing', 0.726239800453186),
('mom_dad', 0.7246347665786743),
('mom', 0.7206332683563232),
('creepy', 0.719312846660614),
('upset', 0.7119840383529663),
('convince', 0.6911271810531616),
('grownup', 0.6909879446029663)]
단어 유사도:
두 단어 사이의 유사도를 확인합니다.
모의 술집과 주점의 유사도:
w2v_model.wv.similarity("moe_'s", 'tavern')
0.91984504
매기와 아기의 유사도:
w2v_model.wv.similarity('maggie', 'baby')
0.68336403
바트와 넬슨의 유사도:
w2v_model.wv.similarity('bart', 'nelson')
0.5517832
이상한 단어 찾기:
리스트에서 어울리지 않는 단어를 찾습니다.
'jimbo', 'milhouse', 'kearney' 중에서 괴롭히는 사람이 아닌 사람은?
w2v_model.wv.doesnt_match(['jimbo', 'milhouse', 'kearney'])
'milhouse'
'nelson', 'bart', 'milhouse' 중에서 어울리지 않는 사람은?
w2v_model.wv.doesnt_match(["nelson", "bart", "milhouse"])
'nelson'
'homer', 'patty', 'selma' 중에서 어울리지 않는 사람은?
w2v_model.wv.doesnt_match(['homer', 'patty', 'selma'])
'homer'
유사성 차이:
어떤 단어가 여성에 대한 것인지, 호머가 마지에 대한 것인지 확인합니다.
'woman', 'homer'에서 'marge'를 뺀 단어는?
w2v_model.wv.most_similar(positive=["woman", "homer"], negative=["marge"], topn=3)
[('man', 0.606171190738678),
('admire', 0.5796200037002563),
('people', 0.5583280324935913)]
'woman', 'bart'에서 'man'을 뺀 단어는?
w2v_model.wv.most_similar(positive=["woman", "bart"], negative=["man"], topn=3)
[('lisa', 0.7005277872085571),
('parent', 0.6505811214447021),
('grownup', 0.6195728778839111)]
t-SNE 시각화
t-SNE는 고차원 데이터를 저차원 공간에 나타내어 벡터 간의 관계를 시각화하는 비선형 차원 축소 알고리즘입니다. 더 자세한 내용은 이 튜토리얼을 참고하세요.
필요한 라이브러리 임포트
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns
sns.set_style("darkgrid")
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
이 섹션의 목표는 300차원의 벡터를 2차원 그래프에 나타내어 흥미로운 패턴을 찾는 것입니다. 이를 위해 scikit-learn의 t-SNE 구현을 사용할 것입니다.
쿼리 단어(빨간색), 모델에서 가장 유사한 단어들(파란색), 그리고 어휘에서의 다른 단어들(녹색)의 관계를 시각화합니다.
t-SNE 시각화 함수
def tsnescatterplot(model, word, list_names):
""" Plot in seaborn the results from the t-SNE dimensionality reduction algorithm of the vectors of a query word,
its list of most similar words, and a list of words.
"""
arrays = np.empty((0, 300), dtype='f')
word_labels = [word]
color_list = ['red']
# adds the vector of the query word
arrays = np.append(arrays, model.wv.__getitem__([word]), axis=0)
# gets list of most similar words
close_words = model.wv.most_similar([word])
# adds the vector for each of the closest words to the array
for wrd_score in close_words:
wrd_vector = model.wv.__getitem__([wrd_score[0]])
word_labels.append(wrd_score[0])
color_list.append('blue')
arrays = np.append(arrays, wrd_vector, axis=0)
# adds the vector for each of the words from list_names to the array
for wrd in list_names:
wrd_vector = model.wv.__getitem__([wrd])
word_labels.append(wrd)
color_list.append('green')
arrays = np.append(arrays, wrd_vector, axis=0)
# Reduces the dimensionality from 300 to 50 dimensions with PCA
reduc = PCA(n_components=50).fit_transform(arrays)
# Finds t-SNE coordinates for 2 dimensions
np.set_printoptions(suppress=True)
Y = TSNE(n_components=2, random_state=0, perplexity=15).fit_transform(reduc)
# Sets everything up to plot
df = pd.DataFrame({'x': [x for x in Y[:, 0]],
'y': [y for y in Y[:, 1]],
'words': word_labels,
'color': color_list})
fig, _ = plt.subplots()
fig.set_size_inches(9, 9)
# Basic plot
p1 = sns.regplot(data=df,
x="x",
y="y",
fit_reg=False,
marker="o",
scatter_kws={'s': 40,
'facecolors': df['color']
}
)
# Adds annotations one by one with a loop
for line in range(0, df.shape[0]):
p1.text(df["x"][line],
df['y'][line],
' ' + df["words"][line].title(),
horizontalalignment='left',
verticalalignment='bottom', size='medium',
color=df['color'][line],
weight='normal'
).set_size(15)
plt.xlim(Y[:, 0].min()-50, Y[:, 0].max()+50)
plt.ylim(Y[:, 1].min()-50, Y[:, 1].max()+50)
plt.title('t-SNE visualization for {}'.format(word.title()))
plt.show()
예시: 10개의 유사 단어와 8개의 무작위 단어 비교
tsnescatterplot(w2v_model, 'homer', ['dog', 'bird', 'ah', 'maude', 'bob', 'mel', 'apu', 'duff'])
예시: 10개의 유사 단어와 10개의 비유사 단어 비교
tsnescatterplot(w2v_model, 'maggie', [i[0] for i in w2v_model.wv.most_similar(negative=["maggie"])])
예시: 1 to 10번째 유사 단어와 11 to 20번째 유사 단어 비교
tsnescatterplot(w2v_model, "mr_burn", [t[0] for t in w2v_model.wv.most_similar(positive=["mr_burn"], topn=20)][10:])
결론
이 튜토리얼을 통해 Word2Vec 모델을 학습하고, t-SNE를 사용하여 단어 벡터를 시각화하는 방법을 배웠습니다. 더 깊이 있는 이해를 위해 추가 자료를 참고하세요.
추가 자료
'Artificial Intelligence > kaggle' 카테고리의 다른 글
[kaggle] 🐘Greyscale MobileNet [LB=0.892] - Review 하기 (0) | 2024.08.05 |
---|---|
[kaggle] Image compression using PCA - Review 하기 (0) | 2024.07.29 |
[kaggle] Single model baseline: XGBoost - Review하기 (6) | 2024.07.22 |