我有一个包含键,值对的字典,其中的值是值的列表,如下所示,要添加更多的问题,我需要预测的类概率以及我已制成字典的相应类,并且我想每个课程获得最高的5个概率:
# gets a dictionary of {'class_name': probability}
prob_per_class_dictionary = dict(zip(loaded_model.classes_, probs))
字典如下:
{0: array([9.65109812e-07, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]),
1: array([9.30082941e-07, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]),
2: array([9.42541599e-07, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]),
3: array([9.54675878e-07, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]),
4: array([9.00161937e-07, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]),
5: array([9.33723827e-07, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]),
6: array([9.6553016e-07, 0.0000000e+00, 0.0000000e+00, ..., 0.0000000e+00,
0.0000000e+00, 0.0000000e+00]),
7: array([9.45838933e-07, 0.00000000e+00, 0.00000000e+00, ...,
0.00000000e+00, 0.00000000e+00, 0.00000000e+00]),
我想对字典进行排序,以便对每个键说0:array([前5个值按降序排列])。我尝试了以下将其按升序排序的方法,但我只希望前5个值按降序排列。
for key, v_list in prob_per_class_dictionary.items():
v_list = v_list.sort()`
请让我知道实现这一目标的最简单方法是什么?
我希望我的结果看起来像这样
sorted(zip(loading_model.classes_,probs [0]),key = lambda x:x [1])[-n:] 这样,对于每个班级,我都会获得相应的概率,而对于前5个班级及其各自的概率,则可以获得相应的概率。
`[(1019, 0.02498873845258007),`
`(1421, 0.3491224577864634),`
`(1295, 0.5342553538931459)]`
答案 0 :(得分:-1)
不是最有效的解决方案,但可以解决问题:
v_list.sort()
v_list = v_list.take((-1,-2,-3,-4,-5))