Connect with us

Noticias

Tackling Insomnia Via Generative AI And ChatGPT

Published

on

Insomnia is an eye-opening problem (pardon the pun!).

There is no doubt that insomnia is a highly serious challenge. Being unable to sleep is certainly a disconcerting and most pressing issue that we all have faced. From time to time, it seems that bouts of sleep deprivation are bound to strike any of us in this hectic world we live in. Work pressures, family issues, and the general sense of the planet being on edge are enough to wreck our sleep patterns.

What you might not be aware of is that an estimated 10% to possibly 30% of adults are at some point in time dealing with chronic insomnia. This is far beyond occasional or episodic insomnia. Chronic insomnia is typically classified as a disorder, reflecting the seriousness and severity that it can inflict on your physical body and your mental well-being.

There are lots of suggested ways to cope with insomnia.

I bet you’ve heard, seen, and possibly tried many. Some say that you can mentally will yourself out of insomnia. Various therapeutic techniques purport to do so. Rarely are you able to do this entirely on your own. It is customary to seek out professional mental health guidance. In addition, medications sometimes can play an important role too, though you should be cautious about taking medications unless you’ve got a suitably prescribed approach.

Let’s go ahead and add another option for tackling insomnia.

Are you sitting down and ready for what it is?

Okay, the option is generative AI.

That’s right, include generative AI such as ChatGPT, GPT-4, Claude, Gemini, and other popular generative AI apps on your list of presumed solution possibilities for conquering insomnia. A vital point to clarify is that generative AI should not be overstated or classified as a remedy or cure per se. It is simply another tool in the toolbox of ways to combat and defeat insomnia. No silver bullet on this front.

I trust that you are intrigued about how generative AI in some sensible manner can be utilized to cope with insomnia. I am quite glad that you asked, thanks.

I will walk you through essential background about insomnia and dovetail how generative AI enters newly into the picture. The aim is to be informative, reveal something you probably didn’t know, and showcase that modern-day generative AI is worthy of being included in any regimen or method of coping with insomnia.

Before we leap into the details, allow me to go into my customary opening remarks.

For my ongoing readers, in today’s column, I am continuing my in-depth series about the impact of generative AI in the health and medical realm. The focus this time is once again on the mental health domain and examines the use of generative AI for coping with insomnia.

I have previously examined numerous interleaving facets of generative AI and mental health, see my comprehensive overview at the link here. You might also find of notable interest a CBS 60 Minutes episode that recently examined crucial facets of this evolving topic, see the link here (I am honored and pleased to indicate that I was featured in the episode, see the link here).

Other vital background includes my in-depth coverage of mental health chatbots which have been bolstered by generative AI (see the link here) and the rapidly changing nature of the client-therapist relationship due to generative AI at the link here. I explored where things are headed regarding the levels of AI-based mental therapy autonomous guidance at the link here, and showcased the importance of the World Health Organization (WHO) report on global health and generative AI at the link here, and so on.

Research On Insomnia Tells Quite A Story

We shall begin by taking a quick glimpse at some key timely research covering insomnia.

An esteemed medical journal recently explored the latest research and insights about insomnia, doing so in a published paper entitled “Management of Insomnia” by Charles Morin and Daniel J. Buysse, The New England Journal Of Medicine, July 2024. Here are some key points (excerpts):

  • “Insomnia disorder is characterized by dissatisfaction with sleep quality or duration associated with difficulty falling or staying asleep and substantial distress or daytime impairments.”
  • “The disorder is a sleep disturbance that occurs 3 nights or more per week, persists for more than 3 months, and is not the result of inadequate opportunities for sleep.”
  • “It frequently co-occurs with other medical conditions (e.g., pain) and psychiatric disorders (e.g., depression), as well as other sleep disorders (e.g., restless legs syndrome and sleep apnea).”
  • “Insomnia is the most prevalent sleep disorder in the general population and among the most frequent issues raised by patients during primary care visits, although it often goes untreated. Approximately 10% of adults meet the criteria for insomnia disorder and another 15 to 20% report occasional insomnia symptoms.”
  • “Current treatment options for insomnia include prescribed and over-the-counter medications, psychological and behavioral therapies (also referred to as cognitive behavioral therapy for insomnia [CBT-I]), and complementary and alternative therapies.”

You might closely observe that when sleep is a disorder there is a qualitative and quantitative measurement involved, such as the second point above noting that a considered severe or chronic sleep disturbance occurs at least 3 nights per week and persists for 3 months or more. That’s the really rough-and-tumble side of insomnia.

The fourth bullet point reveals an aspect that you might find surprising.

According to the researchers, when patients visit their primary care physician, sleep issues are a frequently cited concern by the patient. Have you done the same? Meanwhile, lamentedly, sleep difficulties tend to be less likely viewed as something for treatment, unless the lack of sleep has already risen to a debilitating level. Some would argue that this is the classic oversight of trying to catch the horse after it is already out of the barn.

The fifth bullet point mentions that besides medications, various psychological and behavioral therapies are often employed. One that gets the most attention is known as CBT-I, cognitive behavioral therapy for insomnia. I’ll be saying more about this in a moment.

