python - C中的动态时间扭曲
问题描述
所以我可以找到很多关于 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/指南?因为这对我有很大帮助。如果您愿意帮助我翻译这段代码,我当然会很感激。
解决方案
动态时间扭曲的 AC 实现在https://github.com/wannesm/dtaidistance/tree/master/dtaidistance/lib/DTAIDistanceC/DTAIDistanceC
您始终可以使用 Cython https://people.duke.edu/~ccc14/sta-663/FromPythonToC.html将 python 转换为 C但是生成的代码有时不起作用,完全重写更好
推荐阅读
- mysql - GROUP BY的SQL查询,返回符合LEAST、COALESCE条件的组
- angular - 指令角度 6 中的 @Input 不是双向绑定
- laravel - 为管理员登录和用户登录创建中间件时页面未正确重定向
- javascript - 为什么将 https.get() 存储在节点 js 的请求常量中
- three.js - Threejs在运行时更改图像
- javascript - 使用 axios 在 ReactJS web worker 中调用 web api 方法
- c# - 从 ASP.Net 生成子进程失败
- java - ElasticSearch SpringBoot + Spring Data:java.lang.IllegalStateException:在接口上找不到合适的构造函数
- docker - 通过 dokku 只停止一个 docker 容器
- guzzle - 尝试使用 POSTMAN 注册用户时出现 Laravel 5.6.26 护照问题