【发布时间】:2019-02-07 23:45:51
【问题描述】:
我有以下问题。
我得到1-10个标签,与一张图片相关,每个标签都有一个存在于图片中的概率。
输入:海滩、女人、狗、树……
我想从数据库中检索与标签最相关的已经组成的句子。
例如:
beach -> “在 beach 玩得开心” / “在 beach 放松一下” ....
beach, woman -> “woman at the beach”
海滩,女人,狗 - > 没有找到!
取最接近的存在但考虑概率 可以说:女人 0.95,海滩 0.85,狗 0.7 所以如果存在取女人+海滩(0.95,0.85)然后女人+狗和最后一个海滩+狗,顺序是越高越好,但我们不求和。
我曾想过使用 python sets,但我不确定如何使用。
另一个选项将是 defaultdict:
db['beach']['woman']['dog'],但我也想从以下位置获得相同的结果: db['woman']['beeach']['dog']
我想得到一个很好的解决方案。 谢谢。
编辑:工作解决方案
from collections import OrderedDict
list_of_keys = []
sentences = OrderedDict()
sentences[('dogs',)] = ['I like dogs','dogs are man best friends!']
sentences[('dogs', 'beach')] = ['the dog is at the beach']
sentences[('woman', 'cafe')] = ['The woman sat at the cafe.']
sentences[('woman', 'beach')] = ['The woman was at the beach']
sentences[('dress',)] = ['hi nice dress', 'what a nice dress !']
def keys_to_list_of_sets(dict_):
list_of_keys = []
for key in dict_:
list_of_keys.append(set(key))
return list_of_keys
def match_best_sentence(image_tags):
for i, tags in enumerate(list_of_keys):
if (tags & image_tags) == tags:
print(list(sentences.keys())[i])
list_of_keys = keys_to_list_of_sets(sentences)
tags = set(['beach', 'dogs', 'woman'])
match_best_sentence(tags)
结果:
('dogs',)
('dogs', 'beach')
('woman', 'beach')
此解决方案运行有序字典的所有键, o(n),我希望看到任何性能改进。
【问题讨论】:
-
据我了解您的问题,您不知道选择什么数据结构来存储标签对?
-
数据库有多大?它包含多少个句子和关键词?它是静态的还是动态变化的添加和删除新句子?
-
静态,不变。
-
1000 句,还在不断增加中……
-
@SamperMan 我真的不知道我不知道什么。我没有适合存储和检索的解决方案。
标签: python database search set