Nouvelle publication

Rechercher

Annonce
· Avr 14

Queda menos de un mes para el concurso de artículos técnicos en español ¡Grandes premios!

Hola a todos!! 

Como sabéis, el concurso de artículos técnicos estará activo desde el 12 de mayo. Tendréis algunas semanas para publicar vuestro contenido. No obstante, os recomiendo que vayáis pensando y trabajando en él.

Dentro de muy poco publicaremos las bases del concurso, incluyendo los premios a los ganadores (son fantásticos, ya os aviso). 

Esperamos que este año os animéis a darle forma a esas grandes ideas que tenéis en la cabeza. Es una gran oportunidad para publicar un primer artículo para los más tímidos, y para seguir dando cátedra los más veteranos.

¡Gracias! ¡QUEDA MUY POCO! 📝🎉

Discussion (0)1
Connectez-vous ou inscrivez-vous pour continuer
Article
· Avr 14 15m de lecture

InterSystems para dummies – Machine learning

 

Como todos sabemos, InterSystems es una gran empresa.

Sus productos pueden ser tan útiles como complejos.

Sin embargo, a veces nuestro orgullo nos impide admitir que quizá no entendamos algunos conceptos o productos que InterSystems nos ofrece.

Hoy comenzamos una serie de artículos que explican, de forma sencilla y clara, cómo funcionan algunos de los complejos productos de InterSystems.

En este ensayo, aclararé qué es el Machine Learning y cómo aprovecharlo... porque esta vez, SABRÁS con certeza de qué estoy hablando.

¿Qué (demonios) es Machine Learning?

El Machine Learning (aprendizaje automático) es una rama de la inteligencia artificial que se centra en el desarrollo de algoritmos y modelos que permiten a las computadoras aprender a realizar tareas específicas basadas en datos, sin necesidad de ser programadas explícitamente para cada tarea. En lugar de seguir instrucciones específicas, las máquinas aprenden a través de la experiencia, identificando patrones en los datos y haciendo predicciones o tomando decisiones basadas en ellos.

El proceso implica alimentar algoritmos con conjuntos de datos (llamados conjuntos de entrenamiento) para que aprendan y mejoren su rendimiento con el tiempo. Estos algoritmos pueden diseñarse para realizar una amplia gama de tareas, como el reconocimiento de imágenes, el procesamiento del lenguaje natural, la predicción de tendencias financieras, el diagnóstico médico y mucho más.

En resumen, el Machine Learning permite a las computadoras aprender de los datos y mejorar con la experiencia, lo que les permite realizar tareas complejas sin necesidad de una programación explícita para cada situación de forma autónoma...

Es una definición muy interesante. Sin embargo, supongo que necesitas un ejemplo, así que aquí vamos:

Bueno, imagina que cada día escribes en algún lugar la hora del amanecer y del atardecer. Si alguien te preguntara si el sol saldrá al día siguiente, ¿qué dirías? Solo has anotado la hora del amanecer y el atardecer.

Al observar tus datos, concluirías que, con un 100% de probabilidad, el sol saldrá mañana. Sin embargo, no puedes ignorar que existe la posibilidad de que, debido a una catástrofe natural, no puedas ver el amanecer al día siguiente. Por eso, deberías decir que la probabilidad de presenciar un amanecer al día siguiente es, de hecho, del 99,99%.

Considerando tu experiencia personal, puedes proporcionar una respuesta que coincida con tus datos. El Machine Learning es lo mismo, pero realizado por una computadora.

Observa la tabla a continuación:

A B
1 2
2 4
3 6
4 8

¿Cómo se relacionan las columnas A y B?

La respuesta es sencilla: el valor de B es el doble del de A. B=A*2 es un patrón.

Ahora, examine la otra tabla:

A B
1 5
2 7
3 9
4 11

Este es un poco más complicado… Si no has descubierto el patrón, es B=(A*2) +3.

Un humano, por ejemplo, puede deducir la fórmula, lo que significa que cuantos más datos tengas, más fácil será adivinar el patrón que se esconde tras este misterio.

Así pues, el Machine Learning utiliza la misma lógica para revelar el patrón oculto en los datos.

¿Cómo empezar?

Primero, necesitarás un ordenador. Sí, dado que este artículo trata sobre Machine Learning, tener solo un cuaderno y un lápiz no será suficiente.

En segundo lugar, necesitará una instancia de IRIS Community. Puede descargar una imagen de Docker y ejecutar su prueba aquí. Tenga en cuenta que debe tener ML integrado, por ejemplo, la última versión de InterSystems IRIS Community.

docker pull intersystems/iris-ml-community:latest-em

o

docker pull intersystems/iris-community:latest

Si lo necesitas en otra plataforma, consulta en https://hub.docker.com/r/intersystems/iris-ml-community/tags o en https://hub.docker.com/r/intersystems/iris-community/tags.

Luego, crea un contenedor a partir de este contenedor y ejecútalo:

docker run --name iris-ml -d --publish 1972:1972 --publish 52773:52773 intersystems/iris-m

 

