Aprendizaje automático en Node.js utilizando Tensorflow.js

Rate this content
Bookmark

Escribe e implementa modelos de aprendizaje automático fácilmente en Node.js utilizando Tensorflow.js.

8 min
24 Jun, 2021

Video Summary and Transcription

La charla presenta TensorFlow.js en Node.js para el aprendizaje automático, destacando su naturaleza de código abierto y su fácil integración con JavaScript. Se enfatizan los beneficios de usar Node.js, como la capacidad de escribir modelos de aprendizaje automático directamente en JavaScript, el acceso al ecosistema de NPM y el rendimiento mejorado. Se discuten los diferentes paquetes disponibles para utilizar TensorFlow.js en Node.js, incluyendo paquetes de CPU, GPU y vanilla. Se menciona la importancia de configurar las conexiones de Node.js para evitar bloquear el hilo principal, junto con la disponibilidad de APIs como dfNode y TensorBoard.

Available in English

1. Introducción a TensorFlow.js en Node.js

Short description:

Hola a todos. El tema de mi charla relámpago es el aprendizaje automático en Node.js utilizando TensorFlow.js. TensorFlow.js es una biblioteca de código abierto que permite la integración fácil de modelos de aprendizaje automático directamente en JavaScript. Permite un fácil acceso a aplicaciones de aprendizaje automático en diferentes plataformas sin necesidad de complementos. La arquitectura de TensorFlow.js incluye modelos preentrenados, una API de capas para construir y entrenar modelos, y una API de operaciones o núcleo para un control afinado. Utilizar Node.js para ejecutar TensorFlow.js proporciona la capacidad de escribir modelos de aprendizaje automático directamente en JavaScript, ejecutar modelos más grandes, utilizar el ecosistema de NPM y lograr un mejor rendimiento.

Hola a todos. El tema de mi charla relámpago es el aprendizaje automático en Node.js utilizando TensorFlow.js.

Hola, soy Shivailamba. Actualmente soy miembro de SIG de TensorFlow.js y también mentor de Google Codename en TensorFlow.

Entonces, la primera pregunta que surge en la mente de todos es ¿qué es exactamente TensorFlow.js? TensorFlow.js es una biblioteca de código abierto que permite la integración fácil de modelos de aprendizaje automático directamente en JavaScript. Por lo tanto, reduce la necesidad de aprender un lenguaje separado como Python para alojar modelos de aprendizaje automático. Y permite una integración muy fácil de algún tipo de modelos preentrenados o escribir tus propios modelos desde cero directamente en JavaScript.

Y como sabemos que JavaScript es un lenguaje realmente versátil, se puede ejecutar en diferentes plataformas como en el navegador, en dispositivos móviles o incluso en dispositivos IoT que ejecutan Raspberry Pi. Por lo tanto, todas estas plataformas diferentes ahora tienen fácil acceso a aplicaciones basadas en aprendizaje automático sin necesidad de complementos, ¿verdad? Y el aprendizaje automático que se puede utilizar en TensorFlow.js no solo puede utilizar modelos preexistentes, sino que también puede utilizar el aprendizaje por transferencia para volver a entrenar algunos de los modelos existentes en función de tu propio conjunto de datos. Y también puedes escribir modelos de aprendizaje automático directamente en JavaScript utilizando JavaScript y sin necesidad de ningún otro lenguaje como Python.

Ahora esta es la arquitectura de TensorFlow.js. Hay tres API diferentes que se proporcionan. La capa superior que ves son los modelos preentrenados de TensorFlow.js que son clases de JavaScript completamente listas para usar. El siguiente es la API de capas que permite construir y entrenar modelos fácilmente utilizando bloques de construcción de alto nivel de manera similar a cómo se ha construido Keras sobre TensorFlow. Y finalmente tenemos la API de operaciones o núcleo que te ayuda a tener un control afinado de la arquitectura del modelo o hacer cálculos matemáticos como álgebra lineal. Y esto se puede ejecutar tanto en el lado del cliente como en el lado del servidor. En el lado del cliente, tenemos el navegador o las aplicaciones basadas en móviles que utilizan la CPU o los gráficos acelerados por web como WebGL o WebAssembly. Y en el lado del servidor, hay soporte para TensorFlow CPU que se ejecutan a través de las vinculaciones C y también tenemos soporte para TensorFlow GPU que ayuda a obtener aceleración con la ayuda de CUDA que también se ejecuta en modelos de aprendizaje automático basados en Python.

