tensorflow-hub - 如何使用 TF Hub 模块找到最接近的单词?
问题描述
如果嵌入之间的 np.inner 返回它们的相似性。如何从一个词嵌入中找到最接近的词?我正在使用 Wiki 模块。
解决方案
您可以执行以下操作:
# Download 10k most popular english words.
import urllib2
response = urllib2.urlopen('https://raw.githubusercontent.com/first20hours/google-10000-english/master/google-10000-english-no-swears.txt')
words = response.read().split("\n")
# Compute the embedding for 10k words.
with tf.Graph().as_default():
embed = hub.Module("https://tfhub.dev/google/Wiki-words-250/1")
embeddings = embed(words)
with tf.train.MonitoredSession() as sess:
values = sess.run(embeddings)
data = dict(zip(words, values))
def get_neighbors(all_data, target, count=3):
# Compute points in all_data that are the closest to "target".
# Sort the words based on the length of the vector between them.
# Then pick "count" closest ones.
return sorted(all_data, key=lambda emb_key: np.linalg.norm(all_data[emb_key] - target))[:count]
# Then make queries of your choice, e.g.
print(get_neighbors(data, data["first"]))
# Prints ['first', 'second', 'third']
print(get_neighbors(data, data["woman"] - data["man"] + data["father"], count=10))
# Prints ['mother', 'father', 'wife', 'daughter', 'wed', 'husband', 'uncle', 'son', 'child', 'mistress']
推荐阅读
- bash - 在 conda 环境中,当我关闭终端时,GNU 并行作业停止启动新作业
- html - 使用 CSS 网格垂直扩展网格模板行时遇到问题
- css - 将主题变量的值传递给Angular中的子组件
- java - 如何覆盖父类中的方法并在子类中执行?
- android - 较低的 TextInputEditText 键入时不显示文本,仅在完成(或)下一个操作(或)点击屏幕中的任意位置时显示
- php - FilePond 向服务器发送一个空白请求
- typescript - 为什么我不能将类分配给具有较少属性的类型?
- python - 为什么使用玉米的预定工作在 Django 中不起作用?
- javascript - 一个简单的幻灯片是什么样的
- amazon-web-services - 没有任何过滤模式的 AWS CLI cloudwatch 日志订阅