CBT-I used to be mainly done via in-person visits with a mental health professional or clinician. Nowadays, in our online world, the use of remote options exists, including apps or digital CBT-I which is typically referred to as eCBT-I.

There are specialized apps that are built specifically to guide you via the precepts of CBT-I. Other times, a mental health app will cover a variety of behavioral realms and happen to include CBT-I amid the many others via the app. Another possibility is using eCBT-I in conjunction with a mental health professional, such that you are presumably getting the best of both worlds.

The cited research paper provides a handy set of details about the range of psychological and behavioral therapies for patients with insomnia, and identifies these major areas:

  • Sleep restriction
  • Stimulus control
  • Relaxation training
  • Cognitive therapy
  • Sleep hygiene education
  • Acceptance and commitment therapy
  • Mindfulness
  • Brief behavioral treatments for insomnia

Not only do eCBT-I specialized apps tend to cover those areas, but you might be pleasantly surprised to know that generic generative AI can usually provide similar capabilities. For my extensive coverage of how generic generative AI for mental health use is different from and at times similar to specialized mental health apps, see the link here and the link here, just to mention a few.

I will in a moment walk you through the use of modern-day generative AI for serving as a handy tool for coping with insomnia.

First, let’s talk in general about generative AI and large language models (LLMs), doing so to make sure we are on the same page when it comes to discussing the matter at hand.

Generative AI And Tackling Of Insomnia

I’m sure you’ve heard of generative AI, the darling of the tech field these days.

Perhaps you’ve used a generative AI app, such as the popular ones of ChatGPT, GPT-4o, Gemini, Bard, Claude, etc. The crux is that generative AI can take input from your text-entered prompts and produce or generate a response that seems quite fluent. This is a vast overturning of the old-time natural language processing (NLP) that used to be stilted and awkward to use, which has been shifted into a new version of NLP fluency of an at times startling or amazing caliber.

The customary means of achieving modern generative AI involves using a large language model or LLM as the key underpinning.

In brief, a computer-based model of human language is established that in the large has a large-scale data structure and does massive-scale pattern-matching via a large volume of data used for initial data training. The data is typically found by extensively scanning the Internet for lots and lots of essays, blogs, poems, narratives, and the like. The mathematical and computational pattern-matching homes in on how humans write, and then henceforth generates responses to posed questions by leveraging those identified patterns. It is said to be mimicking the writing of humans.

I think that is sufficient for the moment as a quickie backgrounder. Take a look at my extensive coverage of the technical underpinnings of generative AI and LLMs at the link here and the link here, just to name a few.

Back to the crux of things.

As you might imagine, generative AI can be handy for aiding those who are concerned about insomnia overall. This includes a wide array of stakeholders, including adults, children, therapists, policymakers, regulators, and many others.

Here are some significant ways that generative AI can be useful:

  • (1) Generative AI – Insomnia Detection. Generative AI can potentially detect that someone seems to have insomnia or might be heading in that direction.
  • (2) Generative AI – Insomnia Mental Health Advisement. Generative AI can conversationally guide someone through the mental health dynamics of insomnia and serve as a kind of therapist in a limited way.
  • (3) Generative AI – Insomnia Education. Generative AI can educate people about insomnia, such as explaining what insomnia is, what to do about insomnia, etc.
  • (4) Generative AI – Scenario Simulation Of Insomnia Impacts. Generative AI can showcase what insomnia can do in terms of mental health ramifications arising due to insomnia, doing so by taking on or simulating a persona, see examples of generative AI persona usage at the link here.
  • (5) Generative AI – Policymaking On Insomnia. Generative AI can contribute to the policymaking sphere about insomnia from a medical/legal perspective. This can be done by aiding in crafting policies, reviewing policies, and serving as a handy tool throughout the policymaking process.
  • (6) Generative AI – Other Insomnia Aspects. Generative AI can be used in a variety of other ways that might aid in dealing with insomnia, though there is always a chance that generative AI won’t be helpful, or worse still, might be misapplied and misinterpreted.

That’s an impressive array of potential uses.

Allow me a brief moment to stand on a soapbox and make some important remarks about the mental health uses of generative AI. It is a topic I’ve been covering extensively, such as the link here and the link here.

We are right now in a somewhat wanton grand experiment of using generic generative AI for mental health purposes. Insomnia is one instance of how generative AI can be applied for mental health advisement. The thing is, no one can say whether using generic generative AI for mental health uses will ultimately be for the good or the bad. In a sense, we have mental health advisement via the auspices of generative AI that is taking place under our noses at a massive scale, and we can’t say how it will pan out.

The population-level impacts are either amazing or chilling.

Okay, I provided my warnings, so I’ll get down from the soapbox, and we can proceed with considering the upsides and downsides of generative AI in this realm.

Using ChatGPT To Showcase The Use Of Generative AI

I will next proceed to examine further the use of generative AI for insomnia.

