Last active
August 1, 2022 13:26
-
-
Save andrea-dagostino/b5f4f1f2906d2cce4b91f3a530611069 to your computer and use it in GitHub Desktop.
ts_clustering
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def compute_correlation(a1, a2): | |
| """ | |
| Calculate the correlation between two vectors | |
| """ | |
| return np.corrcoef(a1, a2)[0, 1] | |
| def compute_dynamic_time_warping(a1, a2): | |
| """ | |
| Compute the dynamic time warping between two sequences | |
| """ | |
| DTW = {} | |
| for i in range(len(a1)): | |
| DTW[(i, -1)] = float('inf') | |
| for i in range(len(a2)): | |
| DTW[(-1, i)] = float('inf') | |
| DTW[(-1, -1)] = 0 | |
| for i in range(len(a1)): | |
| for j in range(len(a2)): | |
| dist = (a1[i]-a2[j])**2 | |
| DTW[(i, j)] = dist + min(DTW[(i-1, j)], DTW[(i, j-1)], DTW[(i-1, j-1)]) | |
| return np.sqrt(DTW[len(a1)-1, len(a2)-1]) | |
| # create empty matrix | |
| S = np.zeros((len(A), len(A))) | |
| # populate S | |
| for i in range(len(A)): | |
| for j in range(len(A)): | |
| # weigh the dynamic time warping with the correlation | |
| S[i, j] = compute_dynamic_time_warping(A[i], A[j]) * (1 - compute_correlation(A[i], A[j])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment