TRANSCRIPCIÓN · CC BY 4.0

Aprendizaje profundo práctico para programadores 2022, Lección 2 — Jeremy Howard

Título original en inglés: Lesson 2: Practical Deep Learning for Coders 2022

Jeremy Howard · Publicado el · 1 h 17 min · Audio original en inglés · subtítulos en español · Licencia: CC BY 4.0 · Fuente: ver en YouTube

Esta ficha ofrece el título y el contexto en español junto con la transcripción original íntegra en inglés con marcas de tiempo. Pulsa el botón superior para abrir la vista bilingüe español-inglés sincronizada en el lector.

Resumen generado por IA

Esta lección, grabada desde casa debido a un problema de reserva de aulas en la universidad, cubre la logística del curso y los proyectos de los estudiantes antes de pasar a poner un modelo en producción. El libro gratuito está disponible a través del repositorio fastbook o course.fast.ai, cada capítulo termina con un cuestionario, y forums.fast.ai aloja un tema oficial por lección. Los primeros proyectos incluyeron un clasificador de coches dañados, un detector de barbas y un clasificador de alimentos en producción. Para producción, el notebook reemplaza bing por ddg porque la API de Bing requiere una clave SDK. El ponente propone entrenar antes de limpiar los datos, explica las opciones de redimensionamiento y aug_transforms como aumento de datos, y señala que con solo unas cuatro épocas de ajuste fino el aumento probablemente no era realmente necesario. Una matriz de confusión muestra qué casos son difíciles, y plot_top_losses revela los elementos con mayor pérdida, donde una mala pérdida puede provenir de estar equivocado y seguro o correcto e inseguro; el ImageClassifierCleaner ordena los elementos por pérdida para que los elementos mal etiquetados puedan reetiquetarse o eliminarse. La guía práctica incluye cerrar los notebooks no utilizados en una GPU de 4 GB porque las GPU no pueden intercambiar RAM. Para el despliegue, el enfoque está en HuggingFace Spaces con Gradio, y se entrena un clasificador de mascotas, se exporta con learn.export y se carga con load_learner(), con Gradio necesitando una función que devuelva un diccionario de categoría a probabilidad como floats normales. Los pasos dependientes de GPU pueden usar Colab y Kaggle, mientras que las predicciones pueden ejecutarse localmente, y las aplicaciones web JavaScript pueden alojarse gratis vía GitHub Pages.

Resumen traducido automáticamente con IA a partir de la transcripción. Comprueba los fragmentos enlazados con el vídeo original.

Resúmenes por capítulo con marcas de tiempo

Lección dos: Logística del curso y proyectos de estudiantes

Configuración del curso y recursos del libro

  • [0:00] La lección dos se graba desde casa debido a un problema administrativo de reserva de aulas en la universidad.
  • [0:57] El curso acompaña al libro, que es completamente gratuito a través del repositorio fastbook de fast.ai o course.fast.ai, y contiene material adicional como la historia de las redes neuronales.
  • [1:45] Cada capítulo termina con un cuestionario; se recomienda leer el cuestionario del capítulo dos antes del video y completarlo después.

Sitio de cuestionarios y recursos del foro

  • [2:07] Radek ha creado aiquizzes.com, un sitio con preguntas de cuestionario nuevas y seleccionadas para el libro que utiliza técnicas de aprendizaje basadas en la repetición.
  • [2:38] course.fast.ai aloja enlaces a notebooks y Kaggle, mientras que forums.fast.ai tiene un tema oficial por lección con información más detallada que el material conciso del curso.
  • [3:40] Un botón "resumir este tema" en la parte inferior de la publicación del tema oficial muestra solo las respuestas más votadas, como las de Sanyam y Tanishq.

Proyectos de estudiantes de "Muéstranos lo que has hecho"

  • [4:14] La publicación "muéstranos lo que has hecho" ya tenía bastante más de 39 respuestas, y los primeros proyectos publicados fueron seleccionados para compartir porque todos eran muy buenos.
  • [4:49] La primera publicación fue un clasificador de coches dañados; su creador Matt señaló que se sentía incómodo ejecutando código que aún no entendía, lo que el instructor respaldó como la forma correcta de empezar.
  • [5:20] Otras publicaciones tempranas incluyeron una entrada de blog en fast pages que describía experimentos semanales y un increíble detector de barbas, al que es fácil llegar desde "bird" cambiando una letra por dos.
  • [5:51] Otro proyecto fue una aplicación web completa en producción para clasificar alimentos, descrita como crédito extra; según se informa, el hilo alcanzó 80 respuestas, atribuido a Sanyam.

Implementación de una aplicación web en producción

Del modelo a la aplicación web en producción

  • [6:20] El ponente sugiere que algún día los espectadores podrían crear su propia aplicación web y ponerla en producción.
  • [6:27] El ponente aclara que "algún día" significa hoy y se ofrece a mostrar cómo hacerlo ahora mismo.
  • [6:40] El tema publicado por Suvash se describe como una feliz coincidencia porque es exactamente el tema elegido para hoy.

Primer paso para poner un modelo en producción

  • [6:46] El ponente comienza a explicar cómo poner un modelo en producción, empezando por el paso uno.
  • [6:54] El ponente señala que el paso uno puede que ya esté hecho y comienza a enumerar los pasos uno, dos, tres, cuatro antes de que se corte la transcripción.

Limpieza de datos y navegación por el cuaderno de Jupyter

De la definición del problema a la limpieza de datos

  • [7:00] Después de definir el problema, encontrar y reunir los datos, el siguiente paso es la limpieza de datos.
  • [7:14] El capítulo 2 del libro, que se puede abrir en Colab desde el curso o desde un clon local, trata sobre la limpieza de datos.
  • [7:35] course.fast.ai explica cómo ejecutar los cuadernos, y el capítulo 2 trata sobre poner cosas en producción.
  • [7:46] Las celdas se ejecutan pulsando Shift + Enter.

Extensiones de Jupyter Notebook y tabla de contenidos

  • [8:20] El menú Navegar no aparece por defecto; proviene de instalar las extensiones de Jupyter Notebook mediante pip y reiniciar Jupyter.
  • [8:45] Colab ya tiene una tabla de contenidos, así que la extensión es principalmente para instalaciones locales, donde aparece una pestaña Nbextensions.
  • [8:57] Al hacer clic en Tabla de contenidos (2) en Nbextensions se obtiene una práctica barra de navegación.

Encabezados plegables y navegación por teclado

  • [9:07] La extensión de encabezados plegables añade controles para cerrar y abrir secciones.
  • [9:20] La flecha derecha se desplaza al final de una sección y la flecha izquierda al inicio, lo que facilita moverse entre secciones.
  • [9:35] Pulsar de nuevo a la izquierda cierra una sección y pulsar a la derecha la abre.

API de Bing para la búsqueda de imágenes

  • [9:48] El libro utiliza la API de Bing para buscar imágenes.

Sustituir Bing por DDG y consejos sobre la documentación de Python

Cambiar de Bing a DDG en el cuaderno

  • [9:58] El cuaderno sustituye "bing" por "ddg" porque la API de Bing requiere obtener una clave SDK.
  • [10:05] El ponente bromea diciendo que la parte más difícil del aprendizaje profundo es descifrar el sitio web de Bing Azure y conseguir que funcione, mientras que ddg no lo requiere.
  • [10:21] El cuaderno se compartirá en el foro del sitio web del curso, y el único cambio real es sustituir bing por ddg y eliminar la clave.

Ejemplo de búsqueda de osos reutilizado de la semana pasada

  • [10:33] Como en el libro, el ejemplo busca osos grizzly, osos negros y osos de peluche, motivado por el interés del hijo pequeño del ponente en aquel entonces por identificar osos de peluche.
  • [10:56] El bucle recorre osos grizzly, osos negros y osos de peluche y descarta los que fallaron, igual que la semana pasada.

Encontrar información sobre Python, fastai y PyTorch rápidamente

  • [11:14] Una pregunta común en el foro es cómo encontrar más información sobre cualquier cosa relacionada con Python, fastai o PyTorch, y el libro ofrece algunos consejos.
  • [11:24] Un doble signo de interrogación junto al nombre de una función muestra todo su código fuente, mientras que un solo signo de interrogación proporciona una breve información.
  • [11:48] Con nbdev instalado, escribir doc da un enlace directo a la documentación, que generalmente incluye ejemplos, además de un enlace al código fuente.
  • [12:13] En el código fuente de GitHub puedes hacer clic en los elementos para saltar a su definición, lo que es una buena forma de navegar y entender qué está pasando.

Entrenamiento antes de la limpieza y aumento de imágenes

Entrenar un modelo antes de limpiar los datos

  • [12:48] Contrario al consejo habitual de limpiar los datos primero, el ponente propone entrenar un modelo antes de limpiar los datos y explicará por qué en breve.
  • [13:10] Se usa un DataBlock para obtener los cargadores de datos para el entrenamiento, y show_batch muestra los lotes como antes.

Opciones de redimensionamiento: aplastar, recortar y rellenar

  • [13:37] El redimensionamiento se puede especificar con una cadena o una opción tipo enum, y el aplastamiento puede producir osos muy delgados mientras se mantiene visible toda la imagen.
  • [14:12] El recorte conserva solo el centro de la imagen para una mejor relación de aspecto pero pierde algo de contenido, mientras que el relleno con ceros (negro) preserva toda la imagen y la relación de aspecto correcta.
  • [14:33] Diferentes elecciones de redimensionamiento pueden producir modelos de diferente calidad, pero la diferencia normalmente no es grande, así que no vale la pena preocuparse demasiado.

RandomResizedCrop y aumento de datos

  • [14:49] RandomResizedCrop produce una parte diferente de la imagen cada vez, lo cual es útil para ejecutar muchas épocas en escaneos muy grandes.
  • [15:11] En el foro, alguien quería distinguir texto francés de alemán en escaneos de documentos muy grandes, y el enfoque sugerido de RandomResizedCrop funcionó ligeramente.
  • [15:51] Obtener imágenes diferentes de la misma imagen cada vez se llama aumento de datos, y aug_transforms aplica rotaciones, aplastamiento, deformación, recoloración y cambios de saturación.
  • [16:32] Para entrenar más de unas cinco o diez épocas, generalmente se recomiendan RandomResizedCrop y aug_transforms, con mult dejado vacío en lugar de establecido en 2.

El aumento se produce en memoria, no como copias

  • [17:03] En respuesta a la pregunta de Alex, el ponente aclara que la imagen no se copia varias veces; cada época lee cada imagen y la deforma, recorta y recolorea en RAM en tiempo real durante el entrenamiento.
  • [17:32] No se almacenan copias en el ordenador, pero el modelo efectivamente ve casi infinitas copias ligeramente diferentes.

Ejecución de entrenamiento con cuatro épocas de ajuste fino

  • [17:54] Se usan RandomResizedCrop y las transformaciones de aumento para obtener los DataLoaders y entrenar el modelo, lo que tarda aproximadamente un minuto.
  • [18:06] Esta ejecución usó solo cuatro épocas principales de ajuste fino, así que probablemente RandomResizedCrop y aug_transforms no eran realmente necesarios con tan pocas épocas.

Entrenar más tiempo con más épocas

Ejecutar épocas adicionales

  • [18:24] Ejecutar más épocas se describe como un buen enfoque, con el resultado reportado por debajo del tres por ciento.

Entrenar un clasificador de osos y leer su matriz de confusión

Entrenamiento en una GPU de portátil de 4 GB

  • [18:29] El modelo se entrena antes de cualquier paso de limpieza, como se indicó anteriormente.
  • [18:46] El entrenamiento se ejecuta en el portátil del ponente, que solo tiene una GPU de 4 GB; es básico pero suficiente para empezar.

Matriz de confusión para etiquetas categóricas

  • [18:59] La matriz de confusión solo tiene sentido cuando las etiquetas son categorías, y muestra qué errores de categoría comete el modelo.
  • [19:15] En este punto, el modelo confundió dos veces un oso grizzly real con un oso negro y dos veces confundió un oso negro real con un oso grizzly.
  • [19:27] El modelo nunca se equivocó con los ositos de peluche, lo cual tiene sentido porque los ositos de peluche se ven bastante diferentes de ambos tipos de osos.

Usar matrices de confusión para encontrar clases difíciles

  • [19:39] Una matriz de confusión a menudo da una idea real de qué casos son difíciles.
  • [19:43] En el conjunto de datos de mascotas utilizado en el libro y el curso, la matriz de confusión para las diferentes razas muestra qué razas son difíciles de identificar.
  • [20:00] El ponente leyó páginas de Wikipedia e informes de cría de mascotas sobre cómo identificar estos tipos porque son tan difíciles que incluso los expertos encuentran difícil hacerlo.
  • [20:10] Del curso, el ponente aprendió que los osos negros y los osos grizzly son mucho más difíciles de distinguir de lo que se pensaba, por lo que el ponente ni siquiera lo intentará.

Siguiente paso: interpretación de clasificación

  • [20:21] Con el modelo creado, lo siguiente interesante que mostrar es la interpretación de la clasificación.

Usar plot_top_losses e ImageClassifierCleaner para limpiar im

Interpretación de la salida de plot_top_losses

  • [20:42] plot_top_losses muestra los elementos donde la pérdida es más alta, y la pérdida es la medida de la calidad del modelo tomada después de cada elemento de datos.
  • [21:03] Una pérdida es mala si el modelo predice incorrectamente y tiene mucha confianza; el orden de visualización es predicción, real, pérdida, probabilidad.
  • [21:16] En el ejemplo, el modelo predijo grizzly cuando en realidad era un oso negro y estaba 96% seguro, por lo que un experto tendría que comprobar si el modelo o la etiqueta están equivocados.
  • [21:41] Algunos elementos con pérdida alta son en realidad correctos, como grizzly/grizzly y teddy/teddy, porque el modelo solo tenía 66% o 72% de confianza.
  • [22:01] Una pérdida mala puede provenir tanto de estar equivocado y con confianza como de estar en lo correcto y sin confianza.

Limpieza del conjunto de entrenamiento con ImageClassifierCleaner

  • [22:14] El ImageClassifierCleaner de fast.ai se utiliza para limpiar elementos mal etiquetados en el conjunto de datos.
  • [22:24] ImageClassifierCleaner ejecuta los modelos, por eso se le pasa "learn".
  • [22:42] Después de seleccionar ositos de peluche, muestra los elementos marcados como ositos de peluche en el conjunto de entrenamiento o de validación, ordenados por pérdida, es decir, ordenados por confianza.
  • [23:00] Para un elemento mal recopilado, puedes elegir la categoría correcta o hacer clic en eliminar si no debería estar allí en absoluto.
  • [23:14] Algunos ejemplos difíciles incluyen dos ositos de peluche juntos, uno de aspecto extraño que se parece a un wombat, y uno difícil de ver contra el fondo; si los primeros muestran no tener problemas, el conjunto probablemente esté bien.

Limpieza del conjunto de validación y aplicación de cambios

  • [23:44] El conjunto de validación se limpia de la misma manera, eliminando elementos que no son realmente osos u ositos de peluche.
  • [24:20] El limpiador almacena una lista de elementos modificados y una lista de elementos eliminados.
  • [24:26] Ejecutar la celda elimina los archivos en los índices marcados para eliminación y mueve los elementos marcados para cambio a una nueva carpeta.

Construcción de un modelo antes de limpiar los datos

  • [24:45] Construir primero un modelo para encontrar elementos difíciles de reconocer es una técnica poderosa que se aplica más allá de los modelos de imágenes y que casi nadie conoce ni utiliza.
  • [25:04] Ver los tipos de problemas puede revelar mejores formas de recopilar el siguiente conjunto de datos o de automatizar parte de la limpieza.

Gestión de memoria de la GPU y enfoque de aprendizaje en video

Límites de memoria de la GPU e intercambio

  • [25:23] Con solo una GPU de 4 GB, es muy importante cerrar y detener los cuadernos para liberar memoria.
  • [25:37] La RAM normal que se llena hace que la computadora intercambie RAM al disco duro, pero las GPU no pueden intercambiar.
  • [26:00] Cuando una GPU se queda sin RAM, se acabó, así que cierra los cuadernos que no uses y usa solo una cosa a la vez en la GPU para evitar quedarte sin memoria.

Forma recomendada de ver los videos de programación

  • [26:22] No se espera que los espectadores ejecuten todo el código mientras miran; pueden pausar y retroceder a medida que avanzan, o detenerse e intentarlo repetidamente.
  • [26:42] Un enfoque preferido es ver el video completo sin tocar el teclado para hacerse una idea, y luego volver al inicio y seguirlo.
  • [27:00] Ver primero y luego seguir significa saber qué estás haciendo y qué sucede después, lo que puede ahorrar tiempo, aunque es inusual en comparación con las clases reales que no se pueden rebobinar.

Despliegue de modelos con HuggingFace Spaces y Gradio

Opciones de despliegue: Voilà vs HuggingFace Spaces

  • [27:18] Después de limpiar los datos, el libro usa Voilà para poner el modelo en producción, lo que el ponente considera bastante bueno.
  • [27:29] El ponente cree que hoy en día la mayoría de la gente encontrará HuggingFace Spaces más útil, y hoy el enfoque está en Gradio, una de las herramientas utilizables con él.

La publicación de blog de Tanishq Abraham como material del curso

  • [27:42] Aunque el libro no tiene un capítulo sobre esto, Tanishq Abraham, un asistente docente del curso, escribió una publicación de blog completa que cubre todo en la lección de hoy, enlazada desde el foro y la página del curso.
  • [28:07] El ponente elogia a Tanishq como una de las personas más serviciales, tenaces, consideradas y pacientes de la comunidad de fastai y comparte una foto de él como niño prodigio con Conan.

Creación de un HuggingFace Space

  • [29:05] Partiendo de la página de HuggingFace Spaces enlazada en el curso, el plan es copiar el modelo entrenado al servidor de Spaces y escribir una interfaz de usuario para él.
  • [29:29] Después de registrarse gratis, creas un nuevo space con un nombre mínimo; el ponente usa la licencia Apache para que otros puedan usar fácilmente el trabajo sin preocupaciones de patentes.
  • [29:58] Gradio es la herramienta gratuita elegida para el espacio, y hacer público el espacio permite a los estudiantes compartirlo y construir su portafolio.

Uso de Git y GitHub Desktop con Spaces

Git como mecanismo detrás de Spaces

  • [30:14] Spaces funciona a través de Git, una herramienta que la mayoría de los desarrolladores de software conoce bien, aunque algunos científicos de datos puede que no.
  • [30:24] Se describe Git como una herramienta muy útil, pero el ponente no la trata en detalle y en su lugar pasa a una rápida mirada sobre cómo usarla.

Ventajas de GitHub Desktop

  • [30:38] Git se puede usar a través de GitHub Desktop, que el ponente califica como bastante genial.
  • [30:46] Incluso quienes usan Git a través de la consola deberían considerar GitHub Desktop, porque algunas cosas son mucho más rápidas y fáciles en ella.

Revertir confirmaciones accidentales mediante GitHub Desktop

  • [30:59] El ponente le preguntó a su amigo Hamil, que trabajó en GitHub, cuál era la forma más fácil de revertir dos cosas confirmadas por error.
  • [31:09] En lugar de un comando de consola sofisticado, Hamil recomendó GitHub Desktop, donde simplemente puedes hacer clic, lo que al ponente le pareció una gran idea.

Uso de Git y Linux desde la terminal

Opciones de terminal en distintos sistemas operativos

  • [31:19] Git se usa principalmente desde la consola o terminal, que los usuarios de Linux y Mac ya tienen.
  • [31:30] Los usuarios de Windows pueden obtener Windows Terminal desde Microsoft Store, y el ponente lo usa siempre que aparece una terminal.

Ejecutar Ubuntu en Windows mediante WSL

  • [31:59] En Windows, el ponente recomienda usar Ubuntu, ya que Windows puede ejecutar un entorno Linux completo.
  • [32:15] Instalar WSL implica buscar en Google "WSL install", ejecutar PowerShell como administrador, pegar el comando, esperar unos cinco minutos y reiniciar.

Por qué el ponente prefiere Windows con Linux

  • [32:34] El ponente señala que trabajar en tu propia máquina es un poco más avanzado y puede resultar menos familiar para algunos científicos de datos, pero la terminal da menos miedo de lo esperado.
  • [32:59] El orador elige Windows por sus aplicaciones GUI, dibujo en pantalla y presentaciones, además de un entorno Linux completo que utiliza la GPU.
  • [33:18] La segunda opción del orador es Linux, mientras que Mac es un poco más difícil pero aún usable, con algunas cosas más complicadas.

Desplegando una aplicación Gradio en HuggingFace Spaces

Clonando el repositorio inicial en la terminal

  • [33:37] Una vez que haya una terminal disponible, puedes copiar y pegar comandos en lugar de seguir instrucciones clic por clic.
  • [33:55] Pegar y ejecutar el comando proporcionado crea un nuevo directorio, que inicialmente está vacío.
  • [34:10] Luego las instrucciones te piden crear un archivo que contenga el contenido especificado.

Abriendo la carpeta en un editor

  • [34:24] En Windows, escribir "explorer.exe ." abre el Explorador en el directorio actual.
  • [34:42] En Mac, Linux o Windows, escribir "code ." abre Visual Studio Code con la carpeta cargada.
  • [34:58] VS Code se describe como un gran IDE que vale la pena dedicar unos minutos a sus tutoriales.
  • [35:04] Crearás un archivo app.py que contiene el contenido que especifican las instrucciones.

Confirmando el archivo en HuggingFace Spaces

  • [35:30] Después de guardar, el archivo debe confirmarse en HuggingFace Spaces.
  • [35:37] En Visual Studio Code puedes hacer clic para ingresar un mensaje de confirmación, pulsar la marca y envía la confirmación a HuggingFace Spaces.

Probando la aplicación Gradio construida

  • [35:54] Al volver a huggingface.co/spaces/jhp00/minimal, el sitio tarda aproximadamente un minuto en construirse.
  • [36:15] El sitio construido tiene una interfaz Gradio con una entrada de texto y una salida de texto que ejecuta una función greet() que devuelve "Hello {name}".
  • [36:40] Probar con el nombre Tanishq muestra la salida producida para la entrada.
  • [36:53] La aplicación no es muy emocionante, pero ahora es una aplicación que se ejecuta en producción.

Siguiente paso hacia un modelo de aprendizaje profundo

  • [37:00] El siguiente paso es convertir esta aplicación simple en un modelo de aprendizaje profundo que se ejecuta en producción.

Entrenamiento y exportación de un clasificador de mascotas fastai

Construir el clasificador de perros/gatos en Kaggle

  • [37:10] Primero se debe obtener un modelo de aprendizaje profundo y, básicamente, hay que entrenar uno.
  • [37:29] Los ejemplos de Kaggle y Colab hacen lo mismo: crear un clasificador de perros o gatos.
  • [37:52] Kaggle ya tiene fastai instalado, pero el notebook primero lo instala para asegurarse de usar la última versión.
  • [38:03] El conjunto de datos de mascotas se carga con una función de etiquetado is_cat para ImageDataLoaders, descrita como una forma abreviada de hacer DataBlocks.
  • [38:13] Se crea y ajusta un learner, usando los pasos vistos anteriormente.

