Skip to content

Instantly share code, notes, and snippets.

@andrea-dagostino
Last active August 1, 2022 13:26
Show Gist options
  • Select an option

  • Save andrea-dagostino/b5f4f1f2906d2cce4b91f3a530611069 to your computer and use it in GitHub Desktop.

Select an option

Save andrea-dagostino/b5f4f1f2906d2cce4b91f3a530611069 to your computer and use it in GitHub Desktop.
ts_clustering
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