https://quantum-leap-dep-2612.tistory.com/39 오라클-17 이후 버전을 설치 후, 실습이 가능합니다.

환경변수 설정 및 라이브러리 설치

kopora - 말뭉치 제공 라이브러리 / 코포라 사이트 (https://ko-nlp.github.io/Korpora/ko-docs/introduction/)

gesim - word2vec,fasttext,doc2vec 라이브러리 제공

Word2vec 실습

 

 

!pip install  korpora
!pip install  gensim
!apt-get install openjdk-20-jdk# JVM 설치

 
 

Word2vec(CBOW실습) 5~7분소요

 
from gensim.models import Word2Vec
from Korpora import Korpora

# "korean_petitions" 데이터셋 로드
corpus = Korpora.load("korean_petitions")

# 텍스트 전처리: 문장을 단어로 분할
sentences = [s for doc in corpus.get_all_texts() for s in doc.split('. ')]  # 문서를 문장으로 분할

# 단어로 분할된 문장 리스트
word_sentences = [sentence.split() for sentence in sentences]

# Word2Vec 모델 학습 (CBOW)
cbow_model = Word2Vec(word_sentences, vector_size=100, window=5, min_count=5, workers=4, sg=0)

# 단어 벡터 출력
word_vectors_cbow = cbow_model.wv

# 검색할 단어
target_word = "가상화폐"
print("CBOW - '{}'의 벡터:".format(target_word), word_vectors_cbow[target_word])
# 유사한 단어 찾기
similar_words = word_vectors_cbow.most_similar(target_word)

# 검색한 단어가 유사한 단어 목록에 포함되는 경우 제외한 유사한 단어 목록 생성
filtered_similar_words = [(word, score) for word, score in similar_words if word != target_word and target_word not in word]

print("검색한 단어:", target_word)
print("유사한 단어들:", filtered_similar_words)

 

 

Skip-gram 실습 20~24분소요

 

from gensim.models import Word2Vec
from Korpora import Korpora

# "korean_petitions" 데이터셋 로드
corpus = Korpora.load("korean_petitions")

# 텍스트 전처리: 문장을 단어로 분할
sentences = [s for doc in corpus.get_all_texts() for s in doc.split('. ')]  # 문서를 문장으로 분할

# 단어로 분할된 문장 리스트
word_sentences = [sentence.split() for sentence in sentences]

# Word2Vec 모델 학습 (Skip-Gram)
skipgram_model = Word2Vec(word_sentences, vector_size=100, window=5, min_count=5, workers=4, sg=1)

# 단어 벡터 출력
word_vectors_skipgram = skipgram_model.wv

# "국민"이라는 단어의 벡터 출력
target_word = "가상화폐"
print("Skip-Gram - '{}'의 벡터:".format(target_word), word_vectors_skipgram[target_word])

# 유사한 단어 찾기
similar_words = word_vectors_skipgram.most_similar(target_word)

# 검색한 단어가 유사한 단어 목록에 포함되는 경우 제외한 유사한 단어 목록 생성
filtered_similar_words = [(word, score) for word, score in similar_words if word != target_word and target_word not in word]

print("검색한 단어:", target_word)
print("유사한 단어들:", filtered_similar_words)


 
 

FastText 실습

 

Fasttext(CBOW)실습 15분소요

 

 

from gensim.models import FastText
from Korpora import Korpora
import re

# "korean_petitions" 데이터셋 로드
corpus = Korpora.load("korean_petitions")

# 텍스트 전처리: 문장을 단어로 분할
sentences = [s for doc in corpus.get_all_texts() for s in doc.split('. ')]  # 문서를 문장으로 분할

# 한글이 아닌 글자 제외하고 전처리
korean_sentences = [re.sub("[^가-힣a-zA-Z ]", "", sentence) for sentence in sentences]

# 단어로 분할된 문장 리스트
word_sentences = [sentence.split() for sentence in korean_sentences]

# FastText 모델 학습
fasttext_model = FastText(word_sentences, vector_size=100, window=5, min_count=5, workers=4, sg=0)

# 단어 벡터 출력
word_vectors_fasttext = fasttext_model.wv

# 검색할 단어
target_word = "가상화폐"

# 조사 제거를 위한 함수
def remove_josa(word):
    josa_list = ['은', '는', '이', '가', '을', '를', '와', '과']
    for josa in josa_list:
        if word.endswith(josa):
            return word[:-len(josa)]
    return word

# 검색할 단어에 조사 제거
target_word_no_josa = remove_josa(target_word)

print("FastText - '{}'의 벡터:".format(target_word_no_josa), word_vectors_fasttext[target_word_no_josa])

# 유사한 단어 찾기
similar_words = word_vectors_fasttext.most_similar(target_word_no_josa)

print("검색한 단어:", target_word)
print("유사한 단어들:", similar_words)
 
 

Fasttext(Skip-gram)실습 27~32분소요

from gensim.models import FastText
from Korpora import Korpora
import re

# "korean_petitions" 데이터셋 로드
corpus = Korpora.load("korean_petitions")

# 텍스트 전처리: 문장을 단어로 분할
sentences = [s for doc in corpus.get_all_texts() for s in doc.split('. ')]  # 문서를 문장으로 분할

# 한글이 아닌 글자 제외하고 전처리
korean_sentences = [re.sub("[^가-힣a-zA-Z ]", "", sentence) for sentence in sentences]

# 단어로 분할된 문장 리스트
word_sentences = [sentence.split() for sentence in korean_sentences]

# FastText 모델 학습
fasttext_model = FastText(word_sentences, vector_size=100, window=5, min_count=5, workers=4, sg=1)

# 검색할 단어
target_word = "가상화폐"

# 조사 제거를 위한 함수
def remove_josa(word):
    josa_list = ['은', '는', '이', '가', '을', '를', '와', '과']
    for josa in josa_list:
        if word.endswith(josa):
            return word[:-len(josa)]
    return word

# 검색할 단어에 조사 제거
target_word_no_josa = remove_josa(target_word)

print("FastText - '{}'의 벡터:".format(target_word_no_josa), fasttext_model.wv[target_word_no_josa])

# 유사한 단어 찾기
similar_words = fasttext_model.wv.most_similar(target_word_no_josa)

print("검색한 단어:", target_word)
print("유사한 단어들:", similar_words)

 
 

 

Doc2vec 실습

 
Doc2vec(DBOW)실습 25분소요
 

 

from gensim.models import Doc2Vec
from gensim.models.doc2vec import TaggedDocument
from Korpora import Korpora
import re

# Korpora 라이브러리를 통해 한국어 청원 데이터를 불러옵니다
corpus = Korpora.load("korean_petitions")
petitions = corpus.get_all_texts()

# 전처리 함수 정의: 한글 아닌 글자 제거
def preprocess_text(text):
    text = re.sub("[^가-힣a-zA-Z ]", "", text)  # 한글 이외의 글자 제거
    text = text.strip()  # 문서 양 끝 공백 제거
    return text

# 전처리 적용한 데이터로 TaggedDocument 생성
tagged_data = [TaggedDocument(words=preprocess_text(petition).split(), tags=[str(i)]) for i, petition in enumerate(petitions)]

# DBOW 방식의 Doc2Vec 모델을 초기화하고 학습시킵니다
dbow_model = Doc2Vec(vector_size=100, window=5, min_count=1, workers=4, dm=0, epochs=20)
dbow_model.build_vocab(tagged_data)
dbow_model.train(tagged_data, total_examples=dbow_model.corpus_count, epochs=dbow_model.epochs)

# 특정 문서의 인덱스를 지정합니다
target_doc_index = 0

# DBOW 방식으로 얻은 특정 문서의 벡터 출력
doc_vector_dbow = dbow_model.dv[target_doc_index]
print("DBOW 방식으로 얻은 특정 문서의 벡터:", doc_vector_dbow)

# 특정 문서의 내용 출력
print("\n특정 문서 내용:")
print(petitions[target_doc_index])
print("\n")

# 특정 문서와 유사한 문서를 찾습니다
similar_documents_dbow = dbow_model.dv.most_similar(target_doc_index, topn=5)

print("특정 문서와 유사한 문서 (DBOW 방식):")
for doc_id, score in similar_documents_dbow:
    print(f"유사도 {score:.2f}, 문서 인덱스 {doc_id}:")
    print(petitions[int(doc_id)])
    print("\n")

 
 

Doc2vec(DM 실습) 35분 소요

from gensim.models import Doc2Vec
from gensim.models.doc2vec import TaggedDocument
from Korpora import Korpora
import re

# Korpora 라이브러리를 통해 한국어 청원 데이터를 불러옵니다
corpus = Korpora.load("korean_petitions")
petitions = corpus.get_all_texts()

# 전처리 함수 정의: 한글 아닌 글자 제거
def preprocess_text(text):
    text = re.sub("[^가-힣a-zA-Z ]", "", text)  # 한글 이외의 글자 제거
    text = text.strip()  # 문서 양 끝 공백 제거
    return text

# 전처리 적용한 데이터로 TaggedDocument 생성
tagged_data = [TaggedDocument(words=preprocess_text(petition).split(), tags=[str(i)]) for i, petition in enumerate(petitions)]

# DM 방식의 Doc2Vec 모델을 초기화하고 학습시킵니다
dm_model = Doc2Vec(vector_size=100, window=5, min_count=1, workers=4, dm=1, epochs=20)
dm_model.build_vocab(tagged_data)
dm_model.train(tagged_data, total_examples=dm_model.corpus_count, epochs=dm_model.epochs)

# 특정 문서의 인덱스를 지정합니다
target_doc_index = 0

# DM 방식으로 얻은 특정 문서의 벡터 출력
doc_vector_dm = dm_model.dv[target_doc_index]
print("DM 방식으로 얻은 특정 문서의 벡터:", doc_vector_dm)

# 특정 문서의 내용 출력
print("\n특정 문서 내용:")
print(petitions[target_doc_index])
print("\n")

# 특정 문서와 유사한 문서를 찾습니다
similar_documents_dm = dm_model.dv.most_similar(target_doc_index, topn=5)

print("특정 문서와 유사한 문서 (DM 방식):")
for doc_id, score in similar_documents_dm:
    print(f"유사도 {score:.2f}, 문서 인덱스 {doc_id}:")
    print(petitions[int(doc_id)])
    print("\n")

 

 

+ Recent posts