计算Dynamic Time Warping遇ValueError:输入向量需为1-D的问题求助
解决FastDTW运行时的"ValueError: Input vector should be 1-D."错误
问题原因
scipy提供的euclidean距离函数要求输入必须是1维数组,但fastdtw在计算过程中,会将序列中的每个单独元素作为参数传入距离函数。当你的序列是由标量组成的列表(比如x = [7,1,2,5,9])时,每个元素是单个数值而非1维数组,就会触发这个错误。
两种解决方案
方案一:自定义支持标量的欧氏距离函数
自己实现一个简单的欧氏距离函数,既兼容标量输入,也支持数组输入:
def custom_euclidean(a, b): return np.abs(a - b)
调用fastdtw时替换原有的euclidean函数即可:
dtw_distance, warp_path = fastdtw(x, y, dist=custom_euclidean)
方案二:将输入序列转换为二维数组
把每个标量元素包装成单元素的二维数组,让scipy的euclidean函数可以正确识别:
x = np.array([7, 1, 2, 5, 9]).reshape(-1, 1) y = np.array([1, 8, 0, 4, 4, 2, 0]).reshape(-1, 1)
之后直接使用原有的euclidean函数调用fastdtw即可。
修改后的完整代码示例(方案一)
import pandas as pd import numpy as np # Plotting Packages import matplotlib.pyplot as plt import seaborn as sbn import matplotlib as mpl mpl.rcParams['figure.dpi'] = 150 savefig_options = dict(format="png", dpi=150, bbox_inches="tight") # Computation packages from scipy.spatial.distance import euclidean from fastdtw import fastdtw 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 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 # 自定义兼容标量的欧氏距离函数 def custom_euclidean(a, b): return np.abs(a - b) # Create two sequences x = [7, 1, 2, 5, 9] y = [1, 8, 0, 4, 4, 2, 0] # 使用自定义距离函数调用fastdtw dtw_distance, warp_path = fastdtw(x, y, dist=custom_euclidean) cost_matrix = compute_accumulated_cost_matrix(x, y) # 输出结果验证 print(f"DTW距离: {dtw_distance}") print(f"Warp路径: {warp_path}")
内容的提问来源于stack exchange,提问作者Jab
相关产品推荐
相关产品推荐

