【问题标题】:comparing two numpy 2D arrays for similarity比较两个 numpy 2D 数组的相似性
【发布时间】:2018-11-28 14:18:44
【问题描述】:

我有 2D numpy array1 只包含 0255

 ([[255,   0, 255,   0,   0],
   [  0, 255,   0,   0,   0],
   [  0,   0, 255,   0, 255],
   [  0, 255, 255, 255, 255],
   [255,   0, 255,   0, 255]])

还有一个array2,其大小和形状与array1 相同,并且仅包含0255

 ([[255,   0, 255,   0, 255],
   [  0, 255,   0,   0,   0],
   [255,   0,   0,   0, 255],
   [  0,   0, 255, 255, 255],
   [255,   0, 255,   0,   0]])

如何比较 array1array2 以确定相似度百分比?

【问题讨论】:

  • 到目前为止您尝试过什么?您如何定义数组的相似性?
  • 您可以将数组彼此相减,然后对结果数组的平方求和

标签: arrays numpy python-2.x


【解决方案1】:

由于您只有两个可能的值,我建议使用此算法进行相似性检查:

import numpy as np
A = np.array([[255,   0, 255,   0,   0],
   [  0, 255,   0,   0,   0],
   [  0,   0, 255,   0, 255],
   [  0, 255, 255, 255, 255],
   [255,   0, 255,   0, 255]])

B = np.array([[255,   0, 255,   0, 255],
   [  0, 255,   0,   0,   0],
   [255,   0,   0,   0, 255],
   [  0,   0, 255, 255, 255],
   [255,   0, 255,   0,   0]])

number_of_equal_elements = np.sum(A==B)
total_elements = np.multiply(*A.shape)
percentage = number_of_equal_elements/total_elements

print('total number of elements: \t\t{}'.format(total_elements))
print('number of identical elements: \t\t{}'.format(number_of_equal_elements))
print('number of different elements: \t\t{}'.format(total_elements-number_of_equal_elements))
print('percentage of identical elements: \t{:.2f}%'.format(percentage*100))

它计算相等的元素,并计算相等的元素占元素总数的百分比

【讨论】:

  • 你有没有得到:main:1: DeprecationWarning: elementwise comparison failed;这将在未来引发错误。
  • @skrhee 嗯,很奇怪,我有 numpy 1.19.2,这似乎是最新版本,但我没有收到任何错误。如果不推荐使用元素比较,我会感到惊讶
  • 我认为当我的数组大小不同时会出现错误。当我重写我的代码以循环遍历元素时,它似乎工作正常。感谢您的帮助和帖子!
猜你喜欢
  • 2013-09-17
  • 1970-01-01
  • 2020-12-04
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多