-1

I am a bit new to python and want to get into numpy. I try to solve the gaussian kernel function with 2 for-loops:

for n in range(0, 6):
        for k in range(len(centers_Hex)):
            expo_sum[n+1] += np.exp(-np.linalg.norm(z_approx-center_Matrix[n][k])**2/(2*sigma**2))

where center_Matrix includesa matrix of (x,y) coordinates for the center of the gaussian bell, z_approx is the data_point which i want to calculate and sigma is a variable. So how can I simplify these two for loops? My main problem is the linalg.norm for the simplification.

Thank you!

Krischan Ledwig
  • 51
  • 1
  • 1
  • 2
  • What is `z_approx` (variable type, size, etc)? What is `sigma`? What is `expo_sum`? What is `centers_Hex`? There is a lot of information missing for a good answer. – 9769953 Feb 23 '22 at 08:57
  • Does this answer your question? [How to calculate a Gaussian kernel matrix efficiently in numpy?](https://stackoverflow.com/questions/29731726/how-to-calculate-a-gaussian-kernel-matrix-efficiently-in-numpy) – 9769953 Feb 23 '22 at 08:59
  • to simplify from 3 lines into one line would use `list comprehension`, but in this case `nested for loops` seem appropriate. – D.L Feb 23 '22 at 09:02
  • z_approx is a coordinate (x,y), sigma is a constant value, expo_sum is a double value – Krischan Ledwig Feb 23 '22 at 09:22
  • So `z_approx` is a 2-element tuple, e.g. `(5, 6)`? And is `center_Matrix` 2D or 3D? – 9769953 Feb 23 '22 at 09:34
  • yes. center_matrix is a 2D matrix with 2-element tuples in it – Krischan Ledwig Feb 23 '22 at 09:44

1 Answers1

0

If you can turn center_Matrix into a 3D array, with the 2-element tuples being the inner dimension (so the shape would be (n, k, 2)), you might be able to do the following:

diff = np.linalg.norm([center_Matrix[...,0] - z_approx[0], center_Matrix[...,1] - z_approx[1]], axis=0)
expo_sum = np.exp(-diff**2 / (2*sigma**2))
expo_sum = expo_sum.sum(axis=1)

This does shift the resulting expo_sum by one index, since you use expo_sum[n+1] = ..., but that is something you can adjust elsewhere in your code.

9769953
  • 10,344
  • 3
  • 26
  • 37