After creating word vectors in Gensim 2.2.0 from plain English text files with IMDB movie ratings:
import gensim, logging
import smart_open, os
from nltk.tokenize import RegexpTokenizer
VEC_SIZE = 300
MIN_COUNT = 5
WORKERS = 4
data_path = './data/'
vectors_path = 'vectors.bin.gz'
class AllSentences(object):
def __init__(self, dirname):
self.dirname = dirname
self.read_err_cnt = 0
self.tokenizer = RegexpTokenizer('[\'a-zA-Z]+', discard_empty=True)
def __iter__(self):
for fname in os.listdir(self.dirname):
print(fname)
for line in open(os.path.join(self.dirname, fname)):
words = []
try:
for word in self.tokenizer.tokenize(line):
words.append(word)
yield words
except:
self.read_err_cnt += 1
sentences = AllSentences(data_path)
Training and saving model:
model = gensim.models.Word2Vec(sentences, size=VEC_SIZE,
min_count=MIN_COUNT, workers=WORKERS)
word_vectors = model.wv
word_vectors.save(vectors_path)
And then trying to load it back:
vectors = KeyedVectors.load_word2vec_format(vectors_path,
binary=True,
unicode_errors='ignore')
I get 'UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0' exception (see below). I tried different combinations of 'encoding' parameters including 'ISO-8859-1' and 'Latin1'. Also different combinations of 'binary=True/False'. Nothing helps - the same exception, no matter what parameters are used. What is wrong? How to make loading vectors work?
Exception:
UnicodeDecodeError Traceback (most recent call last)
<ipython-input-64-f353fa49685c> in <module>()
----> 1 w2v = get_w2v_vectors()
<ipython-input-63-cbbe0a76e837> in get_w2v_vectors()
3 vectors = KeyedVectors.load_word2vec_format(word_vectors_path,
4 binary=True,
----> 5 unicode_errors='ignore')
6
7 #unicode_errors='ignore')
D:\usr\anaconda\lib\site-packages\gensim\models\keyedvectors.py in load_word2vec_format(cls, fname, fvocab, binary, encoding, unicode_errors, limit, datatype)
204 logger.info("loading projection weights from %s", fname)
205 with utils.smart_open(fname) as fin:
--> 206 header = utils.to_unicode(fin.readline(), encoding=encoding)
207 vocab_size, vector_size = map(int, header.split()) # throws for invalid file format
208 if limit:
D:\usr\anaconda\lib\site-packages\gensim\utils.py in any2unicode(text, encoding, errors)
233 if isinstance(text, unicode):
234 return text
--> 235 return unicode(text, encoding, errors=errors)
236 to_unicode = any2unicode
237
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte