【发布时间】:2017-08-08 10:32:51
【问题描述】:
我正在尝试比较几个数据集并基本上测试它们是否显示相同的特征,尽管此特征可能会被转移、反转或减弱。 下面是一个非常简单的例子:
A = np.array([0., 0, 0, 1., 2., 3., 4., 3, 2, 1, 0, 0, 0])
B = np.array([0., 0, 0, 0, 0, 1, 2., 3., 4, 3, 2, 1, 0])
C = np.array([0., 0, 0, 1, 1.5, 2, 1.5, 1, 0, 0, 0, 0, 0])
D = np.array([0., 0, 0, 0, 0, -2, -4, -2, 0, 0, 0, 0, 0])
x = np.arange(0,len(A),1)
我认为最好的方法是将这些信号归一化并获得绝对值(现阶段它们的衰减对我来说并不重要,我对位置感兴趣......但我可能错了,所以我也将欢迎有关此概念的想法)并计算它们重叠的区域。我正在跟进this answer - 该解决方案看起来非常优雅和简单,但我可能执行错误。
def normalize(sig):
#ns = sig/max(np.abs(sig))
ns = sig/sum(sig)
return ns
a = normalize(A)
b = normalize(B)
c = normalize(C)
d = normalize(D)
但是,当我尝试从答案中实施解决方案时,我遇到了问题。
旧
for c1,w1 in enumerate([a,b,c,d]):
for c2,w2 in enumerate([a,b,c,d]):
w1 = np.abs(w1)
w2 = np.abs(w2)
M[c1,c2] = integrate.trapz(min(np.abs(w2).any(),np.abs(w1).any()))
print M
产生TypeError: 'numpy.bool_' object is not iterable 或IndexError: list assignment index out of range。但我只包含了.any(),因为没有它们,我得到的是ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()。
编辑 - 新 (感谢@Kody King)
现在的新代码是:
M = np.zeros([4,4])
SH = np.zeros([4,4])
for c1,w1 in enumerate([a,b,c,d]):
for c2,w2 in enumerate([a,b,c,d]):
crossCorrelation = np.correlate(w1,w2, 'full')
bestShift = np.argmax(crossCorrelation)
# This reverses the effect of the padding.
actualShift = bestShift - len(w2) + 1
similarity = crossCorrelation[bestShift]
M[c1,c2] = similarity
SH[c1,c2] = actualShift
M = M/M.max()
print M, '\n', SH
还有输出:
[[ 1. 1. 0.95454545 0.63636364]
[ 1. 1. 0.95454545 0.63636364]
[ 0.95454545 0.95454545 0.95454545 0.63636364]
[ 0.63636364 0.63636364 0.63636364 0.54545455]]
[[ 0. -2. 1. 0.]
[ 2. 0. 3. 2.]
[-1. -3. 0. -1.]
[ 0. -2. 1. 0.]]
移位矩阵现在看起来不错,但实际的相关矩阵却不行。我真的很困惑,最低的相关值是用于将 d 与自身相关联。我现在想要实现的是:
编辑 - 更新
按照建议,我使用了推荐的归一化公式(将信号除以其总和),但问题没有解决,只是颠倒过来。现在 d 与 d 的相关性为 1,但所有其他信号都与自身不相关。
新输出:
[[ 0.45833333 0.45833333 0.5 0.58333333]
[ 0.45833333 0.45833333 0.5 0.58333333]
[ 0.5 0.5 0.57142857 0.66666667]
[ 0.58333333 0.58333333 0.66666667 1. ]]
[[ 0. -2. 1. 0.]
[ 2. 0. 3. 2.]
[-1. -3. 0. -1.]
[ 0. -2. 1. 0.]]
- 在将信号与其自身相关时,相关值应最高(即在主对角线上具有最高值)。
- 要获得介于 0 和 1 之间的相关值,因此,我会在主对角线上使用 1,而在其他位置使用其他数字 (0.x)。
我希望 M = M/M.max() 能完成这项工作,但前提是条件不存在。 1 已实现,但目前尚未实现。
【问题讨论】: