gpt4 book ai didi

python - 根据所选值总结和绘制 ndarrays 列表

转载 作者:行者123 更新时间:2023-12-03 20:17:10 25 4
gpt4 key购买 nike

我有一个 ndarray 列表:

list1 = [t1, t2, t3, t4, t5]

每个 t 包括:

t1 = np.array([[10,0.1],[30,0.05],[30,0.1],[20,0.1],[10,0.05],[10,0.05],[0,0.5],[20,0.05],[10,0.0]], np.float64)

t2 = np.array([[0,0.05],[0,0.05],[30,0],[10,0.25],[10,0.2],[10,0.25],[20,0.1],[20,0.05],[10,0.05]], np.float64)

...

现在我想让整个列表为每个 t 获取对应于第一个元素的值的平均值:

t1out = [[0,0.5],[10,(0.1+0.05+0.05+0)/4],[20,(0.1+0.05)/2],[30,0.075]]

t2out = [[0,0.05],[10,0.1875],[20,0.075],[30,0]]

....

在生成 t_1 ... t_n 之后,我想绘制每个 t 的类别概率,其中第一个元素代表类别 (0,10,20,30),第二个元素显示类别的概率这些类出现 (0.1,0.7,0.15,0)。类似于直方图或条形图形式的概率分布,例如:

plt.bar([classes],[probabilities])

plt.bar([item[0] for item in t1out],[item[1] for item in t1out])

最佳答案

这是使用 NumPy 计算的方法:

import numpy as np

def mean_by_class(t, classes=None):
# Classes should be passed if you want to ensure
# that all classes are in the output even if they
# are not in the current t vector
if classes is None:
classes = np.unique(t[:, 0])
bins = np.r_[classes, classes[-1] + 1]
h, _ = np.histogram(t[:, 0], bins)
d = np.digitize(t[:, 0], bins, right=True)
out = np.zeros(len(classes), t.dtype)
np.add.at(out, d, t[:, 1])
out /= h.clip(min=1)
return np.c_[classes, out]

t1 = np.array([[10, 0.1 ], [30, 0.05], [30, 0.1 ],
[20, 0.1 ], [10, 0.05], [10, 0.05],
[ 0, 0.5 ], [20, 0.05], [10, 0.0 ]],
dtype=np.float64)
print(mean_by_class(t1))
# [[ 0. 0.5 ]
# [10. 0.05 ]
# [20. 0.075]
# [30. 0.075]]

附带说明一下,将类值(整数)存储在 float 组中可能不是最佳选择。您可以考虑使用 structured array相反,例如像这样:

import numpy as np

def mean_by_class(t, classes=None):
if classes is None:
classes = np.unique(t['class'])
bins = np.r_[classes, classes[-1] + 1]
h, _ = np.histogram(t['class'], bins)
d = np.digitize(t['class'], bins, right=True)
out = np.zeros(len(classes), t.dtype)
out['class'] = classes
np.add.at(out['p'], d, t['p'])
out['p'] /= h.clip(min=1)
return out

t1 = np.array([(10, 0.1 ), (30, 0.05), (30, 0.1 ),
(20, 0.1 ), (10, 0.05), (10, 0.05),
( 0, 0.5 ), (20, 0.05), (10, 0.0 )],
dtype=[('class', np.int32), ('p', np.float64)])
print(mean_by_class(t1))
# [( 0, 0.5 ) (10, 0.05 ) (20, 0.075) (30, 0.075)]

关于python - 根据所选值总结和绘制 ndarrays 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60525747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com