<html> <head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js" type="text/javascript"></script> <script src="https://rawgit.com/chen0040/js-regression/master/build/jsregression.min.js" type="application/javascript"></script> <!--<script src="./src/jsregression.js" type="application/javascript"></script>--> </head> <body> <h2>Linear Regression Demo</h2> <canvas id="myChart" width="400" height="400"></canvas> <script> // === training data generated from y = 2.0 + 5.0 * x + 2.0 * x^2 === // var data = []; for(var x = 1.0; x < 100.0; x += 1.0) { var y = 300.0 - 25.0 * x + (Math.random()-0.5) * 100; data.push([x, y]); // Note that the last column should be y the output } // === Create the linear regression === // var regression = new jsregression.LinearRegression({ alpha: 0.0005, // iterations: 3000, lambda: 0.00, trace: true }); // can also use default configuration: var regression = new jsregression.LinearRegression(); // === Train the linear regression === // var model = regression.fit(data); // === Print the trained model === // console.log(model); // === Testing the trained linear regression === // var items = [ ]; var items_predicted = []; for(var x = 1.0; x < 100.0; x += 0.5) { var actual_y = 300.0 - 25.0 * x + (Math.random()-0.5) * 100; var predicted_y = regression.transform([x]); items.push({x: x, y: actual_y}); items_predicted.push({x: x, y: predicted_y}); console.log("actual: " + actual_y + " predicted: " + predicted_y); } console.log(items); var pointBackgroundColors = []; var pointBackgroundColors2 = []; var ctx = document.getElementById("myChart").getContext('2d'); var myChart = new Chart(ctx, { type: 'scatter', data: { datasets: [{ label: 'Actual', data: items, pointBackgroundColor: pointBackgroundColors, pointBorderColor: [] }, { label: 'Predicted', data: items_predicted, pointBackgroundColor: pointBackgroundColors2, pointBorderColor: [] } ] }, options: { } }); for (i = 0; i < myChart.data.datasets[0].data.length; i++) { pointBackgroundColors.push("#90cd8a"); pointBackgroundColors2.push("#f58368"); } myChart.update(); </script> </body> </html>