Nueva publicación

Encontrar

Artículo
· 31 jul, 2024 Lectura de 4 min

d[IA]gnosis: Vectorizing Diagnostics with Embedded Python and LLM Models

In the previous article we presented the d[IA]gnosis application developed to support the coding of diagnoses in ICD-10. In this article we will see how InterSystems IRIS for Health provides us with the necessary tools for the generation of vectors from the ICD-10 code list using a pre-trained language model, its storage and the subsequent search for similarities on all these generated vectors.

Introduction

One of the main features that have emerged with the development of AI models is what we know as RAG (Retrieval-Augmented Generation) that allows us to improve the results of LLM models by incorporating a context into the model. Well, in our example the context is given by the set of ICD-10 diagnoses and to use them we must first vectorize them.

How to vectorize our list of diagnoses?

SentenceTransformers and Embedded Python

For the generation of vectors we have used the Python library SentenceTransformers which greatly facilitates the vectorization of free texts from pre-trained models. From their own website:

Sentence Transformers (a.k.a. SBERT) is the go-to Python module for accessing, using, and training state-of-the-art text and image embedding models. It can be used to compute embeddings using Sentence Transformer models (quickstart) or to calculate similarity scores using Cross-Encoder models (quickstart). This unlocks a wide range of applications, including semantic searchsemantic textual similarity, and paraphrase mining.

Among all the models developed by the SentenceTransformers community we have found BioLORD-2023-M, a pre-trained model that will generate 786-dimensional vectors.

This model was trained using BioLORD, a new pre-training strategy for producing meaningful representations for clinical sentences and biomedical concepts.

State-of-the-art methodologies operate by maximizing the similarity in representation of names referring to the same concept, and preventing collapse through contrastive learning. However, because biomedical names are not always self-explanatory, it sometimes results in non-semantic representations.

BioLORD overcomes this issue by grounding its concept representations using definitions, as well as short descriptions derived from a multi-relational knowledge graph consisting of biomedical ontologies. Thanks to this grounding, our model produces more semantic concept representations that match more closely the hierarchical structure of ontologies. BioLORD-2023 establishes a new state of the art for text similarity on both clinical sentences (MedSTS) and biomedical concepts (EHR-Rel-B).

As you can see in its definition, this model is pre-trained with medical concepts that will be useful when vectorizing both our ICD-10 codes and free text.

For our project, we will download this model to speed up the vectors creation:

if not os.path.isdir('/shared/model/'):
    model = sentence_transformers.SentenceTransformer('FremyCompany/BioLORD-2023-M')            
    model.save('/shared/model/')

Once in our team, we can enter the texts to vectorize in lists to speed up the process, let's see how we vectorize the ICD-10 codes that we have previously recorded in our ENCODER.Object.Codes class.

st = iris.sql.prepare("SELECT TOP 50 CodeId, Description FROM ENCODER_Object.Codes WHERE VectorDescription is null ORDER BY ID ASC ")
resultSet = st.execute()
df = resultSet.dataframe()

if (df.size > 0):
    model = sentence_transformers.SentenceTransformer("/shared/model/")
    embeddings = model.encode(df['description'].tolist(), normalize_embeddings=True)

    df['vectordescription'] = embeddings.tolist()

    stmt = iris.sql.prepare("UPDATE ENCODER_Object.Codes SET VectorDescription = TO_VECTOR(?,DECIMAL) WHERE CodeId = ?")
    for index, row in df.iterrows():
        rs = stmt.execute(str(row['vectordescription']), row['codeid'])
else:
    flagLoop = False

As you can see, we first extract the codes stored in our ICD-10 code table that we have not yet vectorized but that we have recorded in a previous step after extracting it from the CSV file, then we extract the list of descriptions to vectorize and using the Python sentence_transformers library we will recover our model and generate the associated embeddings.

Finally, we will update the ICD-10 code with the vectorized description by executing the UPDATE. As you can see, the command to vectorize the result returned by the model is the SQL command TO_VECTOR in IRIS.

Using it in IRIS

Okay, we have our Python code, so we just need to wrap it in a class that extends Ens.BusinessProcess and include it in our production, then connect it to the Business Service in charge of retrieving the CSV file and that's it!

Let's take a look at what this code will look like in our production:

As you can see, we have our Business Service with the EnsLib.File.InboundAdapter adapter that will allow us to collect the code file and redirect it to our Business Process in which we will perform all the vectorization and storage operations, giving us a set of records like the following:

Now our application would be ready to start looking for possible matches with the texts we send it!

In the following article...

In the next article we will show how the application front-end developed in Angular 17 is integrated with our production in IRIS for Health and how IRIS receives the texts to be analyzed, vectorizes them and searches for similarities in the ICD-10 code table.

Don't miss it!

1 Comentario
Comentarios (1)2
Inicie sesión o regístrese para continuar
Artículo
· 31 jul, 2024 Lectura de 4 min

