wordsim.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2016 Google Inc. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Computes Spearman's rho with respect to human judgements.
  17. Given a set of row (and potentially column) embeddings, this computes Spearman's
  18. rho between the rank ordering of predicted word similarity and human judgements.
  19. Usage:
  20. wordim.py --embeddings=<binvecs> --vocab=<vocab> eval1.tab eval2.tab ...
  21. Options:
  22. --embeddings=<filename>: the vectors to test
  23. --vocab=<filename>: the vocabulary file
  24. Evaluation files are assumed to be tab-separated files with exactly three
  25. columns. The first two columns contain the words, and the third column contains
  26. the scored human judgement.
  27. """
  28. import scipy.stats
  29. import sys
  30. from getopt import GetoptError, getopt
  31. from vecs import Vecs
  32. try:
  33. opts, args = getopt(sys.argv[1:], '', ['embeddings=', 'vocab='])
  34. except GetoptError, e:
  35. print >> sys.stderr, e
  36. sys.exit(2)
  37. opt_embeddings = None
  38. opt_vocab = None
  39. for o, a in opts:
  40. if o == '--embeddings':
  41. opt_embeddings = a
  42. if o == '--vocab':
  43. opt_vocab = a
  44. if not opt_vocab:
  45. print >> sys.stderr, 'please specify a vocabulary file with "--vocab"'
  46. sys.exit(2)
  47. if not opt_embeddings:
  48. print >> sys.stderr, 'please specify the embeddings with "--embeddings"'
  49. sys.exit(2)
  50. try:
  51. vecs = Vecs(opt_vocab, opt_embeddings)
  52. except IOError, e:
  53. print >> sys.stderr, e
  54. sys.exit(1)
  55. def evaluate(lines):
  56. acts, preds = [], []
  57. with open(filename, 'r') as lines:
  58. for line in lines:
  59. w1, w2, act = line.strip().split('\t')
  60. pred = vecs.similarity(w1, w2)
  61. if pred is None:
  62. continue
  63. acts.append(float(act))
  64. preds.append(pred)
  65. rho, _ = scipy.stats.spearmanr(acts, preds)
  66. return rho
  67. for filename in args:
  68. with open(filename, 'r') as lines:
  69. print '%0.3f %s' % (evaluate(lines), filename)