将Numpy代码翻译成C#

本文关键字:翻译 代码 Numpy | 更新日期: 2023-09-27 18:24:00

我怀疑这可能不是一个好问题,但我已经完全遇到了困难,需要一些帮助。

我正在尝试实现这个代码:

http://www.nathanieltroutman.net/content/calculating-minimum-volume-bounding-box

在C#中,原始版本是Python。

在我点击以下部分之前,一切都很顺利:

def calcProjections(points, *vectors):
    """Calculates the projection of points (NxD) onto the vectors 
    (MxD) and return the projections p which is a matrix sized (N, M) 
    where N is the number of points and M is the number of vectors.
    p[i][j], is the projection of points[i] onto vectors[j] (which is
    between 0 and 1)."""
    u = np.array(vectors)
    # project the points onto the vectors into on fell swoop
    d = np.dot(points, u.T)
    # this is the dot product of each vector with itself
    v2 = np.diag(np.inner(u, u))
    p = d / v2
    return p

我只是在努力解读到底发生了什么。我不知道作者把投影到特定向量上是什么意思,也不知道输出的格式(该死的你打字)。这个描述对我来说也有点太模糊了。

有人对这件事有什么建议或解释吗?非常感谢您的帮助。

谢谢。

将Numpy代码翻译成C#

以下是在交互式Ipython shell中完成的示例计算:

In [63]: points=np.arange(12,dtype=float).reshape(4,3)
In [64]: vectors=[np.array([1,0,0],dtype=float),np.array([0,1,1],dtype=float)]
In [65]: u=np.array(vectors)
In [66]: points
Out[66]: 
array([[  0.,   1.,   2.],
       [  3.,   4.,   5.],
       [  6.,   7.,   8.],
       [  9.,  10.,  11.]])
In [67]: u
Out[67]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  1.]])
In [68]: d=np.dot(points, u.T)
In [69]: d
Out[69]: 
array([[  0.,   3.],
       [  3.,   9.],
       [  6.,  15.],
       [  9.,  21.]])
In [70]: v2=np.diag(np.inner(u,u))
In [71]: d/v2
Out[71]: 
array([[  0. ,   1.5],
       [  3. ,   4.5],
       [  6. ,   7.5],
       [  9. ,  10.5]])

如函数doc中所指定的,输入是(4,3) pointsvectors 2个(3,)矢量的列表,输出是(4,2)数组p

d是4x3矩阵与2x3(或转置后的3x2)阵列的矩阵(点)乘积,得到4x2。v2也可以计算为np.sum(u,u, axis=1),即两个"矢量"的大小。CCD_ 10正是由CCD_。

如果你熟悉爱因斯坦求和法(在物理学中使用),计算也可以表示为:

np.einsum('ij,kj->ik',points,u)/np.einsum('ij,ij->i',u,u)