|
| 1 | +const tf = require("@tensorflow/tfjs-node"); |
| 2 | + |
| 3 | +const { |
| 4 | + getAllImages, |
| 5 | + getFirstNImagesByCategory, |
| 6 | + updateDocumentWithGrayscaleClassification, |
| 7 | +} = require("./elasticsearch-util"); |
| 8 | +const { getGrayscaleImageTensor, getGrayscaleTensorsForImageSet, IMAGE_HEIGHT, IMAGE_WIDTH } = require("./tf-util"); |
| 9 | + |
| 10 | +const CLASS_NAMES = ["cake", "not cake"]; |
| 11 | + |
| 12 | +// Build custom model |
| 13 | +run(); |
| 14 | + |
| 15 | +async function run() { |
| 16 | + // Get a subset of the cake images |
| 17 | + const cakesResponse = await getFirstNImagesByCategory(CLASS_NAMES[0], 50); |
| 18 | + const cakeTensors = await getGrayscaleTensorsForImageSet(cakesResponse); |
| 19 | + |
| 20 | + // Get a subset of the unsplash images for not cake images |
| 21 | + const notCakesResponse = await getFirstNImagesByCategory(CLASS_NAMES[1], 50); |
| 22 | + const notCakeTensors = await getGrayscaleTensorsForImageSet(notCakesResponse); |
| 23 | + |
| 24 | + const images = cakeTensors.concat(notCakeTensors); |
| 25 | + const labels = Array.from({ length: cakeTensors.length }) |
| 26 | + .fill([1, 0]) |
| 27 | + .concat(Array.from({ length: notCakeTensors.length }).fill([0, 1])); |
| 28 | + |
| 29 | + tf.util.shuffleCombo(images, labels); |
| 30 | + const singleImageTensor = tf.stack(images); |
| 31 | + const labelsTensor = tf.tensor2d(labels); |
| 32 | + |
| 33 | + const model = createModel(); |
| 34 | + |
| 35 | + const BATCH_SIZE = 32; |
| 36 | + const NUM_EPOCHS = 10; |
| 37 | + |
| 38 | + await model.fit(singleImageTensor, labelsTensor, { |
| 39 | + batchSize: BATCH_SIZE, // Number of samples to work through before updating the internal model parameters |
| 40 | + epochs: NUM_EPOCHS, // Number of passes through the dataset |
| 41 | + shuffle: true, // Shuffle data before each pass |
| 42 | + }); |
| 43 | + |
| 44 | + // Classify images |
| 45 | + await classifyAllImages(model); |
| 46 | + |
| 47 | + // Optional saving of model |
| 48 | + const MODEL_DIR = "./model"; |
| 49 | + |
| 50 | + await model.save(`file://${MODEL_DIR}`); |
| 51 | + |
| 52 | + // Tidy up |
| 53 | + singleImageTensor.dispose(); |
| 54 | + labelsTensor.dispose(); |
| 55 | + tf.dispose(cakeTensors); |
| 56 | + tf.dispose(notCakeTensors); |
| 57 | + |
| 58 | + console.log('Classification complete!'); |
| 59 | +} |
| 60 | + |
| 61 | +/* Functional implementation */ |
| 62 | +// Convolutional Neural Network (CNN) example |
| 63 | +function createModel() { |
| 64 | + const model = tf.sequential(); |
| 65 | + |
| 66 | + /* Creates a 2d convolution layer. |
| 67 | + * Concept from computer vision where a filter (or kernel or matrix) is applied and moves |
| 68 | + through the image by the specified strides to identify features of interest in the image |
| 69 | + See https://www.kaggle.com/discussions/general/463431 |
| 70 | + */ |
| 71 | + model.add( |
| 72 | + tf.layers.conv2d({ |
| 73 | + inputShape: [IMAGE_WIDTH, IMAGE_HEIGHT, 1], // 1 = Grayscale |
| 74 | + filters: 16, // dimensions of the output space |
| 75 | + kernelSize: 3, // 3x3 matrix |
| 76 | + activation: "relu", //f(x)=max(0,x) |
| 77 | + }) |
| 78 | + ); |
| 79 | + |
| 80 | + /* Max pooling reduces the dimensionality of images by reducing the number of pixels in the output from the |
| 81 | + * previous convolutional layer. |
| 82 | + * Used to reduce computational load going forward and reduce overfitting |
| 83 | + * See https://deeplizard.com/learn/video/ZjM_XQa5s6s |
| 84 | + */ |
| 85 | + model.add( |
| 86 | + tf.layers.maxPooling2d({ |
| 87 | + poolSize: 2, |
| 88 | + strides: 2, |
| 89 | + }) |
| 90 | + ); |
| 91 | + |
| 92 | + model.add( |
| 93 | + tf.layers.conv2d({ |
| 94 | + filters: 32, |
| 95 | + kernelSize: 3, |
| 96 | + activation: "relu", |
| 97 | + }) |
| 98 | + ); |
| 99 | + |
| 100 | + model.add( |
| 101 | + tf.layers.maxPooling2d({ |
| 102 | + poolSize: 2, |
| 103 | + strides: 2, |
| 104 | + }) |
| 105 | + ); |
| 106 | + |
| 107 | + // Flattens the inputs to 1D, making the outputs 2D |
| 108 | + model.add(tf.layers.flatten()); |
| 109 | + |
| 110 | + /* Dense Layer is simple layer of neurons in which each neuron receives input from all the neurons of previous layer, |
| 111 | + * thus called as dense. Dense Layer is used to classify image based on output from convolutional layers. |
| 112 | + see https://towardsdatascience.com/introduction-to-convolutional-neural-network-cnn-de*/ |
| 113 | + model.add( |
| 114 | + tf.layers.dense({ |
| 115 | + units: 64, |
| 116 | + activation: "relu", |
| 117 | + }) |
| 118 | + ); |
| 119 | + |
| 120 | + model.add( |
| 121 | + tf.layers.dense({ |
| 122 | + units: CLASS_NAMES.length, |
| 123 | + activation: "softmax", // turns a vector of K real values into a vector of K real values that sum to 1 |
| 124 | + }) |
| 125 | + ); |
| 126 | + |
| 127 | + model.compile({ |
| 128 | + optimizer: tf.train.adam(), // Stochastic Optimization method |
| 129 | + loss: "binaryCrossentropy", |
| 130 | + metrics: ["accuracy"], |
| 131 | + }); |
| 132 | + |
| 133 | + return model; |
| 134 | +} |
| 135 | + |
| 136 | +async function classifyAllImages(model) { |
| 137 | + const imagesResponse = await getAllImages(); |
| 138 | + const images = imagesResponse.hits.hits.flatMap((result) => { |
| 139 | + return { id: result._id, url: result._source.image_url }; |
| 140 | + }); |
| 141 | + |
| 142 | + for (image of images) { |
| 143 | + console.log(image.url); |
| 144 | + const tensor = await getGrayscaleImageTensor(image.url); |
| 145 | + const results = await model.predict(tensor.expandDims()).data(); |
| 146 | + |
| 147 | + const predictions = Array.from(results) |
| 148 | + .map(function (p, i) { |
| 149 | + return { |
| 150 | + probability: p, |
| 151 | + className: CLASS_NAMES[i], // we are selecting the value from the obj |
| 152 | + }; |
| 153 | + }) |
| 154 | + .sort(function (a, b) { |
| 155 | + return b.probability - a.probability; |
| 156 | + }) |
| 157 | + .slice(0, 2); |
| 158 | + |
| 159 | + console.log(predictions); |
| 160 | + updateDocumentWithGrayscaleClassification( |
| 161 | + image.id, |
| 162 | + predictions[0].className, |
| 163 | + predictions |
| 164 | + ); |
| 165 | + |
| 166 | + tensor.dispose(); |
| 167 | + } |
| 168 | +} |
0 commit comments