Si eres de la vieja escuela, puedes descargar una versión gratuita para evaluarla. Sin embargo, es importante tener una cuenta de InterSystems. Consúltala en https://login.intersystems.com/login/SSO.UI.Register.cls.

Posteriormente, solicite una copia de evaluación en https://evaluation.intersystems.com/Eval/.

   

Instálalo y ejecuta tu instancia.

Ahora, accede al portal de IRIS: http://localhost:52773/csp/user/EnsPortal.ProductionConfig.zen

  • Usuario: Superusuario
  • Contraseña: SYS

Nota: Es posible que se te pida cambiar la contraseña la primera vez. No te preocupes, crea una contraseña que puedas recordar fácilmente.

Abre la "Configuración de Machine Learning" para revisar las versiones instaladas.

   

En este punto, puedes ver las configuraciones del proveedor de ML instaladas.

   

Earth, "water" and fire... ¿Cuál es la mejor?

Todos son buenos. Lo importante es cómo entrenar a tu dragón, es decir... tus datos.

Busca más información sobre los modelos existentes:

AutoML: AutoML es un sistema automatizado de aprendizaje automático desarrollado por InterSystems y alojado en la plataforma de datos InterSystems IRIS®. Está diseñado para crear rápidamente modelos predictivos precisos utilizando tus datos. Automatiza varios componentes clave del proceso de aprendizaje automático.

Haz clic en el siguiente enlace para obtener más información: https://docs.intersystems.com/iris20241/csp/docbook/Doc.View.cls?KEY=GAUTOML_Intro

H2O: Es un modelo de aprendizaje automático de código abierto. El proveedor H2O no admite la creación de modelos de series temporales.

Siga el siguiente enlace para obtener más información: https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=GIML_Configuration_Providers#GIML_Configuration_Providers_H2O

PMML: (Lenguaje de Marcado de Modelado Predictivo). Es un estándar basado en XML que expresa modelos analíticos. Permite a las aplicaciones definir modelos estadísticos y de minería de datos, de modo que puedan reutilizarse y compartirse fácilmente.

Para más información, consulte el siguiente enlace: https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=APMML

 

¿Cuál es el primer paso?

Al igual que en el ejemplo del amanecer y el atardecer, necesitamos datos para entrenar nuestro modelo.

Es fundamental conocer el objetivo de los datos y los valores que se deben predecir. También es crucial tener datos claros y sin duplicados. También debes averiguar cuál es el conjunto mínimo de datos.

Voy a usar el proveedor AutoML porque es de Intersystems, ¡jaja! 😉

Existen varios tipos de algoritmos:

Árboles de decisión: Primero se clasifica la información y luego se aplica la siguiente pregunta para evaluar la probabilidad. Ejemplo: ¿Lloverá mañana? Comprueba si el cielo está nublado (muy o ligeramente nublado) o despejado. Si está muy nublado, comprueba la humedad. Después, comprueba la temperatura... Si está muy nublado, con alta humedad y baja temperatura, mañana lloverá.

Bosques aleatorios: Se trata de un conjunto de árboles de decisión, cada uno de los cuales "vota" por una clase. La mayoría de los votos define el modelo seleccionado.

Redes neuronales: Esto no significa que Skynet esté por llegar... Sin embargo, es demasiado complejo para explicarlo en pocas palabras. La idea general es "copiar" la función de las neuronas humanas. Esto significa que cada dato de entrada es analizado por una "neurona", que, a su vez, proporciona los datos de entrada a la siguiente "neurona" para analizar los datos de salida.

Si quieres experimentar con redes neuronales usando Python, puedes crear una y comprobar su funcionamiento. Consulta https://colab.research.google.com/drive/1XJ-Lph5auvoK1M4kcHZvkikOqZlmbytI?usp=sharing.

A través del enlace anterior, puedes ejecutar una rutina en Python con la ayuda de la biblioteca TensorFlow. Para obtener el patrón de las tablas A y B, haz lo siguiente:

import tensorflow as tf
import numpy as np

tableA = np.array([1, 2, 3, 4, 5, 6, 7], dtype=float)
tableB = np.array([5, 7, 9, 11, 13, 15, 17], dtype=float)

hidden1 = tf.keras.layers.Dense(units=3, input_shape=[1])
hidden2 = tf.keras.layers.Dense(units=3)
exit = tf.keras.layers.Dense(units=1)
model = tf.keras.Sequential([hidden1, hidden2, exit])

model.compile(
    optimizer=tf.keras.optimizers.Adam(0.1),
    loss='mean_squared_error'
)

print("Start training...")
history = model.fit(tableA, tableB, epochs=1000, verbose=False)
print("Model trained!")

import matplotlib.pyplot as plt
plt.xlabel("# Epoch")
plt.ylabel("Loss magnitud")
plt.plot(history.history["loss"])

print("Doing a predicction!")
result = model.predict([100])
print("The result is " + str(result) )

print("Internal variables of the model")
print(hidden1.get_weights())
print(hidden2.get_weights())
print(exit.get_weights())

El código anterior utiliza los valores de A y B para crear un modelo que compara y determina la relación entre ambos valores.

Una vez realizada la predicción, se obtiene el valor correcto; en este ejemplo, la predicción es 203.