Vista de edición frente a vista de lector en Kaggle

  • [38:22] Cada notebook de Kaggle tiene una vista de edición y una vista de lector, y cualquier persona puede leer un notebook compartido en la vista de lector.
  • [38:42] El entrenamiento tardó unos cinco minutos; las GPU de Kaggle son algo más lentas que la mayoría de las GPU modernas, pero siguen siendo suficientemente rápidas.

Exportar el modelo entrenado

  • [38:56] Al final, se le da un nombre a learn.export para crear un archivo que contiene el modelo entrenado.
  • [39:07] Crear este archivo es lo único para lo que se necesita una GPU, así que se hace en Kaggle o Colab.

Repetir el flujo de trabajo en Colab

  • [39:12] La versión de Colab usa los mismos pasos: pip install, is_cat, los datos, ImageDataLoaders, un show_batch por diversión y luego crear el learner y exportar.

Exportar un modelo de Kaggle a HuggingFace Spaces

Descargar el modelo guardado desde Kaggle

  • [39:36] Después de ejecutar y guardar un notebook de Kaggle, los archivos guardados aparecen en la pestaña de datos.
  • [39:47] El archivo guardado model.pickle se puede descargar desde la pestaña de datos a la carpeta de descargas.

Mover el modelo al directorio de la aplicación de Spaces

  • [39:57] El modelo descargado debe copiarse en el mismo directorio que la aplicación de HuggingFace Spaces.
  • [40:13] En la terminal, escribir "open ." en Mac o "explorer.exe ." en Windows abre Finder o Explorer en ese directorio para que el archivo pueda pegarse allí.

Consejo para Windows sobre cómo acceder a archivos de Linux

  • [40:36] En Windows, anclar el directorio home de Linux a Acceso rápido brinda acceso rápido a los archivos de Linux.
  • [40:51] Este workaround no es necesario en Mac porque los archivos están integrados, mientras que en Windows actúan como dos máquinas separadas.

Colocar el modelo en el Space de pruebas

  • [41:04] Se creó un Space llamado testing y se pegó en él el "model.pkl" descargado.

Hacer predicciones con un learner de fastai guardado

Cargar el learner guardado y las funciones necesarias

  • [41:41] El notebook importa fastai y Gradio como antes y copia exactamente la misma definición de is_cat usada durante el etiquetado.
  • [41:49] Cualquier función externa usada en el etiquetado debe incluirse porque el learner hace referencia a ellas, aunque no guarda su código fuente.
  • [42:43] En lugar de entrenar un learner, se llama a load_learner() con el nombre del archivo guardado y devuelve un learner idéntico al que había al final del entrenamiento.

Cómo se restaura el learner serializado con pickle

  • [43:03] El learner entrenado quedó congelado en el tiempo como un archivo pickle, guardado en disco, transferido a la computadora y luego cargado y descongelado.
  • [43:23] El learner deserializado puede usarse para cualquier cosa, y uno de sus métodos es el método .predict.

Velocidad de predicción y formato de salida

  • [43:30] Ejecutar .predict en la laptop es prácticamente instantáneo, y las magics de Jupyter pueden medir cuánto tarda.
  • [43:51] La predicción tardó 54 milisegundos en determinar que la imagen no es un gato.
  • [44:02] Devuelve si es un gato como cadena, si es un gato como cero o uno, y las probabilidades para perro y gato.
  • [44:16] Las probabilidades corresponden a cero (falso) y uno (verdadero) para si es un gato, y el resultado es definitivamente un perro.

Construir una interfaz clasificadora de perros y gatos con Gradio

Adaptar la salida de predict para Gradio

  • [44:28] Gradio necesita una función a la que llamar, así que predict devuelve la cadena de predicción, su índice y las probabilidades de perro/gato.
  • [44:45] Gradio espera un diccionario que asigne cada categoría posible (perro o gato) a su probabilidad, el cual se construye con un dict de un zip.
  • [45:12] Gradio actualmente no maneja tensores de PyTorch ni arrays de Numpy, así que cada valor debe convertirse a un float normal.
  • [45:32] Llamar a classify_image() sobre la imagen del perrito devuelve un diccionario con perro como definitivamente y gato como definitivamente no.

Crear y lanzar la interfaz de Gradio

  • [45:51] La interfaz de Gradio especifica la función a llamar, una entrada de imagen y una salida de etiqueta para una interfaz muy simple.
  • [46:16] Los ejemplos proporcionados incluyen un perro, un gato y una imagen de "no lo sé".
  • [46:27] Tras lanzarse, la interfaz se ejecuta en una URL en el propio portátil del ponente, aún no en producción, y responde prácticamente al instante.

El ejemplo de "no lo sé" y el modelo reentrenado

  • [46:55] La imagen de "no lo sé" ahora devuelve 100 en lugar del habitual aproximadamente 50-50, lo que el ponente califica como una lástima.
  • [47:13] La hija de seis años del ponente encontró la imagen del perro mezclado con gato mediante Google Images, y el modelo anterior le daba casi exactamente 50-50.
  • [47:53] El modelo reentrenado ese día ahora está seguro de que es un gato, posiblemente debido a un calendario de entrenamiento ligeramente distinto o a una época adicional, y el ponente dice que no debería haberlo entrenado tanto tiempo.

Deteniendo la interfaz y siguiente paso

  • [48:16] La interfaz está en ejecución, así que hay que hacer clic en el botón de inicio para detenerla, de lo contrario no se puede hacer nada más en el notebook.
  • [48:28] El siguiente paso es convertir la interfaz en un script de Python.

Exportar un notebook a app.py y desplegar en Gradio

Marcar celdas para exportar con hash pipe export

  • [48:35] El código necesario debe copiarse en un script de Python, mientras que las celdas usadas solo para comprobar o experimentar pueden omitirse.
  • [48:54] El ponente marcó cada celda que contenía información necesaria en el script final escribiendo "hash pipe export" en la parte superior de la misma.

Generar app.py con notebook2script de nbdev

  • [49:13] Al final del notebook, el ponente importó notebook2script de nbdev y lo ejecutó con el nombre del notebook para crear app.py.
  • [49:32] Este enfoque conviene a herramientas que esperan un script en lugar de un notebook, como HuggingFace Spaces; copiar y pegar en un archivo de texto también funciona.
  • [49:42] El ponente prefiere este método porque toda la experimentación puede ocurrir en el notebook, y una sola celda al final exporta el resultado.
  • [49:54] El nombre del archivo de salida app.py se establece mediante el ajuste default_exp en la parte superior del notebook.

Desplegar mediante Git push y probar en producción

  • [50:08] El app.py se sube a Gradio mediante un push a Git, ya sea a través de Visual Studio Code o escribiendo "git commit" y luego "git push".
  • [50:34] Antes de publicar, la aplicación en ejecución aún puede mostrar el modelo anterior, lo que el ponente demuestra con el ejemplo del perro y el gato.
  • [50:51] Una vez configurada como pública, cualquiera puede visitar la aplicación y subir imágenes para probar el modelo.
  • [51:02] El modelo identifica correctamente un perro y un gato, aunque el ponente sospecha que entrenar una o dos épocas menos lo hizo menos seguro, y la imagen del perro y el gato sigue clasificándose como definitivamente un gato.

Duración del entrenamiento, exportación de modelos y uso de GPU

Elegir el número de épocas

  • [52:14] A medida que avanza el entrenamiento, la tasa de error mejora, así que la cuestión es si aumentar el número de épocas.
  • [52:26] La ejecución actual usa tres épocas más una para empezar, y si eso es suficiente depende del usuario.
  • [52:32] Con una tasa de error del uno por ciento, el ponente está satisfecho, pero más aumento de datos y un entrenamiento más largo podrían mejorarla.
  • [52:47] Si entrenas durante el tiempo suficiente, la tasa de error empieza a empeorar, lo que se explicará en una lección posterior.
  • [52:58] Puedes entrenar hasta que el resultado sea suficientemente bueno, hasta que te quedes sin paciencia, tiempo o cómputo, o hasta que la tasa de error empiece a empeorar.

Descargar un modelo exportado desde Colab

  • [53:20] En Colab, después de exportar el modelo, abre el explorador de archivos para ver el archivo.
  • [53:30] Hacer clic en descargar no abre inmediatamente un diálogo de guardado; en su lugar aparece un círculo de progreso.
  • [53:43] Según el tamaño del modelo, el círculo de progreso puede tardar unos minutos antes de que el navegador te pida guardar el archivo.

Necesidades de GPU para entrenamiento frente a predicción

  • [53:57] El paso que necesita una GPU puede usar recursos gratuitos como Colab y Kaggle, y otros se tratarán en lecciones futuras.
  • [54:06] Todo lo demás, incluidas las predicciones, puede hacerse en tu propio ordenador.
  • [54:12] Las predicciones son rápidas, así que no se necesita una GPU a menos que hagas miles de ellas.

Configurar Python y Jupyter con fastsetup

Clonar fastsetup desde GitHub

  • [54:52] El repositorio Git de fastsetup en GitHub hace que configurar Python y Jupyter Notebook sea sencillo.
  • [55:03] Ir a Github fastai/fastsetup te permite obtener todo el repositorio mediante el botón Code y abrirlo con Github Desktop para clonarlo.

Instalando Python con setup-conda.sh

  • [55:44] Después de clonarlo, el archivo setup-conda.sh instala Python cuando se ejecuta como ./setup-conda.sh.
  • [56:05] En Linux o Mac, no se debe usar el python del sistema existente porque la computadora lo necesita y modificarlo siempre lleva al desastre.
  • [56:32] Quieres tu propia versión de desarrollo de Python con la última versión y bibliotecas, y las distribuciones basadas en conda son casi con certeza la mejor opción.
  • [56:49] La distribución actualmente recomendada es mambaforge, que añade el comando mamba para instalar paquetes después de que reabras la terminal.

Instalando fastai y nbdev con mamba

  • [57:23] Según docs.fast.ai, el comando correcto es conda install -c fastchan fastai, pero conda debería reemplazarse por mamba porque es mucho más rápido: mamba install -c fastchan fastai.
  • [57:52] Esto instala todo lo necesario, incluidos Pytorch, Numpy y fastai.
  • [58:11] Instalar nbdev de la misma manera es opcional, pero también instala Jupyter, entre otras cosas.

Iniciando Jupyter Notebook

  • [58:42] Escribir jupyter notebook inicia un servidor, y hacer clic en el hipervínculo abre la interfaz que se muestra en las lecciones.

mamba frente a pip para configuraciones de GPU

  • [59:17] pip puede hacer prácticamente cualquier cosa que mamba puede hacer, pero con una GPU, pip generalmente no instalará las cosas para que funcionen en la GPU, lo que requiere muchas otras instalaciones molestas, por lo que se recomienda mamba.

Implementación de modelos con Gradio y Streamlit en HuggingFace Sp

Progreso de la lista de verificación del curso

  • [59:54] La lista de verificación confirma que el espacio, la interfaz básica, la configuración de git y la configuración de conda o mamba están completados.
  • [1:00:26] Perros contra gatos, el learner exportado y nbdev se han completado sin problemas.

Mamba frente a conda

  • [1:00:04] Mamba y conda son lo mismo, pero mamba es una versión mucho más rápida.
  • [1:00:16] Se está trabajando en las mejoras de velocidad de conda gracias a mamba, por lo que conda podría volver a ser adecuado en algún momento, pero por ahora conda es demasiado lento y no debería usarse.

