Using Deep Learning & Neural Networks in Android Applications

Contents

In this tutorial, I’ll show you how to use Deeplearning4J, a popular Java-based deep learning library, to create and train a neural network on an Android device.

Prerequisites

For best results, you’ll need the following:

  • An Android device or emulator that runs API level 21 or higher, and has about 200 MB of internal storage space free. I strongly suggest you use an emulator first because you can quickly tweak it in case you run out of memory or storage space.
  • Android Studio 2.2 or newer
  • A more in-depth look at using DL4J in Android Applications can be found here. This guide covers dependencies, memory management, saving device-trained models, and loading pre-trained models in the application.

Configuring Your Android Studio Project

To be able to use Deeplearning4J in your project, add the following compile dependencies to your app module’s build.gradle file:

  1. compile (group: 'org.deeplearning4j', name: 'deeplearning4j-core', version: '1.0.0-beta4') {
  2. exclude group: 'org.bytedeco.javacpp-presets', module: 'opencv-platform'
  3. exclude group: 'org.bytedeco.javacpp-presets', module: 'leptonica-platform'
  4. exclude group: 'org.bytedeco.javacpp-presets', module: 'hdf5-platform'
  5. exclude group: 'org.nd4j', module: 'nd4j-base64'
  6. }
  7. compile group: 'org.nd4j', name: 'nd4j-native', version: '1.0.0-beta4'
  8. compile group: 'org.nd4j', name: 'nd4j-native', version: '1.0.0-beta4', classifier: "android-arm"
  9. compile group: 'org.nd4j', name: 'nd4j-native', version: '1.0.0-beta4', classifier: "android-arm64"
  10. compile group: 'org.nd4j', name: 'nd4j-native', version: '1.0.0-beta4', classifier: "android-x86"
  11. compile group: 'org.nd4j', name: 'nd4j-native', version: '1.0.0-beta4', classifier: "android-x86_64"
  12. compile group: 'org.bytedeco.javacpp-presets', name: 'openblas', version: '0.3.3-1.4.3'
  13. compile group: 'org.bytedeco.javacpp-presets', name: 'openblas', version: '0.3.3-1.4.3', classifier: "android-arm"
  14. compile group: 'org.bytedeco.javacpp-presets', name: 'openblas', version: '0.3.3-1.4.3', classifier: "android-arm64"
  15. compile group: 'org.bytedeco.javacpp-presets', name: 'openblas', version: '0.3.3-1.4.3', classifier: "android-x86"
  16. compile group: 'org.bytedeco.javacpp-presets', name: 'openblas', version: '0.3.3-1.4.3', classifier: "android-x86_64"
  17. compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.4.3-1.4.3'
  18. compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.4.3-1.4.3', classifier: "android-arm"
  19. compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.4.3-1.4.3', classifier: "android-arm64"
  20. compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.4.3-1.4.3', classifier: "android-x86"
  21. compile group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.4.3-1.4.3', classifier: "android-x86_64"
  22. compile group: 'org.bytedeco.javacpp-presets', name: 'leptonica', version: '1.76.0-1.4.3'
  23. compile group: 'org.bytedeco.javacpp-presets', name: 'leptonica', version: '1.76.0-1.4.3', classifier: "android-arm"
  24. compile group: 'org.bytedeco.javacpp-presets', name: 'leptonica', version: '1.76.0-1.4.3', classifier: "android-arm64"
  25. compile group: 'org.bytedeco.javacpp-presets', name: 'leptonica', version: '1.76.0-1.4.3', classifier: "android-x86"
  26. compile group: 'org.bytedeco.javacpp-presets', name: 'leptonica', version: '1.76.0-1.4.3', classifier: "android-x86_64"

