提高ML算法的python循环速度

时间:2017-01-11 15:04:47

标签: python algorithm numpy image-processing machine-learning

我正在尝试对平均向量和协方差矩阵已知的图像执行最大似然算法。问题是计算真的很慢......而且我处理的是非常大的图像(5100X7020)。

以下代码显示了图像中像素的给定类的概率图的计算

import numpy as np
from numpy.linalg import inv
from numpy.linalg import det
...

probImage1 = []
probImage1Vector = []

norm = 1.0 / (np.power((2*np.pi), i/2) * np.sqrt(np.linalg.det(covMatrixClass1)))
for x in xrange(x_img):
    for y in xrange(y_img):
        X = realImage[x,y]
        mult1 = np.multiply(-0.5,np.transpose(X - meanVectorClass1))
        mult2 = np.dot(np.linalg.inv(covMatrixClass1),(X - meanVectorClass1))
        multMult = np.dot(mult1,mult2)
        expo = np.exp(multMult)     
        probImage1Vector.append(np.multiply(norm,expo))
    probImage1.append(probImage1Vector)
    probImage1Vector = [] 

您是否知道如何加快此算法的速度?

提前致谢

更新

我通过将矩阵逆计算放在for循环之外来减少时间计算时间,但它仍然很慢...... 它自己迭代图像并获得像素值并不需要太多时间,但即使是简单的矩阵减法也会显着降低它...

i,j = covMatrixClass1.shape

probImage1 = [] probImage1Vector = []

norm = 1.0 / (np.power((2*np.pi), i/2) *      np.sqrt(np.linalg.det(covMatrixClass1)))
covMatrixInverz = np.linalg.inv(covMatrixClass1)
for x in xrange(x_img):
    for y in xrange(y_img):
        X = realImage[x,y]
        pixelValueDifference = X - meanVectorClass1
        mult1 = np.multiply(-0.5,np.transpose(pixelValueDifference))
        mult2 = np.dot(covMatrixInverz,pixelValueDifference)
        multMult = np.dot(mult1,mult2)
        expo = np.exp(multMult)     
        probImage1Vector.append(np.multiply(norm,expo))
    probImage1.append(probImage1Vector)
    probImage1Vector = []

请注意,任何有关如何加速此代码的建议都是适当的!

0 个答案:

没有答案