단어 임베딩

2024. 6. 10. 15:08·Machine Learning/Embedding & NLP

1. 원핫 인코딩(One-hot encoding)

원핫 인코딩은 단어를 0과 1로 구성된 벡터로 표현하는 임베딩 방법이다. 예를 들어, 'dog', 'cat', 'apple'이라는 단어가 있다면,

  • dog : [1, 0, 0]
  • cat : [0, 1, 0]
  • apple : [0, 0, 1]

이렇게 각 단어는 고유한 위치에 1을 가지며 나머지는 0으로 채워진 벡터로 표현된다. 이 과정에서 문장은 먼저 단어로 분해되고, 각 고유 단어에는 독립된 인덱스가 부여된다.

2. 학습 기반 임베딩

분포 가설(Distribution Hypothesis)

분포 가설에 따르면, 단어의 의미는 그 단어가 사용되는 문맥에 의해 결정된다. 예를 들어, "우리 엄마는 물을 매일 마신다"에서 '물' 자리에 올 수 있는 '사과 주스'나 '우유' 등은 '물'과 문맥적으로 연관된 의미를 가진다고 볼 수 있다.

Word2Vec

2013년 구글 연구진이 개발한 Word2Vec은 두 가지 방법으로 단어 임베딩을 진행한다.

  • CBOW (Continuous Bag of Words): 주변 단어들을 이용하여 중간에 위치한 단어를 예측한다.
  • Skip-gram: 중간에 위치한 단어를 이용하여 주변 단어를 예측한다.

GloVe (Global Vectors for Word Representation)

GloVe는 단어 간의 공동 출현 통계를 이용하여 벡터 공간 내에서 단어를 임베딩한다. 이 방법은 단어 쌍이 얼마나 자주 함께 나타나는지를 기록하여, 자주 출현하는 단어들이 벡터 공간에서 비슷한 위치에 배치되도록 한다.

3. 실습과 응용

  • 원핫 인코딩 실습: Sklearn의 OneHotEncoder 클래스를 사용하여 전체 문장을 입력하고 각 단어의 벡터를 생성한다.
  • Word2Vec 실습: Gensim 패키지를 이용한 Word2Vec 모델 사용법과 유사도 계산 방법을 실습한다.
  • GloVe 실습: 역시 Gensim 패키지를 활용하여 GloVe 모델을 적용해 본다.
[Part3,_Chap7]_단어_임베딩

원핫 인코딩 (One-hot Encoding) 단어에 적용하기¶

In [ ]:
from sklearn.preprocessing import OneHotEncoder
import numpy as np
In [ ]:
sentence = "사과는 맛있다 바나나는 맛있다"
In [ ]:
# 문장을 단어로 분리
# 띄어쓰기 단위를 사용
words = sentence.split()
print(words)
['사과는', '맛있다', '바나나는', '맛있다']
In [ ]:
# 단어 배열을 NumPy 배열로 변환
words_array = np.array(words).reshape(-1, 1)
print(words_array)
[['사과는']
 ['맛있다']
 ['바나나는']
 ['맛있다']]
In [ ]:
# OneHotEncoder 객체 생성
encoder = OneHotEncoder(sparse_output=False) # sparse_output=False : 수업에서 다룬 0과 1로 이루어진 행렬의 형태로 변환
In [ ]:
# 원핫 인코딩 적용!
one_hot_encoded = encoder.fit_transform(words_array)
print(one_hot_encoded)
[[0. 0. 1.]
 [1. 0. 0.]
 [0. 1. 0.]
 [1. 0. 0.]]
In [ ]:
encoder.get_feature_names_out() # 각 열이 어떤 단어를 나타내는지를 표시
Out[ ]:
array(['x0_맛있다', 'x0_바나나는', 'x0_사과는'], dtype=object)
In [ ]:
def one_hot_encode_words(sentence):
    words = sentence.split()
    words_array = np.array(words).reshape(-1, 1)

    encoder = OneHotEncoder(sparse_output=False)
    one_hot_encoded = encoder.fit_transform(words_array)

    return one_hot_encoded, encoder.get_feature_names_out()
