How to calculate a Gaussian kernel matrix efficiently in numpy?

前端 未结 12 2300
名媛妹妹
名媛妹妹 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 21:20

    I'm trying to improve on FuzzyDuck's answer here. I think this approach is shorter and easier to understand. Here I'm using signal.scipy.gaussian to get the 2D gaussian kernel.

    import numpy as np
    from scipy import signal
    
    def gkern(kernlen=21, std=3):
        """Returns a 2D Gaussian kernel array."""
        gkern1d = signal.gaussian(kernlen, std=std).reshape(kernlen, 1)
        gkern2d = np.outer(gkern1d, gkern1d)
        return gkern2d
    

    Plotting it using matplotlib.pyplot:

    import matplotlib.pyplot as plt
    plt.imshow(gkern(21), interpolation='none')
    

提交回复
热议问题