MC
unknown
javascript
2 years ago
3.4 kB
6
Indexable
function TSPWDif(allClasses, attributes, trainingSet, categoryAttr) {
let bestTests = [];
var maxDif = 0;
var attribute1 = -1;
var attribute2 = -1;
var match = [],
notMatch = [];
var initialEntropy = entropy(trainingSet, categoryAttr);
// Function to find candidate thresholds
function findCandidateThresholds(attr1, attr2) {
let sortedByRatio = [...trainingSet].sort((a, b) => {
let ratioA = parseFloat(a[attr1]) / parseFloat(a[attr2]);
let ratioB = parseFloat(b[attr1]) / parseFloat(b[attr2]);
return ratioA - ratioB;
});
let candidates = [];
for (let i = 0; i < sortedByRatio.length - 1; i++) {
if (sortedByRatio[i][categoryAttr] !== sortedByRatio[i + 1][categoryAttr]) {
let threshold = (parseFloat(sortedByRatio[i][attr1]) / parseFloat(sortedByRatio[i][attr2]) + parseFloat(sortedByRatio[i + 1][attr1]) / parseFloat(sortedByRatio[i + 1][attr2])) / 2;
candidates.push(threshold);
}
}
return candidates;
}
for (let i = 0; i < attributes.length; i++) {
for (let j = i + 1; j < attributes.length; j++) {
let attr1 = attributes[i];
let attr2 = attributes[j];
let candidateThresholds = findCandidateThresholds(attr1, attr2);
for (let weight of candidateThresholds) {
let leftList = [];
let rightList = [];
let classMatrix = [new Array(allClasses.length).fill(0), new Array(allClasses.length).fill(0)];
// Division
for (let element of trainingSet) {
const attribute = element[categoryAttr];
if (parseFloat(element[attr1]) / parseFloat(element[attr2]) < weight) {
leftList.push(element);
classMatrix[0][allClasses.indexOf(attribute)]++;
} else {
rightList.push(element);
classMatrix[1][allClasses.indexOf(attribute)]++;
}
}
let matchEntropy = entropy(leftList, categoryAttr);
let notMatchEntropy = entropy(rightList, categoryAttr);
// Calculating informational gain
let newEntropy = (matchEntropy * leftList.length + notMatchEntropy * rightList.length) / trainingSet.length;
let currentDif = initialEntropy - newEntropy;
if (currentDif > maxDif) {
maxDif = currentDif;
attribute1 = attr1;
attribute2 = attr2;
match = leftList;
notMatch = rightList;
bestTests.push({
maxDif: currentDif,
attribute1: attr1,
attribute2: attr2,
match: leftList,
notMatch: rightList,
direction: '<',
L_weight: weight,
});
}
}
}
}
bestTests.sort((a, b) => b.maxDif - a.maxDif);
return { maxDif, attribute1, attribute2, match, notMatch, direction: '<', L_weight: bestTests[0]?.L_weight, tests: bestTests };
}
Editor is loading...
Leave a Comment