如何在numpy中获取按元素矩阵乘法(Hadamard积)? [英] How to get element-wise matrix multiplication (Hadamard product) in numpy?

查看:152
本文介绍了如何在numpy中获取按元素矩阵乘法(Hadamard积)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个矩阵

a = np.matrix([[1,2], [3,4]])
b = np.matrix([[5,6], [7,8]])

,我想获得元素级乘积[[1*5,2*6], [3*7,4*8]],等于

and I want to get the element-wise product, [[1*5,2*6], [3*7,4*8]], equaling

[[5,12], [21,32]]

我尝试过

print(np.dot(a,b)) 

print(a*b)

但都给出结果

[[19 22], [43 50]]

是矩阵乘积,而不是元素乘积.如何使用内置函数获得按元素分类的产品(又名Hadamard产品)?

which is the matrix product, not the element-wise product. How can I get the the element-wise product (aka Hadamard product) using built-in functions?

推荐答案

对于matrix对象的元素乘法,可以使用

For elementwise multiplication of matrix objects, you can use numpy.multiply:

import numpy as np
a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])
np.multiply(a,b)

结果

array([[ 5, 12],
       [21, 32]])

但是,您应该真正使用array而不是matrix. matrix对象与常规ndarray具有各种可怕的不兼容性.使用ndarray,您可以只使用*进行元素乘法:

However, you should really use array instead of matrix. matrix objects have all sorts of horrible incompatibilities with regular ndarrays. With ndarrays, you can just use * for elementwise multiplication:

a * b

如果您使用的是Python 3.5+,则甚至不会失去使用运算符执行矩阵乘法的功能,因为

If you're on Python 3.5+, you don't even lose the ability to perform matrix multiplication with an operator, because @ does matrix multiplication now:

a @ b  # matrix multiplication

这篇关于如何在numpy中获取按元素矩阵乘法(Hadamard积)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