¿Cómo funciona en IRIS?

El Machine Learning en IRIS se denomina "integratedML". Se implementó desde InterSystems IRIS 2023.2 como una función experimental, lo que significa que no es compatible con entornos de producción. Sin embargo, esta función ha sido ampliamente probada e InterSystems cree que puede aportar un valor significativo a los clientes. Puede encontrar más información en la documentación sobre el uso de integratedML.

Aun así, dado que esta es una lección de Machine Learning para principiantes, explicaré su funcionamiento de la forma más sencilla posible.

Nota: Estoy utilizando un contenedor con una imagen de containers.intersystems.com/iris-ml-community

docker pull containers.intersystems.com/iris-ml-community

Puede descargar la imagen y ejemplos de IRIS desde https://github.com/KurroLopez/iris-mll-fordummies.

📣SUGERENCIA: Puedes abrir el terminal desde Docker con el siguiente comando:
docker-compose exec iris iris session iris

Estudio de Sleepland University

La Universidad Sleepland ha realizado una amplia investigación sobre el insomnio, realizando miles de entrevistas y creando una base de datos con diversos parámetros de pacientes con y sin insomnio.

Los datos recopilados incluyen lo siguiente:

  • Género (masculino/femenino)
  • Edad (edad de la persona en años)
  • Ocupación (ocupación o profesión de la persona)
  • Duración del sueño (horas que la persona duerme al día)
  • Calidad del sueño (puntuación subjetiva de la calidad del sueño, del 1 al 10)
  • Nivel de actividad física (minutos que la persona realiza actividad física al día)
  • Nivel de estrés (puntuación subjetiva del nivel de estrés que experimenta la persona, del 1 al 10)
  • Categoría del IMC (categoría del IMC de la persona: bajo peso, normal, sobrepeso)
  • Sistólica (presión arterial sistólica)
  • Diastólica (presión arterial diastólica)
  • Frecuencia cardíaca (frecuencia cardíaca en reposo de la persona en latidos por minuto)
  • Pasos diarios (pasos que la persona da al día)
  • Trastorno del sueño (ninguno, insomnio, apnea del sueño)

Para el primer ejemplo, creé una clase (St.MLL.insomniaBase) con las columnas mencionadas anteriormente:

Class St.MLL.insonmniaBase Extends %Persistent
{

/// Gender of patient (male/female)
Property Gender As %String;
/// The age of the person in years
Property Age As %Integer;
/// The occupation or profession of the person
Property Occupation As %String;
/// The number of hours the person sleeps per day
Property SleepDuration As %Numeric(SCALE = 2);
/// A subjective rating of the quality of sleep, ranging from 1 to 10
Property QualitySleep As %Integer;
/// The number of minutes the person engages in physical activity daily
Property PhysicalActivityLevel As %Integer;
/// A subjective rating of the stress level experienced by the person, ranging from 1 to 10
Property StressLevel As %Integer;
/// The BMI category of the person: Underweight, Normal, Overweight
Property BMICategory As %String;
/// Systolic blood pressure
Property Systolic As %Integer;
/// Diastolic blood pressure
Property Diastolic As %Integer;
/// The resting heart rate of the person in BPM
Property HeartRate As %Integer;
/// The number of steps the person takes per day
Property DailySteps As %Integer;
/// None, Insomnia, Sleep Apnea
Property SleepDisorder As %String;
}

Luego, creé algunas clases derivadas de insomniaBase: insomnia01, insomniaValidate01 e insomniaTest01. Esto me permitió tener las mismas columnas para cada tabla.

Eventualmente, necesitaremos rellenar nuestras tablas con valores de muestra, así que diseñé un método de clase para tal fin.

