본문 바로가기

명사 美 비격식 (무리 중에서) 아주 뛰어난[눈에 띄는] 사람[것]

AI/NLP

Model load error. Was model saved using code from an older Gensim Version? Python과 gensim의 버전문제 key_to_index 버전에 영향을 덜받도록 key를 숫자화해 사용하기

 

실행하는데 어러가났다. 

Model load error. Was model saved using code from an older Gensim Version?

발견된 ko.bin 경로: ['/content/models/ko.bin', '/content/models/ko.bin']
사용할 ko.bin 경로: /content/models/ko.bin

ERROR:gensim.models.word2vec:Model load error. Was model saved using code from an older Gensim Version? Try loading older model using gensim-3.8.3, then re-saving, to restore compatibility with current code.
Word2Vec.load 실패: 'Word2Vec' object has no attribute 'wv'
binary=True 로딩 실패: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
모든 로딩 방식 실패: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

 

 

 

 

해결방법을 알아보니 파이썬과 gensim의 버전문제. 파이썬을 다운그레이드해야.

코드는 오래됐고, 파이썬은 너무 최신이라 컴파일이 안 됨

Collecting gensim==3.8.3
  Downloading gensim-3.8.3.tar.gz (23.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 23.4/23.4 MB 42.5 MB/s eta 0:00:0000:0100:01
  Preparing metadata (setup.py) ... done
Requirement already satisfied: numpy>=1.11.3 in /usr/local/lib/python3.12/dist-packages (from gensim==3.8.3) (2.0.2)
Requirement already satisfied: scipy>=0.18.1 in /usr/local/lib/python3.12/dist-packages (from gensim==3.8.3) (1.16.3)
Requirement already satisfied: six>=1.5.0 in /usr/local/lib/python3.12/dist-packages (from gensim==3.8.3) (1.17.0)
Requirement already satisfied: smart_open>=1.8.1 in /usr/local/lib/python3.12/dist-packages (from gensim==3.8.3) (7.6.1)
Requirement already satisfied: wrapt in /usr/local/lib/python3.12/dist-packages (from smart_open>=1.8.1->gensim==3.8.3) (2.2.1)
Building wheels for collected packages: gensim
  error: subprocess-exited-with-error
  
  × python setup.py bdist_wheel did not run successfully.
  │ exit code: 1
  ╰─> See above for output.
  
  note: This error originates from a subprocess, and is likely not a problem with pip.
  Building wheel for gensim (setup.py) ...   ERROR: Failed building wheel for gensim
  Running setup.py clean for gensim
Failed to build gensim
ERROR: ERROR: Failed to build installable wheels for some pyproject.toml based projects (gensim)

 

 

 

 

실제 파일 다운.

https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?resourcekey=0-wjGZdNAUop6WykTtMip30g

 

GoogleNews-vectors-negative300.bin.gz

 

drive.google.com

 

 

 

g 드라이브에 업로드.

 

 

 

 

가져와 압축풀기

from google.colab import drive
drive.mount('/content/drive')
from gensim.models import KeyedVectors

import gzip
import shutil
gz_path = "/content/drive/MyDrive/data/GoogleNews-vectors-negative300.bin.gz"
bin_path = "/content/drive/MyDrive/data/GoogleNews-vectors-negative300.bin"

# 이미 풀려 있으면 스킵
if not os.path.exists(bin_path):
    print("압축 해제 시작...")

    with gzip.open(gz_path, 'rb') as f_in:
        with open(bin_path, 'wb') as f_out:
            shutil.copyfileobj(f_in, f_out)

    print("압축 해제 완료:", bin_path)
else:
    print("이미 bin 파일 존재:", bin_path)
from gensim.models import KeyedVectors
pretrained_model = KeyedVectors.load_word2vec_format(
    bin_path,
    binary=True
)

print("로드 성공!")

 

 

 

 

list(pretrained_model.key_to_index.keys())[:50

 

 

 

모델 맞춰주기

pretrained_vectors = pretrained_model

 

 

 

 

 

코드수정

원래 코드 if pretrained_vectors is not None and query_word in pretrained_vectors:에 .key_to_index를 붙였다. 

원래 코드는 'a' in ['a', 'b', 'c'] 를 묻는데

WOrd2Vec 모델 안에서는 단어 - 벡터가 저장되어있어 

{
    "king": [0.12, 0.45, ...],
    "queen": [0.78, 0.23, ...],
    "man": [0.44, 0.11, ...]
} 와 같은 구조.

예전에는 가능한 코드였지만 최신 gensim에서 객체를 사용하는 경우가 더 많다 . 애매한 방식보다 단어를 번호로 저장해서 직접 검사하는것. 

버전영향이 적다 .

# # 검색할 기준 단어를 지정합니다.
# query_word = 'for'

# # 사전학습 벡터가 준비되었고 기준 단어가 모델 어휘에 있는지 확인합니다.
# if pretrained_vectors is not None and query_word in pretrained_vectors:
#     # 기준 단어와 유사한 단어 10개를 검색합니다.
#     similar_words = pretrained_vectors.most_similar(query_word, topn=10)

#     # 검색 결과를 출력합니다.
#     print(f'[{query_word}]와 유사한 단어:')
#     for word, score in similar_words:
#         print(word, score)
# else:
#     # 모델이 없거나 단어가 없을 때 안내 메시지를 출력합니다.
#     print(f'사전학습 모델이 없거나 [{query_word}] 단어가 모델 어휘에 없습니다.')
#     print('이 경우 9번 셀의 직접 학습 모델로 실습을 진행하세요.')


query_word = "for"

if (
    pretrained_vectors is not None
    and query_word in pretrained_vectors.key_to_index
):
    similar_words = pretrained_vectors.most_similar(
        query_word,
        topn=10
    )

    print(f"[{query_word}]와 유사한 단어:")

    for word, score in similar_words:
        print(word, score)

else:
    print(f"{query_word} 없음")

 

 

 

 완료.