在numpy的元素明智的矩阵乘法 [英] Element-wise matrix multiplication in NumPy

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

问题描述

我正在做我第一次真正涉足Python和numpy的做一些图像处理。我有加载为3维数组numpy的,图像,其中0轴重新presents图像波段,而轴1和2重新present列和像素行。从这里,我需要采取的3x1矩阵重新presenting每个像素,并执行其导致另一个的3x1矩阵,其将被用来建立一个结果图像一些操作

I'm making my first real foray into Python and NumPy to do some image processing. I have an image loaded as a 3 dimensional NumPy Array, where axis 0 represents image bands, while axes 1 and 2 represent columns and rows of pixels. From this, I need to take the 3x1 matrix representing each pixel and perform a few operations which result in another 3x1 matrix, which will be used to build a results image.

我的第一个办法(简体和用随机数据)看起来是这样的:

My first approach (simplified and with random data) looks like this:

import numpy as np
import random

factor = np.random.rand(3,3)
input = np.random.rand(3,100,100)
results = np.zeros((3,100,100))

for x in range(100):
    for y in range(100):
        results[:,x,y] = np.dot(factor,input[:,x,y])

但是,这给我的印象不雅,效率低下。有没有办法在各个元素的FASION,例如要做到这一点:

But this strikes me as inelegant and inefficient. Is there a way to do this in an element-wise fasion, e.g.:

results = np.dot(factor,input,ElementWiseOnAxis0)

在试图找到一个解决这个问题我碰到<少时href=\"http://stackoverflow.com/questions/10325078/combining-element-wise-and-matrix-multiplication-with-multi-dimensional-arrays-i\">this问题,这显然是非常相似的。不过,笔者未能解决的问题让他们满意。我希望2012年以来无论是东西已经改变了,还是我的问题是足够不同于他们,使之更容易解决。

In trying to find a solution to this problem I came across this question, which is obviously quite similar. However, the author was unable to solve the problem to their satisfaction. I am hoping that either something has changed since 2012, or my problem is sufficiently different from theirs to make it more easily solvable.

推荐答案

numpy的阵列采用逐元素默认倍增。退房numpy.einsum和numpy.tensordot。我认为你在寻找什么是这样的:

Numpy arrays use element-wise multiplication by default. Check out numpy.einsum, and numpy.tensordot. I think what you're looking for is something like this:

results = np.einsum('ij,jkl->ikl',factor,input)

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

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