-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.js
88 lines (62 loc) · 2.67 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Global Vars
let load_tensorData;
let load_arrayData;
// Function to load and preprocess the CSV data
async function loadCSVData(normalized = false) {
const csvUrl = "0.001percent_2classes.csv";
// Fetch the CSV file
const response = await fetch(csvUrl);
const csvText = await response.text();
// Parse CSV text into an array of objects
const csvData = Papa.parse(csvText, { header: true, dynamicTyping: true }).data;
// Extract features and convert to Tensor
const features = ["duration", "srate", /* ... */];
let arrayData = csvData.map((row) => features.map((feature) => row[feature]));
// Only keep max 1K rows (algorithm already slow)
let tensorData = tf.tensor2d(arrayData).slice([0, 0], [1000, 2]);
// normalization (optional)
if (normalized) {
const { mean, variance } = tf.moments(tensorData, 0);
tensorData = tf.sub(tensorData, mean).div(tf.sqrt(variance));
arrayData = tensorData.arraySync();
}
return [tensorData, arrayData];
}
loadCSVData(false).then(([tensorData, arrayData]) => {
const numCentroids = 10;
const numIters = 1;
const eps = 6.0;
// save loaded values to global vars
load_tensorData = tensorData;
load_arrayData = arrayData;
kMeans(tensorData, numCentroids, numIters, eps).then((bestCentroids) => {
createScatterPlot("init-regular-data-scatter", arrayData,
bestCentroids.arraySync(), "K-Means Clustering with PCA - Initial Centroids");
});
});
function runkmeans() {
const numCentroids = 10;
const numIters = 1;
const eps = 6.0;
document.getElementById('btn-rawkmeans').style.display = 'none';
document.getElementById('txt-train').style.display = 'block'
kMeans(load_tensorData, numCentroids, numIters, eps).then((bestCentroids) => {
document.getElementById('txt-train').style.display = 'none'
createScatterPlot("rawkmeans-regular-data-scatter", load_arrayData,
bestCentroids.arraySync(), "K-Means Clustering with PCA");
});
}
function runkmeans_normalized() {
document.getElementById('btn-normkmeans').style.display = 'none';
document.getElementById('txt-train_norm').style.display = 'block'
loadCSVData(true).then(([tensorData, arrayData]) => {
const numCentroids = 10;
const numIters = 1;
const eps = 6.0;
kMeans(tensorData, numCentroids, numIters, eps).then((bestCentroids) => {
document.getElementById('txt-train_norm').style.display = 'none'
createScatterPlot("normkmeans-regular-data-scatter", arrayData,
bestCentroids.arraySync(), "K-Means Clustering with PCA - Normalized");
});
});
}