[英]Making a dictionary having multiple keys using for loop
I have a dictionary of metric names.我有一个指标名称字典。
metrics = {
'accuracy': accuracy,
'loss': loss
}
I want to create another dictionary that stores the values of the metrics for a set of hierarchical labels.我想创建另一个字典来存储一组分层标签的度量值。 The dictionary is supposed to be something like this:字典应该是这样的:
{'c1_accuracy': 0.84, 'c1_loss': 5.67, 'c2_loss': 8.78, 'c2_accuracy': 0.73}
I am trying to use something like this我正在尝试使用这样的东西
summary_batch = {'c1_{}'.format(metric): metrics['metric'](c1_output, c1_label) for metric in metrics}
How can I do it for all the labels (c1, c2, ...) at once?如何一次为所有标签(c1,c2,...)执行此操作?
Edit: I am trying to solve a hierarchical classification problem where I have two coarse classes (let's say c1 and c2) and one fine class (f).编辑:我正在尝试解决一个层次分类问题,其中我有两个粗略的类(比如说 c1 和 c2)和一个精细的 class(f)。 metrics
dictionary is just used to store the metrics which are used in the training and evaluation loops. metrics
字典仅用于存储在训练和评估循环中使用的指标。 I have separate functions for calculating the metric values.我有单独的函数来计算度量值。 In the above example, metrics['metric'](c1_output, c1_label) for metric in metrics
will call the accuracy
and loss
functions for the true labels ( c1_label
) and model output ( c1_output
).在上面的示例中, metrics['metric'](c1_output, c1_label) for metric in metrics
将调用真实标签 ( c1_label
) 和 model output ( c1_output
) 的accuracy
和loss
函数。
I want to store these metrics for both coarse classes and the fine class.我想为粗略类和精细 class 存储这些指标。 Is there a way I can do that without using add or writing separate loops for each class?有没有一种方法可以做到这一点,而无需为每个 class 使用添加或编写单独的循环?
It would be interesting to know how you obtain the values to fill the dictionary in order to do it while creating it, however, you can create it empty with this loop知道如何获取值以填充字典以便在创建字典时执行它会很有趣,但是,您可以使用此循环将其创建为空
metrics = {}
for n in range(10):
key_constructor = 'c{}_{}'
key_acc = key_constructor.format(n,'accuracy')
key_loss = key_constructor.format(n,'loss')
metrics[key_acc] = 0
metrics[key_loss] = 0
If you want to have a hierarchy why not using a nested dict?如果你想有一个层次结构,为什么不使用嵌套字典?
summuary_batch = {
"c1": {
"accuracy": xxx,
"loss": yyy,
},
"c2": {
"accuracy": zzz,
"loss": ttt,
},
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.