// 归一化
function normalizeSegment(arr) {
let min = Math.min(...arr.map(row => Math.min(...row)));
let max = Math.max(...arr.map(row => Math.max(...row)));
return arr.map(row => row.map(value => (value - min) / (max - min)));
}
// 计算欧几里得距离
function calculateSimilarity(arr1, arr2) {
let similarity = 0;
for (let i = 0; i < arr1.length; i++) {
let distance = 0;
for (let j = 0; j < arr1[i].length; j++) {
distance += Math.pow(arr1[i][j] - arr2[i][j], 2);
}
similarity += 1 / (1 + Math.sqrt(distance));
}
return similarity / arr1.length;
}
// 去重,保留相似序列片段中相似度最大的值
function deduplication(obj) {
let keys = Object.keys(obj).map(Number);
keys.sort((a, b) => a - b);
let result = {};
let maxKey = keys[0];
let maxValue = obj[maxKey];
for (let i = 1; i < keys.length; i++) {
if (keys[i] - keys[i - 1] === 1) {
if (obj[keys[i]] > maxValue) {
maxKey = keys[i];
maxValue = obj[maxKey];
}
} else {
result[maxKey] = maxValue;
maxKey = keys[i];
maxValue = obj[maxKey];
}
}
result[maxKey] = maxValue;
return result
}
// 计算两个数组之间的欧几里得距离,找出与inputArr的所有相似序列片段
function findSimilarSegments(inputArr, largeArr, threshold = 0.8, windowSize = null) {
windowSize = windowSize || inputArr.length;
let nInputArr = normalizeSegment(inputArr);
let similarityDict = {};
for (let i = 0; i < largeArr.length - windowSize + 1; i++) {
let subArr = normalizeSegment(largeArr.slice(i, i + windowSize));
let similarity = calculateSimilarity(nInputArr, subArr);
if (similarity > threshold) {
similarityDict[i] = similarity;
}
}
// return deduplication(similarityDict);
return similarityDict;
}
上一篇
JavaScript-计算两个数组之间的DTW距离
2023-06-20
下一篇
JavaScript-数组转SVG
2023-06-20