If you choose to use a SNAPSHOT version of the dependencies with gradle, you will need to create the a pom.xml file in the root directory and run mvn -U compile on it from the terminal. You will also need to include mavenLocal() in the repository {} block of the build.gradle file. An example pom.xml file is provided below.

  1. <project>
  2. <modelVersion>4.0.0</modelVersion>
  3. <groupId>org.deeplearning4j</groupId>
  4. <artifactId>snapshots</artifactId>
  5. <version>1.0.0-SNAPSHOT</version>
  6. <dependencies>
  7. <dependency>
  8. <groupId>org.nd4j</groupId>
  9. <artifactId>nd4j-native-platform</artifactId>
  10. <version>1.0.0-SNAPSHOT</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.deeplearning4j</groupId>
  14. <artifactId>deeplearning4j-core</artifactId>
  15. <version>1.0.0-SNAPSHOT</version>
  16. </dependency>
  17. </dependencies>
  18. <repositories>
  19. <repository>
  20. <id>sonatype-nexus-snapshots</id>
  21. <url>https://oss.sonatype.org/content/repositories/snapshots</url>
  22. <releases>
  23. <enabled>false</enabled>
  24. </releases>
  25. <snapshots>
  26. <enabled>true</enabled>
  27. <updatePolicy>always</updatePolicy>
  28. </snapshots>
  29. </repository>
  30. </repositories>
  31. </project>

Android Studio 3.0 introduced new Gradle, now annotationProcessors should be defined too If you are using it, add following code to gradle dependencies:

  1. NeuralNetConfiguration.Builder nncBuilder = new NeuralNetConfiguration.Builder();
  2. nncBuilder.updater(Updater.ADAM);

As you can see, DL4J depends on ND4J, short for N-Dimensions for Java, which is a library that offers fast n-dimensional arrays. ND4J internally depends on a library called OpenBLAS, which contains platform-specific native code. Therefore, you must load a version of OpenBLAS and ND4J that matches the architecture of your Android device.

Dependencies of DL4J and ND4J have several files with identical names. In order to avoid build errors, add the following exclude parameters to your packagingOptions.

  1. packagingOptions {
  2. exclude 'META-INF/DEPENDENCIES'
  3. exclude 'META-INF/DEPENDENCIES.txt'
  4. exclude 'META-INF/LICENSE'
  5. exclude 'META-INF/LICENSE.txt'
  6. exclude 'META-INF/license.txt'
  7. exclude 'META-INF/NOTICE'
  8. exclude 'META-INF/NOTICE.txt'
  9. exclude 'META-INF/notice.txt'
  10. exclude 'META-INF/INDEX.LIST'
  11. }

Your compiled code will have well over 65,536 methods. To be able to handle this condition, add the following option in the defaultConfig:

  1. multiDexEnabled true

And now, press Sync Now to update the project. Finally, make sure that your APK doesn’t contain both lib/armeabi and lib/armeabi-v7a subdirectories. If it does, move all files to one or the other as some Android devices will have problems with both present.

Starting an Asynchronous Task

Training a neural network is CPU-intensive, which is why you wouldn’t want to do it in your application’s UI thread. I’m not too sure if DL4J trains its networks asynchronously by default. Just to be safe, I’ll spawn a separate thread now using the AsyncTask class.

  1. AsyncTask.execute(new Runnable() {
  2. @Override
  3. public void run() {
  4. createAndUseNetwork();
  5. }
  6. });

Because the method createAndUseNetwork() doesn’t exist yet, create it.

  1. private void createAndUseNetwork() {
  2. }

Creating a Neural Network

DL4J has a very intuitive API. Let us now use it to create a simple multi-layer perceptron with hidden layers. It will take two input values, and spit out one output value. To create the layers, we’ll use the DenseLayer and OutputLayer classes. Accordingly, add the following code to the createAndUseNetwork() method you created in the previous step:

  1. DenseLayer inputLayer = new DenseLayer.Builder()
  2. .nIn(2)
  3. .nOut(3)
  4. .name("Input")
  5. .build();
  6. DenseLayer hiddenLayer = new DenseLayer.Builder()
  7. .nIn(3)
  8. .nOut(2)
  9. .name("Hidden")
  10. .build();
  11. OutputLayer outputLayer = new OutputLayer.Builder()
  12. .nIn(2)
  13. .nOut(1)
  14. .name("Output")
  15. .build();

Now that our layers are ready, let’s create a NeuralNetConfiguration.Builder object to configure our neural network.

  1. NeuralNetConfiguration.Builder nncBuilder = new NeuralNetConfiguration.Builder();
  2. nncBuilder.updater(Updater.ADAM);