d[IA]gnosis: vectorizando diagnósticos con Embedded Python y modelos LLM

En el artículo anterior presentábamos la aplicación d[IA]gnosis desarrollada para el soporte a la codificación de diagnósticos en CIE-10. En este veremos como InterSystems IRIS for Health nos proporciona las herramientas necesarias para la generación de vectores a partir de la lista de códigos CIE-10 mediante un modelo pre-entrenado de lenguaje, su almacenamiento y la posterior búsqueda de similitudes sobre todos estos vectores generados.

Introducción

Una de las principales funcionalidades que han surgido con el desarrollo de modelos de IA es lo que conocemos como RAG (Retrieval-Augmented Generation) que nos permite mejorar los resultados de modelos LLM mediante la incorporación de un contexto sobre el modelo. Pues bien, en nuestro ejemplo el contexto nos viene dado por el conjunto de diagnósticos CIE-10 y para utilizarlos primeramente deberemos vectorizarlos.

¿Cómo vectorizar nuestra lista de diagnósticos? 

SentenceTransformers con Embedded Python

Para la generación de vectores hemos utilizado la librería de Python SentenceTransformers que nos facilita de sobremanera la vectorización de textos libres a partir de modelos pre-entrenados. De su propia página web:

Sentence Transformers (a.k.a. SBERT) is the go-to Python module for accessing, using, and training state-of-the-art text and image embedding models. It can be used to compute embeddings using Sentence Transformer models (quickstart) or to calculate similarity scores using Cross-Encoder models (quickstart). This unlocks a wide range of applications, including semantic searchsemantic textual similarity, and paraphrase mining.

Dentro de todos los modelos desarrollados por la comunidad de SentenceTransformers hemos encontrado BioLORD-2023-M, un modelo preentrenado que nos generará vectores de 786 dimensiones.

This model was trained using BioLORD, a new pre-training strategy for producing meaningful representations for clinical sentences and biomedical concepts.

State-of-the-art methodologies operate by maximizing the similarity in representation of names referring to the same concept, and preventing collapse through contrastive learning. However, because biomedical names are not always self-explanatory, it sometimes results in non-semantic representations.

BioLORD overcomes this issue by grounding its concept representations using definitions, as well as short descriptions derived from a multi-relational knowledge graph consisting of biomedical ontologies. Thanks to this grounding, our model produces more semantic concept representations that match more closely the hierarchical structure of ontologies. BioLORD-2023 establishes a new state of the art for text similarity on both clinical sentences (MedSTS) and biomedical concepts (EHR-Rel-B).

Como podéis ver en su propia definición, este modelo está preentrenado con conceptos médicos que nos resultará útil a la hora de vectorizar tanto nuestros códigos CIE-10 y el texto libre.

Para nuestro proyecto nos descargaremos dicho modelo para poder agilizar la creación de los vectores:

if not os.path.isdir('/shared/model/'):
    model = sentence_transformers.SentenceTransformer('FremyCompany/BioLORD-2023-M')            
    model.save('/shared/model/')

Una vez en nuestro equipo, podremos introducir los textos a vectorizar en listas para acelerar el proceso, veamos como vectorizamos los códigos CIE-10 que hemos grabado previamente en nuestra clase ENCODER.Object.Codes

st = iris.sql.prepare("SELECT TOP 50 CodeId, Description FROM ENCODER_Object.Codes WHERE VectorDescription is null ORDER BY ID ASC ")
resultSet = st.execute()
df = resultSet.dataframe()

if (df.size > 0):
    model = sentence_transformers.SentenceTransformer("/shared/model/")
    embeddings = model.encode(df['description'].tolist(), normalize_embeddings=True)

    df['vectordescription'] = embeddings.tolist()

    stmt = iris.sql.prepare("UPDATE ENCODER_Object.Codes SET VectorDescription = TO_VECTOR(?,DECIMAL) WHERE CodeId = ?")
    for index, row in df.iterrows():
        rs = stmt.execute(str(row['vectordescription']), row['codeid'])
else:
    flagLoop = False

Como véis, primeramente extraemos los códigos almacenados en nuestra tabla de códigos CIE-10 que aún no hemos vectorizado pero que hemos registrado en un paso anterior tras extraerlo del archivo CSV, a continuación extraemos la lista de descripciones a vectorizar y mediante la librería de Python sentence_transformers recuperaremos nuestro modelo y generaremos los embeddings asociados.

Finalmente actualizaremos el código CIE-10 con la descripción vectorizada ejecutando el UPDATE, como véis, el comando para vectorizar el resultado devuelto por el modelo es el comando TO_VECTOR de SQL en IRIS.

Incluyéndolo en IRIS

Muy bien, ya tenemos nuestro código Python, así que sólo necesitamos incluirlo en una clase que extienda Ens.BusinessProcess e incluirlo en nuestra producción, a continuación lo conectamos con el Business Service encargado de recuperar el archivo CSV y ¡listo!

