Public
Edited
Oct 26, 2023
Importers
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
function SDbw(vectors, labels, centroidNearest=true, centroids=null) {
const grouped = d3.flatGroup(vectors, (d,i) => labels[i])
if (centroids == null) {
centroids = grouped.map(([label, vectors]) => math.mean(vectors, 0))
}

if (centroidNearest) {
for (let i = 0; i < centroids.length; i++) {
const vectorDistances = vectors.map(vec => [vec, math.distance(vec, centroids[i])])
const min = vectorDistances[d3.minIndex(vectorDistances, d => d[1])][0]
centroids[i] = min
}
}

const clusters = grouped.map(([label, vectors], i) => ({vectors, label, centroid: centroids[i]}))

const density = interClusterDensity(clusters, vectors)
const scattering = clusterScattering(clusters, vectors)
return density + scattering
}
Insert cell
Insert cell
Insert cell
Insert cell
function interClusterDensity(clusters, data) {
let meanClusterStd = 0
for (const cluster of clusters) {
const stdMatrix = fstd(cluster.vectors, 0)
meanClusterStd += math.sqrt(math.dot(math.transpose(stdMatrix), stdMatrix))
}
meanClusterStd = math.sqrt(meanClusterStd) / clusters.length


const clusterCentroids = clusters.map(d => d.centroid)

const clusterDensities = clusterCentroids.map(centroid => density(centroid, data, meanClusterStd))

let total = 0
for (let i = 0; i < clusterCentroids.length; i++) {
for (let j = 0; j < clusterCentroids.length; j++) {
if (i == j) continue

const mid = midpoint(clusterCentroids[i], clusterCentroids[j])

const midDensity = (density(mid, data, meanClusterStd))
const iClusterDensity = clusterDensities[i]
const jClusterDensity = clusterDensities[j]

total += midDensity / Math.max(iClusterDensity, jClusterDensity)
}
}

const k = clusters.length
return total / (k * (k - 1))
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more