In [ ]:
example_sentence = '오늘 날씨가 참 맑습니다.'
In [ ]:
encoded_words, feature_names = one_hot_encode_words(example_sentence)
In [ ]:
encoded_words, feature_names
Out[ ]:
(array([[0., 0., 1., 0.],
        [1., 0., 0., 0.],
        [0., 0., 0., 1.],
        [0., 1., 0., 0.]]),
 array(['x0_날씨가', 'x0_맑습니다.', 'x0_오늘', 'x0_참'], dtype=object))

Word2Vec을 단어에 적용하기¶

In [ ]:
from gensim.models import KeyedVectors
from gensim.downloader import load

def use_word2vec(word, model):
    try:
        word_vector = model[word]
        return word_vector
    except KeyError:
        return "단어가 모델의 어휘에 없습니다."
In [ ]:
# 제공하는 기본 Word2Vec 모델 불러오기
# 약 10~12분 정도 소요
word2vec_model = load('word2vec-google-news-300')
[==================================================] 100.0% 1662.8/1662.8MB downloaded
In [ ]:
print(use_word2vec('apple', word2vec_model))
print(use_word2vec('instagram', word2vec_model)) # 학습 당시에 존재하지 않던 단어는 임베딩 불가
[-0.06445312 -0.16015625 -0.01208496  0.13476562 -0.22949219  0.16210938
  0.3046875  -0.1796875  -0.12109375  0.25390625 -0.01428223 -0.06396484
 -0.08056641 -0.05688477 -0.19628906  0.2890625  -0.05151367  0.14257812
 -0.10498047 -0.04736328 -0.34765625  0.35742188  0.265625    0.00188446
 -0.01586914  0.00195312 -0.35546875  0.22167969  0.05761719  0.15917969
  0.08691406 -0.0267334  -0.04785156  0.23925781 -0.05981445  0.0378418
  0.17382812 -0.41796875  0.2890625   0.32617188  0.02429199 -0.01647949
 -0.06494141 -0.08886719  0.07666016 -0.15136719  0.05249023 -0.04199219
 -0.05419922  0.00108337 -0.20117188  0.12304688  0.09228516  0.10449219
 -0.00408936 -0.04199219  0.01409912 -0.02111816 -0.13476562 -0.24316406
  0.16015625 -0.06689453 -0.08984375 -0.07177734 -0.00595093 -0.00482178
 -0.00089264 -0.30664062 -0.0625      0.07958984 -0.00909424 -0.04492188
  0.09960938 -0.33398438 -0.3984375   0.05541992 -0.06689453 -0.04467773
  0.11767578 -0.13964844 -0.26367188  0.17480469 -0.17382812 -0.40625
 -0.06738281 -0.07617188  0.09423828  0.20996094 -0.16308594 -0.08691406
 -0.0534668  -0.10351562 -0.07617188 -0.11083984 -0.03515625 -0.14941406
  0.0378418   0.38671875  0.14160156 -0.2890625  -0.16894531 -0.140625
 -0.04174805  0.22753906  0.24023438 -0.01599121 -0.06787109  0.21875
 -0.42382812 -0.5625     -0.49414062 -0.3359375   0.13378906  0.01141357
  0.13671875  0.0324707   0.06835938 -0.27539062 -0.15917969  0.00121307
  0.01208496 -0.0039978   0.00442505 -0.04541016  0.08642578  0.09960938
 -0.04296875 -0.11328125  0.13867188  0.41796875 -0.28320312 -0.07373047
 -0.11425781  0.08691406 -0.02148438  0.328125   -0.07373047 -0.01348877
  0.17773438 -0.02624512  0.13378906 -0.11132812 -0.12792969 -0.12792969
  0.18945312 -0.13867188  0.29882812 -0.07714844 -0.37695312 -0.10351562
  0.16992188 -0.10742188 -0.29882812  0.00866699 -0.27734375 -0.20996094
 -0.1796875  -0.19628906 -0.22167969  0.08886719 -0.27734375 -0.13964844
  0.15917969  0.03637695  0.03320312 -0.08105469  0.25390625 -0.08691406
 -0.21289062 -0.18945312 -0.22363281  0.06542969 -0.16601562  0.08837891
 -0.359375   -0.09863281  0.35546875 -0.00741577  0.19042969  0.16992188
 -0.06005859 -0.20605469  0.08105469  0.12988281 -0.01135254  0.33203125
 -0.08691406  0.27539062 -0.03271484  0.12011719 -0.0625      0.1953125
 -0.10986328 -0.11767578  0.20996094  0.19921875  0.02954102 -0.16015625
  0.00276184 -0.01367188  0.03442383 -0.19335938  0.00352478 -0.06542969
 -0.05566406  0.09423828  0.29296875  0.04052734 -0.09326172 -0.10107422
 -0.27539062  0.04394531 -0.07275391  0.13867188  0.02380371  0.13085938
  0.00236511 -0.2265625   0.34765625  0.13574219  0.05224609  0.18164062
  0.0402832   0.23730469 -0.16992188  0.10058594  0.03833008  0.10839844
 -0.05615234 -0.00946045  0.14550781 -0.30078125 -0.32226562  0.18847656
 -0.40234375 -0.3125     -0.08007812 -0.26757812  0.16699219  0.07324219
  0.06347656  0.06591797  0.17285156 -0.17773438  0.00276184 -0.05761719
 -0.2265625  -0.19628906  0.09667969  0.13769531 -0.49414062 -0.27929688
  0.12304688 -0.30078125  0.01293945 -0.1875     -0.20898438 -0.1796875
 -0.16015625 -0.03295898  0.00976562  0.25390625 -0.25195312  0.00210571
  0.04296875  0.01184082 -0.20605469  0.24804688 -0.203125   -0.17773438
  0.07275391  0.04541016  0.21679688 -0.2109375   0.14550781 -0.16210938
  0.20410156 -0.19628906 -0.35742188  0.35742188 -0.11962891  0.35742188
  0.10351562  0.07080078 -0.24707031 -0.10449219 -0.19238281  0.1484375
  0.00057983  0.296875   -0.12695312 -0.03979492  0.13183594 -0.16601562
  0.125       0.05126953 -0.14941406  0.13671875 -0.02075195  0.34375   ]
