gensim + word2vec 모델 만들어서 사용하기
참고 : https://www.lucypark.kr/courses/2015-ba/text-mining.html
#Load data
from konlpy.corpus import kobill
docs_ko = [kobill.open(i).read() for i in kobill.fileids()]
#Tokenize
from konlpy.tag import Twitter; t = Twitter()
pos = lambda d: ['/'.join(p) for p in t.pos(d)]
texts_ko = [pos(doc) for doc in docs_ko]
#Train
from gensim.models import word2vec
wv_model_ko = word2vec.Word2Vec(texts_ko)
wv_model_ko.init_sims(replace=True)
wv_model_ko.save('ko_word2vec.model') #model create
#Test - 유사도 분석
wv_model_ko.most_similar(pos('정부'))
wv_model_ko.most_similar(pos('초등학교'))
* 저장된 model 사용하기 : https://radimrehurek.com/gensim/models/word2vec.html
Initialize a model with e.g.:
>>> model = Word2Vec ( sentences , size = 100 , window = 5 , min_count = 5 , workers = 4 )
Persist a model to disk with:
>>> model . save ( fname )
>>> model = Word2Vec . load ( fname ) # you can continue training with the loaded model!
The word vectors are stored in a KeyedVectors instance in model.wv. This separates the read-only word vector lookup operations in KeyedVectors from the training code in Word2Vec.
>>> model . wv [ 'computer' ] # numpy vector of a word
array([-0.00449447, -0.00310097, 0.02421786, ...], dtype=float32)
model 이 잘 불러와졌는지 확인하려면 model의 내용을 보자.
model.vocab 하며 내용을 볼 수 있다.
most_similar 에서 vocaburary에 단어가 없다고 에러나오면 내용을 확인 후 다시 검색해보면 된다.
저장된 vocab이 '국어' 인지, '국어/Noun' 인지 확인 바람요!
>>>len(model.vocab)
9867
>>>model.vocab
Code for the word2vec HTTP server running at https://rare-technologies.com/word2vec-tutorial/#bonus_app
*** 대화 형 word2vec 데모 용 전체 HTTP 서버 코드 :
https://github.com/RaRe-Technologies/w2v_server_googlenews
모델 저장 및로드 표준 gensim 메소드를 사용하여 모델을 저장 /로드 할 수 있습니다.
1
2
model.save(
'/tmp/mymodel'
)
new_model
=
gensim.models.Word2Vec.load(
'/tmp/mymodel'
)
내부적으로 피클을 사용하는 선택적 mmap를 프로세스 간 메모리 공유 디스크 파일에서 직접 가상 메모리에 모델의 내부 큰 NumPy와 행렬을 보내고 '.
또한 텍스트 및 이진 형식을 사용하여 원본 C 도구로 만든 모델을로드 할 수 있습니다.
1
2
삼
model
=
Word2Vec.load_word2vec_format(
'/tmp/vectors.txt'
, binary
=
False
)
model
=
Word2Vec.load_word2vec_format(
'/tmp/vectors.bin.gz'
, binary
=
True
)
온라인 교육 / 훈련 재개 고급 사용자는 모델을로드하고 더 많은 문장으로 계속 교육 할 수 있습니다.
1
2
model
=
gensim.models.Word2Vec.load(
'/tmp/mymodel'
)
model.train(more_sentences)
시뮬레이트 할 학습 속도 감소에 따라 total_words 매개 변수를 train ()에 맞게 조정해야 할 수도 있습니다 .
C 도구 load_word2vec_format ()에 의해 생성 된 모델로는 교육을 재개 할 수 없습니다 . 당신은 여전히 그것들을 질의 / 유사성을 위해 사용할 수 있지만, 훈련에 필수적인 정보 (보캐 트리)가 거기에 없습니다.
모델 사용 Word2vec는 여러 단어 유사 작업을 즉시 지원합니다.
1
2
삼
4
5
6
model.most_similar(positive
=
[
'woman'
,
'king'
], negative
=
[
'man'
], topn
=
1
)
[(
'queen'
,
0.50882536
)]
model.doesnt_match(
"breakfast cereal dinner lunch"
;.split())
'cereal'
model.similarity(
'woman'
,
'man'
)
0.73723527
응용 프로그램에서 원시 출력 벡터가 필요한 경우에는 단어 단위로 이들에 액세스 할 수 있습니다
1
2
model[
'computer'
]
array([
-
0.00449447
,
-
0.00310097
,
0.02421786
, ...], dtype
=
float32)
... 또는 en-masse를 model.syn0 의 2D NumPy 행렬로 사용 하십시오 .
VIDEO
...