在numpy中将几个矩阵相乘 [英] Multiply several matrices in numpy

查看:242
本文介绍了在numpy中将几个矩阵相乘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有n个平方矩阵A1,...,An.无论如何,有没有用整齐的方式将这些矩阵相乘?据我所知,numpy中的点仅接受两个参数.一种明显的方法是定义一个函数以调用自身并获取结果.有没有更好的方法来完成它?

Suppose you have n square matrices A1,...,An. Is there anyway to multiply these matrices in a neat way? As far as I know dot in numpy accepts only two arguments. One obvious way is to define a function to call itself and get the result. Is there any better way to get it done?

推荐答案

这可能是相对较新的功能,但我喜欢:

This might be a relatively recent feature, but I like:

A.dot(B).dot(C)

或者如果您的连锁店很长,可以这样做:

or if you had a long chain you could do:

reduce(numpy.dot, [A1, A2, ..., An])

更新:

有关在此处的更多信息.以下是一个示例,可能帮助.

There is more info about reduce here. Here is an example that might help.

>>> A = [np.random.random((5, 5)) for i in xrange(4)]
>>> product1 = A[0].dot(A[1]).dot(A[2]).dot(A[3])
>>> product2 = reduce(numpy.dot, A)
>>> numpy.all(product1 == product2)
True

2016年更新: 从python 3.5开始,有一个新的matrix_multiply符号@:

Update 2016: As of python 3.5, there is a new matrix_multiply symbol, @:

R = A @ B @ C

这篇关于在numpy中将几个矩阵相乘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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