단어가 모델의 어휘에 없습니다.
In [ ]:
from scipy.spatial.distance import cosine

def word_similarity(word1, word2, model):
    try:
        vector1 = model[word1]
        vector2 = model[word2]

        similarity = 1 - cosine(vector1, vector2) # 코사인 유사도 계산
        return similarity
    except KeyError as e:
        return str(e)

def most_similar(word, model, topn=5):
    try:
        similar_words = model.most_similar(word, topn=topn) # 가장 유사한 단어 찾기
        return similar_words
    except KeyError as e:
        return str(e)
In [ ]:
# 두 단어 사이의 유사도 확인
print('football & basketball 유사도 : ' , word_similarity('football', 'basketball', word2vec_model))
print('football & airplane 유사도 : ' , word_similarity('football', 'airplane', word2vec_model))
football & basketball 유사도 :  0.668246865272522
football & airplane 유사도 :  0.1512438803911209
In [ ]:
# 특정 단어와 가장 유사한 단어 보여주기
print('football과 가장 유사한 단어 5개는 : ' , most_similar('football', word2vec_model, topn=5))
football과 가장 유사한 단어 5개는 :  [('soccer', 0.731354832649231), ('fooball', 0.7139959335327148), ('Football', 0.7124834060668945), ('basketball', 0.668246865272522), ('footbal', 0.6649289727210999)]