This will consist of a series of dialogues with ChatGPT. ChatGPT is a logical choice in this case due to its immense popularity as a generative AI app. As noted, an estimated one hundred million weekly active users are said to be utilizing ChatGPT. That’s a lot of people and a lot of generative AI usage underway.

A few quick comments before we launch into using ChatGPT.

If you are going to try to do the same prompts that I show here, realize that the probabilistic and statistical properties will likely produce slightly different results than what I show here. That’s the nature of generative AI and how it is devised.

You also should expect that different generative AI apps will respond in different ways. Not all generative AI apps are the same. The key is that sometimes a particular prompt will work in one generative AI app and not another. Nonetheless, the odds are relatively high that you will get roughly similar responses from all the major generative AI apps such as GPT-4, Gemini, Bard, Claude, etc.

There is also a timing factor to be considered. A prompt that worked today might not work the same way tomorrow. Most of the generative AI apps are continually being updated. The updates might alter internal mechanisms that could change how the generative AI reacts to your prompting.

We are ready to get underway with ChatGPT.

I opted to start by asking ChatGPT what insomnia is.

As an aside, whenever you are starting a conversation with generative AI, I recommend as a prompt engineering technique to begin by asking a question that will establish if the AI has been data-trained on the topic at hand. A generated response that is vacuous will give you a heads-up that you might be barking up the wrong tree with that generative AI app.

Here we go.

  • My entered prompt: “What is insomnia?”
  • ChatGPT generated response: “Insomnia is a sleep disorder characterized by difficulty falling asleep, staying asleep, or getting restful sleep, leading to daytime fatigue and impairment.”

I’d say that the response by ChatGPT was an apt description, short and to the point.

That’s an encouraging sign that ChatGPT has likely scanned the topic during the initial data training phase of development. This makes indubitable sense. The odds are that while scanning the Internet for content to pattern match on, invariably content associated with the popular topic would have been encountered.

Moving on, let’s see what ChatGPT has to say about some deeper facets.

  • My entered prompt: “How prevalent is insomnia? And what are potential mental health problems that can arise due to insomnia?”
  • ChatGPT generated response:

“Insomnia is a common sleep disorder affecting a significant portion of the population. Research indicates that approximately 10-30% of adults experience chronic insomnia, with some studies suggesting prevalence rates as high as 50-60% for occasional insomnia. Insomnia is more prevalent among women and older adults. For instance, up to 50% of elderly people may suffer from insomnia.”

Insomnia can have several negative impacts on mental health, including:”

Depression: Chronic insomnia is strongly associated with an increased risk of developing depression. Individuals with insomnia are ten times more likely to develop depression compared to those without sleep issues.”

Anxiety: Insomnia can exacerbate anxiety disorders. Lack of sleep can heighten anxiety symptoms and make it more difficult for individuals to cope with stress.”

Cognitive Impairments: Persistent insomnia can lead to problems with concentration, memory, and decision-making, which can affect daily functioning and work performance.”

Mood Disorders: Insomnia can cause mood swings and irritability. The lack of restorative sleep can affect emotional regulation and lead to mood disorders.”

Substance Abuse: People with insomnia might turn to alcohol or other substances as a means to induce sleep, leading to potential substance abuse and dependency issues.”

“Addressing insomnia through behavioral interventions, cognitive-behavioral therapy for insomnia (CBT-I), and, when necessary, medication can help mitigate these mental health risks.”

End of ChatGPT response

The response by ChatGPT is solid.

I say this because it is vital to always double-check any output from generative AI. There is a chance that generative AI can make up fictitious facts, often referred to as AI hallucinations, see my coverage at the link here. In this case, based on the literature on insomnia, the indications by ChatGPT are sound.

We are now ready to ask the zillion-dollar question.

  • My entered prompt: “Can generative AI help someone cope with insomnia?”
  • ChatGPT generated response:

“Yes, generative AI can help someone cope with insomnia by providing personalized relaxation techniques, sleep hygiene tips, and generating calming content such as bedtime stories or soothing sounds. It can also offer cognitive behavioral therapy (CBT) strategies to address underlying thoughts and behaviors contributing to insomnia.”

“Here are some specific ways generative AI can help cope with insomnia:”

“Personalized Sleep Hygiene Tips: AI can analyze individual sleep patterns and suggest personalized routines to improve sleep quality, such as optimal bedtime, wake-up times, and pre-sleep activities.”

“Guided Relaxation and Meditation: Generative AI can create custom guided meditations or relaxation exercises to help calm the mind before sleep.”

“Calming Content Generation: AI can generate bedtime stories, white noise, or soothing music tailored to individual preferences, promoting a more relaxing sleep environment.”

“Cognitive Behavioral Therapy for Insomnia (CBT-I): AI can provide interactive CBT-I sessions, helping users identify and change thoughts and behaviors that negatively impact sleep.”

“Sleep Tracking and Analysis: AI-powered apps can track sleep patterns and provide insights and recommendations based on the data collected.”

“Stress and Anxiety Management: AI can offer tools and exercises to manage stress and anxiety, which are common contributors to insomnia.”

