Numpy: Dot product with max instead of sum

北城余情 提交于 2020-01-03 20:23:10

问题


Is there a way in numpy to do the following (or is there a general mathematical term for this):

Assume normal dot product:

M3[i,k] = sum_j(M1[i,j] * M2[j,k])

Now I would like to replace the sum by sum other operation, say the maximum:

M3[i,k] = max_j(M1[i,j] * M2[j,k])

As you can see it is completely parallel to the above, just we take max over all j and not the sum.

Other options could be min, prod, and whatever other operation that turns a sequence/set into a value.


回答1:


Normal dot product would be (using numpy broadcasting)

M3 = np.sum(M1[:, :, None] * M2[None, :, :], axis = 1)

You can do the same thing with any function you want that has an axis keyword.

M3 = np.max(M1[:, :, None] * M2[None, :, :], axis = 1)



来源:https://stackoverflow.com/questions/41164305/numpy-dot-product-with-max-instead-of-sum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!