본문 바로가기

D.S/ML&DL

gensim 에러 2 - word2vec Index out of bounds with version 4.x

728x90

 

gensim은 참 좋은 패키지이다. 주요 워드임베딩 기능을 편하게 사용할 수 있으니...

word2vec 객체에서 pre-trained 임베딩 벡터를 가져오는데 몇 가지 문제가 생겨서 기록한다.

찾아보니 버전이 3.x 에서 4.x로 업그레이드 되면서 생긴 것들이었다.

 

현재 4.1.2를 사용하고 있음.

  #
  ! pip list | grep gensim  
  
  # gensim                        4.1.2
  #

 

 

1. AttributeError: 'Word2Vec' object has no attribute 'intersect_word2vec_format'

 

intersect_word2vec_format 함수가 Word2Vec 객체의 wv 안으로 들어갔다.

 #
 # 3.x 버전? 
 w2v_model.intersect_word2vec_format('GoogleNews-vectors-negative300.bin.gz', lockf=1.0, binary=True)
 
 # 4.x 버전 
 word2vec_model.wv.intersect_word2vec_format('GoogleNews-vectors-negative300.bin.gz', lockf=1.0, binary=True)  
 #

 

 

2. IndexError: index 32 is out of bounds for axis 0 with size 1

 

1번을 해결하고 돌려보면 다음과 같은 에러가 난다.

IndexError: index 32 is out of bounds for axis 0 with size 1

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/tmp/ipykernel_1173480/3144684932.py in <module>
      2 word2vec_model.build_vocab(corpus)
      3 #word2vec_model.wv.vectors_lockf = np.ones(len(word2vec_model.wv), dtype=np.float32)
----> 4 word2vec_model.wv.intersect_word2vec_format('GoogleNews-vectors-negative300.bin.gz', binary=True)
      5 word2vec_model.train(corpus, total_examples = word2vec_model.corpus_count, epochs = 15)

/usr/local/lib/python3.8/dist-packages/gensim/models/keyedvectors.py in intersect_word2vec_format(self, fname, lockf, binary, encoding, unicode_errors)
   1679                         overlap_count += 1
   1680                         self.vectors[self.get_index(word)] = weights
-> 1681                         self.vectors_lockf[self.get_index(word)] = lockf  # lock-factor: 0.0=no changes
   1682             else:
   1683                 for line_no, line in enumerate(fin):

IndexError: index 32 is out of bounds for axis 0 with size 1

 

에러 로그를 잘 살펴보면 vectors_lockf 리스트 (혹은 array) 인덱스 범위를 넘어서 문제가 생긴다.

vectors_lockf를 살펴보자. 함수는 word2vec.wv 안에 있을 거라 짐작할 수 있다.

 #
 word2vec_model.wv.vectors_lockf  
 # array([1.], dtype=float32)  
 #

 

구글링을 해보면 gensim이 4.x로 업데이트 되면서 유저가 직접 vectors_lockf를 설정하게 둔 것 같다고 말한다. [참조1]

 

밑은 Word2Vec 객체를 초기화할 때 vectors_lockf를 만드는 부분이다.

#
if not hasattr(self, 'wv'):  # set unless subclass already set (eg: FastText)
    self.wv = KeyedVectors(vector_size)
    # EXPERIMENTAL lockf feature; create minimal no-op lockf arrays (1 element of 1.0)
    # advanced users should directly resize/adjust as desired after any vocab growth
    self.wv.vectors_lockf = np.ones(1, dtype=REAL)  # 0.0 values suppress word-backprop-updates; 1.0 allows
#

 

따라서 vectors_lockf를 다음처럼 지정해준다. build_vocab함수 실행 후에 지정해줘야 한다.

#
model.build_vocab(sentences) 
model.wv.vectors_lockf = np.ones(len(model.wv), dtype=np.float32)
#

 

 

 

참조:

 

반응형