将字典值转换为列表并取平均值

时间:2020-05-02 14:28:15

标签: python

我正在尝试从某个字典键中提取值并取这些值的平均值。我的字典的输出称为scores:

{
    'fit_time':       array([0.36260605, 0.36630321, 0.28634191, 0.29873514, 0.15965009]),
    'score_time':     array([0.02901483, 0.03418779, 0.03244114, 0.03267598, 0.01934624]),
    'test_acc':       array([0.83928571, 0.83928571, 0.81785714, 0.84464286, 0.83928571]),
    'train_acc':      array([0.90580357, 0.91071429, 0.90982143, 0.90625, 0.90758929]),
    'test_log_loss':  array([-0.38442156, -0.37268129, -0.37284406, -0.37891302, -0.43271307]),
    'train_log_loss': array([-0.23096467, -0.2320267, -0.23016542, -0.23322982, -0.22868747]),
    'test_recall':    array([0.32323232, 0.35353535, 0.27272727, 0.33333333, 0.23469388]),
     'train_recall':  array([0.55443038, 0.56962025, 0.54683544, 0.55696203, 0.55050505])
}

例如,用于隔离test accuracy的代码如下:

accuracy.append(list(scores["test_acc"]))

这给了我

[[0.8392857142857143, 0.8392857142857143, 0.8178571428571428, 0.8446428571428571, 0.8392857142857143]]

但是为什么我尝试通过mean(accuracy)来理解这个意思,我得到了这个错误:

TypeError:无法将类型“列表”转换为分子/分母

任何建议都非常感谢!

1 个答案:

答案 0 :(得分:0)

这是因为有双[[,您可以通过选择数组中的第一个数组来解决此问题,

Ranvijays-Mac:djangodemo rana.singh$ python3 manage.py migrate --run-syncdb
Operations to perform:
  Synchronize unmigrated apps: messages, staticfiles
  Apply all migrations: admin, auth, contenttypes, msg, sessions
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
Running migrations:
  Applying msg.0001_initial... OK

返回import statistics listOfAccuracy = [[0.8392857142857143, 0.8392857142857143, 0.8178571428571428, 0.8446428571428571, 0.8392857142857143]] print(statistics.mean(listOfAccuracy[0]))