本文整理汇总了Python中fastdtw.fastdtw方法的典型用法代码示例。如果您正苦于以下问题:Python fastdtw.fastdtw方法的具体用法?Python fastdtw.fastdtw怎么用?Python fastdtw.fastdtw使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类fastdtw
的用法示例。
在下文中一共展示了fastdtw.fastdtw方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: compute_dtw_dist
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def compute_dtw_dist(part_list, degreeList, dist_func):
dtw_dist = {}
for v1, nbs in part_list:
lists_v1 = degreeList[v1] # lists_v1 :orderd degree list of v1
for v2 in nbs:
lists_v2 = degreeList[v2] # lists_v1 :orderd degree list of v2
max_layer = min(len(lists_v1), len(lists_v2)) # valid layer
dtw_dist[v1, v2] = {}
for layer in range(0, max_layer):
dist, path = fastdtw(
lists_v1[layer], lists_v2[layer], radius=1, dist=dist_func)
dtw_dist[v1, v2][layer] = dist
return dtw_dist
示例2: calc_distances
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def calc_distances(part, compactDegree = False):
vertices = restoreVariableFromDisk('split-vertices-'+str(part))
degreeList = restoreVariableFromDisk('split-degreeList-'+str(part))
distances = {}
if compactDegree:
dist_func = cost_max
else:
dist_func = cost
for v1,nbs in vertices.iteritems():
lists_v1 = degreeList[v1]
for v2 in nbs:
t00 = time()
lists_v2 = degreeList[v2]
max_layer = min(len(lists_v1),len(lists_v2))
distances[v1,v2] = {}
for layer in range(0,max_layer):
dist, path = fastdtw(lists_v1[layer],lists_v2[layer],radius=1,dist=dist_func)
distances[v1,v2][layer] = dist
t11 = time()
logging.info('fastDTW between vertices ({}, {}). Time: {}s'.format(v1,v2,(t11-t00)))
preprocess_consolides_distances(distances)
saveVariableOnDisk(distances,'distances-'+str(part))
return
示例3: calc_distances_all
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def calc_distances_all(vertices,list_vertices,degreeList,part, compactDegree = False):
distances = {}
cont = 0
if compactDegree:
dist_func = cost_max
else:
dist_func = cost
for v1 in vertices:
lists_v1 = degreeList[v1]
for v2 in list_vertices[cont]:
lists_v2 = degreeList[v2]
max_layer = min(len(lists_v1),len(lists_v2))
distances[v1,v2] = {}
for layer in range(0,max_layer):
#t0 = time()
dist, path = fastdtw(lists_v1[layer],lists_v2[layer],radius=1,dist=dist_func)
#t1 = time()
#logging.info('D ({} , {}), Tempo fastDTW da camada {} : {}s . Distância: {}'.format(v1,v2,layer,(t1-t0),dist))
distances[v1,v2][layer] = dist
cont += 1
preprocess_consolides_distances(distances)
saveVariableOnDisk(distances,'distances-'+str(part))
return
示例4: get_similarity_matrix
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def get_similarity_matrix(self) -> np.ndarray:
"""
Returns time-series similarity matrix computed using dynamic time warping.
Returns:
an asset-to-asset similarity matrix.
Raises:
QiskitFinanceError: no data loaded
"""
try:
if not self._data:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
except AttributeError:
raise QiskitFinanceError(
'No data loaded, yet. Please run the method run() first to load the data.'
)
self.rho = np.zeros((self._n, self._n))
for i_i in range(0, self._n):
self.rho[i_i, i_i] = 1.
for j_j in range(i_i + 1, self._n):
this_rho, _ = fastdtw.fastdtw(self._data[i_i], self._data[j_j])
this_rho = 1.0 / this_rho
self.rho[i_i, j_j] = this_rho
self.rho[j_j, i_i] = this_rho
return self.rho
# gets coordinates suitable for plotting
# it does not have to be overridden in non-abstract derived classes.
示例5: compare_metrics
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def compare_metrics(X, num=10):
"""
"""
fig, axarr = plt.subplots(num, 4, figsize=(15, 15))
xx = np.arange(30)
fig.suptitle(' '.join(['dtw', 'cos', 'euc', 'rbf']))
for (col, distance_measure) in enumerate([fastdtw, cos_dist, euclidean, my_rbf]):
dists = []
for i in range(num):
try:
d, _ = distance_measure(X[0], X[i])
except TypeError:
d = distance_measure(X[0], X[i])
if col == 3:
d = -d
dists.append(dtw)
# now, plot in order
for (i, j) in enumerate(np.argsort(dists)):
axarr[i, col].plot(xx, X[j])
axarr[i, col].plot(xx, X[0], alpha=0.5)
dtw, _ = fastdtw(X[0], X[j])
title = '%.1f %.1f %.1f %.1f' % (dtw, cos_dist(X[0], X[j]), euclidean(X[0], X[j]), my_rbf(X[0], X[j]))
#title = '%.1f' % (dtw)
axarr[i, col].set_title(title)
axarr[i, col].set_ylim(-1.1, 1.1)
plt.tight_layout()
plt.savefig("dtw.png")
plt.clf()
plt.close()
return True
示例6: read_and_synthesize
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def read_and_synthesize(file_list, arch, MCD, input_feat, output_feat):
for i, (bin_path, src_feat_path, trg_feat_path) in enumerate(file_list):
input_feat_dim = arch['feat_param']['dim'][input_feat]
basename = os.path.splitext(os.path.split(bin_path)[-1])[0]
# read source features , target features and converted mcc
src_data = Whole_feature_reader(src_feat_path, arch['feat_param'])
trg_data = Whole_feature_reader(trg_feat_path, arch['feat_param'])
cvt = np.fromfile(bin_path, dtype = np.float32).reshape([-1, arch['feat_param']['dim'][output_feat]])
# Handle if not mcc
if output_feat == 'sp':
cvt = np.power(10., cvt)
en_cvt = np.expand_dims(src_data['en_sp'], 1) * cvt
mcc_cvt = pysptk.sp2mc(en_cvt, arch['feat_param']['mcep_dim'], arch['feat_param']['mcep_alpha'])[:, 1:]
elif output_feat == 'mcc':
mcc_cvt = cvt
else:
logging.info('Currently do not support types other than mcc and sp.' )
raise ValueError
# non-silence parts
trg_idx = np.where(trg_data['f0']>0)[0]
trg_mcc = trg_data['mcc'][trg_idx]
src_idx = np.where(src_data['f0']>0)[0]
mcc_cvt = mcc_cvt[src_idx]
# DTW
_, path = fastdtw(mcc_cvt, trg_mcc, dist=scipy.spatial.distance.euclidean)
twf = np.array(path).T
cvt_mcc_dtw = mcc_cvt[twf[0]]
trg_mcc_dtw = trg_mcc[twf[1]]
# MCD
diff2sum = np.sum((cvt_mcc_dtw - trg_mcc_dtw)**2, 1)
mcd = np.mean(10.0 / np.log(10.0) * np.sqrt(2 * diff2sum), 0)
logging.info('{} {}'.format(basename, mcd))
MCD.append(mcd)
示例7: __init__
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def __init__(self, x, y, dist=lambda x, y: numpy.linalg.norm(x - y), radius=1) -> None:
assert x.ndim == 2 and y.ndim == 2
_, path = fastdtw.fastdtw(x, y, radius=radius, dist=dist)
path = numpy.array(path)
self.normed_path_x = path[:, 0] / len(x)
self.normed_path_y = path[:, 1] / len(y)
示例8: calc_distances
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def calc_distances(part, compactDegree=False):
vertices = restoreVariableFromDisk('split-vertices-' + str(part))
degreeList = restoreVariableFromDisk('split-degreeList-' + str(part))
distances = {}
if compactDegree:
dist_func = ct_max
else:
dist_func = ct
for v1, nbs in vertices.items():
lists_v1 = degreeList[v1]
for v2 in nbs:
t00 = time()
lists_v2 = degreeList[v2]
max_layer = min(len(lists_v1), len(lists_v2))
distances[v1, v2] = {}
for layer in range(0, max_layer):
dist, path = fastdtw(lists_v1[layer], lists_v2[layer], radius=1, dist=dist_func)
distances[v1, v2][layer] = dist
t11 = time()
logging.info('fastDTW between vertices ({}, {}). Time: {}s'.format(v1, v2, (t11 - t00)))
preprocess_consolides_distances(distances)
saveVariableOnDisk(distances, 'distances-' + str(part))
return
示例9: calc_distances_all
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def calc_distances_all(vertices, list_vertices, degreeList, part, compactDegree=False):
distances = {}
cont = 0
if compactDegree:
dist_func = ct_max
else:
dist_func = ct
for v1 in vertices:
lists_v1 = degreeList[v1]
for v2 in list_vertices[cont]:
lists_v2 = degreeList[v2]
max_layer = min(len(lists_v1), len(lists_v2))
distances[v1, v2] = {}
for layer in range(0, max_layer):
# t0 = time()
dist, path = fastdtw(lists_v1[layer], lists_v2[layer], radius=1, dist=dist_func)
# t1 = time()
# logging.info('D ({} , {}), Tempo fastDTW da camada {} : {}s . Distância: {}'.format(v1,v2,layer,(t1-t0),dist))
distances[v1, v2][layer] = dist
cont += 1
preprocess_consolides_distances(distances)
saveVariableOnDisk(distances, 'distances-' + str(part))
return
示例10: mel_cepstral_distorision
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def mel_cepstral_distorision(S1, S2, num_mfcc):
def mcd(s1, s2):
diff = s1 - s2
return np.average(np.sqrt(np.sum(diff*diff, axis=0)))
x, y = get_spectrogram_mfcc(S1, num_mfcc)[1:], get_spectrogram_mfcc(S2, num_mfcc)[1:]
x, y = x.T, y.T
_, path = fastdtw(x, y, dist=mcd)
pathx, pathy = map(list,zip(*path))
x, y = x[pathx].T, y[pathy].T
return mcd(x, y)
示例11: mel_cepstral_distorision
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def mel_cepstral_distorision(S1, S2, mode):
"""Compute Mel Cepstral Distorsion between two mel spectrograms.
Arguments:
S1 and S2 -- mel spectrograms
mode -- 'cut' to cut off frames of longer seq.
'stretch' to stretch linearly the shorter seq.
'dtw' to compute DTW with minimal possible MCD
"""
def mcd(s1, s2):
diff = s1 - s2
return np.average(np.sqrt(np.sum(diff*diff, axis=0)))
x, y = get_spectrogram_mfcc(S1)[1:], get_spectrogram_mfcc(S2)[1:]
if mode == 'cut':
if y.shape[1] > x.shape[1]: y = y[:,:x.shape[1]]
if x.shape[1] > y.shape[1]: x = x[:,:y.shape[1]]
elif mode == 'stretch':
if x.shape[1] > y.shape[1]:
m = x.shape[1]
y = np.array([y[:, i * y.shape[1]//m] for i in range(m)]).T
else:
m = y.shape[1]
x = np.array([x[:, i * x.shape[1]//m] for i in range(m)]).T
elif mode == 'dtw':
x, y = x.T, y.T
_, path = fastdtw(x, y, dist=mcd)
pathx, pathy = map(list,zip(*path))
x, y = x[pathx].T, y[pathy].T
return mcd(x, y)
示例12: estimate_twf
# 需要导入模块: import fastdtw [as 别名]
# 或者: from fastdtw import fastdtw [as 别名]
def estimate_twf(orgdata, tardata, distance='melcd', fast=True, otflag=None):
"""time warping function estimator
Parameters
---------
orgdata : array, shape(`T_org`, `dim`)
Array of source feature
tardata : array, shape(`T_tar`, `dim`)
Array of target feature
distance : str, optional
distance function
`melcd` : mel-cepstrum distortion
fast : bool, optional
Use fastdtw instead of dtw
Default set to `True`
otflag : str,
Perform alignment into either original or target length
`org` : align into original length
`tar` : align into target length
Default set to None
Returns
---------
twf : array, shape(`2`, `T`)
Time warping function between original and target
"""
if distance == 'melcd':
def distance_func(x, y): return melcd(x, y)
else:
raise ValueError('other distance metrics than melcd does not support.')
if otflag is None:
# use dtw or fastdtw
if fast:
_, path = fastdtw(orgdata, tardata, dist=distance_func)
twf = np.array(path).T
else:
_, _, _, twf = dtw(orgdata, tardata, distance_func)
else:
# use dtw_c to align target/original feature vector
ldim = orgdata.shape[1] - 1
if otflag == 'org':
_, twf, _, _ = dtw_c.dtw_org_to_trg(tardata, orgdata,
0, ldim, 5.0, 100.0, 100.0)
else:
_, twf, _, _ = dtw_c.dtw_org_to_trg(orgdata, tardata,
0, ldim, 5.0, 100.0, 100.0)
twf[:, 1] = np.array(range(twf.shape[0])) # replace target index by frame number
twf = twf.T
if otflag == 'org':
twf = twf[::-1, :] # swap cols
assert twf.shape[0] == orgdata.shape[0]
else:
assert twf.shape[1] == tardata.shape[0]
return twf