python - 为什么numpy向量矩阵点积会去除多余的零
问题描述
我希望对矩阵 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) shape v = (p,) shape
结果输出是 v = (n) shape 这个特定的代码编辑修复了这个问题:
z = np.zeros((m.shape[0])).astype(np.int32)
解决方案
当我打印您的示例时,m 和 v 形状如下: m: (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)
,我认为这将解决问题。:) 干杯!!
推荐阅读
- asp.net-mvc - SSRS 不显示在 ReportViewer 中使用 EntityFramwork 数据源
- python - Python:用户输入中的大小写敏感性
- user-interface - Armhf仿真器/汇编器IDE?
- android - 更改 Facebook 登录背景
- html - 网格布局看起来不像我预期的那样
- javascript - JavaScript API 的 HERE 地图:如何计算路线?
- mapbox-gl-js - 如何在 MapBox GL JS 中绘制多个不同半径的圆?
- reactjs - React 派生道具
- scala - 如何在scala中将“Some(123)”转换为123
- excel - 根据excel中的下拉菜单自动填充单元格的宏