Echemos un vistazo a la forma que tomará este código en nuestra producción:

Como véis, tenemos nuestro Business Service con el adaptador EnsLib.File.InboundAdapter que nos permitirá recoger el fichero de códigos y redirigirlo a nuestro Business Process en el cual realizaremos toda la operativa de vectorización y almacenamiento de los mismos, dándonos como resultado un conjunto de registros como el siguiente:

¡Pues ya estaría lista nuestra aplicación para empezar a buscar posibles coincidencias con los textos que le vayamos pasando!

En el próximo artículo...

En la próxima entrega vamos a mostrar como se integra el front-end de la aplicación desarrollado en Angular 17 con nuestra producción en IRIS for Health y cómo IRIS recibe los textos a analizar, los vectoriza y busca similitudes en la tabla de códigos CIE-10.

¡No os lo perdáis!

Comentarios (0)1
Inicie sesión o regístrese para continuar
Pregunta
· 31 jul, 2024

How to get value from Zenpage component from Chrome/edge addon JS

Hi:

I have been adapting the IRIS WHIZ addon as part of the contest. I will soon fork the code on github so the changes are available. 

The next phase is I am storing the date from and to time for a more complete search cache 

zenPage.getComponent(36).value

it works in the chrome console ok 

I'm not sure in external JS how to set the page it is on as a zenpage to use the zenpage functions

3 comentarios
Comentarios (3)1
Inicie sesión o regístrese para continuar
Anuncio
· 31 jul, 2024

[Vidéo en anglais] Utilisation des planifications de tâches InterSystems IRIS par programmation

Bonjour la communauté,

Regardez cette vidéo pour apprendre à gérer par programmation les planifications de tâches à l'aide d'InterSystems IRIS, notamment la création, la modification et la suppression d'une tâche définie par l'utilisateur :

⏯ Utilisation des planifications de tâches InterSystems IRIS par programmation

Abonnez-vous à la chaîne YouTube InterSystems Developers pour rester à l'écoute !

Comentarios (0)1
Inicie sesión o regístrese para continuar
Artículo
· 31 jul, 2024 Lectura de 2 min

Arrêt gracieux d'IRIS sans accès au terminal : saveur *nix

Je me suis retrouvé dans la situation peu confortable de travailler avec un système Linux sur lequel quelqu'un avait accidentellement désactivé l'accès utilisateur au shell Linux. HealthConnect était en cours d'exécution, assurant la maintenance de centaines d'interfaces. Pour résoudre le problème d'accès, cependant, nous devions arrêter l'hôte pour l'application d'un correctif.

Sans le shell, la commande iris n'est pas disponible pour contrôler l'instance, nous étions donc confrontés au risque d'arrêter le serveur de manière inélégante. Nous voulions éviter cela si possible...

La routine ^SHUTDOWN était historiquement une option pour arrêter Caché, mais vous avez besoin d'une session de terminal pour l'exécuter (nous parlerons plus en détail de ce qui constitue une session de terminal dans une minute). Mais ^SHUTDOWN est désormais obsolète, et lorsque vous l'exécutez, vous obtenez le message "Veuillez utiliser la procédure 'iris stop' pour arrêter le système".

Alors rayez-la de la liste... et remplacez-la par INTNOSHUT^SHUTDOWN. Oui, l'exécution de cette commande arrêtera IRIS de manière élégante. Et oui, vous avez besoin d'un shell de commande IRIS pour l'exécuter. Alors, où pouvez-vous obtenir un shell de commande IRIS pour le système dont vous êtes exclu, demandez-vous ?

Dans le studio IRIS, qui n'existera plus très longtemps, bien sûr ! La fenêtre de sortie vous permet d'exécuter des commandes IRIS, et cela ne surprendra pas grand monde. Elle vous permettra certainement d'exécuter D INTNOSHUT^SHUTDOWN dans la fenêtre d'output (après avoir basculé vers l'espace de noms %SYS). Cependant, si vous faites exactement cela, IRIS commencera très probablement à s'arrêter puis à se bloquer, car Studio garde une session ouverte. Il se peut qu'il ne s'arrête jamais complètement, et vous n'auriez aucun moyen de le forcer à s'arrêter autrement qu'en arrêtant le système d'exploitation.

Cela dit, vous pouvez obtenir un arrêt complet en utilisant la commande JOB INTNOSHUT^SHUTDOWN, puis en quittant immédiatement Studio. IRIS s'arrêtera (plus probablement qu'improbable) en douceur et vous pourrez vous sentir mieux en faisant les choses de la "bonne" manière... même si cela semble faux.

En ce qui concerne la récupération de l'accès utilisateur au shell Linux, c'est un sujet pour un autre forum. Mais maintenant qu'IRIS est arrêté en toute sécurité, le problème d'accès peut être résolu (un certain démontage est probablement nécessaire).

Comentarios (0)1
Inicie sesión o regístrese para continuar