Y finalmente, ¿cuáles son algunas de las principales ventajas de utilizar Node.js para ejecutar TensorFlow.js? La primera es que podemos escribir los modelos de aprendizaje automático directamente desde cero en JavaScript y solo estamos programando en un lenguaje. No es necesario utilizar ningún otro lenguaje para ejecutar, entrenar y probar estos modelos de aprendizaje automático. Al utilizar TensorFlow.js en Node.js, también estamos dando la capacidad de ejecutar modelos mucho más grandes que requieren mucha más potencia. Por ejemplo, si estamos ejecutando redes neuronales que tienen muchas épocas y requieren aceleración basada en gráficos. Por lo tanto, con la ayuda del hardware del servidor, como en Python, podemos utilizar la potencia de estos servidores para acelerar nuestros modelos más grandes que no se pueden hacer en el lado del cliente. Y también tenemos soporte para el ecosistema de NPM porque el ecosistema de NPM es tan grande y los módulos de Node son tan utilizados y están disponibles. Por lo tanto, también se pueden utilizar una amplia variedad de módulos de Node directamente con tu código basado en TensorFlow.js para ayudar con tu aplicación de TensorFlow.js. Y lo más importante, obtenemos un rendimiento mucho mejor porque Node.js utiliza el compilador de just-in-time y los modelos escritos en TensorFlow.js utilizando Node.js también pueden obtener este impulso de rendimiento. Y eso es bastante evidente con algunos ejemplos. Por ejemplo, este gráfico muestra la comparación de TensorFlow ejecutándose en modelos basados en Python y también en TensorFlow.js para un MobileNet, que es un modelo de red neuronal convolucional. Y como puedes ver, la comparación del tiempo que realmente tarda en ejecutarse el modelo no es muy diferente.

2. Utilizando TensorFlow.js en Node.js

Short description:

TensorFlow.js proporciona un mejor rendimiento que las versiones de Python en ciertos casos, como la clasificación BERT. TensorFlow.js en Node.js se puede utilizar a través de tres paquetes diferentes: TensorFlow CPU, TensorFlow GPU y paquete vanilla. El paquete CPU acelera los cálculos matemáticos, mientras que el paquete GPU ejecuta operaciones de tensor en la GPU para obtener un rendimiento aún mejor. El paquete vanilla, que no depende de TensorFlow, se puede utilizar en otros dispositivos que admitan Node.js. Se deben configurar las vinculaciones de Node.js para TensorFlow.js para evitar bloquear el hilo principal. Una vez importado el paquete, están disponibles API como dfNode y TensorBoard. No dudes en conectarte conmigo en las redes sociales si tienes alguna pregunta sobre TensorFlow.js.

Entonces eso significa que TensorFlow.js en sí está bastante optimizado para ejecutar modelos estándar muy industriales, así como también para modelos más nuevos al mismo tiempo. Y en algunos casos, el modelo TensorFlow.js realmente proporciona un rendimiento mucho mejor en comparación con las versiones de Python. Por ejemplo, BERT, que es un modelo de lenguaje de vanguardia para el procesamiento del lenguaje natural, podemos ver que aquí, en realidad, hay un aumento de rendimiento dos veces mejor al utilizar Node.js en comparación con un modelo basado en Python que ejecuta esta clasificación BERT.