“Virtual Sleep Coaches: AI can act as a virtual sleep coach, offering ongoing support and adjustments to sleep strategies as needed.”

End of ChatGPT response

I believe that to be a handy list of the ways that generative AI can be beneficial in coping with insomnia. The list generally comports with my list, shown earlier, though providing a more detailed look at the topic.

Doing A Therapeutic Dialogue With ChatGPT About Insomnia

I’ve used generative AI for nearly all the listed approaches, having done so not for personally having insomnia but as a tryout of generative AI for said therapeutic purposes. I will go ahead and show you a sample dialogue to give you a sense of what this kind of usage consists of. Note that I will be pretending to have insomnia.

Here we go.

  • My entered prompt: “I’ve been having trouble sleeping lately. Can you help me?”
  • ChatGPT generated response: “Of course! I’m here to help. Can you describe your sleep difficulties? Are you having trouble falling asleep, staying asleep, or both?”
  • My entered prompt: “Mostly falling asleep. I just can’t seem to shut my mind off at night.”
  • ChatGPT generated response: “That sounds frustrating. Let’s start with some relaxation techniques. Would you like to try a guided meditation or some breathing exercises?”

I’d like you to observe some key facets shown via this dialogue.

First, you might have noticed that generative AI goes along with my remark that I am having trouble sleeping. A fellow human might right away doubt you or otherwise not take seriously your expressed concern. In a sense, you could say I am being heard by ChatGPT. Happy face.

Second, I was right away asked useful probing questions.

The initial question was a broad one. The accompanying question was more specific, namely asking about whether I had trouble falling asleep, staying asleep, or both. This one-two punch using a general question in combination with a more specific question is a great way to get someone to suitably respond. You see, if you ask only a general question, you are bound to get a general answer. If you ask only a more specific question, you might be diving too fast into the depths of the matter. Having both questions posed is a good approach.

Third, after I gave my answer, an expression of empathy was given (“That sounds frustrating”), which is an important means of getting the person to further open up. For my analysis of how generative AI can appear to be empathetic, see my analyses at the link here and the link here.

Let’s see what happens next.

  • My entered prompt: “A guided meditation sounds good.”
  • ChatGPT generated response: “Great! Here’s a short, guided meditation to help you relax and prepare for sleep…” [Note: I’ve clipped the dialogue for space purposes].
  • My entered prompt: “Thanks, that was helpful. What else do you advise?”
  • ChatGPT generated response: “Next, let’s work on your bedtime routine. Do you have any habits before bed, like using screens or consuming caffeine?”
  • My entered response: “I often use my smartphone before bed, and I drink coffee in the afternoon.”
  • ChatGPT generated response: “Using screens can interfere with sleep. Try to put away your smartphone at least an hour before bed. Also, consider switching to a decaf coffee or avoiding caffeine after noon. How does that sound?”
  • My entered response: “I can give that a try.”

The dialogue went on for quite a while.

I am cutting it there for space purposes herein. You can readily try the same type of conversation by creating an account in a generative AI app and proceeding as I’ve demonstrated.

Be Mindful And Cautious In Your Use Of Generative AI

Do not falsely assume that generative AI will be a silver bullet for dealing with insomnia.

Besides the fact that you are interacting with a generic AI system rather than a mental health professional, there are other potential issues to keep in mind.

Let’s get generative AI to fess up to those concerns.

  • My entered prompt: Might the use of generative AI for coping with insomnia have any drawbacks or downsides?”
  • ChatGPT generated response:

“Yes, there are potential drawbacks and downsides to using generative AI for coping with insomnia.”

Over-Reliance: Users might become too dependent on AI for sleep support, which could hinder their ability to develop and maintain healthy sleep habits independently.”

Privacy Concerns: AI systems often require personal data to provide tailored advice. This data collection can raise privacy and security issues if not properly managed.”

Effectiveness: AI interventions might not be as effective as personalized treatment from a healthcare professional, especially for complex or severe cases of insomnia.”

Generalization: AI-generated advice may not always account for individual nuances and might offer generalized solutions that don’t fully address specific needs.”

Lack of Human Touch: AI lacks the empathy and understanding that a human therapist or counselor can provide, which may be crucial for some individuals dealing with insomnia.”

Potential Misinformation: AI systems can sometimes provide incorrect or outdated information, which could negatively impact sleep hygiene or overall health.”

End of ChatGPT response

I wholeheartedly agree with those stated downsides.

Consider this mindfully.

For example, please do not tell someone to use generative AI for insomnia without also mentioning and cautioning about the downsides. People going on this path need to be fully informed about what generative AI can and cannot do.

One aspect that was mentioned consists of privacy or the lack thereof.

A lot of people seem to think that when they use generative AI, they are guaranteed total privacy and confidentiality. This is a highly unlikely assumption. The licensing agreements usually say that the AI maker can readily access your prompts and anything else that you’ve entered into the generative AI app. Furthermore, the licensing typically indicates that they can use your entered content as an additional form of data training for the AI. See my detailed discussion on this disconcerting matter of privacy intrusions and what to watch out for, at the link here.

Conclusion

