【问题标题】:Why is numpy vector-matrix dot product removing extra zeros为什么numpy向量矩阵点积会去除多余的零
【发布时间】:2019-06-01 04:53:38
【问题描述】:

我希望对矩阵 m (2,6) 和向量 v(6,) 应用点积运算

结果向量的形状应为 (6,)

当我自己在 python 中实现逻辑时,我得到了上述所需的结果.. 即。一个大小为 6 的向量。但是,如果我使用 np.dot(m,v) 它会给出相同的结果,但它会删除额外的零

为什么会这样?请帮忙。代码如下

def vector_matrix_multiplication_using_numpy(m, v):
    ''' 
        this is where we multiply a matrix with a vector
        remember it is important that m.shape[1] == v.shape[0]
        also m is a 2D tensor

        resultant will be a vector of the shape
        (m.shape[0])

    '''
    assert len(m.shape) == 2
    assert len(v.shape) == 1
    assert m.shape[1] == v.shape[0]

    return np.dot(m,v)





def vector_matrix_multiplication_using_python(m, v):
    ''' 
        this is where we multiply a matrix with a vector
        remember it is important that m.shape[1] == v.shape[0]
        also m is a 2D tensor

        resultant will be a vector of the shape
        (m.shape[0])

    '''
    assert len(m.shape) == 2
    assert len(v.shape) == 1
    assert m.shape[1] == v.shape[0]

    z = np.zeros((m.shape[1])).astype(np.int32)

    for i in range(m.shape[0]):
        z[i] = vector_multiplication_using_python(m[i, :],v)

    return z


    m = np.random.randint(2,6, (3,7))
    v = np.random.randint(5,17, (7))
    print(vector_matrix_multiplication_using_numpy(m,v),\
                vector_matrix_multiplication_using_python(m, v))

输出如下:

[345 313 350] [345 313 350   0   0   0   0]

编辑:

我错了。向量乘法矩阵的工作原理如下 m = (n,p) 形状 v = (p,) 形状

结果输出是 v = (n) 形状 代码中的这个特殊编辑解决了这个问题:

z = np.zeros((m.shape[0])).astype(np.int32)

【问题讨论】:

  • 放松!这个方法的实现在哪里? vector_multiplication_using_python

标签: python numpy


【解决方案1】:

当我打印您的示例时,m 和 v 形状如下: 米:(3, 7) n:(7,) numpy点积输出如下:

[305 303 319]

这实际上是正确的,因为您看到输出的 shape(3x7) dot shape(7) ==> shape(3,) 形状。所以是正确的。那么你的python实现一定有问题。我要求您分享整个代码或自己研究一下。希望能帮助到你。如果您还有其他问题,请随时询问。 :)

编辑:

请注意,您在这里做错了。

z = np.zeros((m.shape[1])).astype(np.int32)

您在这里分配了 7 个零,您的输出采用前三位数字,其余零保持不变。因此,要回答您的问题,numpy 没有删除零,而是添加了额外的零,这是错误的!

您可以使用z = np.zeros((m.shape[0])).astype(np.int32),我认为这将解决问题。 :) 干杯!!

【讨论】:

    猜你喜欢
    • 2016-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2017-02-26
    • 2019-10-08
    • 2014-12-07
    相关资源
    最近更新 更多