La flexibilidad de Gradio para la creación de prototipos

  • [1:00:50] Al ponente le parece genial que se pueda ofrecer un modelo real y funcional de forma gratuita a cualquiera que quiera usarlo.
  • [1:01:08] Gradio ofrece una cantidad razonable de flexibilidad para la apariencia del sitio web a través de sus diversos widgets.
  • [1:01:22] Gradio no es increíblemente flexible pero sí lo suficiente, y realmente es solo para prototipado.

Streamlit como plataforma alternativa

  • [1:01:36] Streamlit es la otra plataforma principal que HuggingFace Spaces admite actualmente.
  • [1:01:44] Streamlit es más flexible que Gradio pero no tan fácil de empezar a usar, y también es principalmente para crear prototipos.

Ir más allá de los prototipos

  • [1:02:02] En algún momento querrás construir algo más que un prototipo, una aplicación real.
  • [1:02:07] Al ponente le gusta que Gradio en HuggingFace Spaces tenga un botón aquí abajo.

Uso de las API de HuggingFace Spaces con JavaScript

Endpoint de API para predicciones del modelo

  • [1:02:13] Las predicciones del modelo de la aplicación son gestionadas por HuggingFace Spaces Gradio, y se puede escribir una aplicación JavaScript para comunicarse con ella.
  • [1:03:27] Un endpoint de URL se ejecuta con el modelo; pasar datos de imagen a esta URL devuelve un diccionario, haciendo lo mismo que la interfaz de usuario pero como función de API.

Reacciones al trabajo de front-end en JavaScript

  • [1:02:41] Los ingenieros de front-end pueden estar emocionados porque ahora pueden crear cualquier cosa en el mundo escribiendo cualquier código.
  • [1:02:52] Muchos científicos de datos pueden estar preocupados porque JavaScript no está en su inventario.
  • [1:03:07] El ponente aconseja no tener demasiado miedo a JavaScript, y señala que una opción es entregar el modelo a un colega que sepa JavaScript para crear la interfaz.

Llamada a la API con curl

  • [1:03:58] La página de la API incluye ejemplos de cómo llamarla.
  • [1:04:05] El ponente demuestra la API usando la interfaz mínima porque es más simple, haciendo clic en curl y copiando y pegando el comando.
  • [1:04:25] Pasar "hello world" no es un gran ejemplo, pero pasar Tanishq devuelve "Hello Tanishq!", mostrando cómo funcionan estas API.

Creación de aplicaciones web de clasificación de mascotas en JavaScript

Demostración de clasificador de razas de mascotas en un solo archivo

  • [1:04:56] El ponente creó un sitio web llamado "tinypets" que es básico pero funcional y ofrece varios ejemplos.
  • [1:05:17] En el ejemplo de un solo archivo, el modelo realiza una clasificación completa de razas de mascotas en lugar de solo perro versus gato, usando un modelo entrenado para clasificar razas que se discutirá más la próxima semana.
  • [1:05:41] Como la demostración es una aplicación de JavaScript, no hay restricciones sobre lo que se puede hacer, aunque el resultado en sí no es muy impresionante.

Pipeline mínimo de JavaScript en el HTML

  • [1:06:07] Los pasos básicos son crear una importación para la foto y agregar un detector de eventos que llame a la función read cuando la foto cambie.
  • [1:06:19] La función read crea un lector de archivos, lee el archivo y llama a loaded cuando termina la carga.
  • [1:06:30] La función loaded obtiene la ruta de la API, que se copia y pega del ejemplo excepto que usa el modelo completo de mascotas.
  • [1:06:53] Luego, el código obtiene el JSON, toma la etiqueta y las confidencias de los datos y establece el HTML.
  • [1:07:02] El ponente señala que estos conceptos de JavaScript son nuevos para los usuarios que no usan JavaScript, pero no son más difíciles que Python, solo es otro lenguaje que aprender.

Extensión de clasificación de múltiples archivos

  • [1:07:24] Una versión de múltiples archivos permite al usuario seleccionar varias imágenes, como un terranova, un ragdoll, un basset hound y un gato, y las clasifica todas a la vez.
  • [1:07:47] Al parecer, el gato fue clasificado como Bengalí, y también se identificó al terranova.
  • [1:07:57] El código de múltiples archivos no es mucho más largo: obtiene todos los archivos, los mapea a read y agrega cada resultado.

Ejemplo de la comunidad que combina dos modelos

  • [1:08:14] El sitio enlaza a más ejemplos creados por la comunidad durante la semana, incluido uno de alguien del equipo de gradio llamado "get to know your pet".
  • [1:08:34] Este ejemplo combina dos modelos: primero identifica a la mascota como un basset hound y luego permite al usuario escribir preguntas sobre ella.
  • [1:08:45] Preguntas como qué tipo de cola tiene llaman a un modelo de NLP, que respondió que es una cola curva en forma de sable.
  • [1:09:11] Al preguntar qué mantenimiento necesita, la aplicación respondió que las orejas de un basset hound deben limpiarse por dentro y por fuera con frecuencia.
  • [1:09:17] El ponente destaca esto como una combinación de modelos de una manera que una interfaz lista para usar no podría hacer.

Creación y alojamiento de una aplicación web simple en JavaScript

Ejecución local de una aplicación JavaScript de un solo archivo

  • [1:09:52] La versión más básica es un único archivo fuente HTML que se puede guardar y abrir en Visual Studio Code o haciendo doble clic en él en el Explorador o Finder.
  • [1:10:28] El archivo se ejecuta como una aplicación funcional sin instalar ningún software, porque el navegador es el entorno de ejecución completo, incluido un depurador.
  • [1:10:46] La aplicación llama a un endpoint externo de Hugging Face, por lo que todo puede ejecutarse localmente en el ordenador.

Alojamiento en GitHub Pages mediante FastPages

  • [1:11:06] GitHub Pages aloja el sitio web de forma gratuita y, como es solo JavaScript, funciona bien allí.
  • [1:11:22] La forma más sencilla de crear un sitio de GitHub Pages, en opinión del ponente, es FastPages, un proyecto de fast.ai.
  • [1:11:43] La configuración consiste en hacer clic en un enlace para generar una copia, darle un nombre y crear el repositorio, con aproximadamente dos pasos más que llevan unos cinco minutos.
  • [1:12:24] Tras la configuración se obtiene un sitio vacío, que se abre con GitHub Desktop o Visual Studio o pegando un comando en la terminal, y luego se guardan los archivos HTML y se envían de vuelta a GitHub.

Temas y configuración de Jekyll

  • [1:12:49] FastPages muestra el enlace al sitio web creado, cuyo aspecto se puede cambiar con un tema.
  • [1:13:03] Un archivo config.yml permite elegir un tema; el ponente eligió uno llamado "alembic" sin ninguna razón concreta.
  • [1:13:18] GitHub Pages usa Jekyll, así que cualquier tema de Jekyll funcionará, y los archivos guardados aparecen automáticamente en el sitio web y en la lista de archivos.
  • [1:13:38] Cada archivo de GitHub Pages necesita "front meta" en la parte superior: tres guiones, título, diseño y tres guiones.

Bifurcación y personalización del sitio

  • [1:14:18] Para crear una versión diferente, ve a fast.ai/tinypets y haz clic en Fork para crear tu propia copia; el ponente lo hizo con la cuenta jph00.
  • [1:14:38] El ponente cambió el tema en config.yml a "pages-themes/hacker".
  • [1:14:47] Tras hacer fork, debes ir a Settings, hacer clic en Pages y habilitar GitHub Pages, que está desactivado por defecto, usando "Master Branch Root Save".
  • [1:15:09] Con el tema diferente, Tiny Pets de jph tiene la misma información pero parece mucho más hacker.

Empezar sin coste ni herramientas pesadas

  • [1:15:29] No necesitas dinero, IDE ni mucho código para empezar a escribir tus propias aplicaciones web.
  • [1:15:55] Gracias a Hugging Face Spaces, incluso alojarán tu modelo, y todo lo que necesitas es la cadena mágica para llamarlo.

Introducción al procesamiento de lenguaje natural

Próximos temas y métodos de PLN

  • [1:16:15] La próxima sesión tratará el procesamiento de lenguaje natural, aplicando técnicas similares al lenguaje en lugar de a las imágenes.
  • [1:16:23] La sesión profundizará en el funcionamiento interno de estos modelos.
  • [1:16:29] Los temas incluirán el descenso de gradiente estocástico, y puede que se necesite algo de cálculo.

Lee los subtítulos disponibles con marcas de tiempo o transcribe podcasts, clases y audio o vídeo local. Extractor gratuito de subtítulos de YouTube.

[0:00] Hi everybody. Welcome to lesson two. Thanks for coming back… slight change of environment here, we had a bit of an “administrative issue” at our university — somebody booked our room — so I'm doing this from the study at home. so sorry about the lack of decorations behind me. I'm actually really really pumped about this lesson. It feels like going back to what things were like in the very early days, because we're doing some really new, really cool stuff, which…

[0:41] you know… stuff that hasn't really been in courses like this before. So, I'm super super excited. So thanks a lot for coming back after lesson one, and I hope it's worth you coming back. I think… I think you're gonna love it! I am, yeah, I'm really excited about this. Now remember that, you know, the course goes with the book, so be sure that you're following. I mean, not following along in the book, because we're covering similar things in different directions…. but, like, read the book as well, and remember the book is entirely available for free as well. You can go to the fast.ai fastbook repo to see the notebooks, or through course.fast.ai you can read it there — for example, through Colab.

[1:28] And also remember that the book… I mean… the book has a lot of stuff that we didn't cover in the course like, you know, stuff I find pretty interesting, about the history of neural networks, some of which has some really interesting personal stories actually, as you'll read here. And at the end of each chapter there is a quiz. Remember it's not a bad idea before you watch the video to read the quiz, so if you want to read the Chapter Two quiz, you know, and then come back, that's not a bad idea. Then make sure that you can do the quiz after you've watched the video, and you've read chapter two of the book.

[2:07] Something I didn't mention last week, is there's also a very cool thing that Radek — who I mentioned last week — has written, called aiquizzes.com which is a site specifically for quizzes about the book. And it actually uses repetitive based learning techniques to make sure that you never forget. So, do check out aiquizzes.com. It's all brand new questions, they're different to the ones in. the book, and they're really nicely curated, and put together. So check out aiqquizzes.com as well. Remember, as well as course.fast.ai, there's also forums.fast.ai. So course.fast.ai is where you want to go to get, you know, links to all the notebooks, and kaggle stuff, and all that stuff. You'll also find on forums.fast.ai, every lesson has an official topic, you know, with all the information. you'll need. Generally there'll be a bit more info on the forums, we try to keep the course

[3:09] lean and mean, and the forums are a bit more detailed. So if you find — in this case you are gonna look for the Lesson Two official topic, but here's the Lesson One official topic so far. So from the Lesson One official topic, already, after just a few days since I recorded it — we haven't even launched the course so it's just the people doing it live — there's already a lot of replies, and that can get pretty overwhelming.

[3:40] So be aware that there's a button at the bottom of my post that says summarize this topic. And if you hit that, then you'll just see the most upvoted replies, and that's a really good. way to just make sure that you hit on the main stuff. So, there's the button, and here's what it looks like after you hit it. You'll just get… you'll just get the upvoted stuff from fast.ai. legends like Sanyam and Tanishq. So hopefully you'll find that a useful way to use the forum.

[4:14] So one of the cool things about this week is I… as promised, put up the “show us what you've made.” post, and already a lot of people have posted. I took this screenshot a few days ago, it's way. above 39 replies already, if I'm… if I remember correctly. I had a lot of trouble deciding which ones to share because they're all so good, so I've actually decided to kind of, you know, go the easy route, and I just picked the firsts. So I'm just going to show you the first ones that were posted. because they're all so good. So the first, the very very first one to be posted is a damaged. car classifier… so that worked out pretty well — it looks like. And I really liked what Matt, the creator, said about this, is that…. you know, wow, it's a bit uncomfortable to run this code, I don't really understand yet but I'm just doing it. And so I'm like, yeah, good on you Matt for just.…

