improve performance

This commit is contained in:
Fabian Freund
2025-09-30 16:49:43 +02:00
parent 68d0d5584c
commit d8caff6475
2 changed files with 8 additions and 7 deletions
@@ -88,11 +88,10 @@ double _getCentroidInertia(
// Compute sum of squared distances to centroid // Compute sum of squared distances to centroid
for (final index in cluster) { for (final index in cluster) {
final point = embeddings[index]; final point = embeddings[index];
double distanceSquared = 0.0;
for (int i = 0; i < dimensions; i++) { for (int i = 0; i < dimensions; i++) {
distanceSquared += math.pow(point[i] - centroid[i], 2); final diff = point[i] - centroid[i];
totalDistance += diff * diff;
} }
totalDistance += distanceSquared;
} }
} }
@@ -93,7 +93,7 @@ List<List<double>> initializeCentroidsSorted({
} else { } else {
centerId = (randomFunc() * nSamples).floor(); centerId = (randomFunc() * nSamples).floor();
} }
centers[0] = List<double>.from(X[centerId]); centers[0] = X[centerId];
} else { } else {
centers[0] = vectorNormalize( centers[0] = vectorNormalize(
vectorMean(anchorIndices.map((a) => X[a]).toList()), vectorMean(anchorIndices.map((a) => X[a]).toList()),
@@ -158,7 +158,7 @@ List<List<double>> initializeCentroidsSorted({
sumOfDistances = candidatesSumOfDistances[bestCandidateIdx]; sumOfDistances = candidatesSumOfDistances[bestCandidateIdx];
// Pick best candidate // Pick best candidate
centers[c] = List<double>.from(X[bestCandidate]); centers[c] = X[bestCandidate];
} }
return centers; return centers;
@@ -192,7 +192,8 @@ double euclideanDistance(
}) { }) {
double sum = 0; double sum = 0;
for (int i = 0; i < point1.length; i++) { for (int i = 0; i < point1.length; i++) {
sum += math.pow(point1[i] - point2[i], 2); final diff = point1[i] - point2[i];
sum += diff * diff;
} }
return squareResult ? sum : math.sqrt(sum); return squareResult ? sum : math.sqrt(sum);
} }
@@ -231,7 +232,8 @@ List<double> euclideanDistancesSquared(
return X.map((row) { return X.map((row) {
double distSq = 0; double distSq = 0;
for (int i = 0; i < row.length; i++) { for (int i = 0; i < row.length; i++) {
distSq += math.pow(row[i] - point[i], 2); final diff = row[i] - point[i];
distSq += diff * diff;
} }
return distSq; return distSq;
}).toList(); }).toList();