How to calculate a Gaussian kernel matrix efficiently in numpy?

前端 未结 12 2310
名媛妹妹
名媛妹妹 2020-11-29 20:54
def GaussianMatrix(X,sigma):
    row,col=X.shape
    GassMatrix=np.zeros(shape=(row,row))
    X=np.asarray(X)
    i=0
    for v_i in X:
        j=0
        for v_j i         


        
12条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-29 20:59

    Building up on Teddy Hartanto's answer. You can just calculate your own one dimensional Gaussian functions and then use np.outer to calculate the two dimensional one. Very fast and efficient way.

    With the code below you can also use different Sigmas for every dimension

    import numpy as np
    def generate_gaussian_mask(shape, sigma, sigma_y=None):
        if sigma_y==None:
            sigma_y=sigma
        rows, cols = shape
    
        def get_gaussian_fct(size, sigma):
            fct_gaus_x = np.linspace(0,size,size)
            fct_gaus_x = fct_gaus_x-size/2
            fct_gaus_x = fct_gaus_x**2
            fct_gaus_x = fct_gaus_x/(2*sigma**2)
            fct_gaus_x = np.exp(-fct_gaus_x)
            return fct_gaus_x
    
        mask = np.outer(get_gaussian_fct(rows,sigma), get_gaussian_fct(cols,sigma_y))
        return mask
    

提交回复
热议问题