Class St.MLL.insomnia01 Extends St.MLL.insomniaBase
{

/// Populate values
ClassMethod Populate() As %Status
{
    write "Init populate "_$CLASSNAME(),!
    &sql(TRUNCATE TABLE St_MLL.insomnia01)
……
    write $CLASSNAME()_" populated",!
    Return $$$OK
}
📣SUGERENCIA: Para abrir el terminal, escriba el siguiente comando:
docker-compose exec iris iris session iris

Usando el terminal, llame al método Populate de esta clase

Do ##class(St.MLL.insomnia01).Populate()

Si hacemos todo correctamente, tendremos una tabla con los valores para entrenar nuestro ML.

También necesitamos crear una nueva tabla para la validación. Es fácil, ya que solo se necesita una parte de los datos proporcionados para el entrenamiento. En este caso, será el 50% de los elementos.

Por favor, ejecute la siguiente sentencia en la terminal.

Do ##class(St.MLL.insomniaValidate01).Populate()

Por último, prepararemos algunos datos de prueba para ver los resultados de nuestro entrenamiento.

Do ##class(St.MLL.insomniaTest01).Populate()

Entrena, entrena y entrena... te volverás más fuerte

Ahora tenemos todos los datos necesarios para entrenar nuestro modelo. ¿Cómo hacerlo?

Solo necesitas 4 sencillas instrucciones:

  • CREATE MODEL
  • TRAIN MODEL
  • VALIDATE MODEL
  • SELECT PREDICT

Creando el modelo

CREATE MODEL crea los metadatos del modelo de Machine Learning especificando el nombre del modelo, el campo de destino que se predecirá y el conjunto de datos que proporcionará el campo de destino.

En nuestra muestra disponemos de algunos parámetros para evaluar los trastornos del sueño por lo que diseñaremos los siguientes modelos:

  • insomnia01SleepModel: Por género, edad, duración del sueño y calidad del sueño.
    • Comprueba si la edad y los hábitos de sueño afectan a algún tipo de trastorno del sueño.
  • insomnia01BMIModel: Por género, edad, ocupación y categoría de IMC.
    • Examinar si la edad, la ocupación y el IMC afectan algún tipo de trastorno del sueño.
  • insomnia01AllModel: Todos los factores.
    • Inspeccione si todos los factores afectan algún tipo de trastorno del sueño.

Ahora vamos a crear todos esos modelos.

Utilizando la gestión de SQL en el portal de IRIS, escriba la siguiente frase:

CREATE MODEL insomnia01AllModel PREDICTING (SleepDisorder) From St_MLL.insomnia01

En este punto, nuestro modelo sabe qué columna predecir.

Puede comprobar qué se creó y qué contiene la columna de predicción con la siguiente sentencia:

SELECT * FROM INFORMATION_SCHEMA.ML_MODELS 

 

Asegúrese de que el nombre de la columna de predicción y las propias columnas sean correctos.

Sin embargo, también queremos agregar diferentes tipos de modelos, ya que deseamos predecir los trastornos del sueño según otros factores, no todos los campos.

En este caso, usaremos la cláusula "WITH" para especificar las columnas que se usarán como parámetros para realizar la predicción.

Para utilizar la cláusula "WITH", debemos indicar el nombre de las columnas y su tipo.

CREATE MODEL insomnia01SleepModel PREDICTING (SleepDisorder) WITH(Gender varchar, Age integer, SleepDuration numeric, QualitySleep integer) FROM St_MLL.insomnia01
CREATE MODEL insomnia01BMIModel PREDICTING (SleepDisorder) WITH(Gender varchar, Age integer, Occupation varchar, BMICategory varchar) FROM St_MLL.insomnia01

 Asegúrese de que todos esos modelos se hayan creado correctamente.

Entrenando el modelo

El comando TRAIN MODEL ejecuta el motor AutoML y especifica los datos que se utilizarán para el entrenamiento. La sintaxis FROM es genérica y permite entrenar el mismo modelo varias veces con distintos conjuntos de datos. Por ejemplo, se puede entrenar una tabla con datos de la Universidad Sleepland o la Universidad Napcity. Sin embargo, lo más importante es que el modelo de datos tenga los mismos campos, el mismo nombre y el mismo tipo.

El motor AutoML realiza automáticamente todas las tareas de aprendizaje automático necesarias. Identifica las características candidatas relevantes de los datos seleccionados, evalúa los tipos de modelos viables según los datos y la definición del problema, y ​​establece hiperparámetros para crear uno o más modelos viables.

Como nuestro modelo tiene 50 registros, es suficiente para dicho entrenamiento.

TRAIN MODEL insomnia01AllModel FROM St_MLL.insomnia01

 

Haz lo mismo con los otros modelos.

TRAIN MODEL insomnia01SleepModel FROM St_MLL.insomnia01
TRAIN MODEL insomnia01BMIModel FROM St_MLL.insomnia01

Puedes saber si tu modelo ha sido entrenado correctamente con la siguiente sentencia:

SELECT * FROM INFORMATION_SCHEMA.ML_TRAINED_MODELS

 

Es necesario validar el modelo y el entrenamiento con el comando VALIDATE MODEL.

Validando el modelo

En esta etapa, necesitamos confirmar que el modelo se haya entrenado correctamente. Por lo tanto, debemos ejecutar el comando VALIDATE MODEL.

📣Recuerda: antes de completar la clase, valídela con el 50% de los datos de la fuente de datos de entrenamiento.

VALIDATE MODELdevuelve métricas simples para modelos de regresión, clasificación y series temporales, basándose en el conjunto de pruebas proporcionado.

Compruebe lo que se ha validado con la siguiente sentencia:

VALIDATE MODEL insomnia01AllModel From St_MLL.insomniaValidate01

 

Repítelo con otros modelos.

VALIDATE MODEL insomnia01SleepModel FROM St_MLL.insomniaValidate01
VALIDATE MODEL insomnia01BMIModel FROM St_MLL.insomniaValidate01

Consumiendo el modelo

Ahora, consumiremos este modelo e inspeccionaremos si ha aprendido correctamente cómo generar el valor del resultado.

Con la instrucción "SELECT PREDICT", pronosticaremos el valor del resultado. Para ello, usaremos la tabla test1 que ya se rellenó.

SELECT *, PREDICT(insomnia01AllModel) FROM St_MLL.insomniaTest01

El resultado parece extraño después de utilizar el 50% de los datos explotados para entrenar el modelo... ¿Por qué se le diagnosticó insomnio a una enfermera de 29 años, mientras que el modelo predijo apnea del sueño? (ver ID 54).

Deberíamos examinar otros modelos (insomnia01SleepModel e insomnia01BMIModel), creados con diferentes columnas, pero no se preocupen. Te mostraré las columnas utilizadas para diseñarlos.

SELECT Gender, Age, SleepDuration, QualitySleep, SleepDisorder, PREDICT(insomnia01SleepModel) As SleepDisorderPrediction FROM St_MLL.insomniaTest01

 

Se puede ver de nuevo que a una mujer de 29 años se le ha diagnosticado «insomnio», mientras que la predicción indica «apnea del sueño».

¡Tienes razón! También necesitamos saber qué porcentaje de la predicción se ha aplicado a este valor final.

¿Cómo podemos saber el porcentaje de una predicción?

Para saber el porcentaje de la predicción, debemos de usar el comando PROBABILITY”. 

Este comando recupera un valor entre 0 y 1. Sin embargo, no se trata de la probabilidad de predicción, sino de la probabilidad de obtener el valor que se desea comprobar.

Este es un buen ejemplo:

SELECT *, PREDICT(insomnia01AllModel) As SleepDisorderPrediction, PROBABILITY(insomnia01AllModel FOR 'Insomnia') as ProbabilityPrediction FROM St_MLL.insomniaTest01

Es la probabilidad de padecer “insomnio” como trastorno del sueño.

Nuestra enfermera, una mujer de 29 años, diagnosticada con insomnio, tiene un 49,71% de probabilidades de padecerlo. Aun así, la predicción es apnea del sueño… ¿Por qué?

¿Es la misma probabilidad para otros modelos?

SELECT Gender, Age, SleepDuration, QualitySleep, SleepDisorder, PREDICT(insomnia01SleepModel) As SleepDisorderPrediction, PROBABILITY(insomnia01SleepModel FOR 'Insomnia') as ProbabilityInsomnia,
PROBABILITY(insomnia01SleepModel FOR 'Sleep Apnea') as ProbabilityApnea
FROM St_MLL.insomniaTest01

 

Por fin, ahora está un poco más claro. Según los datos (sexo, edad, calidad y duración del sueño), la probabilidad de tener insomnio es de tan solo el 34,63%, mientras que la de tener apnea del sueño es del 64,18%.

¡Guau! ¡Es muy interesante! Aun así, solo estábamos explotando una pequeña parte de los datos insertados directamente en una tabla con un método de clase... ¿Cómo podemos subir un archivo tan grande con datos?

¡Esperen el próximo artículo! ¡Próximamente!

Discussion (0)1
Connectez-vous ou inscrivez-vous pour continuer
Article
· Avr 14 14m de lecture

InterSystems for dummies – Machine learning

 

As we all know, InterSystems is a great company.

Their products can be just as useful as they are complex.

Yet, our pride sometimes prevents us from admitting that we might not understand some concepts or products that InterSystems offers for us.

Today we are beginning a series of articles explaining how some of the intricate InterSystems products work, obviously simply and clearly.

In this essay, I will clarify what Machine Learning is and how to take advantage of it.... because this time, you WILL KNOW for sure what I am talking about.

What (the hell) is Machine Learning?

Machine Learning is a branch of artificial intelligence that focuses on developing algorithms and models that enable computers to learn to perform specific tasks based on data, without being explicitly programmed for each task. Instead of following specific instructions, machines learn through experience, identifying patterns in data and making predictions or decisions based on them.

The process involves feeding algorithms with datasets (called training sets) to make them learn and improve their performance over time. Those algorithms can be designed to perform a wide range of tasks, including image recognition, natural language processing, financial trend prediction, medical diagnosis, and much more.

In summary, Machine Learning allows computers to learn from data and improve with experience, enabling them to perform complex tasks without explicit programming for each situation autonomously...

It is a lovely definition. Yet, I guess you need an example, so here we go:

Well, imagine that every day you write down somewhere the time of sunrise and sunset. If somebody asked you whether the sun would rise the next day, what would you say? All you have noticed was only the time of sunrise and sunset..

By observing your data, you would conclude that with 100% probability, the sun will rise tomorrow. However, you cannot ignore the fact that there is a chance that, due to a natural catastrophe, you will not be able to see the sun rising the next day. That is why you should say that the likelihood of witnessing a sunrise the following day is, in fact, 99.99%.

Considering your personal experience, you can provide an answer that matches your data. Machine Learning is the same thing but done by a computer..

Look at the table below:

A B
1 2
2 4
3 6
4 8

How do columns A and B relate to each other?

The answer is easy, the value of B is double the A. B=A*2, is a pattern.

Now, examine the other table:

A B
1 5
2 7
3 9
4 11

This one is a bit more complicated…. If you haven't uncovered the pattern, it is B=(A*2) +3.

A human, for instance, can deduce the formula, meaning that the more data you have, the easier it is to guess the pattern behind this mystery.

So, Machine Learning uses the same logic to reveal the pattern hidden in the data.

How to start?

First, you will need a computer, Yes, since this article is about Machine Learning, having only a notebook and a pencil will not be enough.

Second, you will require an instance of IRIS Community. You can download a Docker image and execute your test here. Note, that it must have ML integrated, e.g., the latest version of InterSystems IRIS Community:

docker pull intersystems/iris-ml-community:latest-em

or

docker pull intersystems/iris-community:latest

If you need another platform, check https://hub.docker.com/r/intersystems/iris-ml-community/tags or https://hub.docker.com/r/intersystems/iris-community/tags.

Then, create a container from this container and run it:

docker run --name iris-ml -d --publish 1972:1972 --publish 52773:52773 intersystems/iris-m

 

If you are "old-school", you can download a free version for evaluation. Yet, it is important to have an InterSystems account. Check it out at https://login.intersystems.com/login/SSO.UI.Register.cls.

Afterward, ask for an evaluation copy at https://evaluation.intersystems.com/Eval/.

   

Install it and run your instance.

Now, access the IRIS portal. http://localhost:52773/csp/user/EnsPortal.ProductionConfig.zen

  • User: Superuser
  • Pass: SYS

Note: You might be asked to change the password the first time. Do not be afraid, just come up with a password that you can easily remember.

Open the "Machine learning configuration" to review the versions you installed.

   

At this point, you can see the provider configurations of ML installed.

   

Earth, "water" and fire... what is the best?

All of them are good. The important thing is how to train your dragon, I mean... your data.

Explore more info about the existing models:

AutoML: AutoML is an automated Machine Learning system developed by InterSystems and housed within the InterSystems IRIS® data platform. It is designed to build accurate predictive models quickly using your data. It automates several key components of the machine-learning process.

Click the link below to see more info: https://docs.intersystems.com/iris20241/csp/docbook/Doc.View.cls?KEY=GAUTOML_Intro

H2O: It is an open-source Machine Learning model. The H2O provider does not support the creation of time series models.

Follow the link below to discover more: https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=GIML_Configuration_Providers#GIML_Configuration_Providers_H2O

PMML: (Predictive Modelling Markup Language). It is an XML-based standard that expresses analytics models. It provides a way for applications to define statistical and data mining models so that they can be easily reused and shared.

Check out the link below for more info: https://docs.intersystems.com/irislatest/csp/docbook/DocBook.UI.Page.cls?KEY=APMML

What is the first step?

Just like in the sunset and sunrise example, we need some data to train our model.

It is essential to know the data objective and the values that should be predicted. It is also critical to have clear data without any duplicates. You must find out what the minimum set of data is as well.

I am going to use the AutoML provider because it is from Intersystems, ha-ha 😉

There are a few kinds of algorithms:

Decision trees: First, the information is classified, then the next question is applied to evaluate the probability. Example: Will it rain tomorrow? Check if the sky is cloudy (very or slightly) or clear. If it is very cloudy, then check the humidity. After that, check the temperature... If it is very cloudy, with high humidity and low temperature, then it will rain tomorrow..

Random forests: It is a set of decision trees, each of which "votes" for a class. The majority of the votes define the selected model.

Neural networks: It does not mean that Skynet is coming... However, it is too complicated to explain in just a few words. The general idea is to "copy" the function of human neurons. It means that each input data gets analyzed by a "neuron", which, in turn, provides the input data to the next "neuron" to analyze the output data.

If you wish to play around with neural networks using Python, you can create one and check how it works. Please, have a look at https://colab.research.google.com/drive/1XJ-Lph5auvoK1M4kcHZvkikOqZlmbytI?usp=sharing.

Through the link above, you can run a routine in Python, with the help of the TensorFlow library. To get the pattern of tables A and B do the following:

import tensorflow as tf
import numpy as np

tableA = np.array([1, 2, 3, 4, 5, 6, 7], dtype=float)
tableB = np.array([5, 7, 9, 11, 13, 15, 17], dtype=float)

hidden1 = tf.keras.layers.Dense(units=3, input_shape=[1])
hidden2 = tf.keras.layers.Dense(units=3)
exit = tf.keras.layers.Dense(units=1)
model = tf.keras.Sequential([hidden1, hidden2, exit])

model.compile(
    optimizer=tf.keras.optimizers.Adam(0.1),
    loss='mean_squared_error'
)

print("Start training...")
history = model.fit(tableA, tableB, epochs=1000, verbose=False)
print("Model trained!")

import matplotlib.pyplot as plt
plt.xlabel("# Epoch")
plt.ylabel("Loss magnitud")
plt.plot(history.history["loss"])

print("Doing a predicction!")
result = model.predict([100])
print("The result is " + str(result) )

print("Internal variables of the model")
print(hidden1.get_weights())
print(hidden2.get_weights())
print(exit.get_weights())

The code above utilizes the values of A and B to create a model to compare and discover the relation between both values.

When I have done the prediction, it retrieves the correct value, in this sample the prediction is 203.

How does it work in IRIS?

Machine Learning in IRIS is called “integratedML”. It has been implemented since InterSystems IRIS 2023.2 as an Experimental Feature, meaning that it is not supported for production environments. However, the feature is well-tested, and InterSystems believes it can add significant value to customers. You can find more information in Using integratedML documentation.

Still, since this is an ML lesson for beginners, I will explain how to operate it as simply as possible.

Note: I am utilizing a docker with an image from containers.intersystems.com/iris-ml-community

docker pull containers.intersystems.com/iris-ml-community

You can download the IRIS image and samples from https://github.com/KurroLopez/iris-mll-fordummies.

📣TIP: You can open the terminal from Docker with the following command:
docker-compose exec iris iris session iris

Sleepland University studio

Sleepland University has done extensive research on insomnia, conducting thousands of interviews and building a database with various parameters of patients with and without sleeplessness.

The collected data includes the following:

  • Gender (male/female)
  • Age (The age of the person in years)
  • Occupation (The occupation or profession of the person)
  • Sleep Duration (The number of hours the person sleeps per day)
  • Quality of Sleep (A subjective rating of the quality of sleep, ranging from 1 to 10)
  • Physical Activity Level (The number of minutes the person engages in physical activity daily)
  • Stress Level (A subjective rating of the stress level experienced by the person, ranging from 1 to 10)
  • BMI Category (The BMI category of the person: Underweight, Normal, Overweight)
  • Systolic (Systolic blood pressure)
  • Diastolic (Diastolic blood pressure)
  • Heart Rate (The resting heart rate of the person in BPM)
  • Daily Steps (The number of steps the person takes per day)
  • Sleep Disorder (None, Insomnia, Sleep Apnea)

For the first sample, I created a class (St.MLL.insomniaBase) with the columns mentioned above:

Class St.MLL.insonmniaBase Extends %Persistent
{

/// Gender of patient (male/female)
Property Gender As %String;
/// The age of the person in years
Property Age As %Integer;
/// The occupation or profession of the person
Property Occupation As %String;
/// The number of hours the person sleeps per day
Property SleepDuration As %Numeric(SCALE = 2);
/// A subjective rating of the quality of sleep, ranging from 1 to 10
Property QualitySleep As %Integer;
/// The number of minutes the person engages in physical activity daily
Property PhysicalActivityLevel As %Integer;
/// A subjective rating of the stress level experienced by the person, ranging from 1 to 10
Property StressLevel As %Integer;
/// The BMI category of the person: Underweight, Normal, Overweight
Property BMICategory As %String;
/// Systolic blood pressure
Property Systolic As %Integer;
/// Diastolic blood pressure
Property Diastolic As %Integer;
/// The resting heart rate of the person in BPM
Property HeartRate As %Integer;
/// The number of steps the person takes per day
Property DailySteps As %Integer;
/// None, Insomnia, Sleep Apnea
Property SleepDisorder As %String;
}

Then, I built some classes extending from insomniaBase called insomnia01, insomniaValidate01, and insomniaTest01. It allowed me to have the same columns for each table.

Eventually, we will need to populate our tables with sample values, so I designed a class method for that purpose.

Class St.MLL.insomnia01 Extends St.MLL.insomniaBase
{

/// Populate values
ClassMethod Populate() As %Status
{
    write "Init populate "_$CLASSNAME(),!
    &sql(TRUNCATE TABLE St_MLL.insomnia01)
……
    write $CLASSNAME()_" populated",!
    Return $$$OK
}
📣TIP: To open the terminal, type the following command:
docker-compose exec iris iris session iris

Using the terminal, call the method Populate of this class

Do ##class(St.MLL.insomnia01).Populate()

If we do everything right, we will have a table with the values for training our ML.

We also need to create a new table for validation. It is easy because you will only require a part of the data provided for the training. In this case, it will be 50% of the items.

Please, run the following sentence in the terminal.

Do ##class(St.MLL.insomniaValidate01).Populate()

Finally, we will prepare some test data to see the results of our training.

Do ##class(St.MLL.insomniaTest01).Populate()

Train, train, and train... you will become stronger

Now, we have all the data needed to train our model. How to do it?

You will only need 4 simple instructions:

  • CREATE MODEL
  • TRAIN MODEL
  • VALIDATE MODEL
  • SELECT PREDICT

Creating the model

CREATE MODEL creates the Machine Learning model metadata by specifying the model’s name, the target field to be predicted, and the dataset that will supply the target field.

In our sample, we have some parameters to evaluate sleep disorders so we will design the following models:

  • insomnia01SleepModel: By gender, age, sleep duration and quality of sleep.
    • Check if the age and sleeping habits affect any sleep disorder type.
  • insomnia01BMIModel: By gender, age, occupation and BMI category.
    • Examine whether age, occupation and BMI affect any sleep disorder type.
  • insomnia01AllModel: All factors
    • Inspect if all factors affect any sleep disorder type..

We are going to create all those models now.

Using SQL management in IRIS portal, type the following sentence:

CREATE MODEL insomnia01AllModel PREDICTING (SleepDisorder) From St_MLL.insomnia01

At this point, our model knows which column to predict.

You can check what was created and what the predicting column contains with the sentence below:

SELECT * FROM INFORMATION_SCHEMA.ML_MODELS 

 

Ensure that the predicting column name and the columns themselves are correct.

However, we also want to add different model types since we wish to predict sleep disorders according to other factors, not all fields.

In this case, we are going to use the "WITH" clause to specify the columns that should be used as parameters to make the prediction. 

To utilize the "WITH" clause, we must indicate the name of the columns and their type.

CREATE MODEL insomnia01SleepModel PREDICTING (SleepDisorder) WITH(Gender varchar, Age integer, SleepDuration numeric, QualitySleep integer) FROM St_MLL.insomnia01
CREATE MODEL insomnia01BMIModel PREDICTING (SleepDisorder) WITH(Gender varchar, Age integer, Occupation varchar, BMICategory varchar) FROM St_MLL.insomnia01

 Make sure that all those models have been successfully created.

Training the model

The TRAIN MODEL command runs the AutoML engine and specifies the data that will be used for training. FROM syntax is generic and allows the same model to be trained multiple times on various data sets. For instance, you may train a table with data from Sleepland University or Napcity University. The most important thing though is to have the data model with the same fields, same name, and the same type.

The AutoML engine automatically performs all necessary machine-learning tasks. It identifies relevant candidate features from the selected data, evaluates feasible model types based on the data and problem definition, and sets hyperparameters to create one or more viable models.

Since our model has 50 records, it is enough for such training.
 

TRAIN MODEL insomnia01AllModel FROM St_MLL.insomnia01

 

Do the same with other models.

TRAIN MODEL insomnia01SleepModel FROM St_MLL.insomnia01
TRAIN MODEL insomnia01BMIModel FROM St_MLL.insomnia01

You can find out whether your model has been properly trained with the following sentence:

SELECT * FROM INFORMATION_SCHEMA.ML_TRAINED_MODELS

 

It is necessary to validate the model and the training with the command VALIDATE MODEL.

Validating the model

At this stage, we need to confirm that the model has been trained properly. So, we should run the command VALIDATE MODEL.

📣Remember: Before populating the class, validate it with 50% of the data from the training data source. 

VALIDATE MODEL returns simple metrics for regression, classification, and time series models based on the provided testing set.

Check what has been validated with the sentence below:

VALIDATE MODEL insomnia01AllModel From St_MLL.insomniaValidate01

 

Repeat it with other models.

VALIDATE MODEL insomnia01SleepModel FROM St_MLL.insomniaValidate01
VALIDATE MODEL insomnia01BMIModel FROM St_MLL.insomniaValidate01

Consuming the model

Now, we will consume this model and inspect whether the model has been learning accurately how to produce the Result value.

With the help of the sentence “SELECT PREDICT”, we are going to forecast what the value of the Result will be. To do that, we will use the test1 table populated before.

SELECT *, PREDICT(insomnia01AllModel) FROM St_MLL.insomniaTest01

The result looks weird after utilizing 50% of the data exploited to train the model... Why has a 29-year-old female nurse been diagnosed with “insomnia”, whereas the model predicted “sleep apnea”? (see ID 54).

We should examine other models (insomnia01SleepModel and insomnia01BMIModel), created with different columns, but don't worry! I will display the columns used to design them.

SELECT Gender, Age, SleepDuration, QualitySleep, SleepDisorder, PREDICT(insomnia01SleepModel) As SleepDisorderPrediction FROM St_MLL.insomniaTest01

 

You can see again that a 29-year-old female has been diagnosed with “insomnia”, whereas the prediction states “sleep apnea”.  

Ok, you are right! We also need to know what percentage of the prediction has been applied to this final value.

How can we know the percentage of a prediction?

To find out the percentage of the prediction, we should exploit the command “PROBABILITY”. 

This command retrieves a value between 0 and 1. However, it is not the probability of prediction, it is the probability to get the value that you wish to check.

This is a good example:

SELECT *, PREDICT(insomnia01AllModel) As SleepDisorderPrediction, PROBABILITY(insomnia01AllModel FOR 'Insomnia') as ProbabilityPrediction FROM St_MLL.insomniaTest01

It is the probability of getting “Insomnia” as a sleep disorder.

 Our nurse, a woman, 29 years old, diagnosed with “Insomnia” has a 49.71% chance of having Insomnia. Still, the prediction is “Sleep Apnea” … Why?

Is the probability the same for other models? 

SELECT Gender, Age, SleepDuration, QualitySleep, SleepDisorder, PREDICT(insomnia01SleepModel) As SleepDisorderPrediction, PROBABILITY(insomnia01SleepModel FOR 'Insomnia') as ProbabilityInsomnia,
PROBABILITY(insomnia01SleepModel FOR 'Sleep Apnea') as ProbabilityApnea
FROM St_MLL.insomniaTest01

 
Finally, it is a bit clearer now. According to the data (sex, age, sleep quality, and sleep duration), the probability of having insomnia is only 34.63%, whereas the chance of having sleep apnea is 64.18%.

Wow…It is very interesting! Still, we were exploiting only a small portion of data inserted directly into a table with a class method… How can we upload a huge file with data?

Please, wait for the next article!, it is coming soon.

 

1 Comment
Discussion (1)2
Connectez-vous ou inscrivez-vous pour continuer