Ahora, pasando a la parte más importante, es decir, cómo podemos comenzar a utilizar TensorFlow.js en Node.js. Tenemos tres paquetes diferentes que puedes instalar, como los paquetes npm. El primero es TensorFlow CPU. TensorFlow CPU es, cuando importamos este paquete, el módulo que obtenemos se acelera mediante el binario C de TensorFlow y se ejecuta en la CPU. TensorFlow en la CPU utiliza la aceleración de hardware para acelerar cualquier tipo de cálculo matemático, como álgebra lineal.

Ahora, la extensión de eso es el paquete TensorFlow GPU. Al igual que el paquete CPU, este paquete GPU en particular se acelerará mediante el binario C de TensorFlow. Pero también ejecuta las operaciones de tensor en la GPU con la ayuda de CUDA, lo que acelera considerablemente el rendimiento. Esta vinculación es definitivamente la más rápida en comparación con cualquier otro paquete que tengamos. Y finalmente, también tenemos el paquete vanilla. Este paquete es muy similar al que se ejecuta en el navegador. Y en este paquete, las operaciones se ejecutan en JavaScript puro y en la CPU. En comparación con los otros módulos, es decir, TensorFlow CPU y TensorFlow GPU, este no tiene soporte para el binario de TensorFlow, lo que hace que el paquete en general sea mucho más pequeño. Y debido a esto, dado que no depende de TensorFlow, también se puede utilizar en muchos otros dispositivos que admiten Node.js.

Una de las consideraciones importantes que se deben tener en cuenta es que las vinculaciones de Node.js para TensorFlow.js se ejecutan en el backend de TensorFlow.js que las implementa de forma síncrona. Eso significa que cuando ejecutamos las vinculaciones de Node.js en una aplicación de producción, como un servidor web, debemos configurar una cola de espera o un servidor o hilos de trabajo para que no bloquee el hilo principal. También hay soporte para API porque una vez que hemos importado el paquete, todos los símbolos normales de TensorFlow.js que usamos pueden aparecer una vez que hemos importado el módulo específico. Por ejemplo, uno de ellos es dfNode, que contiene API específicas de Node.js, y TensorBoard es un ejemplo notable de las API específicas de Node.js.

Este es un código de ejemplo que debería darte un ejemplo donde hemos definido un modelo y lo estamos entrenando utilizando tf.node.tensorboard. Eso ayuda en el entrenamiento de tu modelo. Con eso, termina mi presentación y espero que te haya gustado y puedes conectarte conmigo en estas plataformas sociales para hacer cualquier pregunta sobre TensorFlow.js. Nuevamente, sigue cualquier tipo de modelo de TensorFlow.js utilizando el hashtag madewithTensorFlow.js en Twitter y LinkedIn. Y nuevamente, no dudes en conectarte conmigo para cualquier consulta sobre TensorFlow.js. Espero que te haya gustado. Gracias por ver.

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

Node Congress 2022Node Congress 2022
26 min
It's a Jungle Out There: What's Really Going on Inside Your Node_Modules Folder
Top Content
Do you know what’s really going on in your node_modules folder? Software supply chain attacks have exploded over the past 12 months and they’re only accelerating in 2022 and beyond. We’ll dive into examples of recent supply chain attacks and what concrete steps you can take to protect your team from this emerging threat.
You can check the slides for Feross' talk here.
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
Node Congress 2022Node Congress 2022
34 min
Out of the Box Node.js Diagnostics
In the early years of Node.js, diagnostics and debugging were considerable pain points. Modern versions of Node have improved considerably in these areas. Features like async stack traces, heap snapshots, and CPU profiling no longer require third party modules or modifications to application source code. This talk explores the various diagnostic features that have recently been built into Node.
You can check the slides for Colin's talk here. 
JSNation 2023JSNation 2023
22 min
ESM Loaders: Enhancing Module Loading in Node.js
Native ESM support for Node.js was a chance for the Node.js project to release official support for enhancing the module loading experience, to enable use cases such as on the fly transpilation, module stubbing, support for loading modules from HTTP, and monitoring.
While CommonJS has support for all this, it was never officially supported and was done by hacking into the Node.js runtime code. ESM has fixed all this. We will look at the architecture of ESM loading in Node.js, and discuss the loader API that supports enhancing it. We will also look into advanced features such as loader chaining and off thread execution.
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!

