Search code examples
pythonnumpyk-meanskernel-density

calculate kernel density estimation for kmeans algorithm


kde_numpyI have been asked to calculate K(z) based on a probability density function using np.linalg.norm.

this is what i tried, does anyone know what I'm doing wroing?

def kernel(z):
# z: (N, 2) numpy.array
# returns (N, 1) numpy.array

k_zee=[]
for i in range (0,len(z)):
    dat=z[i]
    norm=LA.norm(dat, ord=2)
    k_zee.append((1/(np.sqrt(2*math.pi)))**(-(norm/2)))
return np.array(k_zee)

Solution

  • Replace ** with np.exp:

    Also, your indentation's wrong - after the def line all code should be indented once.

    def kernel(z):
    # z: (N, 2) numpy.array
    # returns (N, 1) numpy.array
        k_zee=[]
        for i in range (0,len(z)):
            dat=z[i]
            norm=np.linalg.norm(dat, ord=2)
            k_zee.append((1/(np.sqrt(2*math.pi)))*np.exp(-(norm**2/2)))
        return np.array(k_zee)