如何从此请求中获取所需的值?

时间:2017-08-21 23:01:41

标签: python watson

我正在使用rest api模型提出以下请求:

def predict(path):
    with open(path) as img:
            res = vr.classify(images_file=img, threshold=0, classifier_ids=['food'])
            print res

当我运行我的脚本时,我得到:

{u'images': [{u'image': u'/tacos.jpg', u'classifiers': [{u'classes': [{u'score': 0.0495783, u'class': u'pizza'}, {u'score': 0.553117, u'class': u'tacos'}], u'classifier_id': u'food', u'name': u'food-test'}]}], u'custom_classes': 2, u'images_processed': 1}

但是我想获得具有更高价值的课程如下:

this is the corresponding class: tacos

所以我想感谢支持修改我的功能以获得所需的输出

2 个答案:

答案 0 :(得分:1)

这是一本字典,所以你可以遍历这些课程'并找到最高分。

免责声明:我不是python2或watson用户。

访问课程

res['images'][0]['classifiers'][0]['classes']

所以迭代这些类......

highest_class = ['', 0]
for class in res['images'][0]['classifiers'][0]['classes']:
    if class['score'] > highest_class[1]:
        highest_class = [class['class'], [class['score']
print "this is the corresponding class: " + highest_class[0]

当然,如果你有超过1个分类器,你必须有另一个外部for循环来遍历分类器(如果你需要这个功能)

答案 1 :(得分:1)

如何使用python-native sorted函数,为每个分类器的id获取更高的值?使用(太)大对象名称​​以便清楚,并避免代码打高尔夫球,您可能需要执行以下操作

def predict(path):
    with open(path) as img:
        res = vr.classify(images_file=img, threshold=0, classifier_ids=['food'])

        dict_of_higher_value_per_ = {} # in order to record and reuse values sooner or later.
        for image in res['images']:
            for classifier in image['classifiers']:
                classes       = classifier['classes']
                classifier_id = classifier['classifier_id']
                sorted_scores = sorted(classes, 
                                       key=lambda class_:class_['score'],
                                       reverse=True)
                best_match    = sorted_scores[0] # which corresponds to the best score since elements are sorted.
                dict_of_higher_value_per_[classifier_id] = best_match

                print "Classifier '{cid}' says this is the corresponding class: {class}".format(cid=classifier_id,
                                                                                                **best_match)

打印

Classifier 'food' says this is the corresponding class: tacos