使用 python 进行动态时间扭曲(最终映射)

2024-03-04

我需要对齐两个声音信号,以便将一个声音信号映射到另一个声音信号(两个信号对应相同的行为)。我尝试从以下位置实现 python 代码:https://nipunbatra.github.io/blog/2014/dtw.html https://nipunbatra.github.io/blog/2014/dtw.html

作为我的代码调用的函数。一个例子:

#time warping sound function trial

import numpy as np
import matplotlib.pyplot as plt
from pylab import *

my_path ='/home/...'
def time_warping (x,y,fs,name):

    distances             = np.zeros((len(y), len(x)))
    accumulated_cost      = np.zeros((len(y), len(x)))
    accumulated_cost[0,0] = distances[0,0]

    def distance_cost_plot(distances):
                #function to visualize the distance matrix      
        im = plt.imshow(distances, interpolation='nearest', cmap='Reds') 
        plt.gca().invert_yaxis()
        plt.xlabel("X")
        plt.ylabel("Y")
        plt.grid()
        plt.colorbar();
        #plt.show()
        plt.close()

    def path_cost(x, y, accumulated_cost, distances):
        #this is like mlpy.dtw_std (I gues..)
        path = [[len(x)-1, len(y)-1]]
        cost = 0
        i = len(y)-1
        j = len(x)-1
        while i>0 and j>0:
            if i==0:
                j = j - 1
            elif j==0:
                i = i - 1
            else:
                if accumulated_cost[i-1, j] == min(accumulated_cost[i-1, j-1], accumulated_cost[i-1, j], accumulated_cost[i, j-1]):
                    i = i - 1
                elif accumulated_cost[i, j-1] == min(accumulated_cost[i-1, j-1], accumulated_cost[i-1, j], accumulated_cost[i, j-1]):
                    j = j-1
                else:
                    i = i - 1
                    j= j- 1
            path.append([j, i])
        path.append([0,0])
        for [y, x] in path:
            cost = cost +distances[x, y]
        return path, cost

    #Here I apply the function over function x and y
    path, cost = path_cost(x, y, accumulated_cost, distances)   

    for i in range(len(y)):
        for j in range(len(x)):
            distances[i,j] = (x[j]-y[i])**2

    #Here I plot the distance   
    g=distance_cost_plot(distances)

    accumulated_cost      = np.zeros((len(y), len(x)))
    accumulated_cost[0,0] = distances[0,0]

    for i in range(1, len(y)):
        accumulated_cost[i,0] = distances[i, 0] + accumulated_cost[i-1, 0]
    for i in range(1, len(x)):
        accumulated_cost[0,i] = distances[0,i] + accumulated_cost[0, i-1] 
    for i in range(1, len(y)):
        for j in range(1, len(x)):
            accumulated_cost[i, j] = min(accumulated_cost[i-1, j-1], accumulated_cost[i-1, j], accumulated_cost[i, j-1]) + distances[i, j]

    #empy list for the maping

    map_x_final   =[]
    map_y_final   =[]
    map_x_f_final =[]
    map_y_f_final =[]

    paths         = path_cost(x, y, accumulated_cost, distances)[0] #no entiendo la sintaxis de esta linea

    print 'path',paths
    print 'accumulated_cost',accumulated_cost
    print 'distances',distances

    #print 'paths.shape',path.shape

    plt.figure(figsize=(14,8)) # 8 plots in one
    plt.subplot(2,1,1)
    grid(True)

    map_x_fx         =[]
    map_y_fy         =[]        
        map_y_fy_newlist =[]
    for [map_x, map_y] in paths:

        #print map_x, x[map_x], ":", map_y, y[map_y]

        plt.plot([map_x*float(1)/float(fs), map_y*float(1)/float(fs)], [x[map_x], y[map_y]], 'r')
        #plt.plot([map_x, map_y], [x[map_x], y[map_y]], 'r')

        #saving in empy list        

        map_x_fx.append([map_x,x[map_x]])
            map_y_fy.append([map_x,y[map_y]])

        map_x_final.append(map_x)
        map_y_final.append(map_y)

        map_x_f_final.append(x[map_x])
        map_y_f_final.append(y[map_y])

        dif_a_sumar = (map_y-map_x)*float(1)/float(fs)      

    map_x_final     = np.asarray(map_x_final)
    map_y_final     = np.asarray(map_y_final)
    map_x_f_final   = np.asarray(map_x_f_final)
    map_y_f_final   = np.asarray(map_y_f_final)

    ####
    map_x_final_vec     = np.asarray(map_x_fx)
    map_y_final_vec     = np.asarray(map_y_fy)

    #Erase the elements that has been alrady map

    lista_aux=[]
    for j,[a,b] in enumerate(map_y_fy):
        print j,':', [a,b]
        print  len( map_x_final[:j])
        if a not in map_x_final[:j]:
            lista_aux.append([a,b])
        else:
            pass  
    print'++++++'
    print'lista aux len: ',len(lista_aux)

    map_y_final_vec_    =np.asarray(lista_aux)

    print'++++'
    print 'map_y_fy',len(map_y_fy)
    print'*************************'
    #print ' a veer map_x_fx: ',map_x_fx
    #print ' a veer map_x_fx type: ',type(map_x_fx)
    #print ' map_y_f_final_vec shape',map_y_f_final_vec.shape
    #print ' a veer map_x_final_vec: ',map_x_final_vec
    #print ' a veer map_x_final_vec[0]: ',map_x_final_vec[0]
    print'*************************'
    print 'x shape',x.shape
    print 'y shape',y.shape
    print 'map_x_f_final',map_x_f_final.shape
    print 'map_y_f_final',map_y_f_final.shape

    print 'map_y_final_vec shape',map_y_final_vec.shape
    print 'map_y_final_vec_ shape',map_y_final_vec_.shape
    print'*************************'

    #print map_x_final.size, map_y_final.size, map_x_f_final.size, map_y_f_final.size

    time_x     = np.arange(x.size)*float(1)/float(fs)
    time_y     = np.arange(y.size)*float(1)/float(fs)
        time_map_x = np.arange(map_x_f_final.size)*float(1)/float(fs)
    time_map_y = np.arange(map_y_f_final.size)*float(1)/float(fs)

    plt.plot(time_x,x, 'bo-',linewidth=1 ,label='funcion target: X ')#'bo-'
    plt.plot(time_y,y, 'go-',linewidth=1,markersize=3, label = 'funcion a proyectar :Y')#'g^-'

    plt.legend(fontsize= 'small')       
    plt.ylabel('Signal')
    plt.xlabel('time [s]') 
    plt.subplot(2,1,2) #los graficos mapeados
    grid(True)

    plt.plot(time_x,x, 'b',linewidth=1 ,label='funcion target: X sonido-vs')#o-
    plt.plot(time_y,y, 'g',linewidth=1,markersize=3, label = 'funcion a proyectar :Y sonido-p')#'g^-'

    plt.plot(map_y_final_vec_[:, 0]*float(1)/float(fs), map_y_final_vec_[:,1],'yo-',markersize=5, label='funcion Y mapeada donde convergen con DTW sobre X')#'m^'
    plt.ylabel('Signal')
    plt.xlabel('time [s]')          
    plt.legend(fontsize= 'small')       
    figname = "%s.jpg"%('alineado_dtw_'+name)
    plt.savefig(my_path+figname,dpi=200)    
    #plt.show()
        plt.close()
    mapeo_time      = map_y_final_vec_[:, 0]*float(1)/float(fs)
    mapeo_amplitude =  map_y_final_vec_[:,1]

    return mapeo_time, mapeo_amplitude

