Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added Word2vec to Tensorflow 2D tensor file #1051

Merged
merged 11 commits into from
Dec 22, 2016
86 changes: 86 additions & 0 deletions gensim/scripts/word2vec2tensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Missing license (LGPL, like the rest of gensim). @tmylk @loretoparisi

# Copyright (C) 2016 Loreto Parisi <loretoparisi@gmail.com>
# Copyright (C) 2016 Silvio Olivastri <silvio.olivastri@gmail.com>
# Copyright (C) 2016 Radim Rehurek <radim@rare-technologies.com>

"""
USAGE: $ python -m gensim.scripts.word2vec2tensor --input <Word2Vec model file> --output <TSV tensor filename prefix> [--binary] <Word2Vec binary flag>
Where:
<Word2Vec model file>: Input Word2Vec model
<TSV tensor filename prefix>: 2D tensor TSV output file name prefix
<Word2Vec binary flag>: Set True if Word2Vec model is binary. Defaults to False.
Output:
The script will create two TSV files. A 2d tensor format file, and a Word Embedding metadata file. Both files will
us the --output file name as prefix
This script is used to convert the word2vec format to Tensorflow 2D tensor and metadata formats for Embedding Visualization
To use the generated TSV 2D tensor and metadata file in the Projector Visualizer, please
1) Open http://projector.tensorflow.org/.
2) Choose "Load Data" from the left menu.
3) Select "Choose file" in "Load a TSV file of vectors." and choose you local "_tensor.tsv" file
4) Select "Choose file" in "Load a TSV file of metadata." and choose you local "_metadata.tsv" file

For more information about TensorBoard TSV format please visit:
https://www.tensorflow.org/versions/master/how_tos/embedding_viz/

"""

import os
import sys
import random
import logging
import argparse

import gensim

logger = logging.getLogger(__name__)

def word2vec2tensor(word2vec_model_path,tensor_filename, binary=False):
'''
Convert Word2Vec mode to 2D tensor TSV file and metadata file
Args:
param1 (str): word2vec model file path
param2 (str): filename prefix
param2 (bool): set True to use a binary Word2Vec model, defaults to False
'''
model = gensim.models.Word2Vec.load_word2vec_format(word2vec_model_path, binary=binary)
outfiletsv = tensor_filename + '_tensor.tsv'
outfiletsvmeta = tensor_filename + '_metadata.tsv'

with open(outfiletsv, 'w+') as file_vector:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use smart_open instead.

with open(outfiletsvmeta, 'w+') as file_metadata:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Dtto.

for word in model.index2word:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use model.wv.index2word

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fixed.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did this change get overwritten?

file_metadata.write(word.encode('utf-8') + '\n')
vector_row = '\t'.join(map(str, model[word]))
file_vector.write(vector_row + '\n')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please log the location and name of the written files.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I have added further instructions and logging.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done thanks.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had an error occurring at line 54. TypeError: can't concat str to bytes


logger.info("2D tensor file saved to %s" % outfiletsv)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@tmylk little nitpick, but for the future, prefer logger.xyz("log %s", something), not logger.xyz("log %s" % something) (use lazy argument formatting).

logger.info("Tensor metadata file saved to %s" % outfiletsvmeta)

if __name__ == "__main__":
logging.basicConfig(format='%(asctime)s : %(threadName)s : %(levelname)s : %(message)s', level=logging.INFO)
logging.root.setLevel(level=logging.INFO)
logger.info("running %s", ' '.join(sys.argv))

# check and process cmdline input
program = os.path.basename(sys.argv[0])
if len(sys.argv) < 2:
print(globals()['__doc__'] % locals())
sys.exit(1)

parser = argparse.ArgumentParser()
parser.add_argument(
"-i", "--input", required=True,
help="Input word2vec model")
parser.add_argument(
"-o", "--output", required=True,
help="Output tensor file name prefix")
parser.add_argument( "-b", "--binary",
Copy link
Owner

@piskvorky piskvorky Dec 26, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No vertical indent in gensim -- use normal hanging indent.

required=False,
help="If word2vec model in binary format, set True, else False")
args = parser.parse_args()

word2vec2tensor(args.input, args.output, args.binary)

logger.info("finished running %s", program)