将word2vec bin文件转换为文本

从word2vec网站,我可以下载GoogleNews-vectors-negative300.bin.gz。 .bin文件(大约3.4GB)是对我无用的二进制格式。 Tomas Mikolov 向我们保证 :“将二进制格式转换为文本格式应该相当简单(尽pipe这会占用更多的磁盘空间)。检查距离工具中的代码,读取二进制文件相当简单。 不幸的是,我不知道C了解http://word2vec.googlecode.com/svn/trunk/distance.c 。

据说gensim也可以做到这一点,但我发现的所有教程似乎是文本转换,而不是其他方式。

有人可以build议修改C代码或说明gensim发出文字?

我使用这个代码来加载二进制模型,然后将模型保存到文本文件,

from gensim.models.keyedvectors import KeyedVectors model = KeyedVectors.load_word2vec_format('path/to/GoogleNews-vectors-negative300.bin', binary=True) model.save_word2vec_format('path/to/GoogleNews-vectors-negative300.txt', binary=False) 

参考: API和nullege 。

注意:

以上代码是针对gensim的版本。 对于以前的版本,我使用这个代码

 from gensim.models import word2vec model = word2vec.Word2Vec.load_word2vec_format('path/to/GoogleNews-vectors-negative300.bin', binary=True) model.save_word2vec_format('path/to/GoogleNews-vectors-negative300.txt', binary=False) 

在word2vec-toolkit邮件列表中,Thomas Mensink以小C程序的forms提供了一个答案 ,该程序将把.bin文件转换为文本。 这是distance.c文件的修改。 我用下面的Thomas代码replace了原始的distance.c,并重build了word2vec(make clean; make),并将编译的距离重命名为readbin。 然后./readbin vector.bin将创build./readbin vector.bin的文本版本。

 // Copyright 2013 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <stdio.h> #include <string.h> #include <math.h> #include <malloc.h> const long long max_size = 2000; // max length of strings const long long N = 40; // number of closest words that will be shown const long long max_w = 50; // max length of vocabulary entries int main(int argc, char **argv) { FILE *f; char file_name[max_size]; float len; long long words, size, a, b; char ch; float *M; char *vocab; if (argc < 2) { printf("Usage: ./distance <FILE>\nwhere FILE contains word projections in the BINARY FORMAT\n"); return 0; } strcpy(file_name, argv[1]); f = fopen(file_name, "rb"); if (f == NULL) { printf("Input file not found\n"); return -1; } fscanf(f, "%lld", &words); fscanf(f, "%lld", &size); vocab = (char *)malloc((long long)words * max_w * sizeof(char)); M = (float *)malloc((long long)words * (long long)size * sizeof(float)); if (M == NULL) { printf("Cannot allocate memory: %lld MB %lld %lld\n", (long long)words * size * sizeof(float) / 1048576, words, size); return -1; } for (b = 0; b < words; b++) { fscanf(f, "%s%c", &vocab[b * max_w], &ch); for (a = 0; a < size; a++) fread(&M[a + b * size], sizeof(float), 1, f); len = 0; for (a = 0; a < size; a++) len += M[a + b * size] * M[a + b * size]; len = sqrt(len); for (a = 0; a < size; a++) M[a + b * size] /= len; } fclose(f); //Code added by Thomas Mensink //output the vectors of the binary format in text printf("%lld %lld #File: %s\n",words,size,file_name); for (a = 0; a < words; a++){ printf("%s ",&vocab[a * max_w]); for (b = 0; b< size; b++){ printf("%f ",M[a*size + b]); } printf("\b\b\n"); } return 0; } 

我从printf删除了“\ b \ b”。

顺便说一下,结果文本文件仍然包含文本字和一些不必要的空白,我不希望进行一些数值计算。 我用bash命令删除了每行的初始文本列和尾随空白。

 cut --complement -d ' ' -f 1 GoogleNews-vectors-negative300.txt > GoogleNews-vectors-negative300_tuples-only.txt sed 's/ $//' GoogleNews-vectors-negative300_tuples-only.txt 