[5:14] for just doing it. That's the way to get started, it's all going to make sense, don't worry. Very nice to see that the next one posted was actually a blog post in fast pages. — very nice. to see —, so just describing some stuff, some experiments that they ran over the week and what did they find. Next one was the amazing beard detector which if I understand correctly was mainly because it's very easy to get from bird to beard by just changing one letter to two, and this is doing a very good job of finding gentlemen with beards. Very nice. And then this one is.…

[5:51] another level again, it's a whole in-production web app to classify food, which is kind of like extra credit. . Apparently we're up to 80 replies now in that thread, thank you Sanyam, very cool. So, you know, obviously.… so this was actually created by Suvash who's been doing the courses for. a few years now, I believe. And so you know, one day you too might be able to create your very own. web app and put it in production. And when I say one day, more specifically.… today! I'm actually. going to show you how to do this right now! So it's actually quite a lucky coincidence that Suvash put this up there because it's exactly the topic that we're going to pick today.

[6:46] So, how do we go about putting a model in production? Step, one, is…. well… you've kinda done step one, right? Step one is… step one, two, three, four… is to figure out。 what problem you want to solve, figure out how to find the data for it, go gather some data, and so forth. So what's the kind of first step after you've got your data? The next step is. data cleaning, and if you go to Chapter 2 of the book, which I'm going to go ahead and open up now.…

[7:23] So here is the book.… so you can open it in Colab directly from the course, or if you've. cloned it to your computer, or whatever, you can… you can do it there. So remember, course.fast.ai will run you through exactly how to run, these notebooks, and so you can see Chapter 2 is all about putting stuff in production, and so here is Chapter 2. All right, and so, remember we hit Shift + Enter to run cells, okay? …to execute them. And so we're going to go to the part of the book where we start cleaning the data.

[7:59] So I'll click on Navigate, and we'll go down here… gathering data… there we are! So we could do a quick bit of revision first. By the way, I will mention, a lot of people ask me what are the little tricks I use for getting around a Jupyter notebook so quickly and easily. One of the really nice ones as you'll see is this navigate menu, which actually doesn't. appear by default. So if you install something called Jupyter Notebook Extensions - Jupyter…

[8:30] Notebook… Extensions… and so you just… you just “pip install” them, follow the instructions and then restart Jupyter. Obviously this… Colab already has a table of contents by the way so this is just if you're using something local, for example, then you'll see here that this “Nbextensions” thing will appear, and if you click on “Table of Contents (2)” that gives you this handy navigation bar. The other thing I really like is this one here called collapsible headings, and that's the one which gives me these nice little things here, to close, and open up. And actually that's not even the best part. The best part for me is if I hit the right arrow, it goes to the end of a section, and if I hit the left arrow it goes to the start of a section. So it's like, if I want to move around sections I just press up left, down right, down right, very handy,

[9:35] and if you hit left again when you're here it 'll close it up. Hit right again here, open it up. So that's collapsible headings. Anyway, a couple of really handy things, and we'll be talking a lot more about getting your notebook set up today in a moment. Okay, so one thing you'll notice is in the book, we use the Bing API for searching images. I've just gone ahead, and replaced “bing” with “ddg” because, the Bing API requires getting an SDK key which honestly, it’s like the hardest thing in deep learning is, figuring out the Bing Azure website, and getting that sorted out. ddg doesn't! So it's basically exactly the same… (and you can…)

[10:21] I'll share this notebook as well, on the course website in the forum but, all I've basically done is I've replaced bing with ddg, and got rid of the key. So then, just like we did last week, we can search for things, and so in the book we did a bear detector because, at the time I wrote it my then toddler was very interested in me helping identify teddy bears, and I certainly didn't want her accidentally cuddling a grizzly bear, so we show how here how we can search for grizzly bears, just like last week.

[10:56] Something that loops through grizzly bears, black bears, and teddy bears, just like last week. Get rid of the ones that failed, just like last week. And one thing a few people have asked on the forum is? how do i find out more information about basically any python or fastai or pytorch thing. There's a few tips here in the book. One. is that if you put a double question mark next to any function name you'll actually get the whole. source code for it, and by the same token if you put a single question mark you'll get a brief.…

[11:41] you know… a little bit of information. If you've got nbdev installed (I think it's nbdev you need) then you can type doc, and that will give you perhaps most importantly a link straight to the documentation. where you can find out more information and generally there will be examples as well. And also a link here to the source code, if you want to.…

[12:13] (let's do that with a control okay) …a link to the source code and that way you can jump. around. And notice that in github in the source code you can click on things and jump to their. definition. So it's kind of a nice way of skipping around to understand exactly what's going on. Okay, so lots of great ways of getting help. But what I promised you is that we're going to now clean the data. So I'm going to tell you something that you might find really surprising. Before you clean the data, you train a model.

[12:55] Now, I know that's going to sound really backwards, to what you've probably heard a thousand times, which is that first you… ~(build/you/train) …you clean your data and then you train your. model. But I'm going to show you something really amazing. First we're going to train a model and you'll see why in a moment. So to train a model, just like before, we use a DataBlock to grab our. data loaders — there's lots of information here in the book about what's going on here. There we go… and so then we can call show_batch to see them as per usual.

[13:33] There's a little side bar here in the book, I'll quickly mention, which is about the different. ways we can resize. I think we briefly mentioned it last week… we can squish.… last week I used a string, you can use a string or this kind of enum like thing that we have. You can see with a squish, you can end up with some very thin bears, right? So this is the real size, the shape, of the bear. Here its become thin but you can see. now we've got all of its cubs… (are they called clubs? yeah bear cubs) …so it squished it to. make sure we can see the whole picture. Same one here. This one was out of the picture, we squished. it and this guy now looks weirdly thin, but we can see the whole thing. So that's squishing!

[14:12] Or else this one here is cropping. It's cropped, out just the center of the image, so we get a better aspect ratio but we lose some stuff. This is so we can get square images. And the other. approach is we can use “pad.”. And so you can pad with various different things. If you pad with zeros, which is black, you can see here now we've got the whole image and the correct aspect ratio. So that's another way we can do it and you know, different situations, you know, result in. different quality models. You can try them, all it doesn't normally make too big a difference.

[14:44] So I wouldn't worry about it too much. I'll tell you one though that is very interesting. is RandomResizedCrop. So instead of saying resize, we can say RandomResizedCrop. And if we do that. you'll see we get a different bit of an image every time. So, during the week… this week, somebody asked on the forum… I'm trying to…. (this. is a really interesting idea, which it turned out worked slightly,) they wanted to recognize pictures of French and German texts. So obviously this is not the normal way you would do that, but just for a bit of experiment, (and I love experiments, so,) they had very big scans of documents and they wanted to figure out whether it was french or german just by looking at images, and they said the pictures were too big? what. should I do? I said, use RandomResizedCrop and that way you'd grab different bits of the image, and this is very nice because you could run lots and lots

[15:44] of epochs and get slightly different pictures each time. So this is a very good technique. And this idea of getting different pictures each time from the same image is called “data augmentation.” And again, I'm not going to go into too much detail about data augmentation, because it's in the book, but i'll just quickly, you know, point out here that if you use this thing called “aug_transforms” so augmentation transforms, and here I have multiplied them by two, – so I've made them super big so you can see them more easily. You can see that these teddies are getting turned, and squished, and warped, and recolored, and saturated, all this stuff to make every picture different. And generally speaking if you're training for more than about five or ten epochs, which you'll probably want to do most of the time unless you've got a super easy problem to solve, you'll probably want to use RandomResizedCrop and these “aug_transforms.”. Don't put the mult=2,

[16:49] just leave that empty. I'm just putting it there so you can see them more clearly. So I've got an interesting question here from Alex in our audience, which is: “Is this… is this copying the image multiple times? …doing something like this? …or something like this?” and the answer is “no we're not copying the image. What. happens is that image… so each epoch, every image gets read. And what happens here is though…. is…. is kind of…. in memory, in RAM, this…. the image is being “warped,”, right? it's being… we're cropping it and recoloring it, and so forth. So it's a real time process that's happening during model training. So, there's no copies being stored on your computer, but effectively it's almost like there's infinitely slightly different copies because that's what the model ends up seeing. So, I hope that makes sense Alex, and everybody else,

[17:52] so that's a great question! Okay, so we've got…. we're. going to use RandomResizeCrop, we're going to use augmentation transforms, so that we can get at DataLoaders from that and then we can go ahead and train our model. It takes about a minute. In this case we only did four epochs of fine tuning, and we'll talk about why there's five here later in the course, but four main epochs of fine tuning. So we probably didn't really need RandomResizedCrop and aug_transforms because there's so few epochs, but. you know, if you want to run more epochs this is a good approach. Under three percent! error! that's good! Okay, so remember I said we're going to train a model before we clean?

[18:36] Okay so let's go ahead and train it. So while that's training… so it's running on my laptop, which only has a 4GB GPU, it's pretty. basic, but it's enough to get started. While that's training we'll take a look at the next one. So the first thing we're going to look at is, the confusion matrix and, the confusion matrix is something that… it only is meaningful for when your labels are categories, right!

[19:09] And what it says is how/what category errors are you making. And so this is showing that the model that we've got at this point… there were two times when there was actually a grizzly bear. and it thought it was a black bear, and, there was two times, when there was actually a black bear, and it thought it was a grizzly bear, and, there was no times, that it got teddies wrong, which makes sense right because teddies do look quite different to both. In a lot of situations when you look at this, it'll kind of give you a real sense of, like okay, well what are the hard ones? right? So for example if you use the pets data set that we quite often. play with in the book and the course, this classification [**] matrix for different breeds. of pets, you know, really shows you which ones are difficult to identify, and I've actually gone in, and like, read wikipedia pages, and pet breeding reports about how to identify. these particular types, because they're so difficult, and even experts find it difficult.

[20:10] And one of the things I've learned from doing the course actually is… black bears and grizzly. bears are much harder to pick apart than I had realized... so I'm not even going to try! But I'll show you, the really interesting thing we can do with this model, is that now we've created this classification interpretation. object, which we use for confusion matrix, we can say plot_top_losses. We can say plot top losses, and this is very interesting. What it does is, it tells us the places where the “loss” is the highest. Now if you remember from the last lesson, the loss is that measurement – of how good our model is – that we take after each time we run. through an item of data. A loss will be “bad” if we predict wrongly, and we're very confident.

[21:11] about that prediction. So here's an example where we predicted…. (here's the order here: prediction, actual loss, probability). …where we predicted grizzly and it was actually a black, and we were 96% sure (our model was) that it's a grizzly. Now, I don't know enough about bears to know whether the model made a mistake or whether this actually. is a picture of a grizzly bear… but so, an expert would obviously go back and check those out.…

[21:41] right? Now, you'll notice a couple here... it's got grizzly/grizzly, teddy/teddy… they're actually. correct, right? So why is this loss “bad”? When it's correct? And the reason is…. because it wasn't very confident. It was only 66% confident, right? So here's a teddy…. it's only 72% confident. right? So you can have a bad loss, either by being wrong and confident, or being right and. unconfident. Now the reason that's really helpful, is that now we can use something called the fast.ai ImageClassifierCleaner to clean up the ones that are wrongly labeled in our data set.

