Skip to content
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
21 changes: 21 additions & 0 deletions src/modules/Animal_class/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Aryan Misra

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
10 changes: 10 additions & 0 deletions src/modules/Animal_class/animal_classes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const ANIMAL_CLASSES ={
0: 'Dogs, Dogs make for the best friends, and it’s only right that we celebrate them for all the joy and love they’ve given us.',
1: 'Cats, If you have a cat, there’s a good chance your camera roll is already full of photos of your furry feline.',
2: 'Pandas, I thought the secret of life was obvious: be here now, love as if your whole life depended on it, find your lifes work and try to get hold of a giant',
3: 'Rabbit, I have got that resilient thing inside me. But I was not a happy bunny.',
4: 'Wild_Rabbit, How is rabbit wild',
5: 'Bear, Pooh is a bear',
6: 'pig, Pigssss'

}
86 changes: 86 additions & 0 deletions src/modules/Animal_class/animal_classifier.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<!DOCTYPE html>
<html>

<head>
<title>Only some animal classifier App</title>
<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="shortcut icon" type="image/x-icon" href="favicon1.ico" />

</head>

<body>
<script
type="text/javascript"
src="http://code.jquery.com/jquery-1.7.1.min.js"
></script>
<main>
<div class="jumbotron text-center">
<h1>Few and Not all Animal Classfier App</h1>
</div>
<div class="container mt-5">
<div class="row">
<div class="col-12">
<div class="progress progress-bar progress-bar-striped progress-bar-animated mb-2"
style="display:none">
Loading Model
</div>
</div>
</div>
<div class="row">
<div class="col-3">
<select id="model-selector" class="custom-select">
<option selected disabled>Select Model</option>
<option>animal_classes</option>

</select>
</div>
<div class="col-8">
<input id="image-selector" class="form-control border-0" type="file">
</div>
<div class="col-1">
<button id="predict-button" class="btn btn-primary float-right">Predict</button>
</div>
</div>
<hr>
<div class="row">
<div class="col-6">
<h2 class="ml-3">Predictions</h2>
<ol id="prediction-list"></ol>
</div>
<div class="col-6">
<h2 class="ml-3">Image</h2>
<img id="selected-image" class="ml-3" src="" />
</div>
</div>
<hr>
<div class="row">
<h2></h2>
</div>
<div class="row">
<div class="col-6">

<h2 class="ml-3">Sample Images</h2>
<p>
<a class="list-group-item" download="image1.jpg" href="images/sample/image1.jpg">Image 1</a></br>
<a class="list-group-item" download="image2.jpg" href="images/sample/image2.jpg">Image 2</a></br>
<a class="list-group-item" download="image3.jpg" href="images/sample/image3.jpg">Image 3</a></br>
<a class="list-group-item" download="image5.jpg" href="images/sample/image5.jpg">Image 4</a></br>
<a class="list-group-item" download="image6.jpg" href="images/sample/image6.jpg">Image 5</a></br>
<a class="list-group-item" download="image7.jpg" href="images/sample/image7.jpg">Image 6</a></br>
<a class="list-group-item" download="image8.jpg" href="images/sample/image8.jpg">Image 7</a></br>
<p>
</div>

</div>
</div>
</main>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.3/dist/tf.min.js"></script>
<script src="animal_classes.js"></script>
<script src="predict.js"></script>

</body>

</html>
59 changes: 59 additions & 0 deletions src/modules/Animal_class/predict.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
$("#image-selector").change(function() {
let reader = new FileReader();
reader.onload = function() {
let dataURL = reader.result;
$("#selected-image").attr("src", dataURL);
$("#prediction-list").empty();
};
let file = $("#image-selector").prop("files")[0];
reader.readAsDataURL(file);
});

$("#model-selector").change(function() {
loadModel($("#model-selector").val());
});

let model;
async function loadModel(name) {
$(".progress-bar").show();
model = undefined;
model = await tf.loadModel(`tfjs-models/Classification_Models/model.json`);
$(".progress-bar").hide();
}

