python - 比较两个二维数组的准确性的非断言方法
问题描述
我目前正在训练一个对帧进行分类的 LSTM。我想要做的是比较两个 2d numpy 数组以检查我的预测和目标之间的准确性。我目前正在寻找使用 NumPy / SciPy 解决这个问题的非天真的方法。
我知道有 np.testing.assert_array_equal(x, y) 它使用断言来输出结果。我正在寻找一种使用 NumPy / SciPy 解决此问题的方法,以便我可以存储结果而不是 Assert 打印输出:
Arrays are not equal
(mismatch 14.285714285714292%)
x: array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
y: array([0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
x = np.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
y = np.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 0, 0], [0, 0, 0]])
try:
np.testing.assert_array_equal(x, y)
res = True
except AssertionError as err:
res = False
print (err)
我正在寻找一种方法来存储这两个数组的不匹配而不使用幼稚的方式(两个比较循环):
accuracy = thisFunction(x,y)
我确信 NumPy 中有一些东西可以解决这个问题,我没有运气搜索内置函数。
解决方案
np.array_equal(x, y)
大致相当于(x == y).all()
。您可以使用它来计算差异:
def array_comp(x, y):
"""
Return the status of the comparison and the discrepancy.
For arrays of the same shape, the discrepancy is a ratio of mismatches to the total size.
For arrays of different shapes or sizes, the discrepancy is a message indicating the mismatch.
"""
if x.shape != y.shape:
return False, 'shape'
count = x.size - np.count_nonzero(x == y)
return count == 0, count / x.size
推荐阅读
- php - “无法获取尚未返回的生成器的返回值” php 回溯
- sql - DB2 SQL 多个 JOIN 问题
- python - 如何使用表情符号和特殊字符对国际字符串进行编码以存储在数据库中
- dynamic - 为什么特征对象 vtable 包含大小和对齐方式?
- php - PHP多维数组根据键提取特定值
- ios - 完成处理程序闭包是否总是在后台线程中运行?
- cryptography - “从不使用专有密码”是什么意思?
- python - 使用 Tor + Privoxy 时在 Localhost 上请求 API 内容
- c++ - QtOpenGLWidget 绘制三角形
- javascript - 带有 TextboxIO 的 Textarea 不发布