所以我可以找到很多关于 DTW for python 的指南,它们可以正常工作。但我需要将代码翻译成 C,但我已经一年多没有写 C 代码了。
所以在 C 代码中我有这两个数组
static int codeLock[6][2] = {
{1, 0},
{2, 671},
{3, 1400},
{4, 2000},
{5, 2800},
};;
static int code[6][2] = {
{1, 0},
{2, 600},
{3, 1360},
{4, 1990},
{5, 2800},
};;
而且我要使用 DTW 来比较数组的右侧codeLock(n)(1) / code(m)(1)
,所以 1..5 不应该看。
但是是的..
在 python 中,我有两个函数,euclidean distance
其中一个是:
def compute_euclidean_distance_matrix(x, y) -> np.array:
"""Calculate distance matrix
This method calcualtes the pairwise Euclidean distance between two sequences.
The sequences can have different lengths.
"""
dist = np.zeros((len(y), len(x)))
for i in range(len(y)):
for j in range(len(x)):
dist[i,j] = (x[j]-y[i])**2
return dist
另一个用于accumulated cost
:
def compute_accumulated_cost_matrix(x, y) -> np.array:
"""Compute accumulated cost matrix for warp path using Euclidean distance
"""
distances = compute_euclidean_distance_matrix(x, y)
# Initialization
cost = np.zeros((len(y), len(x)))
cost[0,0] = distances[0,0]
for i in range(1, len(y)):
cost[i, 0] = distances[i, 0] + cost[i-1, 0]
for j in range(1, len(x)):
cost[0, j] = distances[0, j] + cost[0, j-1]
# Accumulated warp path cost
for i in range(1, len(y)):
for j in range(1, len(x)):
cost[i, j] = min(
cost[i-1, j], # insertion
cost[i, j-1], # deletion
cost[i-1, j-1] # match
) + distances[i, j]
return cost
这段代码来自我遵循的指南,以了解 DTW 如何工作,但它在 python 中,我需要它在 C 中。
这可以很容易地在 python 中进行测试,如下所示:
x = [0, 671, 1400, 2000, 2800]
y = [0, 600, 1360, 1990, 2800]
compute_euclidean = compute_euclidean_distance_matrix(x, y)
compute_accumulated = compute_accumulated_cost_matrix(x, y)
print("\ncompute_euclidean_distance_matrix")
print(compute_euclidean)
print("\ncompute_accumulated_cost_matrix")
print(compute_accumulated)
print("\nflipud")
print(np.flipud(compute_accumulated))
这是我的输出
我也调查过fastdtw
,然后我的测试看起来像这样
x = [0, 671, 1400, 2000, 2800]
y = [0, 600, 1360, 1990, 2800]
dtw_distance, warp_path = fastdtw(x, y, dist=euclidean)
print("\ndtw_distance")
print(dtw_distance)
这是我的输出
你们有谁知道哪里有关于如何在 C 中完成所有这些操作的 GitHub/指南?因为这对我有很大帮助。如果您愿意帮助我翻译这段代码,我当然会很感激。