【发布时间】:2021-01-24 17:30:32
【问题描述】:
我有两个形状为(436, 1024, 2) 的numpy 数组。最后一个维度 (2) 表示二维向量。我想逐元素比较两个 numpy 数组的二维向量,以找到平均角度误差。
为此,我想使用点积,它在遍历数组的第一个维度时工作得非常好(python 中的for 循环可能很慢)。因此我想使用一个 numpy 函数。
我发现np.tensordot 允许按元素执行点积。但是,我没有成功使用它的axes 参数:
import numpy as np
def average_angular_error_vec(estimated_oc : np.array, target_oc : np.array):
estimated_oc = np.float64(estimated_oc)
target_oc = np.float64(target_oc)
norm1 = np.linalg.norm(estimated_oc, axis=2)
norm2 = np.linalg.norm(target_oc, axis=2)
norm1 = norm1[..., np.newaxis]
norm2 = norm2[..., np.newaxis]
unit_vector1 = np.divide(estimated_oc, norm1)
unit_vector2 = np.divide(target_oc, norm2)
dot_product = np.tensordot(unit_vector1, unit_vector2, axes=2)
angle = np.arccos(dot_product)
return np.mean(angle)
我有以下错误:
ValueError: shape-mismatch for sum
下面是我正确计算平均角度误差的函数:
def average_angular_error(estimated_oc : np.array, target_oc : np.array):
h, w, c = target_oc.shape
r = np.zeros((h, w), dtype="float64")
estimated_oc = np.float64(estimated_oc)
target_oc = np.float64(target_oc)
for i in range(h):
for j in range(w):
unit_vector_1 = estimated_oc[i][j] / np.linalg.norm(estimated_oc[i][j])
unit_vector_2 = target_oc[i][j] / np.linalg.norm(target_oc[i][j])
dot_product = np.dot(unit_vector_1, unit_vector_2)
angle = np.arccos(dot_product)
r[i][j] = angle
return np.mean(r)
【问题讨论】:
-
顺便说一下,班级是
np.ndarray。np.array是一个静态构造函数。如果你想使用鸭子类型,请将x = np.asanyarray(x)左右粘贴到函数的开头。 -
@JavaiMaster。链接的问题不是重复的。它准确地解释了为什么
tensordot绝对是不是这里的答案。 -
@JavaiMaster。话虽如此,我觉得我以前回答过类似的问题。既然我已经回答了,我会试着找到骗子:)
-
@AlixL 你到底在哪里得到错误?它看起来更像是输入中的形状不匹配而不是任何东西。
标签: python numpy dot-product