Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Creating a custom Machine Learning Model for yo...

Creating a custom Machine Learning Model for your applications - Java Dev Day 2019

Aprenderás como puede ser creado un modelo de Machine Learning que puedas implementar en tu aplicación móvil o Java. Iré mostrando cada uno de los pasos que se tienen que seguir, los tipos de problemas que se pueden resolver, los datos que necesitas para que funcione y por último, las opciones para realizar la implementación de nuestro modelo en nuestras aplicaciones.

Isabel Palomar

September 28, 2019
Tweet

More Decks by Isabel Palomar

Other Decks in Programming

Transcript

  1. Agenda • Challenges and Initial ideas • Main Deep Learning

    concepts • Using the model! ◦ Android app ◦ Java app … that’s all 3
  2. “ 7 7 @jeremyphoward @math_rachel I started a Deep Learning

    Course last year at the University of San Francisco. MY STORY: TAKING MY FIRST DEEP LEARNING CLASS
  3. 8 After the class….. The key outcome of this lesson

    is that we'll have trained an image classifier which can recognize pet breeds at state of the art accuracy. The key to this success is the use of transfer learning, which will be a key platform for much of this course. We also discuss how to set the most important hyper-parameter when training neural networks: the learning rate, using Leslie Smith's fantastic learning rate finder method. Finally, we'll look at the important but rarely discussed topic of labeling, and learn about some of the features that fastai provides for allowing you to easily add labels to your images. https://course.fast.ai/videos/?lesson=1
  4. challenges…. ‐ Many courses, even basic, assume that you already

    know the subject. ‐ Reaching the final result without learning the basics is not good. 9
  5. “ When you are starting to learn about Deep Learning

    it seems that there are thousands of concepts, mathematical functions and scientific articles that you have to read. 10 myths
  6. Let’s take a look of the implementation We are going

    to build an app to classify the artisanal beers of Cervecería Colima And…. I will show you how to use the Interpreter for your Java apps Place your screenshot here 13
  7. How? Where do we get data from? Data curation is

    the organization and integration of data collected from various sources. 17 Techniques You can use techniques like Questionnaires and surveys, conducting interviews, using data scraping and data crawling techniques.
  8. Public datasets • Google AI • UCI ML Repository •

    Data.gov.in • Kaggle Where do we get data from? Crowdsourcing Marketplaces • Amazon Mechanical Turk • Dataturks • Figure-eight 18
  9. BACK TO OUR EXAMPLE... • Google Images • https://github.com/hardikvasa/google-images-download •

    https://forums.fast.ai/t/tips-for-building-large-image-datasets/26688 19
  10. Image classification A common use of machine learning is to

    identify what an image represents. The task of predicting what an image represents is called image classification. 23
  11. models 25 There are many models that are created over

    the years. Each model has its own advantages and disadvantages based on the type of data on which we are creating a model.
  12. IMAGE CLASSIFICATION MODEL An image classification model is trained to

    recognize various classes of images. 26 When we subsequently provide a new image as input to the model, it will output the probabilities of the image representing each of the types it was trained on.
  13. An example output might be as follows: Beer type Probability

    Cayaco 0.02 Colimita 0.96 Piedra Lisa 0.01 Ticus 0.00 Paramo 0.01 27 Based on the output, we can see that the classification model has predicted that the image has a high probability of representing a Colimita Beer.
  14. In this example, we will retrain a MobileNet. MobileNet is

    a a small efficient convolutional neural network. https://ai.googleblog.com/2017/06/mobilenets-open-source-models-for.html Model for our example 28
  15. Retraining the mobileNet model 29 We use MobileNet model and

    retrain it. python3 -m scripts.retrain --bottleneck_dir=tf_files/bottlenecks --model_dir=tf_files/models/"${ARCHITECTURE}" --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}" --output_graph=tf_files/retrained_graph.pb --output_labels=tf_files/retrained_labels.txt --architecture="${ARCHITECTURE}" --image_dir=tf_files/beer_photos IMAGE_SIZE=224 ARCHITECTURE="mobilenet_0.50_${IMAGE_SIZE}" tHE RESULT...
  16. USING THE RETRAINED MODEL 30 30 Evaluation time (1-image): 0.250s

    ticus (score=0.99956) paramo (score=0.00043) cayaco (score=0.00000) piedra lisa (score=0.00000) colimita (score=0.00000) python3 -m scripts.label_image --graph=tf_files/retrained_graph.pb --image=tf_files/beer_photos/ticus/"3. ticus.jpg"
  17. 4.- loss function How do we know which model is

    better? Loss function (also known as the error) answers this question. 31
  18. Classification losses: • Mean Square Error/L2 Loss • Mean Absolute

    Error/L1 Loss Regression losses: • Hinge Loss/Multi-class SVM Loss • Cross Entropy • Loss/Negative Log Likelihood LOSS FUNCTIONS To know which model is good for our data, we compute the loss function by comparing the predicted outputs to actual output. 32
  19. Is something you do everyday... You are optimizing variables and

    basing your personal decisions all day long, most of the time without even recognizing the process consciously https://mitsloan.mit.edu/ideas-made-to-matter/how-to-use -algorithms-to-solve-everyday-problems 34
  20. First Order Optimization Algorithms  • Gradient Descent Types of learning

    algorithms Second Order Optimization Algorithms • Hessian https://towardsdatascience.com/types-of-optimization-algorithms-used-in-neural-networks-and- ways-to-optimize-gradient-95ae5d39529f 35
  21. Evaluation/performance metrics 38 • Confusion matrix • Area Under the

    ROC curve (AUC — ROC) • Root Mean Squared Error (RMSE) (used in regression)
  22. MACHINE LEARNING IN YOUR APPS • ML Kit For Firebase

    • Core ML (Apple) • TensorFlow Lite • Cloud-based web services • Your own service Place your screenshot here 41
  23. USING THE RETRAINED MODEL 43 43 Evaluation time (1-image): 0.250s

    ticus (score=0.99956) paramo (score=0.00043) cayaco (score=0.00000) piedra lisa (score=0.00000) colimita (score=0.00000) python3 -m scripts.label_image --graph=tf_files/retrained_graph.pb --image=tf_files/beer_photos/ticus/"3. ticus.jpg"
  24. TENSORFLOW LITE 44 TensorFlow Lite is a set of tools

    to help developers run TensorFlow models on mobile, embedded, and IoT devices. • TensorFlow Lite converter • TensorFlow Lite interpreter TensorFlow Lite converter Converts TensorFlow models into an efficient form for use by the interpreter
  25. Command line: tflite_convert Starting from TensorFlow 1.9, the command-line tool

    tflite_convert is installed as part of the Python package. 45 pip install --upgrade "tensorflow==1.9.*"
  26. Using TFLite Converter 46 Output: IMAGE_SIZE=224 tflite_convert \ --graph_def_file=tf_files/retrained_graph.pb \

    --output_file=tf_files/optimized_graph.lite \ --input_format=TENSORFLOW_GRAPHDEF \ --output_format=TFLITE \ --input_shape=1,${IMAGE_SIZE},${IMAGE_SIZE},3 \ --input_array=input \ --output_array=final_result \ --inference_type=FLOAT \ --input_data_type=FLOAT
  27. repositories { maven { url 'https://google.bintray.com/tensorflow' } } dependencies {

    // ... compile 'org.tensorflow:tensorflow-lite:+' } TensorFlow Lite interpreter 50 android { aaptOptions { noCompress "tflite" noCompress "lite" } } The TensorFlow Lite interpreter is designed to be lean and fast. The interpreter uses a static graph ordering and a custom (less-dynamic) memory allocator to ensure minimal load, initialization, and execution latency. dependencies settings
  28. Load model and create interpreter class ImageClassifier constructor(private val assetManager:

    AssetManager) { init { interpreter = Interpreter(loadModelFile(assetManager, MODEL_PATH)) labels = loadLabelList(assetManager) ... } } 51 // Name of the model file stored in Assets. const val MODEL_PATH = "graph.lite"; // Name of the label file stored in Assets. const val LABEL_PATH = "labels.txt";
  29. cAMERA, Read the labels….. 52 https://developer.android.com/training/camerax // Convert the image

    to bytes convertBitmapToByteBuffer(bitmap) // An array to hold inference results, to be feed into Tensorflow Lite as outputs. val recognitions = ArrayList<Result>() val recognitionsSize = Math.min(pq.size, MAX_RESULTS) for (i in 0 until recognitionsSize) recognitions.add(pq.poll()) return@flatMap Single.just(recognitions)
  30. Show the results 53 // Get the results textToShow =

    String.format("\n%s: %4.2f", label.key, label.value) // Label (In this case PARAMO) label.key // Value (In this case 1.0) label.value ticus (score=0.00000) paramo (score=1.00000) cayaco (score=0.00000) piedra lisa (score=0.00000) colimita (score=0.00000)
  31. repositories { maven { url 'https://google.bintray.com/tensorflow' } } dependencies {

    // ... compile 'org.tensorflow:tensorflow-lite:+' } TensorFlow Lite interpreter 56 The TensorFlow Lite interpreter is designed to be lean and fast. The interpreter uses a static graph ordering and a custom (less-dynamic) memory allocator to ensure minimal load, initialization, and execution latency. dependencies
  32. Load model and create interpreter // Or with a MappedByteBuffer:

    public Interpreter(@NotNull MappedByteBuffer mappedByteBuffer); 57 // You can initialize an Interpreter using a .tflite file: public Interpreter(@NotNull File modelFile);
  33. Load the image, run the interpreter 58 // Convert the

    image to bytes convertBitmapToByteBuffer(bitmap) // To then run an inference with the model, simply call Interpreter.run() try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) { interpreter.run(input, output); }
  34. Show the results 59 // Get the results textToShow =

    String.format("\n%s: %4.2f", label.getKey(), label.getValue()) // Label (In this case PARAMO) label.getKey() // Value (In this case 1.0) label.getValue() ticus (score=0.00000) paramo (score=1.00000) cayaco (score=0.00000) piedra lisa (score=0.00000) colimita (score=0.00000)
  35. Call to action! Now you are ready to start building

    your first custom ML model. 61