|
| 1 | +package org.tensorflow.model.examples.mnist; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | +import org.tensorflow.Graph; |
| 5 | +import org.tensorflow.Operand; |
| 6 | +import org.tensorflow.Session; |
| 7 | +import org.tensorflow.Tensor; |
| 8 | +import org.tensorflow.model.examples.mnist.data.ImageBatch; |
| 9 | +import org.tensorflow.model.examples.mnist.data.MnistDataset; |
| 10 | +import org.tensorflow.op.Ops; |
| 11 | +import org.tensorflow.op.core.Assign; |
| 12 | +import org.tensorflow.op.core.Constant; |
| 13 | +import org.tensorflow.op.core.Gradients; |
| 14 | +import org.tensorflow.op.core.Placeholder; |
| 15 | +import org.tensorflow.op.core.Variable; |
| 16 | +import org.tensorflow.op.math.Mean; |
| 17 | +import org.tensorflow.op.nn.Softmax; |
| 18 | +import org.tensorflow.op.train.ApplyGradientDescent; |
| 19 | +import org.tensorflow.tools.Shape; |
| 20 | +import org.tensorflow.tools.ndarray.ByteNdArray; |
| 21 | +import org.tensorflow.types.TFloat32; |
| 22 | +import org.tensorflow.types.TInt64; |
| 23 | + |
| 24 | +public class SimpleMnist implements Runnable { |
| 25 | + |
| 26 | + public static void main(String[] args) { |
| 27 | + MnistDataset dataset = MnistDataset.create(VALIDATION_SIZE); |
| 28 | + try (Graph graph = new Graph()) { |
| 29 | + SimpleMnist mnist = new SimpleMnist(graph, dataset); |
| 30 | + mnist.run(); |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + @Override |
| 35 | + public void run() { |
| 36 | + Ops tf = Ops.create(graph); |
| 37 | + |
| 38 | + // Create placeholders and variables, which should fit batches of an unknown number of images |
| 39 | + Placeholder<TFloat32> images = tf.placeholder(TFloat32.DTYPE); |
| 40 | + Placeholder<TFloat32> labels = tf.placeholder(TFloat32.DTYPE); |
| 41 | + |
| 42 | + // Create weights with an initial value of 0 |
| 43 | + Shape weightShape = Shape.of(dataset.imageSize(), MnistDataset.NUM_CLASSES); |
| 44 | + Variable<TFloat32> weights = tf.variable(weightShape, TFloat32.DTYPE); |
| 45 | + Assign<TFloat32> weightsInit = tf.assign(weights, tf.zerosLike(weights)); |
| 46 | + |
| 47 | + // Create biases with an initial value of 0 |
| 48 | + Shape biasShape = Shape.of(MnistDataset.NUM_CLASSES); |
| 49 | + Variable<TFloat32> biases = tf.variable(biasShape, TFloat32.DTYPE); |
| 50 | + Assign<TFloat32> biasesInit = tf.assign(biases, tf.zerosLike(biases)); |
| 51 | + |
| 52 | + // Predict the class of each image in the batch and compute the loss |
| 53 | + Softmax<TFloat32> softmax = |
| 54 | + tf.nn.softmax( |
| 55 | + tf.math.add( |
| 56 | + tf.linalg.matMul(images, weights), |
| 57 | + biases |
| 58 | + ) |
| 59 | + ); |
| 60 | + Mean<TFloat32> crossEntropy = |
| 61 | + tf.math.mean( |
| 62 | + tf.math.neg( |
| 63 | + tf.reduceSum( |
| 64 | + tf.math.mul(labels, tf.math.log(softmax)), |
| 65 | + tf.array(1) |
| 66 | + ) |
| 67 | + ), |
| 68 | + tf.array(0) |
| 69 | + ); |
| 70 | + |
| 71 | + // Back-propagate gradients to variables for training |
| 72 | + Gradients gradients = tf.gradients(crossEntropy, Arrays.asList(weights, biases)); |
| 73 | + Constant<TFloat32> alpha = tf.val(LEARNING_RATE); |
| 74 | + ApplyGradientDescent<TFloat32> weightGradientDescent = tf.train.applyGradientDescent(weights, alpha, gradients.dy(0)); |
| 75 | + ApplyGradientDescent<TFloat32> biasGradientDescent = tf.train.applyGradientDescent(biases, alpha, gradients.dy(1)); |
| 76 | + |
| 77 | + // Compute the accuracy of the model |
| 78 | + Operand<TInt64> predicted = tf.math.argMax(softmax, tf.val(1)); |
| 79 | + Operand<TInt64> expected = tf.math.argMax(labels, tf.val(1)); |
| 80 | + Operand<TFloat32> accuracy = tf.math.mean(tf.dtypes.cast(tf.math.equal(predicted, expected), TFloat32.DTYPE), tf.array(0)); |
| 81 | + |
| 82 | + // Run the graph |
| 83 | + try (Session session = new Session(graph)) { |
| 84 | + |
| 85 | + // Initialize variables |
| 86 | + session.runner() |
| 87 | + .addTarget(weightsInit) |
| 88 | + .addTarget(biasesInit) |
| 89 | + .run(); |
| 90 | + |
| 91 | + // Train the model |
| 92 | + for (ImageBatch trainingBatch : dataset.trainingBatches(TRAINING_BATCH_SIZE)) { |
| 93 | + try (Tensor<TFloat32> batchImages = preprocessImages(trainingBatch.images()); |
| 94 | + Tensor<TFloat32> batchLabels = preprocessLabels(trainingBatch.labels())) { |
| 95 | + session.runner() |
| 96 | + .addTarget(weightGradientDescent) |
| 97 | + .addTarget(biasGradientDescent) |
| 98 | + .feed(images.asOutput(), batchImages) |
| 99 | + .feed(labels.asOutput(), batchLabels) |
| 100 | + .run(); |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + // Test the model |
| 105 | + ImageBatch testBatch = dataset.testBatch(); |
| 106 | + try (Tensor<TFloat32> testImages = preprocessImages(testBatch.images()); |
| 107 | + Tensor<TFloat32> testLabels = preprocessLabels(testBatch.labels()); |
| 108 | + Tensor<TFloat32> accuracyValue = session.runner() |
| 109 | + .fetch(accuracy) |
| 110 | + .feed(images.asOutput(), testImages) |
| 111 | + .feed(labels.asOutput(), testLabels) |
| 112 | + .run() |
| 113 | + .get(0) |
| 114 | + .expect(TFloat32.DTYPE)) { |
| 115 | + System.out.println("Accuracy: " + accuracyValue.data().getFloat()); |
| 116 | + } |
| 117 | + } |
| 118 | + } |
| 119 | + |
| 120 | + private static final int VALIDATION_SIZE = 0; |
| 121 | + private static final int TRAINING_BATCH_SIZE = 100; |
| 122 | + private static final float LEARNING_RATE = 0.2f; |
| 123 | + |
| 124 | + private static Tensor<TFloat32> preprocessImages(ByteNdArray rawImages) { |
| 125 | + Ops tf = Ops.create(); |
| 126 | + |
| 127 | + // Flatten images in a single dimension and normalize their pixels as floats. |
| 128 | + long imageSize = rawImages.get(0).shape().size(); |
| 129 | + return tf.math.div( |
| 130 | + tf.reshape( |
| 131 | + tf.dtypes.cast(tf.val(rawImages), TFloat32.DTYPE), |
| 132 | + tf.array(-1L, imageSize) |
| 133 | + ), |
| 134 | + tf.val(255.0f) |
| 135 | + ).asTensor(); |
| 136 | + } |
| 137 | + |
| 138 | + private static Tensor<TFloat32> preprocessLabels(ByteNdArray rawLabels) { |
| 139 | + Ops tf = Ops.create(); |
| 140 | + |
| 141 | + // Map labels to one hot vectors where only the expected predictions as a value of 1.0 |
| 142 | + return tf.oneHot( |
| 143 | + tf.val(rawLabels), |
| 144 | + tf.val(MnistDataset.NUM_CLASSES), |
| 145 | + tf.val(1.0f), |
| 146 | + tf.val(0.0f) |
| 147 | + ).asTensor(); |
| 148 | + } |
| 149 | + |
| 150 | + private Graph graph; |
| 151 | + private MnistDataset dataset; |
| 152 | + |
| 153 | + private SimpleMnist(Graph graph, MnistDataset dataset) { |
| 154 | + this.graph = graph; |
| 155 | + this.dataset = dataset; |
| 156 | + } |
| 157 | +} |
0 commit comments