【发布时间】: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