[英]Why is numpy vector-matrix dot product removing extra zeros
我正在将点积运算应用于矩阵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)
当我打印示例时,m和v形状如下:m: (3, 7)
3,7 (3, 7)
n: (7,)
numpy点积输出如下:
[305 303 319]
这实际上是正确的,因为您看到输出的shape(3x7)点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)
,我认为这将解决问题。 :)干杯!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.