diff options
author | David Luevano Alvarado <55825613+luevano@users.noreply.github.com> | 2020-03-02 12:02:52 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-03-02 12:02:52 -0700 |
commit | 1628e8c079c7c6c68c47a29347d2cfabd5abaa9f (patch) | |
tree | dd42fddfb03f1ff201d6f770bb92c3f32cae9329 /ml_exp/kernels.py | |
parent | 86faabeac5aed75c1dfc883fe757c21eba94b645 (diff) | |
parent | 62cef5f1782caf4ff379cd021744b98be4be6c8b (diff) |
Merge pull request #3 from luevano/addbags
Addbags
Diffstat (limited to 'ml_exp/kernels.py')
-rw-r--r-- | ml_exp/kernels.py | 28 |
1 files changed, 19 insertions, 9 deletions
diff --git a/ml_exp/kernels.py b/ml_exp/kernels.py index 3914ffc20..feaf9a990 100644 --- a/ml_exp/kernels.py +++ b/ml_exp/kernels.py @@ -26,20 +26,30 @@ import numpy as np def gaussian_kernel(X1, X2, - sigma): + sigma, + opt=True): """ Calculates the Gaussian Kernel. X1: first representations. X2: second representations. sigma: kernel width. + opt: if the optimized algorithm should be used. For benchmarking purposes. """ - inv_sigma = -0.5 / (sigma*sigma) - - K = np.zeros((X1.shape[0], X2.shape[0]), dtype=float) - for i, x1 in enumerate(X1): - for j, x2 in enumerate(X2): - f_norm = np.linalg.norm(x1 - x2) - # print(f_norm) - K[i, j] = math.exp(inv_sigma * f_norm) + i_sigma = -0.5 / (sigma*sigma) + + K = np.zeros((X1.shape[0], X2.shape[0]), dtype=np.float64) + if opt: + # Faster way of calculating the kernel (no numba support). + for i, x1 in enumerate(X1): + if X2.ndim == 3: + norm = np.linalg.norm(X2 - x1, axis=(1, 2)) + else: + norm = np.linalg.norm(X2 - x1, axis=-1) + K[i, :] = np.exp(i_sigma * np.square(norm)) + else: + for i, x1 in enumerate(X1): + for j, x2 in enumerate(X2): + f_norm = np.linalg.norm(x2 - x1) + K[i, j] = math.exp(i_sigma * f_norm**2) return K |