-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinearregression.html
More file actions
424 lines (327 loc) · 15.9 KB
/
linearregression.html
File metadata and controls
424 lines (327 loc) · 15.9 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Tensorflow js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis"></script>
<!-- Compiled and minified CSS -->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>tensorflow.js</title>
</head>
<body>
<script>
console.log("Connected");
//---------------------------------------------------------------------------------
async function plot(pointsArray, featureName, predictedPointsArray = null) {
const values = [pointsArray.slice(0, 1000)];
const series = ["original"];
if (Array.isArray(predictedPointsArray)) {
values.push(predictedPointsArray);
series.push("predicted");
}
tfvis.render.scatterplot({
name: `${featureName} vs House Price`
}, {
values,
series
}, {
xLabel: featureName,
yLabel: "Price",
height: 300,
})
}
//--------------------------------------------------------
async function plotPredictionLine() {
const [xs, ys] = tf.tidy(() => {
const normalisedXs = tf.linspace(0, 1, 100);
const normalisedYs = model.predict(normalisedXs.reshape([100, 1]));
const xs = denormalise(normalisedXs, normalisedFeature.min, normalisedFeature.max)
const ys = denormalise(normalisedYs, normalisedLabel.min, normalisedLabel.max);
return [xs.dataSync(), ys.dataSync()];
});
const predictedPoints = Array.from(xs).map((val, index) => {
return {
x: val,
y: ys[index]
};
});
await plot(points, "Square feet", predictedPoints);
}
//-------------------------------------------------------------------------
function normalise(tensor, previousMin = null, previousMax = null) {
const min = previousMin || tensor.min();
const max = previousMax || tensor.max();
const normalisedTensor = tensor.sub(min).div(max.sub(min));
return {
tensor: normalisedTensor,
min,
max
};
}
function denormalise(tensor, min, max) {
const denormalisedTensor = tensor.mul(max.sub(min)).add(min);
return denormalisedTensor;
}
//---------------------------------------------------------------------
//creating model area
function createModel() {
model = tf.sequential();
model.add(tf.layers.dense({
units: 10,
useBias: true,
activation: 'sigmoid',
inputDim: 1,
}));
model.add(tf.layers.dense({
units: 10,
useBias: true,
activation: 'sigmoid',
}));
model.add(tf.layers.dense({
units: 1,
useBias: true,
activation: 'sigmoid',
}));
const optimizer = tf.train.sgd(0.1);
model.compile({
loss: 'meanSquaredError',
optimizer,
})
return model;
}
//---------------------------------------------------------------------
async function trainModel(model, trainingFeatureTensor, trainingLabelTensor) {
const {
onBatchEnd,
onEpochEnd
} = tfvis.show.fitCallbacks({
name: "Training Performance"
}, ['loss'])
return model.fit(trainingFeatureTensor, trainingLabelTensor, {
batchSize: 32,
epochs: 20,
validationSplit: 0.2,
callbacks: {
onEpochEnd,
onEpochBegin: async function() {
await plotPredictionLine();
const layer = model.getLayer(undefined, 0);
tfvis.show.layer({
name: "Layer 1"
}, layer);
}
}
});
}
//----------------------------------------------------------------------------
async function predict() {
const predictionInput = parseInt(document.getElementById("prediction-input").value);
if (isNaN(predictionInput)) {
alert("Please enter a valid number!");
} else if (predictionInput < 200) {
alert("please enter a number greater then 200 or equal");
} else {
tf.tidy(() => {
const inputTensor = tf.tensor1d([predictionInput]);
const normalisedInput = normalise(inputTensor, normalisedFeature.min, normalisedFeature.max);
const normalisedOutputTensor = model.predict(normalisedInput.tensor);
const outputTensor = denormalise(normalisedOutputTensor, normalisedLabel.min, normalisedLabel.max);
const outputValue = outputTensor.dataSync()[0];
const outputValueRounded = (outputValue / 1000).toFixed(0) * 1000;
document.getElementById("prediction-output").innerHTML = `The Predicted house price is <br>` +
`<span style = "font-size: 2em">\$ ${outputValueRounded}</span>`;
});
}
}
//---------------------------------------------------------------------------------------------
async function load() {
const storageKey = `localstorage://${storageID}`;
const models = await tf.io.listModels();
const modelInfo = models[storageKey];
if (modelInfo) {
model = await tf.loadLayersModel(storageKey);
tfvis.show.modelSummary({
name: "Model summary"
}, model);
await plotPredictionLine();
const layer = model.getLayer(undefined, 0);
tfvis.show.layer({
name: "Layer 1"
}, layer);
document.getElementById("model-status").innerHTML = `Trained(saved ${modelInfo.dateSaved})`;
document.getElementById("predict-button").removeAttribute("disabled");
document.getElementById("test-button").removeAttribute("disabled");
} else {
alert("Could not load:no saved model found");
}
}
//------------------------------------------------------------------------------------
const storageID = "king-county-price-regression"
async function save() {
const saveResults = await model.save(`localstorage://${storageID}`);
document.getElementById("model-status").innerHTML = `Trained(saved ${saveResults.modelArtifactsInfo.dateSaved})`;
}
//-----------------------------------------------------------------------------
async function test() {
const lossTensor = model.evaluate(testingFeatureTensor, testingLabelTensor);
const loss = (await lossTensor.dataSync())[0];
console.log(`Testing set loss:${loss}`);
document.getElementById("testing-status").innerHTML = `Testing set loss:${loss.toPrecision(5)}`;
}
//-----------------------------------------------------------------------------
// Train model
async function train() {
// Disable all buttons and update status
["train", "test", "load", "predict", "save"].forEach(id => {
document.getElementById(`${id}-button`).setAttribute("disabled", "disabled");
});
document.getElementById("model-status").innerHTML = "Training in progress....";
const model = createModel();
tfvis.show.modelSummary({
name: "Model summary"
}, model);
const layer = model.getLayer(undefined, 0);
tfvis.show.layer({
name: "Layer 1"
}, layer);
await plotPredictionLine();
const result = await trainModel(model, trainingFeatureTensor, trainingLabelTensor);
console.log(result);
const trainingLoss = result.history.loss.pop();
console.log(`Training set loss: ${trainingLoss}`);
const validationLoss = result.history.val_loss.pop();
console.log(`Validation set loss: ${validationLoss}`);
document.getElementById("model-status").innerHTML = "Trained(unsaved)\n" +
`Loss: ${trainingLoss.toPrecision(5)}\n` + `Validation loss: ${validationLoss.toPrecision(5)}`;
document.getElementById("test-button").removeAttribute("disabled");
document.getElementById("save-button").removeAttribute("disabled");
}
async function toggleVisor() {
tfvis.visor().toggle();
}
//---------------------------------------------------------------------------------------
// we need to make variables global so we can call them from anywhere.
let normalisedFeature, normalisedLabel;
let trainingFeatureTensor, trainingLabelTensor;
let model;
let points;
//---------------------------------------------------------------
async function plotParams(weight, bias) {
model.getLayer(null, 0).setWeights([
tf.tensor2d([
[weight]
]), //kernel or weight (input multiplier)
tf.tensor1d([bias]), //bias
])
await plotPredictionLine();
const layer = model.getLayer(undefined, 0);
tfvis.show.layer({
name: "Layer 1"
}, layer);
}
//-----------------------------------------------------------------
async function run() {
// Ensure backend has initialized
await tf.ready();
// Import from CSV
const houseSalesDataset = tf.data.csv("http://127.0.0.1:8080/kc_house_data.csv");
// Extract x and y values to plot
const pointsDataset = houseSalesDataset.map(record => ({
x: record.sqft_living,
y: record.price,
}));
points = await pointsDataset.toArray();
if (points.length % 2 !== 0) { // If odd number of elements
points.pop(); // remove one element
}
tf.util.shuffle(points);
plot(points, "Square feet");
// Extract Features (inputs)
const featureValues = points.map(p => p.x);
const featureTensor = tf.tensor2d(featureValues, [featureValues.length, 1]);
// Extract Labels (outputs)
const labelValues = points.map(p => p.y);
const labelTensor = tf.tensor2d(labelValues, [labelValues.length, 1]);
// Normalise features and labels
normalisedFeature = normalise(featureTensor);
normalisedLabel = normalise(labelTensor);
// memory management
featureTensor.dispose();
labelTensor.dispose();
///*********************************
[trainingFeatureTensor, testingFeatureTensor] = tf.split(normalisedFeature.tensor, 2);
[trainingLabelTensor, testingLabelTensor] = tf.split(normalisedLabel.tensor, 2);
//update status and enable train button section
document.getElementById("model-status").innerHTML = "Model not Trained";
document.getElementById("train-button").removeAttribute("disabled");
document.getElementById("load-button").removeAttribute("disabled");
}
run();
</script>
<!-- start of UI -->
<!-- Header -->
<div class="section no-pad-bot" id="index-banner">
<div class="container">
<h5 class="header center blue-text small">Linear regression with TensorFlow.js</h5>
<div class="row center">
<h6 class="header col s12 light">Train a model to predict house price from living space.</h6>
</div>
</div>
</div>
<!-- Misc buttons -->
<div class="section no-pad-bot light-blue lighten-4">
<div class="container">
<div class="row center">
<button id="toggle-button" class="waves-effect waves-light light-blue btn-small" onclick="toggleVisor()">Toggle Visor</button>
<br/><br/>
</div>
</div>
</div>
<!-- Main functionality -->
<div class="container">
<div class="section">
<div class="row">
<!-- Training -->
<div class="col s12 m6">
<div class="icon-block">
<h3 class="center light-blue-text"><i class="material-icons" style="font-size: 2em">build</i></h3>
<h5 class="center">Train & Test</h5>
<p class="light"></p>
<div>
<p><label>Training status:</label></p>
<pre class="grey lighten-4" style="overflow-x: auto"><em id="model-status">Loading data...</em></pre>
<p><label>Testing status:</label></p>
<pre class="grey lighten-4" style="overflow-x: auto"><em id="testing-status">Not yet tested</em></pre>
<button autocomplete="off" id="train-button" class="waves-effect light-blue waves-light btn" disabled onclick="train()">Train New Model</button>
<button autocomplete="off" id="test-button" class="waves-effect light-blue waves-light btn" disabled onclick="test()">Test Model</button>
</div>
<br/>
<div>
<button autocomplete="off" id="load-button" class="waves-effect light-blue waves-light btn-small" disabled onclick="load()">Load Model</button>
<button autocomplete="off" id="save-button" class="waves-effect light-blue waves-light btn-small" disabled onclick="save()">Save Model</button>
</div>
</div>
</div>
<!-- Prediction -->
<div class="col s12 m6">
<div class="icon-block">
<h3 class="center light-blue-text"><i class="material-icons" style="font-size: 2em">timeline</i></h3>
<h5 class="center">Predict</h5>
<label>Square feet of living space: <input type="number" id="prediction-input" placeholder="2000"/></label>
<button autocomplete="off" id="predict-button" class="waves-effect light-blue waves-light btn" disabled onclick="predict()">Predict house price</button>
<p><strong id="prediction-output"></strong></p>
</div>
</div>
</div>
</div>
</div>
</body>
</html>