We must now create a NeuralNetConfiguration.ListBuilder object to actually connect our layers and specify their order.

  1. NeuralNetConfiguration.ListBuilder listBuilder = nncBuilder.list();
  2. listBuilder.layer(0, inputLayer);
  3. listBuilder.layer(1, hiddenLayer);
  4. listBuilder.layer(2, outputLayer);

Additionally, enable backpropagation by adding the following code:

  1. listBuilder.backprop(true);

At this point, we can generate and initialize our neural network as an instance of the MultiLayerNetwork class.

  1. MultiLayerNetwork myNetwork = new MultiLayerNetwork(listBuilder.build());
  2. myNetwork.init();

Creating Training Data

To create our training data, we’ll be using the INDArray class, which is provided by ND4J. Here’s what our training data will look like:

  1. INPUTS EXPECTED OUTPUTS
  2. ------ ----------------
  3. 0,0 0
  4. 0,1 1
  5. 1,0 1
  6. 1,1 0

As you might have guessed, our neural network will behave like an XOR gate. The training data has four samples, and you must mention it in your code.

  1. final int NUM_SAMPLES = 4;

And now, create two INDArray objects for the inputs and expected outputs, and initialize them with zeroes.

  1. INDArray trainingInputs = Nd4j.zeros(NUM_SAMPLES, inputLayer.getNIn());
  2. INDArray trainingOutputs = Nd4j.zeros(NUM_SAMPLES, outputLayer.getNOut());

Note that the number of columns in the inputs array is equal to the number of neurons in the input layer. Similarly, the number of columns in the outputs array is equal to the number of neurons in the output layer.

Filling those arrays with the training data is easy. Just use the putScalar() method:

  1. // If 0,0 show 0
  2. trainingInputs.putScalar(new int[]{0, 0}, 0);
  3. trainingInputs.putScalar(new int[]{0, 1}, 0);
  4. trainingOutputs.putScalar(new int[]{0, 0}, 0);
  5. // If 0,1 show 1
  6. trainingInputs.putScalar(new int[]{1, 0}, 0);
  7. trainingInputs.putScalar(new int[]{1, 1}, 1);
  8. trainingOutputs.putScalar(new int[]{1, 0}, 1);
  9. // If 1,0 show 1
  10. trainingInputs.putScalar(new int[]{2, 0}, 1);
  11. trainingInputs.putScalar(new int[]{2, 1}, 0);
  12. trainingOutputs.putScalar(new int[]{2, 0}, 1);
  13. // If 1,1 show 0
  14. trainingInputs.putScalar(new int[]{3, 0}, 1);
  15. trainingInputs.putScalar(new int[]{3, 1}, 1);
  16. trainingOutputs.putScalar(new int[]{3, 0}, 0);

We won’t be using the INDArray objects directly. Instead, we’ll convert them into a DataSet.

  1. DataSet myData = new DataSet(trainingInputs, trainingOutputs);

At this point, we can start the training by calling the fit() method of the neural network and passing the data set to it. The for loop controls the iterations of the data set through the network. It is set to 1000 iterations in this example.

  1. for(int l=0; l<=1000; l++) {
  2. myNetwork.fit(myData);
  3. }

And that’s all there is to it. Your neural network is ready to be used.

Conclusion

In this tutorial, you saw how easy it is to create and train a neural network using the Deeplearning4J library in an Android Studio project. I’d like to warn you, however, that training a neural network on a low-powered, battery operated device might not always be a good idea.

A second example DL4J Android Application which includes a user interface can be found here. This example trains a neural network on the device using Anderson’s iris data set for iris flower type classification. The application includes user input for the measurements and returns the probability that these measurements belong to one of three iris types (Iris serosa, Iris versicolor, and Iris virginica).

The limitations of processing power and battery life on mobile devices make training robust, multi-layer networks unfeasible. As an alternative to training a network on the device, the neural network being used by your application can be trained on the desktop, saved via ModelSerializer, and then loaded as a pre-trained model in the application. A third example DL4J Android Application can be found here which loads a pre-trained Mnist network and uses it to classify user drawn numbers.