Last active
June 12, 2021 18:36
-
-
Save zhangmozhi/1e37c997514115e9b63476e322ca2ad0 to your computer and use it in GitHub Desktop.
Code for "Are Girls Neko or Shōjo? Cross-Lingual Alignment of Non-Isomorphic Embeddings with Iterative Normalization"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Iterative Normalization""" | |
from argparse import ArgumentParser | |
import numpy as np | |
def load_embed(filename, max_vocab=-1): | |
words, embeds = [], [] | |
with open(filename, 'r') as f: | |
next(f) | |
for line in f: | |
word, vector = line.rstrip().split(' ', 1) | |
vector = np.fromstring(vector, sep=' ') | |
words.append(word) | |
embeds.append(vector) | |
if len(embeds) == max_vocab: | |
break | |
return words, np.array(embeds) | |
def main(): | |
parser = ArgumentParser() | |
parser.add_argument('input_file') | |
parser.add_argument('output_file') | |
parser.add_argument('--normalize', default='renorm,center,renorm,center,renorm,center,renorm,center,renorm,center,renorm', type=str) | |
parser.add_argument('--max_vocab', default=-1, type=int) | |
args = parser.parse_args() | |
words, embeds = load_embed(args.input_file, max_vocab=args.max_vocab) | |
for t in args.normalize.split(','): | |
if t == 'center': | |
embeds -= embeds.mean(axis=0)[np.newaxis, :] | |
elif t == 'renorm': | |
embeds /= np.linalg.norm(embeds, axis=1)[:, np.newaxis] + 1e-8 | |
elif t != '': | |
raise Exception('Unknown normalization type: "%s"' % t) | |
with open(args.output_file, 'w') as f: | |
print >> f, embeds.shape[0], embeds.shape[1] | |
for word, embed in zip(words, embeds): | |
vector_str = ' '.join(`x` for x in embed) | |
print >> f, word, vector_str | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment