ML en el Edge

Rate this content
Bookmark

El mundo está lleno de miles de millones de teléfonos inteligentes pequeños, conectados, inteligentes y eficientes en el cálculo. ¿Qué pasaría si pudiéramos aprovechar este poder y hacer más en el edge? Resulta que el aprendizaje automático encaja perfectamente aquí. Vamos a explorar la biblioteca MLKit para incorporar inteligencia en aplicaciones de react-native.

7 min
02 Aug, 2021

Video Summary and Transcription

Esta charla discute el aprendizaje automático en el edge y sus beneficios para aplicaciones móviles. ML en el edge utiliza la potencia de cálculo de los dispositivos móviles para el procesamiento seguro y en tiempo real, así como para capacidades sin conexión. ML Kit, el SDK de Google, proporciona una integración sencilla de soluciones de ML en aplicaciones móviles sin necesidad de tener amplios conocimientos de ML. La charla cubre la configuración de Firebase y la integración de ML Kit en proyectos de React Native, mostrando las posibilidades de aplicar filtros y generar avatares con ML en el edge.

Available in English

1. Introducción a ML en el Edge

Short description:

Me complace hablar sobre el aprendizaje automático en el edge y cómo puede mejorar las aplicaciones móviles. ML en el edge aprovecha la capacidad de cómputo de los dispositivos móviles, lo que hace que el procesamiento sea más seguro, en tiempo real y brinde una mejor experiencia sin conexión. ML Kit, el SDK de Google, ofrece API base y personalizadas para tareas de visión y lenguaje, lo que facilita a los desarrolladores móviles integrar soluciones de ML sin una amplia experiencia en ML. La integración de ML Kit en un proyecto de React Native implica configurar el proyecto como uno de Firebase y actualizar el archivo de compilación o gradle.

Entonces, empecemos. Me complace hablarles a todos sobre el tema, el aprendizaje automático en el edge. Soy Sangeeta y trabajo como desarrollador en Amazon. Durante los últimos cuatro años, he estado construyendo aplicaciones móviles profesionalmente y como proyectos secundarios. Naturalmente, siempre estoy buscando formas de hacer que las aplicaciones sean más rápidas, más inteligentes, más seguras y poder brindar mejores experiencias al cliente.

Como tal, cuando Google lanzó ML Kit como parte de su ION, que prometía aprendizaje automático en el edge, tuve que probarlo. Ahora, ¿qué es el ML en el edge y por qué debería importarnos? Tradicionalmente, construir soluciones de ML requería que los desarrolladores recopilaran datos, construyeran modelos, los entrenaran, los ajustaran, los implementaran en algún servidor remoto en la nube y los sirvieran en dispositivos móviles en los llamados bordes de Internet.

Ahora, como todos sabemos, con el paso del tiempo, los dispositivos móviles se han vuelto mucho más eficientes en sus capacidades de cómputo. ¿Por qué no aprovechar la capacidad de cómputo de los dispositivos localmente, en lugar de hacer el procesamiento en algún lugar remoto en la nube? Eso es el ML en el edge. Ahora, ¿cuáles son los beneficios de hacerlo? No tener que transferir datos de un lado a otro del mundo significa una latencia y un ancho de banda más fáciles. Localizar todo el procesamiento que ocurre en el dispositivo significa que los datos son más seguros, los resultados son más en tiempo real y puedes brindar una mejor experiencia sin conexión a tus clientes. Y finalmente, esto reduce en gran medida la barrera para que cualquier desarrollador móvil con poca o ninguna experiencia en ML integre soluciones de ML en sus aplicaciones.

Espero que ahora estén convencidos de que el ML en el edge es interesante y tengan curiosidad por saber más al respecto. Ahora, intentemos entender cómo lograr esto. ML Kit es el SDK de Google, que engloba toda su experiencia en aprendizaje automático en un SDK simple pero poderoso. Esto se basa en TensorFlow Lite, que es una versión optimizada para dispositivos móviles de TensorFlow y se puede utilizar tanto para el desarrollo de Android como de iOS. Las API que ofrece ML Kit se pueden clasificar en dos tipos, base y personalizadas. La idea es que si una de tus necesidades no se satisface con las API base disponibles, puedes construir tus propios modelos de TensorFlow Lite personalizados y hacer que se rendericen en dispositivos móviles. Las API base disponibles se pueden clasificar aún más según su uso en visión y lenguaje. Por ejemplo, respuestas inteligentes, escaneo de códigos de barras, detección de rostros, detección e identificación de imágenes, y más. Nuevamente, los desarrolladores móviles no necesariamente necesitan entender la magia del aprendizaje automático que ocurre bajo el capó. Todo eso se abstrae de manera limpia y está disponible como API listas para usar, que se pueden aprovechar con solo unas pocas líneas de código.

Hablando de código, a continuación, entendamos qué se necesita para integrar ML Kit en un proyecto de React Native. Debemos saber que ML Kit se puede utilizar tanto para desarrollo nativo como para desarrollo de React Native, pero para este taller, me centraré en el flujo de trabajo de React Native para Android, aunque el proceso debería ser bastante similar para iOS también. El primer paso para integrar ML Kit es configurar tu proyecto como uno de Firebase. Firebase proporciona un conjunto de herramientas que facilitan mucho el desarrollo de aplicaciones. Herramientas como registro, autenticación, todo este proceso pesado está disponible como parte de Firebase. Entonces, los desarrolladores de Google pensaron, ¿por qué el aprendizaje automático debería ser diferente? Y es por eso que ML Kit también está disponible como parte de Firebase. Para comenzar con Firebase, ingresas a la consola de Firebase e ingresas el nombre de tu paquete. Esto genera un archivo de configuración de Firebase que se coloca en la raíz de la carpeta de tu proyecto. Luego, actualizamos el archivo de compilación o gradle para declarar los servicios de Google como una de nuestras dependencias y ejecutamos el complemento.

2. Configuración de Firebase e Integración de ML Kit

Short description:

Esta sección cubre la configuración de Firebase y React Native Firebase, la instalación del modelo de visión de ML y el uso de las API de ML Kit para el reconocimiento de texto y la detección de rostros. Las posibilidades de ML en el edge son infinitas, incluyendo la aplicación de filtros y la generación de avatares. En general, aprendimos sobre los beneficios del aprendizaje automático en el edge e integrando ML Kit en proyectos de React Native.

Esto nos permite utilizar los productos de Firebase en nuestro proyecto. Con la configuración de Firebase, pasemos a la sección de código base de React Native. Firebase para React Native es la biblioteca oficialmente recomendada para el desarrollo de Firebase en React Native. Para usar esto, primero instalamos el módulo de la aplicación Firebase de React Native utilizando npm o Yarn. Después de esto, según nuestro caso de uso, instalamos el modelo requerido. En este caso, estoy instalando el modelo de visión de ML y actualizando mi archivo firebase.json para habilitar true.

Ahora viene la parte divertida, con Firebase conectado y los modelos de ML requeridos instalados, utilizamos las API para procesar nuestra entrada. En este caso, estoy esperando la descarga del modelo de visión y luego proporciono la ruta de mi imagen local a la API de procesamiento de reconocimiento de texto de la imagen. Lo que esto hace es procesar la imagen y devolver una matriz de bloques de texto para cada texto en la imagen. Cada uno de estos bloques de texto contiene información como ¿cuál es el texto real dentro de él? ¿Cuáles son los límites? ¿Cuáles son las coordenadas? ¿Y cuál es el idioma del texto? Esto es una acción. Vemos que se ha determinado con precisión caminar sobre el césped y diferentes bloques de texto en la salida se han utilizado para superponer en la imagen. Este es otro ejemplo de la API de detección de rostros de ML Kit. Aquí he dado la imagen y ha sido capaz de determinar con precisión los contornos del rostro y darnos coordenadas. Considera esto como un punto de partida para aplicar filtros a esto o generar avatares para esta imagen y así sucesivamente. Las posibilidades son simplemente infinitas.

Eso es prácticamente lo que quería cubrir como parte de esta charla. Hoy aprendimos, ¿qué es el aprendizaje automático en el edge? ¿Cuáles son sus beneficios? ¿Qué es ML Kit y qué se necesita para integrar ML Kit como parte de tu proyecto de React Native? Espero haberte inspirado con la idea de usar ML en el edge en tu próxima aplicación móvil. Si tienes alguna pregunta, no dudes en enviarme un mensaje directo en mi Twitter o enviarme un correo. Muchas gracias por ver. Adiós.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

6 min
Charlie Gerard's Career Advice: Be intentional about how you spend your time and effort
Featured Article
When it comes to career, Charlie has one trick: to focus. But that doesn’t mean that you shouldn’t try different things — currently a senior front-end developer at Netlify, she is also a sought-after speaker, mentor, and a machine learning trailblazer of the JavaScript universe. "Experiment with things, but build expertise in a specific area," she advises.

What led you to software engineering?My background is in digital marketing, so I started my career as a project manager in advertising agencies. After a couple of years of doing that, I realized that I wasn't learning and growing as much as I wanted to. I was interested in learning more about building websites, so I quit my job and signed up for an intensive coding boot camp called General Assembly. I absolutely loved it and started my career in tech from there.
 What is the most impactful thing you ever did to boost your career?I think it might be public speaking. Going on stage to share knowledge about things I learned while building my side projects gave me the opportunity to meet a lot of people in the industry, learn a ton from watching other people's talks and, for lack of better words, build a personal brand.
 What would be your three tips for engineers to level up their career?Practice your communication skills. I can't stress enough how important it is to be able to explain things in a way anyone can understand, but also communicate in a way that's inclusive and creates an environment where team members feel safe and welcome to contribute ideas, ask questions, and give feedback. In addition, build some expertise in a specific area. I'm a huge fan of learning and experimenting with lots of technologies but as you grow in your career, there comes a time where you need to pick an area to focus on to build more profound knowledge. This could be in a specific language like JavaScript or Python or in a practice like accessibility or web performance. It doesn't mean you shouldn't keep in touch with anything else that's going on in the industry, but it means that you focus on an area you want to have more expertise in. If you could be the "go-to" person for something, what would you want it to be? 
 And lastly, be intentional about how you spend your time and effort. Saying yes to everything isn't always helpful if it doesn't serve your goals. No matter the job, there are always projects and tasks that will help you reach your goals and some that won't. If you can, try to focus on the tasks that will grow the skills you want to grow or help you get the next job you'd like to have.
 What are you working on right now?Recently I've taken a pretty big break from side projects, but the next one I'd like to work on is a prototype of a tool that would allow hands-free coding using gaze detection. 
 Do you have some rituals that keep you focused and goal-oriented?Usually, when I come up with a side project idea I'm really excited about, that excitement is enough to keep me motivated. That's why I tend to avoid spending time on things I'm not genuinely interested in. Otherwise, breaking down projects into smaller chunks allows me to fit them better in my schedule. I make sure to take enough breaks, so I maintain a certain level of energy and motivation to finish what I have in mind.
 You wrote a book called Practical Machine Learning in JavaScript. What got you so excited about the connection between JavaScript and ML?The release of TensorFlow.js opened up the world of ML to frontend devs, and this is what really got me excited. I had machine learning on my list of things I wanted to learn for a few years, but I didn't start looking into it before because I knew I'd have to learn another language as well, like Python, for example. As soon as I realized it was now available in JS, that removed a big barrier and made it a lot more approachable. Considering that you can use JavaScript to build lots of different applications, including augmented reality, virtual reality, and IoT, and combine them with machine learning as well as some fun web APIs felt super exciting to me.


Where do you see the fields going together in the future, near or far? I'd love to see more AI-powered web applications in the future, especially as machine learning models get smaller and more performant. However, it seems like the adoption of ML in JS is still rather low. Considering the amount of content we post online, there could be great opportunities to build tools that assist you in writing blog posts or that can automatically edit podcasts and videos. There are lots of tasks we do that feel cumbersome that could be made a bit easier with the help of machine learning.
 You are a frequent conference speaker. You have your own blog and even a newsletter. What made you start with content creation?I realized that I love learning new things because I love teaching. I think that if I kept what I know to myself, it would be pretty boring. If I'm excited about something, I want to share the knowledge I gained, and I'd like other people to feel the same excitement I feel. That's definitely what motivated me to start creating content.
 How has content affected your career?I don't track any metrics on my blog or likes and follows on Twitter, so I don't know what created different opportunities. Creating content to share something you built improves the chances of people stumbling upon it and learning more about you and what you like to do, but this is not something that's guaranteed. I think over time, I accumulated enough projects, blog posts, and conference talks that some conferences now invite me, so I don't always apply anymore. I sometimes get invited on podcasts and asked if I want to create video content and things like that. Having a backlog of content helps people better understand who you are and quickly decide if you're the right person for an opportunity.What pieces of your work are you most proud of?It is probably that I've managed to develop a mindset where I set myself hard challenges on my side project, and I'm not scared to fail and push the boundaries of what I think is possible. I don't prefer a particular project, it's more around the creative thinking I've developed over the years that I believe has become a big strength of mine.***Follow Charlie on Twitter