$("#predict-button").click(async function() {
let image = $("#selected-image").get(0);
let modelName = $("#model-selector").val();
let tensor = tf
.fromPixels(image)
.resizeNearestNeighbor([224, 224])
.toFloat();

let offset = tf.scalar(127.5);

tensor = tensor
.sub(offset)
.div(offset)
.expandDims();

let predictions = await model.predict(tensor).data();
let top5 = Array.from(predictions)
.map(function(p, i) {
return {
probability: p,
className: ANIMAL_CLASSES[i]
};
})
.sort(function(a, b) {
return b.probability - a.probability;
})
.slice(0, 3);

$("#prediction-list").empty();
top5.forEach(function(p) {
$("#prediction-list").append(
`<li>${p.className}: ${p.probability.toFixed(6)}</li>`
);
});
});

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

Large diffs are not rendered by default.

Binary file added src/modules/layer_conversion/group1-shard1of1.bin
Binary file not shown.
3 changes: 3 additions & 0 deletions src/modules/layer_conversion/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#my-file {
visibility: hidden;
}
21 changes: 21 additions & 0 deletions src/modules/layer_conversion/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script
type="text/javascript"
src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@0.13.5"
></script>
<script
type="text/javascript"
src="http://code.jquery.com/jquery-1.7.1.min.js"
></script>

