如何选择Numpy张量轴

问题描述

我有两个形状为(436,1024,2)的numpy数组。最后一个维度(2)代表2D向量。我想逐个元素比较两个numpy数组的2D向量,以求出平均角度误差。

为此,我想使用点积,该点积在遍历数组的两个第一维时效果很好(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)

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)