I am able to obtain the distance between both signals:maping test But I'm not sure with the final mapping. Am I doing something wrong with my mapping? I need to project one signal over the other, rescaling the first one with the other. I also tried with these two real signals:enter image description here I try to compare with:https://pypi.python.org/pypi/fastdtw https://pypi.python.org/pypi/fastdtw and also with mlp library, but I get different signal mapping.

我也把一切都装上了https://github.com/katejarne/dtw https://github.com/katejarne/dtw使用数据集生成最后的图形和映射。


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 python 进行动态时间扭曲(最终映射) 的相关文章

  • python 中的并行处理

    在 python 2 7 中进行并行处理的简单代码是什么 我在网上找到的所有示例都很复杂 并且包含不必要的代码 我该如何做一个简单的强力整数分解程序 在每个核心 4 上分解 1 个整数 我真正的程序可能只需要2个核心 并且需要共享信息 我知
  • 如何检查python xlrd库中的excel文件是否有效

    有什么办法与xlrd库来检查您使用的文件是否是有效的 Excel 文件 我知道还有其他库可以检查文件头 我可以使用文件扩展名检查 但为了多平台性我想知道是否有任何我可以使用的功能xlrd库本身在尝试打开文件时可能会返回类似 false 的内
  • 保留完整姓氏,在 pandas 列中获取名字的首字母(如果有的话,还有中间名)

    我有一个 pandas 数据框 其中有一列表示几位网球运动员的姓氏和姓名 如下所示 Player 0 Roddick Andy 1 Federer Roger 2 Tsonga Jo Wilfred 我想保留完整的姓氏并获取姓名的首字母和中
  • 如何在Python中同时运行两只乌龟?

    我试图让两只乌龟一起移动 而不是一只接着另一只移动 例如 a turtle Turtle b turtle Turtle a forward 100 b forward 100 但这只能让他们一前一后地移动 有没有办法让它们同时移动 有没有
  • Mac OS X 中文件系统的 Unicode 编码在 Python 中不正确?

    在 OS X 和 Python 中处理 Unicode 文件名有点困难 我试图在代码中稍后使用文件名作为正则表达式的输入 但文件名中使用的编码似乎与 sys getfilesystemencoding 告诉我的不同 采取以下代码 usr b
  • 如何在 Python 中加密并在 Java 中解密?

    我正在尝试在 Python 程序中加密一些数据并将其保存 然后在 Java 程序中解密该数据 在Python中 我像这样加密它 from Crypto Cipher import AES KEY 1234567890123456789012
  • 如何使用文本相似性删除 pandas 数据框中相似(不重复)的行?

    我有数千个数据 这些数据可能相似也可能不相似 使用 python 的默认函数 drop duplicates 并没有真正的帮助 因为它们只检测相似的数据 例如 如果我的数据包含类似以下内容怎么办 嗨 早上好 嗨 早上好 Python 不会将
  • 结构差异 sudo() run('sudo 命令')

    我想知道函数之间有什么区别sudo 和函数run sudo u user smth 文档上有 sudo 在所有运行方式上都是相同的 除了它总是换行 调用 sudo 程序中的给定命令以提供超级用户 特权 但有几次 sudo cmd 提示我输入
  • Django 的 request.FILES 出现 UnicodeDecodeError

    我在视图调用中有以下代码 def view request body u for filename f in request FILES items body body Filename filename n f read n 在某些情况下
  • 使用 python 绘制正值小提琴图

    我发现小提琴图信息丰富且有用 我使用 python 库 seaborn 然而 当应用于正值时 它们几乎总是在低端显示负值 我发现这确实具有误导性 尤其是在处理现实数据集时 在seaborn的官方文档中https seaborn pydata
  • 使用Python计算目录的大小?

    在我重新发明这个特殊的轮子之前 有没有人有一个很好的例程来使用 Python 计算目录的大小 如果例程能够很好地以 Mb Gb 等格式格式化大小 那就太好了 这会遍历所有子目录 总结文件大小 import os def get size s
  • Jython 和 SAX 解析器:允许的实体不超过 64000 个?

    我做了一个简单的测试xml saxJython 中的解析器在处理大型 XML 文件 800 MB 时遇到以下错误 Traceback most recent call last File src project xmltools py li
  • 使用 Keras np_utils.to_categorical 的问题

    我正在尝试将整数的 one hot 向量数组制作为 keras 将能够使用的 one hot 向量数组来拟合我的模型 这是代码的相关部分 Y train np hstack np asarray dataframe output vecto
  • 返回表示每组内最大值的索引的一系列数字位置

    考虑一下这个系列 np random seed 3 1415 s pd Series np random rand 100 pd MultiIndex from product list ABDCE list abcde One Two T
  • Elasticsearch 通过搜索返回拼音标记

    我用语音分析插件 https www elastic co guide en elasticsearch plugins current analysis phonetic html由于语音转换 从弹性搜索中进行一些字符串匹配 我的问题是
  • Django Admin 中的反向内联

    我有以下 2 个型号 现在我需要将模型 A 内联到模型 B 的页面上 模型 py class A models Model name models CharField max length 50 class B models Model n
  • 如何根据第一列创建新列,同时考虑Python Pandas中字母和列表的大小? [复制]

    这个问题在这里已经有答案了 我在 Python Pandas 中有 DataFrame 如下所示 col1 John Simon prd agc Ann White BeN and Ann bad list Ben Wayne 我需要这样做
  • TKinter 中的禁用/启用按钮

    我正在尝试制作一个像开关一样的按钮 所以如果我单击禁用按钮 它将禁用 按钮 有效 如果我再次按下它 它将再次启用它 我尝试了 if else 之类的东西 但没有成功 这是一个例子 from tkinter import fenster Tk
  • 从 pandas DataFrame 中删除少于 K 个连续 NaN

    我正在处理时间序列数据 我在从数据帧列中删除小于或等于阈值的连续 NaN 时遇到问题 我尝试查看一些链接 例如 标识连续 NaN 出现的位置以及计数 Pandas NaN 孔的游程长度 https stackoverflow com que
  • 查找总和为给定数字的值组合的函数

    这个帖子查找提供的 Sum 值的组合 https stackoverflow com a 20194023 1561176呈现函数subsets with sum 它在数组中查找总和等于给定值的值的组合 但由于这个帖子已经有6年多了 我发这

随机推荐