[22:24] So when we use the ImageClassifierCleaner it actually runs our models. That's why we pass it “learn”, right? And I mentioned that I don't know much about black bears and grizzly bears but I do. know a lot about teddy bears, so I'll pick teddy bears. And if I click teddy bears it's now showing. me all the things in the training set (you can pick training or valid) that were marked as teddy. bears and here's what's really important: they're ordered by loss, so they're ordered by confidence, right? So I can scroll through just the first few and check they're correct, right? And oh, here's a mistake, right? So when I find one that was wrongly gathered, I can either, put it…if it's in the wrong category, I can choose the correct category… or, if it shouldn't be there at all, I click delete. So here I'll go ahead and click delete, right?

[23:14] So you can see some reasons that some of these are hard, like for example here's two teddies, which is just, I guess, confusing since it doesn't see that often. This one here is a bit weird looking, it looks almost like a wombat. This is an awful lot of teddies. This one maybe is just a bit hard to see from the background, but these, otherwise, they look fine.… Fine, so we just look through the first few and if you don't see any problem, or problems in the first year, you're probably fine. So that's cleaned up our training set, let's clean up our validation set as well. So here's that one it had trouble with, I don't know why it had trouble with that one but so be it, and we'll have a quick scroll through…

[23:59] Okay I'm not really sure that's a bear so I'm just going to go ahead and delete it. It's a teddy something…. but, you know, it's a problem. Okay, that's not a teddy either…. So you see the idea, right? So after we've done that, what that does is… the cleaner. has now stored a list of the ones that we changed and the list of the ones we deleted, so we can now go ahead and run this cell. And so that's going to go through a list of all of the indexes that we said to delete, and it will delete those files. And we'll go through all the ones we set to change, and it will move them to the new folder, there we go, done!

[24:45] So, this is like, not just something for image models. It's just…. it's actually…. a really powerful technique that almost nobody knows about and uses, which is, before you start data cleaning, always build a model to find out what things are difficult to recognize in your data and to find the things that the model can. help you find data problems. And then as you see them, you'll kind of say “okay, I see the kinds of problems we're having” and you might find better ways to gather the next. data set, or you might find ways to kind of automate some of the cleaning and so forth.

[25:23] Okay, so, that is data cleaning and since I only have a 4GB GPU it's very important for me. to close and halt, because that will free up the memory. So it's important to know… on your computer, your normal RAM doesn't really, get filled up, because if you use up too much RAM, what will happen is that instead, your computer will start (it's called) swapping, which is basically to save that RAM onto the hard disk to use it later. GPUs can't swap.

[26:00] GPUs, when they run out of RAM, that's it, you're done. So you need to make sure that you close any notebooks that are using the GPU that you're not using. and really only use one thing at a time on the GPU, otherwise you're almost certainly run out of memory. So we've got the first few reds starting to appear. So remember to ask and, in terms of the yellows, it's important to know, as you watch the video, I'm not asking you to run all this code, okay? The idea is to kind of watch it, and then go back and pause, you know, as you go along. Or you can just stop, try, stop, try. The approach I really like — and a lot of students really like — for watching these videos is to actually watch the entire thing without touching the keyboard, to get a sense of what the video is about, and then go back to the start and watch it again and follow along. That way, at every point you know what it is you're

[27:00] doing, you know what's going to happen next. That can actually save you some time. It's a bit of an unusual way because, obviously like, real life lectures you can't do that, you can't rewind the professor and get them to say it again, but it's a good way to do it here. So now that we've cleaned our data, how are we going to put it into production? Well in the book we use something called Voilà. And it's… it's pretty good! But there's actually, something that I think most of you are probably going to find a lot more useful nowadays, which is something called HuggingFace Spaces, and there's a couple of things. you can use with that. We're going to look at something called Gradio today.

[27:42] And there isn't a chapter about this in the book but that doesn't matter because Tanishq Abraham — who's actually one of the TAs in the course — has written a fantastic blog post about really everything we're going to cover today. So there's a link to that from the forum and from the course page, so this is like the equivalent of the chapter of the book, if you like. And I would be remiss if I didn't stop for a moment and call out Tanishq in a big way for two reasons: the first is he is one of the most helpful people in the fastai community, he's been around quite a few years, incredibly tenacious, thoughtful and patient; and also because I have this fantastic picture of him a few years ago with Conan when he was a famous child prodigy, so now you know what happens to famous child prodigies when they grow up – they became even more famous fastai community members and deep learning experts.

[28:41] So you should definitely check out this video of him telling jokes to Conan. I think he's still only 18 actually, this is probably not that many years ago. So thank you very much Tanishq, for all your help in the community。 and sorry for embarrassing you with that picture of you as a nine-year-old, — I'm not really, haha. Okay, now, the thing is for doing Gradio and HuggingFace Spaces, well, it's easy enough to start. Okay, we start over here on the HuggingFace Spaces page, — which we've linked to from the forum in the course. And we're going to put a model in production, where we're going to take the model we trained, and we are going to basically copy。 it to this HuggingFace Spaces server and write a user interface for it.

[29:29] So… let's go! Create new space. Okay, so, you can just go ahead and say, all right… so obviously you sign up… the whole thing's free. Basically everything I'm showing you in this entire course, you can do for free, that's the good news. Okay, so, give it a name, just create something minimal. I always use the Apache license because it means other people can use your work, really easily but you don't have to worry too much about patents. As I say there's a few different products you can use with it, we're going to use Gradio, also free.

[30:04] If you make it public then you can share it, which is always a good idea when you're a student, particularly to… to really be building up that portfolio. Okay, so we're done. We've created。 a space. Now, what do we do next? Well, Spaces works through Git, now, most software developers will be very familiar with Git. Some data scientists might not be. And so Git is a very, very useful tool. I'm not going to talk about it, in detail, but let's kind of quickly learn about. how to use it, right? Now, Git, you can use it through something called Github Desktop which is actually pretty great and even people who use Git through the console should probably be, considering using Github Desktop as well, because some things are just much faster and easier in it, in fact I was talking to my friend Hamil today and I was like, oh, help, I've accidentally committed。 this two things by mistake, what's the easiest way to revert it, and he used to work at Github,

[31:09] and I thought he was going to have some fancy console command and he's like “oh, you should, use Github Desktop and you can just click on it.” Oh! That's a great idea. So that's… that's useful. But most of the time we do use Git from the console, from the terminal. If you're a Linux user or a Mac user you've already got a terminal, very straightforward, no worries. If you're a Windows user I've got good news, nowadays Windows has a terrific terminal. It's called Windows Terminal, you get it from the Microsoft Store, so in fact every time you see me using a terminal, I'm actually using that Windows Terminal, works。 very well. God knows why you'd want it to, with all these ridiculous colors but, there you go.

[31:54] Now, what do you want to be running inside your terminal? Obviously, if you're in Linux or Mac, you've already got a shell set up. In Windows, you almost certainly want to use Ubuntu. So Windows, believe it or not, can actually run a full Linux environment and to do it, is right typing a single。 line, which is this… So, if you go to (just google for WSL install) run PowerShell as administrator, paste that command, wait about five minutes reboot, you're done.

[32:30] You now have a complete Linux environment. Now, one of the reasons I'm mentioning this is, I'm going to show you how to do stuff on your own machine now, and, so, this is like going to a bit of an extra level of geekery, which some data scientists may be less familiar with. So you know, don't be worried about the terminal, you're gonna.. I think you're gonna… find it really helpful and much less scary than you expect. And, I particularly say, like for me, I choose to use Windows and that's because I get, you know, all the nice Windows GUI apps and I can draw on my screen, and do presentations, and I have a complete Linux environment as well. And that Linux environment uses my GPU and everything, so for me, you know, my first choice is to use Windows, my second choice, by not very much, really like it, would be, to use Linux. Mac is a little bit harder, but it's still usable. Some things are a little bit trickier on Mac, but, you should be fine.

