Skip to content

Instantly share code, notes, and snippets.

@abhisheksoni27
Last active June 18, 2017 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhisheksoni27/ed8aa6616e22727bd52b76ce44c60a7e to your computer and use it in GitHub Desktop.
Save abhisheksoni27/ed8aa6616e22727bd52b76ce44c60a7e to your computer and use it in GitHub Desktop.
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