GloVe를 단어에 적용하기¶

In [ ]:
def use_glove(word, model):
    try:
        word_vector = model[word]
        return word_vector
    except KeyError:
        return "단어가 모델의 어휘에 없습니다."
In [ ]:
# 제공하는 GloVe 모델 불러오기
# 약 5분정도 소요
glove_model = load('glove-wiki-gigaword-300')
[==================================================] 100.0% 376.1/376.1MB downloaded
In [ ]:
print(use_glove('apple', glove_model))
print(use_glove('airpods', glove_model)) # 역시 학습 당시에 없던 단어는 임베딩 불가
[-0.20842   -0.019668   0.063981  -0.71403   -0.21181   -0.59283
 -0.15316    0.044217   0.63289   -0.84821   -0.21129   -0.19763
  0.19029   -0.56226    0.27126    0.23782   -0.5189    -0.24518
  0.035243   0.096833   0.24898    0.71279    0.038279  -0.10514
 -0.4779    -0.39515   -0.27194   -0.44428    0.06113   -0.2318
 -0.35901   -0.18239    0.035507  -0.087719  -1.0816    -0.42521
  0.003224  -0.45991   -0.043462  -0.39031    0.519      0.21139
 -0.25527    1.1805    -0.19041   -0.12156    0.034186  -0.062316
  0.14421   -0.53366    0.47425   -0.4471     0.58047    0.43578
  0.1321    -0.095712  -0.37182   -0.013837   0.20601   -0.10099
  0.10685   -0.33723    0.10986    0.34796   -0.099839   0.36942
 -0.52917    0.12407   -0.46127   -0.38483   -0.10114   -0.17634
  0.37574    0.16377   -0.2198    -0.26841    0.84706   -0.35619
 -0.083992  -0.20276   -0.56542    0.19112   -0.14134   -0.7812
  0.69188   -0.083628  -0.54293    0.16437    0.037606  -0.68896
 -0.68711   -0.13367   -0.4779     0.20125    0.085122  -0.063865
 -0.17104   -0.32432   -0.17623   -0.514     -0.50289    0.23204
 -0.11324   -1.064     -0.035359  -0.5068    -0.27118   -0.16621
 -0.63016    0.054252  -0.048178   0.29282   -0.030666  -0.24645
 -0.27084   -0.42563   -0.39171    0.18428   -0.017772  -0.35334
 -0.49075   -0.90782    0.13872   -0.76521   -0.46318   -0.32124
 -0.086228   1.0448    -0.39919    0.69478   -0.10377    0.86715
  0.22742    0.4384     0.085767  -0.22846    0.4309     0.064187
 -0.027926  -0.093056   0.65188    0.59143   -0.3376    -0.37732
  0.0052212  1.1193    -0.23845   -0.16029    0.42877   -0.16228
 -0.12202   -0.1061     0.015761   0.022745  -0.17734   -0.091711
 -0.29158    0.19034   -0.35168    0.27563   -0.20577    0.11472
 -0.34126   -0.0065915  0.14896   -0.026762   0.0019373  0.53279
 -0.76088    0.063085  -0.72089   -0.04128   -0.96164    0.020769
  0.16123   -0.34342    0.69713   -0.16018   -0.11701   -0.070239
 -0.30774    0.39741    0.39994   -0.678      0.57684   -0.48099
  0.59317   -0.42262    0.28613   -0.26203    0.052727   0.61659
 -0.36801   -0.28429   -0.40054   -0.30055   -0.27444   -0.045729
 -0.56105    0.24176    0.86631   -0.83715    0.13562    0.26196
 -0.43055    0.34558    0.059441   0.61845    0.11837   -0.019168
  0.47697   -0.32465   -0.15463   -0.23556   -0.64263   -0.092156
 -0.19622    0.40666    0.18009    0.094309   0.046917   0.26369
 -0.50727    0.37491   -0.66773    0.35095   -0.033835   0.30534
  0.23166    0.023526  -0.68365    0.26078   -0.22526   -0.2656
  0.59967    0.2598     0.36248    0.15564   -0.45549    0.11153
 -0.33287    0.081364  -0.36989   -0.25543   -1.1628    -0.14622
 -0.032971  -0.55619    0.47717   -0.29021    0.42688    1.2397
 -0.81391    0.21084   -0.25426   -0.08684   -0.078412   0.26035
  0.3281    -0.23777    0.05138   -0.030247  -0.15669    0.057147
  0.33902    0.12795   -0.21468   -0.75208    0.41422    0.0062719
 -0.52904    0.92193   -0.42179   -0.69638    0.074115   0.19071
 -1.2031    -0.081333  -0.4914    -0.22159   -0.29876    0.30094
  0.018634   0.18786   -0.45429   -0.29296    0.3695    -0.24218
 -0.11803    0.071775   0.44026   -0.59978    0.45354    0.17854
 -0.17155    0.018811  -0.62354   -0.014163   0.16799   -0.064392 ]