[33:37] Okay, so, whatever you've got, at this point you've now got a terminal available. And so, in your terminal,… (one of the really nice things about using a terminal is you don't have to follow lots of instructions about click here, click here, click here. You just copy and paste things.) So I'm just going to… you just copy this, and you go over to your terminal, and you paste it in, and you run it, and after you do that, you'll find that you've now got a directory. And so that new directory initially is empty and they tell you, okay, go ahead and create a file with this in it. Okay, so, how do you create a file with that in it, when we're in here, in our Linux environment on Windows, or in the terminal on Mac, or whatever? Well, all you do in Windows, if you just type “explorer.exe. .”, it'll open up explorer here, or better still, on either Mac, or Linux, or Windows,…

[34:42] So, yeah, regardless of what computer (type of computer on), you can just type “code .”. and it will pop up Visual Studio Code and open up your folder. And so then you can just go ahead and… (if you haven't used VS Code before it's really well worth taking a few minutes to read, some tutorials, it's a really great IDE). …and so, you can go ahead and create an app.py file, like they tell you to, app.py file, containing what they told you to put in it. Here it is, here.

[35:22] All right, we're nearly there. So you can now go ahead and save that, and then you need to commit it, to Gradio… (not Gradio…) to HuggingFace Spaces. So one really easy way is just, in Visual Studio itself, you can just click here, and that'll give you a place where you type a message, and you hit tick, and it'll send it off to HuggingFace Spaces for you. So once you've done that, you can then go to… back to… the exact same website you're in before: “huggingface.co/spaces/jhp00/minimal,”, and what you'll find now is that — it'll take about a minute, to build your website. And it's…

[36:15] the website it's building is going to have a Gradio interface with a text input, a text output, and it's going to run a function called “greet()” on the input, and my function called “greet()” will return “Hello {name}”. So that's what it's going to do. Now there it goes, let's try it! We'll say hello to Tanishq. I'm not always very good at remembering how to spell his name, I think it's like that.

[36:50] And there you go, so you can see it's put the output, for our input. So not a very exciting app, but we now have, to be fair, an app running in production, right? Now, I told you we'd have a deep learning model running in production. so now we have to take the next step which is to turn this into a deep learning model. All right, so, first we're going to need a deep learning model. And there's a few different ways we can get ourselves a deep learning model, but basically we're gonna have to train one. So, I've got a couple of examples: I've got a Kaggle example and a Colab example. Maybe I'll quickly show you both. They're gonna be the same thing. And I'm just going to create a dog or a cat classifier. Okay, so here's our Kaggle model, I'll click on edit so you can actually see what it looks like in edit view.

[37:52] Now, Kaggle already has fastai installed but I always put this first, just to make sure we've got the latest version. And obviously import stuff, we… So we're going to grab the pets data set, a function to check whether it's a cat, that's our labeling function for our ImageDataLoaders — remember this is just another way of doing DataBlocks, it's like a little shorthand. And we create our learner, and we fine tune it. Okay, so, that's all stuff we've seen before. So, in Kaggle every notebook has an edit-view (which is what you just saw) and a reader-view.

[38:27] And so you can share your notebook — if you want to. And then anybody can read the reader-view, as you see. And so, here, you can see, it shows you what happened when I ran it. And so, I trained it, it took… you know, the GPUs on Kaggle are a bit slower than most modern GPUs but they're still fast enough, I mean, it takes five minutes. And there's one bit at the end here, which you haven't seen before, which is I got learn.export and I give it a name.

[39:02] Now, that's going to create a file containing our trained model, and… that's the only thing! Creating this file is the only thing you need a GPU for, right? So you do that on Kaggle, or on Colab. So here's exactly the same thing on Colab… you can see “pip install”, is_cat, our data, ImageDataLoaders, so I've got a show_batch here as well, just for fun. Create my learner and then export. So, while we wait I might go ahead and just run that.

[39:36] One nice thing about Kaggle is once you've run it and saved it, you can then go to the data tab and, here is basically anything you've saved, it's going to appear here, and here it is: model.pickle, right? So now I can go ahead and download that and that will then be downloaded to my downloads folder. And then I need to copy it into the same directory that my HuggingFace Spaces App is in. Now, my HuggingFace Spaces App is currently open in my terminal, on Mac you can type “open .” or in Windows you can type “explorer.exe .” and that'll bring up. your finder or explorer in that directory. And, so then you can just paste that, that thing you downloaded into this directory. Something by the way, in Windows I do, which I find really helpful is, I actually grab my… my home directory in Linux

[40:43] and I pin it to my Quick Access and that way I can always jump in Windows straight to my Linux files. Not really something you have to worry about on Mac because it's all kind of integrated, but on Windows they're like, kind of like, two separate machines. Okay, so…. Let's do… so, I created a Space called testing and I downloaded my “model.pkl” and I pasted it into. testing. So now we need to know how do we do predictions on a saved model?

[41:23] So we've got a notebook for that…. Okay, so we've got a notebook for that and… so I'm going to take you through how we use a model that we've trained to make predictions. There's a few funny things with hash pipe which I'll explain in a moment, just ignore. those for now. So we import fastai as usual. We import Gradio as we did before. And we copy in. the exact same is_cat definition we had before. That's important, any external functions that you, used in your labeling, need to be included, here as well because that learner refers to those functions, okay? It saves... that learner saves everything about your model, but it doesn't have the source code of the function, so you need to keep those with you.

[42:12] So, let's try running this. So, for example, I just grabbed… (as you might have seen in my explorer) I just popped a dog picture there. And so we can create a python image library image from that dog, turn it into a slightly smaller, one so it doesn't overwhelm my whole screen and there is a picture of a dog. So, how do we make. predictions of whether that's a dog or a cat? Well, it's very simple, all we do is… instead of, training a learner, we use load_learner(). We pass in the file name that we saved, and that returns. a learner. This learner is exactly the same as the learner you get when you finish training. So here we are, here's Colab, right? We've just been training a learner, so at the end of that, there's, a learner that's been trained, and so we… We kind of froze it in time, something called a pickle, file — which is a python concept. It's like a frozen object, we saved it to disk, we transferred,

[43:17] it to our computer, and we've now loaded it, and we've now unfreezed thought it. This is our unpickled learner and we can now do whatever we like with that. So one of the things that… One of the methods that a learner has is a dot predict method, so, if I run it, you can see, even on my laptop, it's basically ~(instance) instant. In fact we can see how long it took. If you — in Jupyter things that start with percent are called magics, they're special Jupyter things, so for example, there's a thing to see how long something takes.

[43:51] There you go, okay, so it took 54 milliseconds to figure out that this is not a cat. So it's returning two things: is it a cat? (as a string); is it a cat? (as a zero or one), and then the probability that it's a dog, and the probability that it's a cat. So the probability of. zero (false) and one (true) of is it a cat? so definitely a dog. So we now want to create a Gradio interface which basically has this information.

[44:28] So Gradio requires us to give it a function, that it's going to call, so here's our function. So we're going to call predict, and that returns as we said three things: the prediction is a string; the index of that; and the probabilities of whether it's a. dog or a cat. And what Gradio wants, is it wants to get back a dictionary containing each of the. possible categories — which in this case is dog or cat — and the probability of each one. So, if you haven't done much python before, a dict of a zip may be something you haven't seen.

[45:04] Very handy little idiom well worth checking out. Ditto if you haven't seen map before, anyway, here it is. One slightly annoying thing about Gradio at the moment is that it doesn't handle Pytorch Tensors, you can see here Pytorch is not returning normal numbers, it's returning Tensors. It's not even returning Numpy Arrays. In fact radio can't handle Numpy either, so we have to change everything just to a normal float, so that's all that this is doing, it's changing each one to a float. So, for example, if I now call classify_image(). with our doggy image, we get back a dictionary of a dog, yes definitely; cat, definitely not.

[45:45] So now we've got all that we can go ahead and create a Gradio interface. So Gradio interface is something where we say, well, what function do you call. to get the output, what is the input — in this case we say, oh, the input is an image —. and so check out the Gradio docs, it can be all kinds of things like a webcam picture, or a text, or you know, all kinds of things. Give it a shape that it's going to put it into, the output's just going to be a label so we're going to create very, very simple interface. And we can also provide some examples, and so there's a dog, a cat, and a dunno — which I'll. tell you about in a moment — which you'll see here there's a dog, and a cat, and a don't know.

[46:27] So once I launch it, it says, okay, that's now running on this url. So if I open that up; you can see now, we have just like Suvash, we have our own — not yet in production, but running on our own box — classifier. So let's check: dog, so you can click it and upload one, or just choose the examples…. Here they are! So it's running on my own laptop, basically instant. And I really have to tell you the story about this guy here, this is the dunno.

[47:01] Submit, wait, why is it saying 100? Normally this says like 50 50. That's a bummer, this model's. got… messed up my whole story. So last time I trained this model, and I ran it on the… dunno, it said, it said like it's almost exactly 50 50. And the way we found this picture. is… I showed my six-year-old daughter, she's like: “what are you doing dad?”, like, I'm coding, “what are you coding?” Oh, you know, dog cat classifier. She checks it out and her first question is: “can I take your keyboard for a moment”, and she goes to google, and she's like: what is a dog mixed with a cat called. Like, there's no such thing as a dog mixed with a cat. Anyway, she goes, to the images tab, and finds this picture, and she's like: “look there's a dog mixed with a cat”.

[47:47] She said: “run it on that dad!, run it on that!” And I ran it and it was like: 50-50. It had no。 idea if it's a dog or a cat. Now, this model I just retrained today, now it's sure it's a cat. So there you go, I think I used a slightly different training schedule or something, or gave, it an extra epoch, anyway, so that's a dog-cat, but apparently it's a cat. I guess it is a cat. It's probably right. I shouldn't have trained it for as long. Okay, so there's our interface. Now, that's actually running, so you actually have to click the start button to stop it running, so otherwise you won't be able to do anything else in your notebook. Okay, so, now we have to turn that into a python script. So, one way to turn it into a python script would be to copy and paste into a python script all the things that you need.

[48:42] I need to copy and paste into a python script all these parts of this that you need, so, for example, we wouldn't need this — it's just to check something out, we wouldn't need this — it was just experimenting. This was just experimenting. We'd need this, right? So, what I did,… is I went through and I wrote “hash pipe export” at the top of each cell, that contains information that I'm going to need in my final script, and then — so they're the steps, right? And then, at the very bottom here, I've imported something, called notebook2script from nbdev, and if I run that, and pass in the name of this notebook, that creates a file for me called app.py, containing that script. So this is a nice, easy way to — like when you're working with stuff that's expecting a script and not a notebook, like HuggingFace Spaces does. It's fine to just copy and paste into a text file if you like,

[49:42] but I really like this way of doing it because that way I can do all of my experimentation, in a notebook, and when I'm done, I just have a cell at the bottom I just run and export it. How does it know to call it app.py? That's because there's a special thing at the top default export: default_exp, which says what python file name to create. So that's just a little trick that I use. So now we've got an app.py. We need to upload this to Gradio, how do we do that? You just… you just push it to Git. So… you can either do it with Visual Studio Code, or you can type “git commit”.

[50:28] And then “git push”. And once you've done that,…if we change minimal to testing,… I think this hopefully might still be running, my previous model — because I didn't push it, and that way, we can see our crazy dog-cat. All right, so here it is, you can see it running in production. So now this is something that anybody can —, if you set it to public —, anybody can go here and check out your model, and so they can upload it. And so, here's my doggy.

[51:02] Yep, definitely a dog. Cat, yeah I think I might have trained this for an epoch or two less, so it's less confident. Yeah, definitely a cat. Dog-cat… hey dog-cat… hmm, still thinks it's definitely a cat. Oh well, so weird. Okay, so, that is…Okay, so, that is an example of getting a simple model in production. There's a couple of questions from the forum, from the community.

[51:49] Okay so one person's asking: “what's the difference between a pytorch model and a fastai learner?” Okay, that's fine, we'll get to that shortly. Don't know if it'd be the lesson, it might be this lesson or the next lesson. And then somebody else asked, basically it's asking: “how many epochs do we train for?” So, as you train a model your error rate, as you can see, it improves.

[52:21] And so the question is: should I run more? Should I increase the number of epochs? This is doing three epochs, right? Here's my three epochs plus one to get started. Look, it's up to you, right? I mean, for this, is here saying: there's a one percent error. I'm… I'm okay with the one percent error, you know, if you want it to be better, then you could use more data augmentation, and you could train it for longer. If you train for long enough, as we'll learn about soon, and then… maybe the next lesson. If you train for long enough, your error rate actually starts getting worse. And, you'll see, we'll learn about why. So basically yeah, you can train until it's good enough or until you've run out of patience, or time, or run out of compute, or until you… or until the error rate starts getting worse.

[53:14] Okay, oh, and then in Colab, how do you grab your model? All you need to do in Colab is, after you've exported it, is, if you go into their file browser, you'll actually see it here, right? And you can click download. It's a bit weird, it doesn't like, pop up a box saying where do you want to download it to, but instead this kind of progress circle thing pops up, and so depending on how big it is, and so forth, it can take a few minutes. And once that circle fills up then it'll, the browser thing will finally pop up and say, okay, you can save it. Okay so that's how you…

[53:57] that's how you actually grab your model. So as you can see, the step where you actually need a GPU, you can use these totally free resources: Colab, Kaggle, and there are other ones we'll talk about in future lessons. And then you can do everything else on your own computer, including the predictions, the predictions are fast, right? So, you really don't need to use a GPU for that, unless you're doing thousands of them. Okay, here it goes, now it's asking me to save it. Okay, so now one big issue is, we needed…. to run it on our computer…. we needed python and Jupyter Notebooks running on our computer, so how do you do that?

[54:41] Because this is where often people get in all kinds of trouble…. “I'm, trying to figure out how to get this all working.” So, the good news is we've actually got something that makes it very, very straightforward. It's called fastsetup. There's really only just one part of it you need, so let me show you…. it's… it's… actually a Git repository on Github. Github's the place where most Git repositories live. So if you go to Github fastai/fastsetup you'll see it. And so what you can do is you can now grab this whole repository, just by clicking here on code, and if you've got Github Desktop installed, click on open with Github Desktop and, as you'll see, it brings this up saying: okay I'm ready to save this for you, so I click clone, so it's making a copy of it. There we go.…

[55:39] So, basically, once you've cloned it, you'll then find there's a file in there called setup-conda.sh…. which, you know, the details don't really matter, it's pretty short, but, that's the thing that's going to install python for you. So at that point you can just run “./setup-conda.sh” and it'll run this installer. Now, if you've got Linux or Mac you've already got python on your machine. Don't use that python!!

[56:14] And the reason is because that python, it's called the system python, it's used by your computer to do computery stuff, right? It's actually… it's actually needed. You don't want to be messing with it, I promise you, like… it's, it always leads to disaster, always! You want your own development version of python, it's also going to make sure you've got the latest version, and all the libraries you want, and, by far, the best one for you is almost certainly going to be these conda based python distributions, so if you run setup conda you'll get the one that we recommend. And, the one we recommend at the moment is something called mambaforge. So basically once you run it, you'll find that you've now, — you close your terminal and reopen it — you'll find you've now got one extra command, which is called mamba, and mamba lets you install stuff.

[57:10] So once you've run it, you'll be able to go “mamba install fastai.”. And that's gonna… actually we should probably, I should mention this, actually more, a bit more detail about how to install it correctly. If we go to docs.fast.ai, installing. Yeah, okay, we actually want to do “conda install -c fastchan fastai”. So let's just copy and paste. Oh sorry, not actually… and then, the other thing I'll say is, instead of using conda, replace conda with mamba because nowadays it's much faster. So “mamba install -c fastchan fastai.”.

[57:52] Now, this is going to install everything you need. It's going to install Pytorch, it's going to install Numpy, it's going to install fastai… and so forth, right? And… so obviously I've already got it. And then the other thing you'll want to do is install nbdev, so you can do exactly the same thing for nbdev. You don't have to, right? It's just that… but that'll install Jupyter for you, amongst other things.

[58:28] And so at that point you can now, you can now use Jupyter. And so the way Jupyter works is — you can see it over here. This is my… (I'll go ahead and close it so we can start again.) So basically, to use Jupyter you just type “jupyter notebook”, okay? And when you run it, it'll say: okay, we're now running a server for you, and so if you click on that hyperlink, it'll pop up this, okay?, which is exactly what you see me use all the time. Okay so, you know, that hopefully is enough to kind of get you started with python, and with Jupyter Notebook….

[59:17] The other way people tend to install software is using something called pip instead of mamba. Pretty much anything you can do with mamba you can also do with pip, but if you've got a GPU, pip isn't going to install things generally, so that, it works on your GPU, you have to install lots of other stuff, which is annoying, so, that's why I kind of tell people to use mamba, but you can use pip otherwise. Still a little bit of red. Please let us know how we can help you again.

[59:54] Okay so let's see how we’re going with our steps. I forgot I had these steps here to remind myself. We created a space, tick. We created a basic interface, tick. Okay we got git setup, we got conda set up, or mamba. So mamba and conda are the same thing, mamba is just a much faster version, and we'll keep some notes on the course website, because at the moment they're actually working on including the speed ups from mamba into conda. So at some point, maybe it'll be fine to use conda again. At the moment conda is way too slow, so don't use it.

[1:00:26] Okay we've done dogs versus cats no problem. Yeah so we could also look, at pet breeds (well yeah we'll briefly look at that.) Okay, we've used an exported learner, no problem. We’ve used nbdev, no problem. Oh! okay… try the api… alright this is interesting. So I think we can all agree, hopefully, that this is pretty cool that we can provide to, anybody who wants to use it, for free, a real working model, and you know, with gradio, there's actually, you know, a reasonable amount of flexibility, around like how you can make your, website look, you know, using these various different widgets.

[1:01:22] It's not amazingly flexible, but it's flexible enough to kind of… it's really, just for prototyping, right. So gradio has a lots of widgets and things that you can use. The other main platform at the moment that HuggingFace Spaces supports is called streamlit. streamlit is more flexible, I would say, than gradio - not quite as easy to get started with, but you know, it's kind of that nice in between, I guess, so also a very good thing, you know again mainly for, kind of, building prototypes. But at some point you're going to, want to build more than a prototype. You want to build an app, right, and one of the things, I really like about gradio in HuggingFace Spaces is…. there's a button down here “view the api”. So we can actually create any app we want and the key point is that the thing,

[1:02:27] that does the actual model predictions for us is going to be handled by HuggingFace Spaces Gradio, right, and then we can write a Javascript application that then talks to that. Now there's going to be two reactions here … Anybody who's done some front-end engineering, is going to be like, “oh great, I can now literally create anything in the world, because I just write any code and I can do it and they'll be excited.” And a lot of data scientists, might be going “uh oh… I have no idea how to use javascript, it's not in my, you know, inventory.”

[1:03:07] So this is again where I'm going to say: look, don't be too afraid of Javascript. I. mean obviously one option here is just to kind of say, “hey I've got a model” and throw it over to. the wall to your mate who does know Javascript and say please create a Javascript interface for me. But let me just give you a sense of how really not hard this actually is. So there's a… end point. There's now a url that's running with our model on it. and if you pass it some data… an image… some image data… to this… to this url, it's going to return back the dictionary. So it's going to do exactly the same thing. that this UI does but as an api, as a function we can call.

[1:03:58] And so it's got like, examples here of how to call it… so for example, i can actually.… let me show you the api as an example using that minimal interface we had … because it's. just going to be a bit simpler. So if I click curl and I copy that… copy that… and paste. So you can see there … (oh that's not a great example passing in hello world) …if I pass in. Tanishq again, let's see how I'm going with his name Tanishq.

[1:04:37] Here you can see it returns back “Hello Tanishq!” So this is how these apis work, right. So we can use javascript to call the api and we've got some examples. So I've created a website, and here is my website “tinypets”. and on this website as you can see it's not the most amazingly beautiful thing but it's. a website. It's a start right, and up here I've got some examples, here we go, single file, click, choose file, click… and in this example I'm actually doing full pet classification. So I. actually trained a model to classify breed, which we'll talk about more next week, rather than just dog versus cats. So let's pick a particular breed… and we run it.…

[1:05:41] Oh! And there it is! Now not very amazing right, but the fact is that this is now a Javascript App. means we have no restrictions about what we can do. And let's take a look at that HTML.… that's it! It easily fits in a screen, right, and the basic steps are. not crazy, right, it's basically… we create an import for our photo, we add an event listener that says when you change the photo call the read function, the. read function says create a file reader, read the file and when you finished loading, call loaded, and then loaded says… fetch that… now that path there… is.…

[1:06:39] that path there! Right! Except we're doing the full pets one. So this is basically just copied and pasted from their… from their sample. And then grab the JSON, and then grab from the data the first thing… the confidences… the label, and then set the HTML. So as you can see it's like (okay) if you haven't used javascript before these. are all new things, right, but they're not… it's not harder than python, right, it's just.… it's just another just another language to learn. And so from here you can start to build up, right!

[1:07:20] So for example we've created. a multi-file version. So with the multi-file version, let me show you… multi-file… choose.… so we can now click a few… so we've got a newfie, a ragdoll, a basset hound, and some kind of cat. I'm not much of a cat person. So we chose four files and bang! they've all been classified! Apparently it's a Bengal! (I wouldn't know) Here's our newfoundland.

[1:07:52] So there's the multifile version, and if you look at the code, it's not much more, right, it's now just doing… it's getting all the files and mapping them to read, and now appending each one, so not much more code at all. And as you might have seen on our site here, there's a few more examples, which is some of the community during the week, has created their own versions. So this one here is…. I think this is…. the yeah…. this is from one of the gradio guys... they called it “get to know your pet.” So if i choose a pet… I kind of… I really like this because it actually combines two models. So first of all it says, oh! It's a basset hound, and then it lets me type in and ask things about it. So i can see, “oh, what kind of tail does it have?...” search, and so that's now going to call an NLP model,

[1:08:56] which asks about this… it's a curved saber tail. There we go! “What maintenance does it need?” So again, like here you can kind of see how (oh) a basset hound’s ears must be cleaned inside and out frequently. So this is like combining models.So you can see this is something that you couldn't do with just a kind of a… a ready to go interface. And so the next thing i wanted to point out is how did we create the website? I showed you how to create an HTML file, but like how do you create those, and how do you make a website out of them? Well watch this! Let's… here's…. here's….

[1:09:52] here's the source code to our most basic version, okay! So i could just save this… there we go… Okay so we could open that with Visual Studio Code… and… what we could actually do is, we could… here it just is in explorer or mac & finder. I could just double click on it and here it is! It's a working app!!

[1:10:32] So you can see i don't need any software installed on my computer to use a Javascript App, right! It's a single file… I just run it in a browser… a browser is our complete execution environment. It's a got a debugger. It's got the whole thing. So here you can (yeah) here you can see it's… it's just calling out to this external hacking faces endpoint, so I can do it all sitting here on my computer. So once I've got my HTML file that's working fine on my computer, in VSCode, how do I then put it on the web, so that other people can use it?

[1:11:06] Again, the whole thing's free. There's a really cool thing called github pages, which basically will host your website for you. And because it's just Javascript, it'll… it'll all work just fine! The easiest way to create a github pages site in my opinion, is to use something called fastpages, which is a fast.ai thing! And… basically all you do… is you follow the setup process.

[1:11:43] So first it does it's… let's just go through it… so it says generate a copy by clicking on this link. So I click the link, all right, okay, give it a name…. (I try to make everything public! I always think it's good good practice… you don't have to) …create repo, generating, okay, and then there's basically two more steps, takes about five minutes. We don't have five minutes, so I'll show you the one that I've already built, which is “fast.ai/tinypets” And so once it's done, you'll basically end up with this empty site, which, again, you just go “code” “open with github desktop”, or “open with visual studio”, whatever…. so “open with github desktop”...

[1:12:37] or you can copy & paste this to your terminal…. and, so any one of those is going to get you this whole thing on your computer. You can save your HTML files there…. push it back up to github. And what you'll find is we… we've…, FastPages, will show you the link to the website that is created for you. Now, the website that's created for you, you can make it look however you want using something called a “Theme”. So you'll see it's created a file called config.yml, where you can pick a theme. So, in this case, I picked a theme called “alembic” for no particular reason.

[1:13:18] So Github Pages uses something called “Jekyll”, and so any “Jekyll” theme will, will basically. work. So I picked out this theme, and so, as a result, when I now save things into this repo, they will automatically appear in this website, and the files automatically appear up here in this list. So, if you look at my index, that's the home page…. the entire file is just this, right! The only slightly weird thing is at the top of every Github Pages. file, you have to have three dashes, title, and layout, and three dashes. It's called “front meta”. And so, once you do that… and save it, it will appear in your website. So, something else I did then, I was like, okay, well…. that's all very well that fast.ai has created this website, but I don't really like what it looks like. I want to create a different version.

[1:14:18] No worries. You can go to “fast.ai/tinypets” and click “Fork”. And, when you click “Fork”, it's going to create your own copy. So, I did that under my personal account which is jph00. And look! Now I've got my own version of it, and now I can make changes here. So I made a few changes. One change I made was: I went to config.yml and I changed the theme…. to “pages-themes/hacker”. So once you fork, one thing you have to do, which normally FastPages does for you, is you do have to. go to “Settings”, and click “Pages”, and actually enable “Github Pages”. So you basically have to, by default, it's turned off, so here you'll just have to turn it on. So use the “Master Branch. Root Save”. and then it'll say, “No worries, it's ready to be published”. And so I changed. the config.yml file to point at a different theme. And so, if you look at now…, the jph's Tiny Pets…

[1:15:17] it's different! Okay? So it's got the same info, but it's much more “hackerish” because jph00. is a serious hacker, as you can tell from his website. So, anyway, look, it's a very brief taste of this kind of world of Javascript and websites and so, forth, but I wanted to give you a sense of, like, you know, you don't need any money. You don't need any IDEs. You know, you don't really need much code to get started with writing your own web. apps, and, thanks to hugging face spaces, you know, they'll even host your model. for you and all you need to do is just have the magic string, as a thing to call. Okay!

[1:16:07] So… signing out: Hacker Jeremy Howard. Thanks very much for, watching, and, in the next lesson, we're going to be digging into some natural language processing. We're going to be doing some of the same stuff, but we're going to be doing it with language rather than pictures. And we're going to be diving under the hood to see how these models actually work. We're going to learn about things like stochastic gradient descent, and we might even be having to brush off a little bit of calculus. I hope I haven't put you off by saying the “C” word.

[1:16:38] I will see you next time! Thanks all! Bye!

Abrir en el lector de Vidleaf

Busca citas exactas entre comillas, compara subtítulos bilingües y exporta TXT, SRT o Markdown con marcas de tiempo.

Atribución y licencia

«Lesson 2: Practical Deep Learning for Coders 2022» por Jeremy Howard (https://www.youtube.com/@howardjeremyp), con licencia CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Vídeo original: https://www.youtube.com/watch?v=F4tvM4Vb3A0. Esta página presenta una transcripción con marcas de tiempo; la persona o entidad creadora no está afiliada a Vidleaf ni lo avala.

¿Eres el autor o titular de derechos? Solicita correcciones o retirada en copyright@vidleaf.app.

Última actualización