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

Push some Machine Learning into your App

Push some Machine Learning into your App

English version of my previous talk, and up-to-date with new command line.
JokeBox gif: https://i.ibb.co/JrhHDKv/jokebox.gif
Corgi video: https://giant.gfycat.com/SardonicQuerulousAnemoneshrimp.webm
Monkey gif: https://i.ibb.co/RvJXZwq/monkey.gif
Blur gif: https://i.ibb.co/k4MJM2S/blur.gif

Sandra Dupre

February 27, 2019
Tweet

More Decks by Sandra Dupre

Other Decks in Programming

Transcript

  1. Machine learning ? Supervised learning No Supervised learning Reinforcement learning

    Independent agent capable of learning from mistakes Clustering K-mean ... Decision Tree Logistic regression Boosting Neural Network …
  2. a Neuron (with Pooling) input 1 input n output 1

    output n POOLING Linear operation Filter function
  3. Lightweight solution Uses FlatBuffers models Optimized for mobile use Supports

    part of TensorFlow operations Still considered as a contribution to TensorFlow TensorFlow Lite ?
  4. T O C O TENSORFLOW LITE OPTIMIZING CONVERTER Saved Model,

    Frozen Graph or Keras → FlatBuffer
  5. Image → ByteBuffer private fun fromBitmapToByteBuffer(bitmap: Bitmap): ByteBuffer { val

    imgData = ByteBuffer.allocateDirect((if (isQuantized) 1 else 4) * IMG_SIZE * IMG_SIZE * 3) .apply { order(ByteOrder.nativeOrder()) rewind() } val pixels = IntArray(IMG_SIZE * IMG_SIZE) val createScaledBitmap = Bitmap.createScaledBitmap(bitmap, IMG_SIZE, IMG_SIZE, false) createScaledBitmap.apply { getPixels(pixels, 0, width, 0, 0, width, height) } pixels.forEach { value -> imgData.add(value shr 16 and 0xFF) imgData.add(value shr 8 and 0xFF) imgData.add(value and 0xFF) } return imgData } private fun ByteBuffer.add(pixel: Int) = if (isQuantized) put(pixel.toByte()) else putFloat((pixel - MEAN) / STD)
  6. Interpreter val fileInputStream = context.assets.openFd(MODEL_NAME).let { FileInputStream(it.fileDescriptor).channel.map( FileChannel.MapMode.READ_ONLY, it.startOffset, it.declaredLength

    ) } val interpreter = Interpreter(fileInputStream) val labels = context.assets.open("labels.txt").bufferedReader().readLines()
  7. Run ! fun recognizeDog(bitmap: Bitmap) { val imgData = fromBitmapToByteBuffer(bitmap)

    val outputs = Array(1, { FloatArray(labels.size) }) interpreter.run(imgData, outputs) val dog = labels .mapIndexed { index, label -> Pair(label, outputs[0][index]) } .sortedByDescending { it.second } .first() view?.displayDog(dog.first) }
  8. OCR (device & cloud) Faces detection (device) Barcode scanning (device)

    Image labelling (device & cloud) Landmark detection (cloud) Smart Reply
  9. Example : Faces detection • Bounding polygon • Angles of

    rotation • Tracking ID • Facial landmarks ◦ Left eye ◦ Right eye ◦ Bottom of mouth ... • Feature probabilities ◦ Smiling ◦ Left eye open ◦ Right eye open • Facial contours: ◦ Nose bridge ◦ Left eye ◦ Top of upper lip
  10. Example : Faces detection • Bounding polygon • Angles of

    rotation • Tracking ID • Facial landmarks ◦ Left eye ◦ Right eye ◦ Bottom of mouth ... • Feature probabilities ◦ Smiling ◦ Left eye open ◦ Right eye open • Facial contours: ◦ Nose bridge ◦ Left eye ◦ Top of upper lip...
  11. Example : Faces detection The Joke Box If you don't

    smile, it offers you a joke If you smile, everything is fine. API : Dad Jokes https://icanhazdadjoke.com/ Confettis : nl.dionsegijn:konfetti Camera (don’t talk about Camera2) : com.camerakit:camerakit (Warning: beautiful design) In collaboration with Nicolas Telera
  12. Example : Faces detection implementation 'com.google.firebase:firebase-ml-vision:17.0.1' implementation 'com.google.firebase:firebase-core:16.0.4' [...] apply

    plugin: 'com.google.gms.google-services' Don't forget to register your app on Firebase and integrate google.services
  13. Example : Faces detection init { val options = FirebaseVisionFaceDetectorOptions

    .Builder() .setClassificationType( FirebaseVisionFaceDetectorOptions .ALL_CLASSIFICATIONS ) .build() detector = FirebaseVision.getInstance().getVisionFaceDetector(options) }
  14. fun recognizePicture(bitmap: Bitmap) { } Example : Faces detection val

    firebaseVisionImage = FirebaseVisionImage.fromBitmap(bitmap) detector.detectInImage(firebaseVisionImage) .addOnSuccessListener { faces -> } .addOnFailureListener { view.displayFail() } try { if (faces.first().smilingProbability > 0.70) { view.displaySmile() } else { view.displaySad() } } catch (e: NoSuchElementException) { view.displayFail() }
  15. Device or Cloud ? Performance Device < Performance Cloud Cloud

    pricing: “Free for first 1000 uses of this feature per month” Device: possible Offline! Warning: data protection
  16. Initialization val dataType = if (isQuantized) FirebaseModelDataType.BYTE else FirebaseModelDataType.FLOAT32 dataOptions

    = FirebaseModelInputOutputOptions.Builder() .setInputFormat(0, dataType, intArrayOf(1, IMG_SIZE, IMG_SIZE, 3)) .setOutputFormat(0, dataType, intArrayOf(1, labels.size)) .build() val labels = context.assets.open("labels.txt").bufferedReader().readLines()
  17. Interpreter initialization: Cloud Source val conditions = FirebaseModelDownloadConditions .Builder() .requireWifi()

    .build() val cloudSource = FirebaseCloudModelSource.Builder(MODEL_NAME) .enableModelUpdates(true) .setInitialDownloadConditions(conditions) .setUpdatesDownloadConditions(conditions) .build()
  18. Interpreter initialization: Cloud Source val conditions = FirebaseModelDownloadConditions .Builder() .requireWifi()

    .build() val cloudSource = FirebaseCloudModelSource.Builder(MODEL_NAME) .enableModelUpdates(true) .setInitialDownloadConditions(conditions) .setUpdatesDownloadConditions(conditions) .build() Other conditions >= Nougat: requireCharging(), requireDeviceIdle()
  19. Interpreter initialization: Cloud Source val conditions = FirebaseModelDownloadConditions .Builder() .requireWifi()

    .build() val cloudSource = FirebaseCloudModelSource.Builder(MODEL_NAME) .enableModelUpdates(true) .setInitialDownloadConditions(conditions) .setUpdatesDownloadConditions(conditions) .build()
  20. Interpreter initialization FirebaseModelManager.getInstance().apply { registerLocalModelSource(localSource) registerCloudModelSource(cloudSource) } val interpreter =

    FirebaseModelInterpreter.getInstance( FirebaseModelOptions.Builder() .setCloudModelName(MODEL_NAME) .setLocalModelName(ASSET) .build() )
  21. Run ! val inputs = FirebaseModelInputs.Builder() .add(fromBitmapToByteBuffer(bitmap)) .build() interpreter?.run(inputs, dataOptions)

    ?.addOnSuccessListener { val output = it.getOutput<Array<FloatArray>>(0) val label = labels .mapIndexed { index, label ->Pair(label, output[0][index])} .maxBy { it.second }.first() view?.displayDog(label) } ?.addOnFailureListener { view?.displayError() }
  22. But : Download the model is long and random What

    about the bugs in TensorFlow Lite? TOCO, quantized model and other misunderstandings Incomplete documentation Difficult examples (with quite dirty code) Online Based API pricing
  23. Lose It Nutrition facts with ML Kit Text Recognition API

    https://developers.google.com/ml-kit/ “Snap it” features to recognize food with TensorFlow Lite https://loseitblog.com/2017/11/10/on-device-image-recognition/
  24. Anonymize By Nicolas Telera Detect and blur faces in a

    picture. https://github.com/NicolasTelera/Anonymize
  25. Why not in your app? Fraud detection User help Adding

    documents Games Picture filter Automatic photo tags Proposal for hashtags and your ideas?