단어가 모델의 어휘에 없습니다.
In [ ]:
# 두 단어 사이의 유사도 확인 (GloVe)
print('football & basketball 유사도 : ' , word_similarity('football', 'basketball', glove_model))
print('football & airplane 유사도 : ' , word_similarity('football', 'airplane', glove_model))
football & basketball 유사도 :  0.7341024279594421
football & airplane 유사도 :  0.002223522402346134
In [ ]:
# 특정 단어와 가장 유사한 단어 보여주기  (GloVe)
print('football과 가장 유사한 단어 5개는 : ' , most_similar('football', glove_model, topn=5))
football과 가장 유사한 단어 5개는 :  [('soccer', 0.7682591676712036), ('basketball', 0.7341024279594421), ('league', 0.6599653959274292), ('baseball', 0.6479504704475403), ('rugby', 0.6429778933525085)]
In [ ]:
 

'Machine Learning > Embedding & NLP' 카테고리의 다른 글

감정 분석(Sentiment Analysis)  (1) 2024.06.10
문장 임베딩  (0) 2024.06.10
텍스트 마이닝과 데이터 마이닝  (0) 2024.05.14
'Machine Learning/Embedding & NLP' 카테고리의 다른 글
  • 감정 분석(Sentiment Analysis)
  • 문장 임베딩
  • 텍스트 마이닝과 데이터 마이닝
Juson
Juson
  • Juson
    Juson의 데이터 공부
    Juson
  • 전체
    오늘
    어제
    • 분류 전체보기 (95)
      • RAG (2)
      • AI (2)
        • NLP (0)
        • Generative Model (0)
        • Deep Reinforcement Learning (2)
        • LLM (0)
      • Logistic Optimization (0)
      • Machine Learning (37)
        • Linear Regression (2)
        • Logistic Regression (2)
        • Decision Tree (5)
        • Naive Bayes (1)
        • KNN (2)
        • SVM (2)
        • Clustering (4)
        • Dimension Reduction (3)
        • Boosting (6)
        • Abnomaly Detection (2)
        • Recommendation (4)
        • Embedding & NLP (4)
      • Reinforcement Learning (5)
      • Deep Learning (10)
        • Deep learning Bacis Mathema.. (10)
      • Optimization (2)
        • OR Optimization (0)
        • Convex Optimization (0)
        • Integer Optimization (0)
      • SNA 분석 (0)
      • 포트폴리오 최적화 공부 (0)
        • 최적화 기법 (0)
        • 금융 베이스 (0)
      • Finanancial engineering (0)
      • 프로그래머스 데브코스(Boot camp) (15)
        • SQL (9)
        • Python (5)
        • Machine Learning (1)
      • Python (22)
      • Project (0)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.4
Juson
단어 임베딩
상단으로

티스토리툴바