为什么 `np.mean(x.flatten()==y)` 的结果与 `np.mean(x==y)` 的结果不同?

当我在做机器学习实验并计算准确率时,我发现了一些奇怪的事情。

np.mean(scores.flatten()==y) 的结果与 np.mean(scores==y) 的结果不同?

是因为形状差异吗?

enter image description here

enter image description here

enter image description here

enter image description here

y:[-1 1 -1 -1 1 1 1 -1 -1 -1 -1 -1 -1 -1 1 1 1 -1 1 1 1 -1 1 11 -1 -1 1 1 1 1 -1 1 1 -1 -1 1 -1 -1 -1 -1 1 1 -1 1 1 1 1-1 1 1 1 -1 -1 -1 -1 1 1 -1 1 1 -1 -1 -1 -1 -1 -1 -1 -1 -1 1 -1-1 -1 1 -1 1 1 1 1 -1 -1 1 -1 ]scores:[-1. -1. -1. -1. 1. 1. 1. -1. 1. -1. -1. -1. 1. -1. 1. 1. 1. -1. 1. 1. 1. -1. 1. 1. 1. 1. -1. 1. 1. -1. 1. -1. 1. 1. -1. -1.-1. -1. -1. -1. -1. 1. -1. -1. 1. 1. 1. 1. -1. 1. -1. 1. 1. -1 -1. -1. 1. 1. 1. 1. 1. 1. -1. ]


回答:

嗯,我认为问题在于形状,或者更准确地说,是广播(broadcasting)如何工作的。基本上,你将 scores 的第一个值与 y 的整个数组进行比较,scores 的第二个值与 y 的整个数组进行比较,以此类推。

一个简单的例子 – 200 个随机整数 [1…10],在两个形状不同的数组中,所以应该期望其中一些是相等的,但由于广播规则,平均值会有所不同

import numpy as nprng = np.random.default_rng(312345)q = np.reshape(rng.integers(0, 10, size=200), (-1, 1)) # 形状为 (200,1) 的数组t = rng.integers(0, 10, size=200) # 形状为 (200,) 的数组z = q.flatten() # q 数组中的值,形状为 (200,)print(np.mean(z == t))print(np.mean(q == t))print("---------------------------------")print(q.shape)print(z.shape)print(t.shape)print("---------------------------------")print(len(z == t))print(len((q == t).flatten()))

它会打印出

0.10.0998---------------------------------(200, 1)(200,)(200,)---------------------------------20040000

看到最后一行了吗?由于广播,你有 200*200 个项目

Related Posts

ValueError: 层 sequential_40 的输入 0 与该层不兼容

我在修改一个旧代码,通过向模型中添加注意力层。但我无法…

如何训练标签为[5,30]形状的模型?

如何训练一个数据集,其中每个标签的形状为[5,30]?…

从DataFrameIterator中显示图像及其标签

我正在从一个数据集(使用flow_from_dataf…

在Opencv中接收到错误:(-215:Assertion failed) !_src.empty() 在函数’cvtColor’中

我目前正在使用opencv来识别屏幕上的个体,并且我已…

我使用TensorFlow的估算器构建了分类模型,保存模型后,在将其转换为TensorFlow Lite时出现了错误

使用Keras模型拟合混合类型的BatchDataset和numpy数组输入

我创建了一个接收两个输入的模型。当我使用两个numpy…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注