forked from metamath1/noviceml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinreg2.html
631 lines (543 loc) · 30.9 KB
/
linreg2.html
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!--link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous"-->
<link rel="stylesheet" type="text/css" href="style/bootstrap.min.css"/>
<link rel="stylesheet" type="text/css" href="style/style.css"/>
<link href="http://cdn.jsdelivr.net/gh/joungkyun/font-d2coding/d2coding.css" rel="stylesheet" type="text/css">
<style>
#jog_dial_w_wheel {
background-color: rgb(100,100,100) !important;
}
#jog_dial_w_knob {
background-color: rgb(100,100,100) !important;
}
#jog_dial_b_wheel {
background-color: rgb(100,100,100) !important;
}
#jog_dial_b_knob {
background-color: rgb(100,100,100) !important;
}
.hypothesis {
color: rgb(52,138,189);
}
.target{
color: rgb(213,94,0);
}
</style>
</head>
<body style="background-color:#F9F9F9;">
<div class="container" style="margin-top:20px;border:0px solid #FF0000;">
<div class="row">
<div class="col-6" style="border:0px solid #00FF00;">
<div class="card" style="float:left;margin-top:5px;">
<div class="card-header">Linear Regression</div>
<div class="card-body" style="border:0px solid #FF0000;">
<div id="graph1" style="float:left;width:490px;height:434px;border:0px solid #FF0000;margin-top:10px;"></div>
</div>
</div>
<!--휠 여기로...-->
<div style="display:inline-block;border:0px solid #FF0000;vertical-align:top;margin-left:100px;margin-top:30px;">
<div style="display: inline-block;width:120px;border:0px solid #FF0000;margin-top:55px;vertical-align:top;">
<div class="dial">
<div id="jog_dial_w"></div>
<p id="jog_dial_w_meter">
w<sub>1</sub> : <span id="w_value">0</span>
</p>
</div>
</div>
<div style="display: inline-block;width:120px;border:0px solid #0000FF;margin-top:55px;margin-left:10px;vertical-align:top;">
<div class="dial">
<div id="jog_dial_b"></div>
<p id="jog_dial_b_meter">
w<sub>0</sub> : <span id="b_value">0</span>
</p>
</div>
</div>
<div style="border:0px solid #0000FF;margin-top:20px;margin-left:5px;margin-right:5px;">
<div class="form-group">
<select class="custom-select" id="dataset">
<option value="line">Linear</option>
<!--option value="sin">Sin</option-->
</select>
</div>
</div>
<div style="border:0px solid #0000FF;margin-top:10px;margin-left:5px;margin-right:5px;">
<div class="form-group">
<div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="view-cost">
<label class="custom-control-label" for="view-cost">cost</label>
</div>
</div>
<div class="form-group">
<button type="button" class="btn btn-primary btn-sm" id="learn">Learn</button>
<button type="button" class="btn btn-danger btn-sm" id="stop">Stop</button>
</div>
</div>
</div>
</div>
<div class="col-6" style="border:0px solid #00FF00;">
<div class="card" style="float:left;margin-top:5px;">
<div class="card-header">Cost Function 2D</div>
<div class="card-body" style="border:0px solid #FF0000;padding:10px;">
<h5 class="card-title"><span id="cost_meter"></span></h5>
<div id="graph2" style="float:left;width:400px;height:300px;border:0px solid #FF0000;margin-top:10px;margin-left:20px;"></div>
</div>
</div>
<div class="card" style="float:left;margin-top:5px;">
<div class="card-header">Cost Function 3D</div>
<div class="card-body" style="border:0px solid #FF0000;padding:3px;">
<div id="graph3" style="float:left;width:434px;height:300px;border:0px solid #FF0000;margin-top:10px;margin-left:0px;"></div>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="./jogDial.min.js"></script><!--https://github.com/ohsiwon/JogDial.js-->
<!--script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script-->
<script>
/*
* numpy.linspace() 함수의 구현
* https://gist.github.com/joates/6584908
*/
var linspace = function(a, b, n) {
if(typeof n === "undefined") n = Math.max(Math.round(b-a)+1,1);
if(n<2) { return n===1 ? [a] : []; }
var i,ret = Array(n);
n--;
for(i=n; i>=0; i--) { ret[i] = (i*b+(n-i)*a)/n; }
return ret;
}
/*
* cost function 1/2 * sum_{i=1}^{N} (t_i - y_i)^2
*/
var cost = function(w, b, X, T) {
Y = X.map(function(x){return w*x + b;});
C = 0.0;
for(var i in X) { C += Math.pow(T[i]-Y[i], 2); }
C = (1/2)*C;
return C;
}
/*
* calc. cost function value Z for drawing cost function
*/
var draw_cost = function(X, Y, data) {
var i, j;
var grid_size = X.length;
var Z = new Array(grid_size);
for(i = 0; i < grid_size; i++) {
Z[i] = new Array(grid_size);
for(j = 0; j < grid_size; j++)
Z[i][j] = cost(X[j], Y[i], data.x, data.y);
}
return Z;
}
$( document ).ready(function() {
var GRAPH = document.getElementById('graph1');
var GRAPH2 = document.getElementById('graph2');
var GRAPH3 = document.getElementById('graph3');
var domain = {'line' : linspace(-1, 1, 100), 'sin' : linspace(-0.5, 1.5, 100)}
// 셀렉트 박스로 부터 현재 데이터 세트의 문자열을 받아온다.
var cur_data = $( "select" ).val();
/*
* 선형 데이터와 사인 데이터를 피팅 그래프에 그리기 위한 plotly 레이아웃을 미리 정의한다.
*/
var layout_linreg = {'line' : {
margin: {
l: 33, r: 20, b: 33, t: 0, pad: 0
},
xaxis: {range: [-1, 1], title:'x Axis'},
yaxis: {range: [-1, 1], title:'y Axis'},
legend: {
x: 0,
y: 1,
traceorder: 'normal',
bgcolor: '#E2E2E2',
bordercolor: '#E2E2E2',
borderwidth: 2
}
},
'sin' : {
margin: {
l: 33, r: 20, b: 33, t: 0, pad: 0
},
xaxis: {range: [-0.2, 1.2], title:'x Axis'},
yaxis: {range: [-1.6, 1.6], title:'y Axis'},
legend: {
x: 0,
y: 1,
traceorder: 'normal',
bgcolor: '#E2E2E2',
bordercolor: '#E2E2E2',
borderwidth: 2
}
}
}
/*
* 선형 데이터와 사인 데이터에 대한 코스트 그래프를 위한 plotly 레이아웃을 미리 정의한다.
*/
var layout_cost = { 'line' : {
margin: {
l: 33, r: 20, b: 33, t: 0, pad: 0
},
xaxis: {range: [-1, 1], title:'w1 Axis'},
yaxis: {range: [-1, 1], title:'w0 Axis'},
},
'sin' : {
margin: {
l: 33, r: 20, b: 33, t: 0, pad: 0
},
xaxis: {range: [-2.0, -1.0], title:'w1 Axis'},
yaxis: {range: [0, 1], title:'w0 Axis'}
}
}
var layout_cost3d = {
'line' : {
hovermode:'closest',
spikedistance:-1,
margin: {
l: 33, r: 20, b: 33, t: 20, pad: 0
},
scene:{
xaxis:{showspikes:false, title:'w1 Axis'},
yaxis:{showspikes:false, title:'w0 Axis'},
zaxis:{showspikes:true, spikecolor:'#0072b2', spikesides:false},
},
},
'sin' : {
hovermode:'closest',
spikedistance:-1,
margin: {
l: 33, r: 20, b: 33, t: 20, pad: 0
},
scene:{
xaxis:{showspikes:false, title:'w1 Axis'},
yaxis:{showspikes:false, title:'w0 Axis'},
zaxis:{showspikes:true, spikecolor:'#0072b2', spikesides:false},
}
}
}
// 해당 레이아웃을 선택해서 초기화한다.
var linreg_layout = layout_linreg[cur_data];
var cost_layout = layout_cost[cur_data];
var cost3d_layout = layout_cost3d[cur_data];
//////////////////////////////////////////////////////////////////////////////////////////////
// REGRESSION START
//////////////////////////////////////////////////////////////////////////////////////////////
var w = 0;
var b = 0;
var timer_id = -1;
// 최초 직선 0*x+0 에 대해서 직선을 한번 그린다.
var trace1 = {
x: domain[cur_data],
y: domain[cur_data].map(function(x){return w*x + b;}),
name: 'hyphothesis',
};
// 미리 세팅된 점데이터
var data = {'line' :{
x: [-0.75, -0.6, -0.51, -0.3, -0.15, 0.15, 0.45, 0.53, 0.85, 0.98],
y: [ 0.00, -0.4, 0.02, 0.0, 0.33, 0.50, 0.50, 0.83, 0.70, 0.90],
mode: 'markers',
type: 'scattergl',
name: 'data'
},
'sin': {
x: [ 0. , 0.1111, 0.2222, 0.3333, 0.4444, 0.5556, 0.6667, 0.7778, 0.8889, 1. ],
y: [ -0.0834, 0.6315, 0.5576, 1.1941, -0.0167, -0.5104, -0.7654, -1.2339, -0.8544, -0.1818],
mode: 'markers',
type: 'scattergl',
name: 'data'
}
};
// 현재 선택된 데이터를 trace2에 대입하여 초기화 한다.
var trace2 = data[cur_data];
var data_regression = [trace1, trace2];
// 회귀 그래프를 그린다.
Plotly.plot(GRAPH, data_regression, linreg_layout);
/////////////////////////////////////////////////////////////////////////////////////////////
// REGRESSION END
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
// COST FUNCTION 2d START
//////////////////////////////////////////////////////////////////////////////////////////////
$('#cost_meter').html('COST : <span id="cost_value">'+cost(w, b, trace2.x, trace2.y).toFixed(3)+'</span>');
var W = linspace(layout_cost[cur_data]['xaxis']['range'][0], layout_cost[cur_data]['xaxis']['range'][1], 50);
var B = linspace(layout_cost[cur_data]['yaxis']['range'][0], layout_cost[cur_data]['yaxis']['range'][1], 50);
var Z = draw_cost(W, B, trace2);
// COST FUNC. 데이터
var trace3 = {
z: Z, x: W, y: B,
type: 'contour',
colorscale: 'Portland',
name: 'cost',
showscale:false
}
// 현재 위치
var visible_cost = $("#view-cost").prop("checked");
var trace4 = {
x: [w], y: [b],
type: 'scattergl',
name: 'current',
visible: visible_cost,
marker:{color:['#FF0000']}
}
// 3d point
var trace5 = {
x: [w], y: [b], z: [(cost(w, b, trace2.x, trace2.y)+0.2).toFixed(3)],
mode: 'markers',
type: 'scatter3d',
name: 'current3d',
visible: visible_cost,
marker: {
size: 2,
opacity: 0.8,
color: ['#FF0000']
}
};
// var points_3d = {
// x: X_train,
// y: X_train.map( function(v,i) { return Math.pow(v,2);} ),
// z: Y_train,
// mode: 'markers',
// marker: {
// size: 3,
// opacity: 0.8,
// color: ['#348ABD','#A60628','#7A68A6','#467821','#D55E00']
// },
// type: 'scatter3d'
// };
var data_contour = [ trace3, trace4 ];
Plotly.plot(GRAPH2, data_contour, cost_layout);
//////////////////////////////////////////////////////////////////////////////////////////////
// COST FUNCTION 2d END
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
// COST FUNCTION 3d START
//////////////////////////////////////////////////////////////////////////////////////////////
// surface 데이터
var surface = {
z: Z, x: W, y: B,
type: 'surface', showscale:false,
colorscale: 'Portland', opacity:1.0, hoverinfo:'x+y+z',
name: 'surface',
contours: { x:{ show:false, highlight:false, },
y:{ show:false, highlight:false, },
z:{ show:true, highlight:false, color:'#a60628',
highlightcolor:'#000000', highlightwidth:5,
project:{z:true}
},
},
}
var data_3d = [ surface, trace5 ];
Plotly.plot(GRAPH3, data_3d, cost3d_layout);
//////////////////////////////////////////////////////////////////////////////////////////////
// COST FUNCTION 3d END
//////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////
// TABLE INIT START
//////////////////////////////////////////////////////////////////////////////////////////////
// $('#data-table tr').each(function(i) {
// if(i > 0) {
// //insert td for data
// var tr = $(this);
// var num_data = trace2.x.length;
// h = trace2.x.map( function(x){return (w*x)+b;} );
// if(i == 1) { //x
// for(j = 0; j < num_data; j++) {
// tr.append("<td>"+trace2.x[j]+"</td>")
// }
// }
// else if(i == 2) {//y
// for(j = 0; j < num_data; j++) {
// tr.append("<td>"+trace2.y[j]+"</td>")
// }
// }
// else if(i == 3) {//h
// var hs = '';
// for(j = 0; j < num_data; j++) {
// if(h[j] >= 0) hs = '+'+h[j].toFixed(3).toString();
// else hs = h[j].toFixed(3).toString();
// tr.append("<td>"+hs+"</td>");
// }
// }
// else { //(h-y)^2
// for(j = 0; j < num_data; j++) {
// tr.append("<td>"+Math.pow(h[j]-trace2.y[j], 2).toFixed(3)+"</td>");
// }
// }
// }
// });
//////////////////////////////////////////////////////////////////////////////////////////////
// TABLE INIT END
//////////////////////////////////////////////////////////////////////////////////////////////
var dial_w = JogDial(document.getElementById('jog_dial_w'),
{debug:true, wheelSize:'100px', knobSize:'30px', degreeStartAt: 0}).on('mousemove', function(evt) {
w = Math.round(evt.target.rotation)/500.;
b = parseFloat($('#b_value').text());
cur_cost = cost(w, b, trace2.x, trace2.y)
$('#jog_dial_w_meter').html('w<sub>1</sub> : <span id="w_value">'+w+'</span>');
$('#cost_meter').html('COST : <span id="cost_value">'+cur_cost.toFixed(3)+'</span>');
h = domain[cur_data].map( function(x){return (w*x)+b;} );
// $('#hypothesis').children('td').each(function(i) {
// hs = (w*trace2.x[i]+b).toFixed(3)
// if(hs >= 0) hs = '+'+hs.toString();
// else hs = hs.toString();
// $(this).html(hs);
// });
// $('#indivusual_cost').children('td').each(function(i) {
// $(this).html( Math.pow((w*trace2.x[i]+b)-trace2.y[i], 2).toFixed(3) );
// });
Plotly.restyle(GRAPH, {y: [h]}, 0);
Plotly.restyle(GRAPH2, 'x', [[w]], 1);
Plotly.restyle(GRAPH3,
{
x: [[w]],
z: [[(cur_cost+0.2).toFixed(3)]]
},
[1]);
});
var dial_b = JogDial(document.getElementById('jog_dial_b'),
{debug:true, wheelSize:'100px', knobSize:'30px', degreeStartAt: 0}).on('mousemove', function(evt) {
b = Math.round(evt.target.rotation)/500.;
w = parseFloat($('#w_value').text());
cur_cost = cost(w, b, trace2.x, trace2.y)
$('#jog_dial_b_meter').html('w<sub>0</sub> : <span id="b_value">'+b+'</span>');
$('#cost_meter').html('COST : <span id="cost_value">'+cur_cost.toFixed(3)+'</span>');
h = domain[cur_data].map(function(x){return (w*x)+b;} );
// $('#hypothesis').children('td').each(function(i) {
// hs = (w*trace2.x[i]+b).toFixed(3)
// if(hs >= 0) hs = '+'+hs.toString();
// else hs = hs.toString();
// $(this).html(hs);
// });
// $('#indivusual_cost').children('td').each(function(i) {
// $(this).html( Math.pow((w*trace2.x[i]+b)-trace2.y[i], 2).toFixed(3) );
// });
Plotly.restyle(GRAPH, {y: [h]}, 0);
Plotly.restyle(GRAPH2, 'y', [[b]], 1);
Plotly.restyle(GRAPH3,
{
y: [[b]],
z: [[(cur_cost+0.2).toFixed(3)]]
},
[1]);
});
$( "select" ).change(function() {
//데이터 셋 교체
cur_data = $( this ).val();
linreg_layout = layout_linreg[cur_data];
cost_layout = layout_cost[cur_data];
trace2 = data[cur_data];
// 직선 다시 그리기
trace1.x = domain[cur_data];
trace1.y = domain[cur_data].map(function(x){return w*x + b;});
data_regression = [trace1, trace2];
Plotly.newPlot(GRAPH, data_regression, linreg_layout);
// 코스트 다시 그리기
W = linspace(layout_cost[cur_data]['xaxis']['range'][0], layout_cost[cur_data]['xaxis']['range'][1], 50);
B = linspace(layout_cost[cur_data]['yaxis']['range'][0], layout_cost[cur_data]['yaxis']['range'][1], 50);
Z = draw_cost(W, B, trace2);
trace3.x = W;
trace3.y = B;
trace3.z = Z;
data_contour = [ trace3, trace4 ];
Plotly.newPlot(GRAPH2, data_contour, cost_layout);
surface.x = W;
surface.y = B;
surface.z = Z;
data_3d = [ surface, ];
Plotly.newPlot(GRAPH3, data_3d, cost3d_layout);
//테이블 데이터 리셋
// $('#data-x').children('td').each(function(i) {
// $(this).html(trace2.x[i]);
// });
// $('#data-target').children('td').each(function(i) {
// $(this).html(trace2.y[i]);
// });
// $('#hypothesis').children('td').each(function(i) {
// hs = (w*trace2.x[i]+b).toFixed(3)
// if(hs >= 0) hs = '+'+hs.toString();
// else hs = hs.toString();
// $(this).html(hs);
// });
// $('#indivusual_cost').children('td').each(function(i) {
// $(this).html( Math.pow((w*trace2.x[i]+b)-trace2.y[i], 2).toFixed(3) );
// });
});
$("#view-cost").change(function () {
if ($(this).prop("checked")) {
Plotly.restyle(GRAPH2, 'visible', true, 1);
Plotly.restyle(GRAPH3, 'visible', true, 1);
visible_cost = true;
return;
}
Plotly.restyle(GRAPH2, 'visible', false, 1);
Plotly.restyle(GRAPH3, 'visible', false, 1);
visible_cost = false;
});
$("#stop").click(function () {
if(timer_id != -1) {
clearInterval(timer_id);
}
});
$("#learn").click(function () {
const eta = 0.01;
const ms = 100;
cur_data = $("#dataset").val();
train_x = data[cur_data].x;
train_y = data[cur_data].y;
is_break = 0;
//for (step = 0; step < 1500; step++) {
timer_id = setInterval( function (){
h = train_x.map(function(x){return w*x + b;});
//console.log(w, b)
error = h.map(function(item, index) {
return item - train_y[index];
})
dw = error.map(function(item, index) {
return item * train_x[index]
}).reduce(function add(sum, currValue) {
return sum + currValue;
}, 0);
db = error.reduce(function add(sum, currValue) {
return sum + currValue;
}, 0);
//console.log( dw, db );
if (Math.sqrt(dw*dw + db*db) < 1.0e-3) {
console.log('break')
clearInterval(timer_id);
}
//if (is_break >= 100) {
// console.log(is_break)
// clearInterval(timer_id);
//}
w = w - eta*dw;
b = b - eta*db;
$('#w_value').html(w.toPrecision(3));
$('#b_value').html(b.toPrecision(3));
$('#cost_meter').html('COST : <span id="cost_value">'+cost(w, b, trace2.x, trace2.y).toFixed(3)+'</span>');
h = domain[cur_data].map(function(x){return (w*x)+b;} );
$('#hypothesis').children('td').each(function(i) {
hs = (w*trace2.x[i]+b).toFixed(3)
if(hs >= 0) hs = '+'+hs.toString();
else hs = hs.toString();
$(this).html(hs);
});
$('#indivusual_cost').children('td').each(function(i) {
$(this).html( Math.pow((w*trace2.x[i]+b)-trace2.y[i], 2).toFixed(3) );
});
Plotly.restyle(GRAPH, {y: [h]}, 0);
Plotly.restyle(GRAPH2, {'x':[[w]], 'y':[[b]]}, 1);
Plotly.restyle(GRAPH3, {'x':[[w]], 'y':[[b]],
'z':[[(cost(w, b, trace2.x, trace2.y)+0.2).toFixed(3)]]}, 1);
is_break += 1;
}, 100);
console.log(timer_id)
});
});
</script>
</body>
</html>