<script src="script.js" defer="defer"></script>
</head>
<div>
<input type="button" id="my-button" value="Select Files" />
<input type="file" name="my_file" id="my-file" />
</div>
<body></body>
</html>
1 change: 1 addition & 0 deletions src/modules/layer_conversion/model.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"format": "layers-model", "generatedBy": "keras v2.2.4-tf", "convertedBy": "TensorFlow.js Converter v1.5.2", "modelTopology": {"keras_version": "2.2.4-tf", "backend": "tensorflow", "model_config": {"class_name": "Sequential", "config": {"name": "sequential_2", "layers": [{"class_name": "Conv2D", "config": {"name": "conv2d_2", "trainable": true, "batch_input_shape": [null, 28, 28, 1], "dtype": "float32", "filters": 32, "kernel_size": [3, 3], "strides": [1, 1], "padding": "valid", "data_format": "channels_last", "dilation_rate": [1, 1], "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": {"class_name": "L1L2", "config": {"l1": 0.0, "l2": 0.019999999552965164}}, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "MaxPooling2D", "config": {"name": "max_pooling2d_2", "trainable": true, "dtype": "float32", "pool_size": [2, 2], "padding": "valid", "strides": [2, 2], "data_format": "channels_last"}}, {"class_name": "Flatten", "config": {"name": "flatten_2", "trainable": true, "dtype": "float32", "data_format": "channels_last"}}, {"class_name": "Dropout", "config": {"name": "dropout_1", "trainable": true, "dtype": "float32", "rate": 0.1, "noise_shape": null, "seed": null}}, {"class_name": "Dense", "config": {"name": "dense_2", "trainable": true, "dtype": "float32", "units": 64, "activation": "relu", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}, {"class_name": "BatchNormalization", "config": {"name": "batch_normalization_1", "trainable": true, "dtype": "float32", "axis": [1], "momentum": 0.99, "epsilon": 0.001, "center": true, "scale": true, "beta_initializer": {"class_name": "Zeros", "config": {}}, "gamma_initializer": {"class_name": "Ones", "config": {}}, "moving_mean_initializer": {"class_name": "Zeros", "config": {}}, "moving_variance_initializer": {"class_name": "Ones", "config": {}}, "beta_regularizer": null, "gamma_regularizer": null, "beta_constraint": null, "gamma_constraint": null}}, {"class_name": "Dense", "config": {"name": "dense_3", "trainable": true, "dtype": "float32", "units": 10, "activation": "linear", "use_bias": true, "kernel_initializer": {"class_name": "GlorotUniform", "config": {"seed": null}}, "bias_initializer": {"class_name": "Zeros", "config": {}}, "kernel_regularizer": null, "bias_regularizer": null, "activity_regularizer": null, "kernel_constraint": null, "bias_constraint": null}}]}}, "training_config": {"loss": {"class_name": "SparseCategoricalCrossentropy", "config": {"reduction": "auto", "name": "sparse_categorical_crossentropy", "from_logits": true}}, "metrics": ["accuracy"], "weighted_metrics": null, "sample_weight_mode": null, "loss_weights": null, "optimizer_config": {"class_name": "Adam", "config": {"name": "Adam", "learning_rate": 0.0010000000474974513, "decay": 0.0, "beta_1": 0.8999999761581421, "beta_2": 0.9990000128746033, "epsilon": 1e-07, "amsgrad": false}}}}, "weightsManifest": [{"paths": ["group1-shard1of1.bin"], "weights": [{"name": "batch_normalization_1/gamma", "shape": [64], "dtype": "float32"}, {"name": "batch_normalization_1/beta", "shape": [64], "dtype": "float32"}, {"name": "batch_normalization_1/moving_mean", "shape": [64], "dtype": "float32"}, {"name": "batch_normalization_1/moving_variance", "shape": [64], "dtype": "float32"}, {"name": "conv2d_2/kernel", "shape": [3, 3, 1, 32], "dtype": "float32"}, {"name": "conv2d_2/bias", "shape": [32], "dtype": "float32"}, {"name": "dense_2/kernel", "shape": [5408, 64], "dtype": "float32"}, {"name": "dense_2/bias", "shape": [64], "dtype": "float32"}, {"name": "dense_3/kernel", "shape": [64, 10], "dtype": "float32"}, {"name": "dense_3/bias", "shape": [10], "dtype": "float32"}]}]}
94 changes: 94 additions & 0 deletions src/modules/layer_conversion/script.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// "./" must be required to load json from sub path
//const modelP = tf.loadModel("./model.json");
const modelP = tf.loadModel("./model.json");

const canvas = document.createElement("canvas");
canvas.width = canvas.height = 28 * 8;
canvas.style.display = "block";
canvas.style.borderStyle = "solid";
//canvas.style.backgroundColor = "white";
document.body.appendChild(canvas);

// simple scribble
const c2d = canvas.getContext("2d");
c2d.lineWidth = 8;
c2d.strokeStyle = "black";
c2d.fillStyle = "white";
let prev = null;
canvas.addEventListener(
"mousedown",
ev => {
prev = ev;
},
false
);
canvas.addEventListener(
"mouseup",
ev => {
prev = null;
},
false
);
canvas.addEventListener(
"mousemove",
ev => {
if (prev === null) return;
const bounds = canvas.getBoundingClientRect();
c2d.beginPath();
c2d.moveTo(prev.clientX - bounds.left, prev.clientY - bounds.top);
c2d.lineTo(ev.clientX - bounds.left, ev.clientY - bounds.top);
c2d.stroke();
prev = ev;
predict().catch(console.error);
},
false
);

// NOTE: white filling is required: tf.fromPixel() ignores alpha channel
function clear() {
c2d.fillRect(0, 0, canvas.width, canvas.height);
}
clear();
const clearButton = document.createElement("button");
clearButton.style.display = "block";
clearButton.textContent = "clear";
clearButton.addEventListener("click", clear, false);
document.body.appendChild(clearButton);

// for result
const pre = document.createElement("pre");
document.body.appendChild(pre);

// apply trained keras model
async function predict() {
const model = await modelP;
const img = c2d.getImageData(0, 0, canvas.width, canvas.height);
// tf.tidy(): auto-release block ([NOTE] tf.keep(t): avoid auto-release)
tf.tidy(() => {
// data.shape == [28, 28, 3], value: 0(black)-255(color)
const data = tf.image.resizeBilinear(tf.fromPixels(img), [28, 28]);
const r = data.slice([0, 0, 0], [data.shape[0], data.shape[1], 1]);
const g = data.slice([0, 0, 1], [data.shape[0], data.shape[1], 1]);
const b = data.slice([0, 0, 2], [data.shape[0], data.shape[1], 1]);
// input.shape == [n, 28, 28, 1], value: 0(white)-1(black)
const input = r
.add(g)
.add(b)
.cast("float32")
.div(tf.scalar(-1 * 3 * 255))
.add(tf.scalar(1))
.reshape([1, 28, 28, 1]);
const result = model.predict(input);
// result.shape == [n, 10], value: 0-1 (as categorical probability)

// display result
const probs = [...result.buffer().values];
const num = result.argMax(1).buffer().values[0];
pre.textContent = [`predict number: ${num}`]
.concat(probs.map((p, n) => `${n} = ${p}`))
.join("\n");
});
}
$("#my-button").click(function() {
$("#my-file").click();
});