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
80 changes: 80 additions & 0 deletions gensim/scripts/word2vec2tensor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
#!/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>
Where:
<Word2Vec model file>: Input Word2Vec model
<TSV tensor filename prefix>: 2D tensor TSV output file name prefix
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):
'''
Convert Word2Vec mode to 2D tensor TSV file and metadata file
@word2vec_model_path word2vec model
@tensor_filename tensor filename prefix
'''
model = gensim.models.Word2Vec.load_word2vec_format(word2vec_model_path, binary=True)
Copy link
Contributor

Choose a reason for hiding this comment

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

Better use text format here, or make it optional atleast

Copy link
Contributor

Choose a reason for hiding this comment

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

You can ask for format as optional like,
parser.add_argument( "-b", "--binary", required=False, help="If word2vec model in binary format, set True, else False ")
and pass the argument to word2vec2tensor function
def word2vec2tensor(word2vec_model_path,tensor_filename, binary=False):
model = gensim.models.Word2Vec.load_word2vec_format(word2vec_model_path, binary=binary)

keeping text format as default

Copy link
Contributor Author

Choose a reason for hiding this comment

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

All done thanks.

Copy link
Contributor

@parulsethi parulsethi Dec 21, 2016

Choose a reason for hiding this comment

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

Sorry, forgot this earlier, space before tensor_filename in def word2vec2tensor()

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")
args = parser.parse_args()

word2vec2tensor(args.input, args.output)

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