Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an example for classification using iris dataset #92

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions examples/iris_classification/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@

# Created by https://www.gitignore.io/api/node

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env



# End of https://www.gitignore.io/api/node
10 changes: 10 additions & 0 deletions examples/iris_classification/ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#Instructions

Make sure you have installed [Nodejs](https://nodejs.org/en/)

Then cd into this directory from cmd prompt. And then run the below commands,

`npm install`
`npm start`

Once the training process has completed your neural net model will be saved as model.json
106 changes: 106 additions & 0 deletions examples/iris_classification/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>CSV NeuralNetwork Parser</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="./main.js"></script>
</head>

<body>
<div class="container">
<div class="table-responsive">
<h1 align="center">CSV FiletoHTMLTable using AJAX Jquery</h1>
<br />
<div align="center">
<input type="file" id="csv-upload" accept=".csv">
</div>
<div align="center">
<button type="button" name="load_data" id="load_data" class="btn btn-info">Load IRIS Data</button>
</div>
<br />
<div id="data_table">

</div>
<table class="table table-condensed">
<colgroup>
<col></col>
<col class="bg-info"></col>
<col></col>
<col></col>
<col></col>
</colgroup>
<thead>
<tr>
<th class="text-center">ID</th>
<th class="text-center bg-primary">First Name</th>
<th class="text-center">Last Name</th>
<th class="text-center">Fisrt Name</th>
<th class="text-center">Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Johnny</td>
<td>English</td>
<td>Bud</td>
<td>Spencer</td>
</tr>
<tr>
<td>1</td>
<td>Johnny</td>
<td>English</td>
<td>Bud</td>
<td>Spencer</td>
</tr>
<tr>
<td>1</td>
<td>Johnny</td>
<td>English</td>
<td>Bud</td>
<td>Spencer</td>
</tr>
<tr>
<td>1</td>
<td>Johnny</td>
<td>English</td>
<td>Bud</td>
<td>Spencer</td>
</tr>
<tr>
<td>1</td>
<td>Johnny</td>
<td>English</td>
<td>Bud</td>
<td>Spencer</td>
</tr>
<tr>
<td>1</td>
<td>Johnny</td>
<td>English</td>
<td>Bud</td>
<td>Spencer</td>
</tr>
<tr>
<td>1</td>
<td>Johnny</td>
<td>English</td>
<td>Bud</td>
<td>Spencer</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>

</html>
110 changes: 110 additions & 0 deletions examples/iris_classification/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
const NeuralNet = require("../../lib/nn");
const csv = require("csvtojson");
const fs = require("fs");
require("colors");

const LoggerType = Object.freeze({
Error: 1,
Warn: 2,
Info: 3,
Data: 4
});
function debug(text, type) {
if (type) {
if (type === LoggerType.Error) {
process.stdout.write("ERROR: ".red);
console.error(JSON.stringify(text) || text);
} else if (type === LoggerType.Warn) {
process.stdout.write("WARN: ".yellow);
console.warn(JSON.stringify(text) || text);
} else if (type === LoggerType.Info) {
process.stdout.write("INFO: ".cyan);
console.log(JSON.stringify(text) || text);
} else if (type === LoggerType.Data) {
process.stdout.write("DATA: ".green);
console.log(JSON.stringify(text) || text);
}
return;
}
console.log(text);
}

const trainIP = [];
const trainOP = [];
const testIP = [];
const testOP = [];

const noOfInputs = 4;
const noOfOutputs = 3;
const nn = new NeuralNet.NeuralNetwork(noOfInputs, 5, noOfOutputs);

function outputArrGenerator(op, opSize) {
let opArr = new Array(opSize);
opArr.fill(0);
op = parseInt(op, 10);
opArr[op - 1] = 1;
return opArr;
}

csv()
.fromFile("./train.csv")
.on("json", jsonObj => {
const temp = Object.values(jsonObj);
trainOP.push(temp.slice(temp.length - 1, temp.length));
trainIP.push(temp.slice(0, temp.length - 1));
})
.on("done", error => {
if (error) {
throw error;
}
const epoch = 20000;
for (let i = 0; i < epoch; i++) {
const randomIndex = Math.floor(Math.random() * trainIP.length);
nn.train(trainIP[randomIndex], outputArrGenerator(trainOP[randomIndex][0], noOfOutputs));
}
debug("Training Complete...", LoggerType.Info);
});

const predVal = [];

csv()
.fromFile("./test.csv")
.on("json", jsonObj => {
const temp = Object.values(jsonObj);
testOP.push(temp.slice(temp.length - 1, temp.length));
testIP.push(temp.slice(0, temp.length - 1));
})
.on("done", error => {
if (error) {
throw error;
}
debug(
`|************************************|`,
LoggerType.Info
);
debug(
`| Predicted Class | Actual Class |`,
LoggerType.Info
);
debug(
`|************************************|`,
LoggerType.Info
);
for (let i = 0; i < testIP.length; i++) {
predVal.push(nn.predict(testIP[i]));
debug(
`| ${predVal[i].indexOf(Math.max(...predVal[i])) + 1} | ${testOP[i]} |`,
LoggerType.Info
); debug(
`|------------------------------------|`,
LoggerType.Info
);
}
const modal = nn.serialize();
fs.writeFile("./model.json", modal, err => {
if (err) {
debug(err, LoggerType.Error);
}
});
debug("end", LoggerType.Info);
});
66 changes: 66 additions & 0 deletions examples/iris_classification/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
$(document).ready(function () {
function checkCSVFile(name) {
return (name.slice(name.length - 4, name.length) === '.csv')
}
function renderCSVtoTable(data) {
var csv_data = data.split(/\r?\n|\r/);
var table_data = '<table class="table table-bordered table-striped">';
for (let row_count = 0; row_count < csv_data.length; row_count++) {
const cell_data = csv_data[row_count].split(',');
table_data += '<tr>';
for (let cell_count = 0; cell_count < cell_data.length; cell_count++) {
const element = cell_data[cell_count];
if (cell_count === 0) {
table_data += '<th>' + element + '</th>';
} else {
table_data += '<th>' + element + '</th>';
}
}
table_data += '</tr>';
}
table_data += '</table>';
return table_data;
}
function loadHandler(event) {
var csv = event.target.result;
$('#data_table').html(renderCSVtoTable(csv));;
}
function errorHandler(evt) {
if (evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
function getAsText(fileToRead) {
var reader = new FileReader();
// Read file into memory as UTF-8
reader.readAsText(fileToRead);
// Handle errors load
reader.onload = loadHandler;
reader.onerror = errorHandler;
}
function handleFiles(files) {
// Check for the various File API support.
if (window.FileReader) {
// FileReader are supported.
getAsText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
}
// detect a change in a file input with an id of “the-file-input”
$("#csv-upload").change(function () {
// will log a FileList object, view gifs below
if(checkCSVFile(this.files[0].name)) {
$('#data_table').html(handleFiles(this.files));
}
});
$('#load_data').click(function () {
$.ajax({
url: "train.csv",
dataType: "text",
success: function (data) {
$('#data_table').html(renderCSVtoTable(data));
}
})
})
})
Loading