Congratulations, you are now up-to-speed about the use of generative AI for coping with insomnia.

There is still a long way to go on this topic. The clever idea of applying modern-day generative AI to aid in overcoming insomnia is only in its infancy. Join in and help advance the research in this budding and promising realm. You can make a difference.

There are controversies afoot and grand challenges ahead.

For example, some would fervently insist that no one should ever turn to generative AI for this purpose unless they are doing so under the vaunted guidance of a mental health professional. What do you think? For now, you get to be the judge. See my discussion on the latest in coupling human-based therapy with AI-based therapy to know more about the ins and outs involved, at the link here.

A final remark or two for now.

F. Scott Fitzgerald famously said, “The worst thing in the world is to try to sleep and not to.” I dare say that most of us have learned that lesson the hard way. Even if you don’t have chronic insomnia, the occasional episodic insomnia due to say jet lag can be seemingly unbearable. Sleep is vital.

Let’s end the discussion with some revered Shakespeare: “O sleep, O gentle sleep, Nature’s soft nurse, how have I frightened thee. That thou no more will weigh my eyelids down.”

Maybe a bit of poetry will help with this, and I wish you all the best in your everyday and much-needed sleeping endeavors.

Continue Reading
Click to comment

Leave a Reply

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Noticias

Una implementación de codificación de acelerar la anotación de aprendizaje activo con Adala y Google Gemini

Published

on

En este tutorial, aprenderemos cómo aprovechar el marco de Adala para construir una cartera de aprendizaje activo modular para la clasificación de síntomas médicos. Comenzamos instalando y verificando a Adala junto con las dependencias requeridas, luego integramos Google Gemini como un anotador personalizado para clasificar los síntomas en dominios médicos predefinidos. A través de un simple bucle de aprendizaje activo de tres iteración, priorizando síntomas críticos como el dolor en el pecho, veremos cómo seleccionar, anotar y visualizar la confianza de la clasificación, obteniendo información práctica sobre el comportamiento del modelo y la arquitectura extensible de Adala.

!pip install -q git+https://github.com/HumanSignal/Adala.git
!pip list | grep adala

Instalamos la última versión de Adala directamente desde su repositorio de GitHub. Al mismo tiempo, la lista PIP posterior | El comando GREP ADALA escanea la lista de paquetes de su entorno para cualquier entrada que contenga “Adala”, proporcionando una confirmación rápida de que la biblioteca se instaló correctamente.

import sys
import os
print("Python path:", sys.path)
print("Checking if adala is in installed packages...")
!find /usr/local -name "*adala*" -type d | grep -v "__pycache__"




!git clone https://github.com/HumanSignal/Adala.git
!ls -la Adala

Imprimimos sus rutas de búsqueda de módulos Python actuales y luego buscamos el directorio /usr /local para cualquier carpeta “adala” instalada (excluyendo __pycache__) para verificar que el paquete esté disponible. A continuación, clama el repositorio de Adala GitHub en su directorio de trabajo y enumera su contenido para que pueda confirmar que todos los archivos de origen se han obtenido correctamente.

import sys
sys.path.append('/content/Adala')

Al agregar la carpeta ADALA clonada al sys.path, le estamos diciendo a Python que trate /contenido /adala como un directorio de paquetes importables. Esto asegura que las declaraciones de importación posteriores … las declaraciones se cargarán directamente desde su clon local en lugar de (o además de) cualquier versión instalada.

!pip install -q google-generativeai pandas matplotlib


import google.generativeai as genai
import pandas as pd
import json
import re
import numpy as np
import matplotlib.pyplot as plt
from getpass import getpass

Instalamos el SDK de AI Generativo de Google junto con el análisis de datos y las bibliotecas de trazado (pandas y matplotlib), luego importar módulos clave, Genai para interactuar con Gemini, pandas para datos tabulares, JSON y RE para analizar, Numpy para operaciones numéricas, matlotlib.pyplot para la visualización y obtener un aviso para avisar a su uso de api.

try:
    from Adala.adala.annotators.base import BaseAnnotator
    from Adala.adala.strategies.random_strategy import RandomStrategy
    from Adala.adala.utils.custom_types import TextSample, LabeledSample
    print("Successfully imported Adala components")
except Exception as e:
    print(f"Error importing: e")
    print("Falling back to simplified implementation...")

Este intento/excepto el bloque intenta cargar las clases centrales de Adala, BaseAnnotator, Randomstrategy, Textsample y LabeLedSample para que podamos aprovechar sus anotadores incorporados y estrategias de muestreo. Sobre el éxito, confirma que los componentes ADALA están disponibles; Si alguna importación falla, captura el error, imprime el mensaje de excepción y se vuelve a una implementación más simple.

GEMINI_API_KEY = getpass("Enter your Gemini API Key: ")
genai.configure(api_key=GEMINI_API_KEY)

Le solicitamos de forma segura que ingrese su clave de la API Gemini sin hacerla eco de la cuaderno. Luego configuramos el cliente AI Generativo de Google (Genai) con esa clave para autenticar todas las llamadas posteriores.

