首页 > 解决方案 > 我无法使用 python 字典中的键获取值

问题描述

我正在使用基于 keras 的“Matchzoo”文本检索库。我想使用经过训练的结果,但它是字典,我无法使用显示的键获取值。

训练模型后,

>>> history = model.fit_generator(train_generator, epochs=1, callbacks=[evaluate], workers=5, use_multiprocessing=False)
Epoch 1/1
17/17 [==============================] - 1s 84ms/step - loss: 1.0864
Validation: normalized_discounted_cumulative_gain@3(0.0): 0.03594548089735716 - normalized_discounted_cumulative_gain@5(0.0): 0.04159539212363794 - mean_average_precision(0.0): 0.044539607256746286

结果在history.history字典中。

>>> history.history
{'loss': [1.2375952883301495],
 mean_average_precision(0.0): [0.02962496886265635],
 normalized_discounted_cumulative_gain@3(0.0): [0.018740542440172665],
 normalized_discounted_cumulative_gain@5(0.0): [0.027987588892336258]}

有 4 个键,当我检查字典的键时我可以看到它们。

>>> history.history.keys()
dict_keys(['loss', normalized_discounted_cumulative_gain@3(0.0), normalized_discounted_cumulative_gain@5(0.0), mean_average_precision(0.0)])

但是当我尝试使用它们时,我不能。

>>> history.history[normalized_discounted_cumulative_gain@3(0.0)]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-9526d848c6d7> in <module>()
----> 1 history.history[normalized_discounted_cumulative_gain@3(0.0)]

NameError: name 'normalized_discounted_cumulative_gain' is not defined

我无法理解的是我可以使用一些键,但不是全部。

>>> history.history['loss']
[1.0869888107353283]
>>> history.history[mean_average_precision(0.0)]
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-43-985db34a9846> in <module>()
----> 1 history.history[mean_average_precision(0.0)]

NameError: name 'mean_average_precision' is not defined

我想知道是不是因为键不是字符串,但它也不起作用。

>>> history.history['mean_average_precision(0.0)']
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-43-985db34a9846> in <module>()
----> 1 history.history[mean_average_precision(0.0)]

NameError: name 'mean_average_precision' is not defined

有人能告诉我为什么以及如何解决这个问题吗?有什么我应该检查的吗?

标签: pythondictionarykeras

解决方案


正如你所说,这可能是因为它们不是字符串。如果您确定这是它们进入的顺序,请尝试使用如下所示的键在字典中进行索引。

history.history[list(history.history.keys())[2]]

history.history[list(history.history.keys())[3]]

ETC..

通过这样做,我们通过让计算机检索对象来避免猜测键的数据类型。

最有可能,normalized_discounted_cumulative_gain@3(0.0)等不是字符串。它们可能是不同类型的对象。如果你想检查它到底是什么,你可以试试这个

type(list(history.history.keys())[2])

这将显示 str 表示“损失”,因为它是一个字符串,而其他字符串则是其他的。如果您尝试这样做,请在评论中评论它是什么类型。


推荐阅读