格式是IEEE 754单精度二进制浮点格式:binary32 http://en.wikipedia.org/wiki/Single-precision_floating-point_format它们使用little-endian。;

举个例子:

  • 第一行是string格式:“3000000 300 \ n”(vocabSize&vecSize,getByte到byte =='\ n')
  • 下一行首先包括词汇单词,然后(300 * 4字节的浮点值,每个维度4个字节):

     getByte till byte==32 (space). (60 47 115 62 32 => <\s>[space]) 
  • 那么每个下一个4字节将代表一个浮点数

    接下来的4字节:0 0 -108 58 => 0.001129150390625。

你可以查看维基百科链接,看看如何让我做这个例子:

(小尾 – >倒序)00111010 10010100 00000000 00000000

  • 首先是符号位=>符号= 1(否则= -1)
  • 接下来的8位=> 117 => exp = 2 ^(117-127)
  • 接下来的23位=> pre = 0 * 2 ^( – 1)+ 0 * 2 ^( – 2)+ 1 * 2 ^( – 3)+ 1 * 2 ^( – 5)

值= sign * exp * pre

您可以在word2vec中加载二进制文件,然后像这样保存文本版本:

 from gensim.models import word2vec model = word2vec.Word2Vec.load_word2vec_format('Path/to/GoogleNews-vectors-negative300.bin', binary=True) model.save("file.txt") 

`

我正在使用gensim来处理GoogleNews-vectors-negative300.bin,并在加载模型时join了binary = True标志。

 from gensim import word2vec model = word2vec.Word2Vec.load_word2vec_format('Path/to/GoogleNews-vectors-negative300.bin', binary=True) 

似乎工作正常。

我有一个类似的问题,我想要bin / non-bin(gensim)模型输出为CSV。

这里是python的代码,它假定你已经安装了gensim:

https://gist.github.com/dav009/10a742de43246210f3ba

这是我使用的代码:

 import codecs from gensim.models import Word2Vec def main(): path_to_model = 'GoogleNews-vectors-negative300.bin' output_file = 'GoogleNews-vectors-negative300_test.txt' export_to_file(path_to_model, output_file) def export_to_file(path_to_model, output_file): output = codecs.open(output_file, 'w' , 'utf-8') model = Word2Vec.load_word2vec_format(path_to_model, binary=True) print('done loading Word2Vec') vocab = model.vocab for mid in vocab: #print(model[mid]) #print(mid) vector = list() for dimension in model[mid]: vector.append(str(dimension)) #line = { "mid": mid, "vector": vector } vector_str = ",".join(vector) line = mid + "\t" + vector_str #line = json.dumps(line) output.write(line + "\n") output.close() if __name__ == "__main__": main() #cProfile.run('main()') # if you want to do some profiling 

convertvec是一个小工具,用于在word2vec库的不同格式之间转换vector。

将vector从二进制转换为纯文本:

./convertvec bin2txt input.bin output.txt

将vector从纯文本转换为二进制文件:

./convertvec txt2bin input.txt output.bin

现在只是一个快速更新,更简单的方法。

如果您使用的是https://github.com/dav/word2vec中的; word2vec ,还有一个名为-binary选项,它接受1生成二进制文件或者生成文本文件0 。 这个例子来自demo-word.sh在回购:

time ./word2vec -train text8 -output vectors.bin -cbow 1 -size 200 -window 8 -negative 25 -hs 0 -sample 1e-4 -threads 20 -binary 0 -iter 15

如果你得到错误:

 ImportError: No module named models.word2vec 

那么这是因为有一个API更新。 这将工作:

 from gensim.models.keyedvectors import KeyedVectors model = KeyedVectors.load_word2vec_format('./GoogleNews-vectors-negative300.bin', binary=True) model.save_word2vec_format('./GoogleNews-vectors-negative300.txt', binary=False)