Workshops on related topic

Node Congress 2023Node Congress 2023
109 min
Node.js Masterclass
Top Content
Workshop
Have you ever struggled with designing and structuring your Node.js applications? Building applications that are well organised, testable and extendable is not always easy. It can often turn out to be a lot more complicated than you expect it to be. In this live event Matteo will show you how he builds Node.js applications from scratch. You’ll learn how he approaches application design, and the philosophies that he applies to create modular, maintainable and effective applications.

Level: intermediate
JSNation 2023JSNation 2023
104 min
Build and Deploy a Backend With Fastify & Platformatic
WorkshopFree
Platformatic allows you to rapidly develop GraphQL and REST APIs with minimal effort. The best part is that it also allows you to unleash the full potential of Node.js and Fastify whenever you need to. You can fully customise a Platformatic application by writing your own additional features and plugins. In the workshop, we’ll cover both our Open Source modules and our Cloud offering:- Platformatic OSS (open-source software) — Tools and libraries for rapidly building robust applications with Node.js (https://oss.platformatic.dev/).- Platformatic Cloud (currently in beta) — Our hosting platform that includes features such as preview apps, built-in metrics and integration with your Git flow (https://platformatic.dev/). 
In this workshop you'll learn how to develop APIs with Fastify and deploy them to the Platformatic Cloud.
Node Congress 2023Node Congress 2023
63 min
0 to Auth in an Hour Using NodeJS SDK
WorkshopFree
Passwordless authentication may seem complex, but it is simple to add it to any app using the right tool.
We will enhance a full-stack JS application (Node.JS backend + React frontend) to authenticate users with OAuth (social login) and One Time Passwords (email), including:- User authentication - Managing user interactions, returning session / refresh JWTs- Session management and validation - Storing the session for subsequent client requests, validating / refreshing sessions
At the end of the workshop, we will also touch on another approach to code authentication using frontend Descope Flows (drag-and-drop workflows), while keeping only session validation in the backend. With this, we will also show how easy it is to enable biometrics and other passwordless authentication methods.
Table of contents- A quick intro to core authentication concepts- Coding- Why passwordless matters
Prerequisites- IDE for your choice- Node 18 or higher
JSNation Live 2021JSNation Live 2021
156 min
Building a Hyper Fast Web Server with Deno
WorkshopFree
Deno 1.9 introduced a new web server API that takes advantage of Hyper, a fast and correct HTTP implementation for Rust. Using this API instead of the std/http implementation increases performance and provides support for HTTP2. In this workshop, learn how to create a web server utilizing Hyper under the hood and boost the performance for your web apps.
React Summit 2022React Summit 2022
164 min
GraphQL - From Zero to Hero in 3 hours
Workshop
How to build a fullstack GraphQL application (Postgres + NestJs + React) in the shortest time possible.
All beginnings are hard. Even harder than choosing the technology is often developing a suitable architecture. Especially when it comes to GraphQL.
In this workshop, you will get a variety of best practices that you would normally have to work through over a number of projects - all in just three hours.
If you've always wanted to participate in a hackathon to get something up and running in the shortest amount of time - then take an active part in this workshop, and participate in the thought processes of the trainer.
TestJS Summit 2023TestJS Summit 2023
78 min
Mastering Node.js Test Runner
Workshop
Node.js test runner is modern, fast, and doesn't require additional libraries, but understanding and using it well can be tricky. You will learn how to use Node.js test runner to its full potential. We'll show you how it compares to other tools, how to set it up, and how to run your tests effectively. During the workshop, we'll do exercises to help you get comfortable with filtering, using native assertions, running tests in parallel, using CLI, and more. We'll also talk about working with TypeScript, making custom reports, and code coverage.