ML conf EU 2020ML conf EU 2020
41 min
TensorFlow.js 101: ML in the Browser and Beyond
Discover how to embrace machine learning in JavaScript using TensorFlow.js in the browser and beyond in this speedy talk. Get inspired through a whole bunch of creative prototypes that push the boundaries of what is possible in the modern web browser (things have come a long way) and then take your own first steps with machine learning in minutes. By the end of the talk everyone will understand how to recognize an object of their choice which could then be used in any creative way you can imagine. Familiarity with JavaScript is assumed, but no background in machine learning is required. Come take your first steps with TensorFlow.js!
React Advanced Conference 2021React Advanced Conference 2021
21 min
Using MediaPipe to Create Cross Platform Machine Learning Applications with React
Top Content
This talk gives an introduction about MediaPipe which is an open source Machine Learning Solutions that allows running machine learning models on low-powered devices and helps integrate the models with mobile applications. It gives these creative professionals a lot of dynamic tools and utilizes Machine learning in a really easy way to create powerful and intuitive applications without having much / no knowledge of machine learning beforehand. So we can see how MediaPipe can be integrated with React. Giving easy access to include machine learning use cases to build web applications with React.
JSNation Live 2021JSNation Live 2021
39 min
TensorFlow.JS 101: ML in the Browser and Beyond
Discover how to embrace machine learning in JavaScript using TensorFlow.js in the browser and beyond in this speedy talk. Get inspired through a whole bunch of creative prototypes that push the boundaries of what is possible in the modern web browser (things have come a long way) and then take your own first steps with machine learning in minutes. By the end of the talk everyone will understand how to recognize an object of their choice which could then be used in any creative way you can imagine. Familiarity with JavaScript is assumed, but no background in machine learning is required. Come take your first steps with TensorFlow.js!
ML conf EU 2020ML conf EU 2020
32 min
An Introduction to Transfer Learning in NLP and HuggingFace
In this talk I'll start introducing the recent breakthroughs in NLP that resulted from the combination of Transfer Learning schemes and Transformer architectures. The second part of the talk will be dedicated to an introduction of the open-source tools released HuggingFace, in particular our Transformers, Tokenizers and Datasets libraries and our models.

Workshops on related topic

ML conf EU 2020ML conf EU 2020
160 min
Hands on with TensorFlow.js
Workshop
Come check out our workshop which will walk you through 3 common journeys when using TensorFlow.js. We will start with demonstrating how to use one of our pre-made models - super easy to use JS classes to get you working with ML fast. We will then look into how to retrain one of these models in minutes using in browser transfer learning via Teachable Machine and how that can be then used on your own custom website, and finally end with a hello world of writing your own model code from scratch to make a simple linear regression to predict fictional house prices based on their square footage.
ML conf EU 2020ML conf EU 2020
112 min
The Hitchhiker's Guide to the Machine Learning Engineering Galaxy
Workshop
Are you a Software Engineer who got tasked to deploy a machine learning or deep learning model for the first time in your life? Are you wondering what steps to take and how AI-powered software is different from traditional software? Then it is the right workshop to attend.
The internet offers thousands of articles and free of charge courses, showing how it is easy to train and deploy a simple AI model. At the same time in reality it is difficult to integrate a real model into the current infrastructure, debug, test, deploy, and monitor it properly. In this workshop, I will guide you through this process sharing tips, tricks, and favorite open source tools that will make your life much easier. So, at the end of the workshop, you will know where to start your deployment journey, what tools to use, and what questions to ask.
ML conf EU 2020ML conf EU 2020
146 min
Introduction to Machine Learning on the Cloud
Workshop
This workshop will be both a gentle introduction to Machine Learning, and a practical exercise of using the cloud to train simple and not-so-simple machine learning models. We will start with using Automatic ML to train the model to predict survival on Titanic, and then move to more complex machine learning tasks such as hyperparameter optimization and scheduling series of experiments on the compute cluster. Finally, I will show how Azure Machine Learning can be used to generate artificial paintings using Generative Adversarial Networks, and how to train language question-answering model on COVID papers to answer COVID-related questions.