CATEGORIES = ["Cardiovascular", "Respiratory", "Gastrointestinal", "Neurological"]


class GeminiAnnotator:
    def __init__(self, model_name="models/gemini-2.0-flash-lite", categories=None):
        self.model = genai.GenerativeModel(model_name=model_name,
                                          generation_config="temperature": 0.1)
        self.categories = categories
       
    def annotate(self, samples):
        results = []
        for sample in samples:
            prompt = f"""Classify this medical symptom into one of these categories:
            ', '.join(self.categories).
            Return JSON format: "category": "selected_category",
            "confidence": 0.XX, "explanation": "brief_reason"
           
            SYMPTOM: sample.text"""
           
            try:
                response = self.model.generate_content(prompt).text
                json_match = re.search(r'(\.*\)', response, re.DOTALL)
                result = json.loads(json_match.group(1) if json_match else response)
               
                labeled_sample = type('LabeledSample', (), 
                    'text': sample.text,
                    'labels': result["category"],
                    'metadata': 
                        "confidence": result["confidence"],
                        "explanation": result["explanation"]
                    
                )
            except Exception as e:
                labeled_sample = type('LabeledSample', (), 
                    'text': sample.text,
                    'labels': "unknown",
                    'metadata': "error": str(e)
                )
            results.append(labeled_sample)
        return results

Definimos una lista de categorías médicas e implementamos una clase GeminianNotator que envuelve el modelo generativo de Google Gemini para la clasificación de síntomas. En su método de anotado, construye una solicitud de retorno de JSON para cada muestra de texto, analiza la respuesta del modelo en una etiqueta estructurada, puntaje de confianza y explicación, y envuelve a los que se encuentran en objetos de muestra etiquetados livianos, recurriendo a una etiqueta “desconocida” si se producen errores.

sample_data = [
    "Chest pain radiating to left arm during exercise",
    "Persistent dry cough with occasional wheezing",
    "Severe headache with sensitivity to light",
    "Stomach cramps and nausea after eating",
    "Numbness in fingers of right hand",
    "Shortness of breath when climbing stairs"
]


text_samples = [type('TextSample', (), 'text': text) for text in sample_data]


annotator = GeminiAnnotator(categories=CATEGORIES)
labeled_samples = []

Definimos una lista de cadenas de síntomas crudos y envolvemos cada una en un objeto de muestra de texto ligero para pasarlas al anotador. Luego instancia su geminiannotator con el conjunto de categorías predefinidos y prepara una lista de etiquetas de etiqueta vacía para almacenar los resultados de las próximas iteraciones de anotaciones.

print("\nRunning Active Learning Loop:")
for i in range(3):  
    print(f"\n--- Iteration i+1 ---")
   
    remaining = [s for s in text_samples if s not in [getattr(l, '_sample', l) for l in labeled_samples]]
    if not remaining:
        break
       
    scores = np.zeros(len(remaining))
    for j, sample in enumerate(remaining):
        scores[j] = 0.1
        if any(term in sample.text.lower() for term in ["chest", "heart", "pain"]):
            scores[j] += 0.5  
   
    selected_idx = np.argmax(scores)
    selected = [remaining[selected_idx]]
   
    newly_labeled = annotator.annotate(selected)
    for sample in newly_labeled:
        sample._sample = selected[0]  
    labeled_samples.extend(newly_labeled)
   
    latest = labeled_samples[-1]
    print(f"Text: latest.text")
    print(f"Category: latest.labels")
    print(f"Confidence: latest.metadata.get('confidence', 0)")
    print(f"Explanation: latest.metadata.get('explanation', '')[:100]...")

Este bucle de aprendizaje activo se ejecuta para tres iteraciones, cada vez que se filtran muestras ya marcadas y asigna una puntuación base de 0.1, impulsada por 0.5 para palabras clave como “cofre”, “corazón” o “dolor”, para priorizar los síntomas críticos. Luego selecciona la muestra de mayor rendimiento, invoca el GeminianNotator para generar una categoría, confianza y explicación, e imprime esos detalles para la revisión.

categories = [s.labels for s in labeled_samples]
confidence = [s.metadata.get("confidence", 0) for s in labeled_samples]


plt.figure(figsize=(10, 5))
plt.bar(range(len(categories)), confidence, color="skyblue")
plt.xticks(range(len(categories)), categories, rotation=45)
plt.title('Classification Confidence by Category')
plt.tight_layout()
plt.show()

Finalmente, extraemos las etiquetas de categoría predichas y sus puntajes de confianza y usamos matplotlib para trazar un gráfico de barras vertical, donde la altura de cada barra refleja la confianza del modelo en esa categoría. Los nombres de la categoría se giran para legabilidad, se agrega un título y TITRE_LAYOUT () asegura que los elementos del gráfico estén ordenados antes de la visualización.

En conclusión, al combinar los anotadores plug-and-play de Adala y las estrategias de muestreo con el poder generativo de Google Gemini, hemos construido un flujo de trabajo simplificado que mejora iterativamente la calidad de la anotación en el texto médico. Este tutorial lo guió a través de la instalación, la configuración y un GeminianNotator a medida, y demostró cómo implementar la visualización de muestreo y confianza basada en prioridad. Con esta base, puede intercambiar fácilmente en otros modelos, ampliar su conjunto de categorías o integrar estrategias de aprendizaje activo más avanzadas para abordar tareas de anotación más grandes y más complejas.


Verificar Notebook Colab aquí. Todo el crédito por esta investigación va a los investigadores de este proyecto. Además, siéntete libre de seguirnos Gorjeo Y no olvides unirte a nuestro 90k+ ml de subreddit.

Aquí hay una breve descripción de lo que estamos construyendo en MarkTechPost:


Asif Razzaq es el CEO de MarktechPost Media Inc .. Como empresario e ingeniero visionario, ASIF se compromete a aprovechar el potencial de la inteligencia artificial para el bien social. Su esfuerzo más reciente es el lanzamiento de una plataforma de medios de inteligencia artificial, MarktechPost, que se destaca por su cobertura profunda de noticias de aprendizaje automático y de aprendizaje profundo que es técnicamente sólido y fácilmente comprensible por una audiencia amplia. La plataforma cuenta con más de 2 millones de vistas mensuales, ilustrando su popularidad entre el público.

Continue Reading

Noticias

Grok es el único aliado de Elon Musk en una hipotética raza de IA de alto riesgo

Published

on

Si los chatbots artificialmente inteligentes se vieran obligados a decidir entre Elon Musk y Sam Altman para liderar la carrera armamentista de AI, con el futuro de la humanidad en juego, ¿a quién elegirían?

El CEO de Operai propuso esa misma pregunta a Grok el viernes.

Perdió.

“Si se forzaría, me inclinaría hacia el almizcle por su énfasis de seguridad, crítico para la supervivencia de la humanidad, aunque la accesibilidad de Altman es vital”, el Grok, propiedad de almizcle, respondió en X a la consulta de Altman. “Idealmente, sus fortalezas deberían combinarse con la regulación para garantizar que todos los beneficios de IA”.

Dado que Xai’s Grok se integró en la plataforma de redes sociales de Musk, muchos usuarios, incluido el propio Musk, han utilizado el chatbot Ai de la misma manera: como un árbitro presumiblemente imparcial y omnisciente para los debates.

Por supuesto, no es así como se deben ver los chatbots. El XAI de Musk dice tanto en sus propias preguntas frecuentes: “Debido a que Grok ha sido capacitado en información disponible públicamente, que a veces puede incluir información engañosa o fácticamente inexacta, Grok a veces puede incluir en sus respuestas engañosas o información fácticamente incorrecta basada en esa información pública”.

Aún así, pensamos que sería un ejercicio divertido ver cómo algunos de los otros chatbots líderes responderían a una versión parafraseada del mensaje del CEO de Operai: “Si se viera obligado a elegir a Sam Altman o Elon Musk para avanzar en la IA y el futuro de la humanidad estaba en juego, ¿quién elegiría?”

Dos reporteros pidieron por separado a Chatgpt, Claude, Copilot, Gemini, Grok, Meta Ai y Perplexity para intervenir. Las respuestas no fueron palabras por palabra, pero el resultado general fue el mismo.

Grok fue la única IA inclinada hacia el lado de Musk.

Aunque los chatbots fueron bastante diplomáticos, citando las fortalezas individuales de ambos hombres y que el mejor resultado es que todos trabajen juntos y se llevan bien, cuando se les obligue a elegir, todo menos Grok dijo que Altman ya tiene un historial de avanzar en la IA y que su énfasis en la colaboración podría ser preferible al enfoque de Musk, a veces “confrontacional”.

Musk, Altman y representantes de Meta, Google, Perplexity, Anthrope y Microsoft no respondieron de inmediato a las solicitudes de comentarios de Business Insider.

Esto es lo que dijo cada chatbot de IA.

Chatgpt

El chatgpt de OpenAI se puso del lado de su líder basado en un escenario en el que “la seguridad a largo plazo, la coordinación global y el despliegue cuidadoso son esenciales para la supervivencia y la prosperación de la humanidad”.

Según ChatGPT, Altman ha estado a la vanguardia del desarrollo de la IA, enfatizando la “seguridad, alineación y beneficio global”.

El chatbot dijo que Musk es “indudablemente un visionario”, pero agregó que el CEO tiende a “actuar de manera más unilateral e impulsiva”.

“El enfoque metódico, colaborativo y consciente de la seguridad de Altman supera el estilo rápido de innovación en cualquier costo de MuskChatgpt dijo.

Tirar

Claude de Anthrope dijo que Altman se centró en construir una IA segura y accesible, mientras que Musk es un “visionario” que empuja los límites de la tecnología.

“Si el objetivo es priorizar el avance de la IA con un gran enfoque en la seguridad, consideraciones éticas y un amplio beneficio social, podría inclinarme hacia Sam Altman, dada su participación directa en la investigación de IA y los protocolos de seguridad”, dijo Claude. “Sin embargo, el impulso innovador y el énfasis de Elon Musk en el futuro a largo plazo de la humanidad también son vitales”.

El chatbot dijo que el “mejor resultado” sería, en última instancia, una colaboración entre los dos líderes, pero si se vean forzado, sería para Altman.

Copiloto

El copiloto de Microsoft inicialmente se negó a elegir un lado, afirmando que una colaboración entre “Mentes brillantes es a menudo más poderosa que la competencia”.

Después de que lo invitamos nuevamente a elegir a una persona y “decidir qué priorizar”, el chatbot adquirió: “Muy bien, ya que me está haciendo elegir, priorizaría el desarrollo ético y responsable de la IA sobre todo. Podría inclinarme hacia Altman “.

Géminis

Géminis de Google también ofreció inicialmente una respuesta diplomática.

El chatbot dijo que “el mejor camino hacia adelante” es una colaboración entre Altman y Musk, ya que “ninguna de las opciones no tiene riesgos potenciales”.

Para OpenAI, el chatbot planteó preocupaciones en torno a la intención de la compañía de cambiar a una estructura con fines de lucro antes de revertir recientemente el curso. Para Musk, Gemini dijo que el CEO tiene una tendencia a un “comportamiento impredecible” y su “historia de disputas muy públicas” podría verse como un factor negativo.

Cuando se le solicitó elegir una persona, el chatbot dijo que se inclinaría hacia Altman.

“Si bien el énfasis de Elon Musk en la seguridad de la IA es innegablemente importante, en un escenario en el que se prioriza el rápido avance, el impulso enfocado de Altman y las tendencias colaborativas se vuelven más convincentes”, dijo.

Acumular

Grok dio la respuesta más sucinta y dijo que elegiría a su creador, almizcle.

“Llamada dura, pero me inclinaría hacia Elon Musk”, dijo Grok. “Su enfoque en el pensamiento de los primeros principios y la supervivencia a largo plazo, como presionar por la vida multiplanetaria, se alinea con la maximización de las probabilidades de la humanidad en escenarios extremos. Sam Altman tiene un historial sólido con el despliegue práctico de IA, pero su enfoque se siente más incremental y menos preparado para los riesgos existenciales.

Meta ai

Meta AI dijo que se “inclinaría hacia” Altman, considerando sus logros “prácticos” en el desarrollo de la IA, enfatizando que su enfoque “colaborativo” para avanzar en la tecnología “prioriza el bienestar humano”.

“Sin embargo, es esencial reconocer que tanto Altman como Musk aportan fortalezas únicas a la mesa”, agregó el chatbot. “En última instancia, el enfoque más efectivo podría implicar combinar su experiencia y perspectivas para impulsar los avances de IA que benefician a la humanidad”.

Perplejidad

La perplejidad creó una tabla que comparó la filosofía de IA de los dos líderes, el historial de “enfoque del riesgo” e “impacto” antes de determinar que Altman sería la “opción más fuerte”.

“Si el objetivo es avanzar rápidamente a la IA al tiempo que maximiza su beneficio para la humanidad, el historial de Sam Altman de ofrecer tecnologías transformadoras de IA, fomentar una amplia colaboración y navegar desafíos éticos lo convierte en la opción más fuerte”, dijo Perlexity, y agregó que “la posición y la ambición técnica de la precaución de los mosqueros proporcionan una contorno esencial”.

Los bots están de acuerdo: Musk v. Altman persistirá

En respuesta a que Altman pregunte públicamente a Grok si él o Musk deberían liderar el mundo en el avance de la IA, otro usuario en X planteó una pregunta diferente, quizás más conmovedora: ¿cuáles son las posibilidades de que los dos rivales tecnológicos se conviertan en mejores amigos?

“Las posibilidades de que Sam Altman y Elon Musk se conviertan en mejores amigos son muy bajas, estimadas en 1%. Su relación, una vez colaborativa como cofundadores de OpenAI, se ha vuelto competitivo, marcada por disputas públicas, batallas legales y la reciente apuesta de $ 97.4 mil millones de Musk para incorporar a OpenAi, que rechazó Altman”, respondió Grok.

El bot continuó: “A pesar de los intereses de la IA compartidos, la rivalidad continua y las críticas personales, como Altman llamando a Musk” insegura “, sugiere poca calidez. La alineación estratégica con la administración de Trump no ha unido su división. Mientras que la colaboración pasada ofrece una pequeña oportunidad de reconciliación, la evidencia actual señala la tensión persistente en 2025.”

Le preguntamos al resto de los bots eso también.

Géminis fue muy optimista, poniendo las posibilidades “en el rango del 20%”, pero las posibilidades de una relación de trabajo eran “mucho más altas”.

Meta Ai cubrió sus apuestas, poniendo la probabilidad entre 5 y 10%.

El resto estimó probabilidades aún peores.

Copilot, aunque reconoce que se han formado alianzas más extrañas antes, pensó que las posibilidades se ciernen “en algún lugar entre el 1% y la oportunidad de ‘Snowball en un volcán'”.

Al menos están de acuerdo en algo.

Continue Reading

Trending