Last active
June 18, 2017 19:32
-
-
Save abhisheksoni27/ed8aa6616e22727bd52b76ce44c60a7e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const ml = require('ml-regression'); | |
const csv = require('csvtojson'); | |
const SLR = ml.SLR; // Simple Linear Regression | |
const csvFilePath = 'advertising.csv'; // Data | |
let csvData = [], // parsed Data | |
X = [], // Input | |
y = []; // Output | |
let regressionModel; | |
const readline = require('readline'); // For user prompt to allow predictions | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}); | |
csv() | |
.fromFile(csvFilePath) | |
.on('json', (jsonObj) => { | |
csvData.push(jsonObj); | |
}) | |
.on('done', () => { | |
dressData(); // To get data points from JSON Objects | |
performRegression(); | |
}); | |
function performRegression() { | |
regressionModel = new SLR(X, y); // Train the model on training data | |
console.log(regressionModel.toString(3)); | |
predictOutput(); | |
} | |
function dressData() { | |
/** | |
* One row of the data object looks like: | |
* { | |
* TV: "10", | |
* Radio: "100", | |
* Newspaper: "20", | |
* "Sales": "1000" | |
* } | |
* | |
* Hence, while adding the data points, | |
* we need to parse the String value as a Float. | |
*/ | |
csvData.forEach((row) => { | |
X.push(f(row.Radio)); | |
y.push(f(row.Sales)); | |
}); | |
} | |
function f(s) { | |
return parseFloat(s); | |
} | |
function predictOutput() { | |
rl.question('Enter input X for prediction (Press CTRL+C to exit) : ', (answer) => { | |
console.log(`At X = ${answer}, y = ${regressionModel.predict(parseFloat(answer))}`); | |
predictOutput(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment