Generative AI

Implementation of Restricted References Practical Study Version with Adamba and Google Gemini

In this lesson, we will learn how we can apply for an ancient frame to build a practical learning pipeline. We start by installing and verifying Adults beside it, then combines Google Gemini as a custom convotator to separate symptoms from predefined media. By using a simple learning loop, it prioritizes the critical symptoms such as chest pain, we will see how we can choose, appreciate, and see practical understanding of model and increased by Lbalela.

!pip install -q git+
!pip list | grep adala

We include the latest removal of an elders directly from its Gitity repository. At the same time, the next PIP list | Grep Hold Command Scan a list of your natural package for any container entries “created,” to provide a quick guarantee that the library was successfully installed.

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 
!ls -la Adala

We print your Python Modul Modul Modif methods, Clones putting the Danla Gitab your working cursor and counts content to ensure that all source files are well.

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

By creating an ancient folder of Adama combined on Sys.Path, we tell Python to manage / content / elders as a package guide. This ensures that the following creativity of Ananda … statements will upload directly from your CLONE of the area rather than (or more) any entry featured.

!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

We include Google ORANDOME AI Data Analysis and libraries (pandas and matplotlib), and import the user, and Geploylib.pyplot for secure API keys.

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...")

This attempt / without a blocking attempts to load the main classes of Acadha, Basuanator, RandomMstream, laws, and funDsamplee so we can tolerate their own built-in strategies and sample strategies. Successful, ensuring that ancient things are available; If any additional failure fails, it holds an error, printing a different message, and kindly fallen back into simple performance.

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

We move you safely to enter your Gemini API key without installing it in a letter of writing. Then we prepare Google AI client (Genaai) with the key to verify all the following calls.

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

It describes a list of medical phases and uses the Geminiannotator class that has threatened the Google Gemini model to the separation phase. In its prescriptions, it creates JSS-Retunting Prompt for each text, includes a model feedback on the correct label, confidence school, and describing the “unknown” label if any errors occur.

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 = []

It describes a list of green symptoms and wrapping each one of the best advertisampless item to pass it to the Annotator. Then your Gemininnotator with a previously defined section is set and preparing empty-in-listing icon.

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]}...")

The active LOOP runs three samples, each period of samples labeled labels and provide the basis of 0.5 words.

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()

Finally, we remove the foretold sections of their self-esteem and use matplotlib to organize the vertical bar chart, where each of the bar is displayed the confidence of the model in that section. The names of the section are rotated to read, the title, and Tight_lout () are confirmed by the chart items are well organized before displaying before displaying before displaying before displaying before displaying before displaying before displaying before displaying before displaying before displaying before displaying before displaying before displaying before displaying before shown.

In conclusion, by combining plug-and-play techniques and sample strategies with productive Google Gemini, we build full spills improve the quality of the medical system. The study is to pass, setup, and betpoke Geminiannottor, and show how to use to see based on seeing and seeing self-esteem. Through this basis, you can easily replace other models, increasing your section set, or combine advanced learning strategies for developing large and complex activities of complex activities.


Survey Brochure in the corner here. All credit for this study goes to research for this project. Also, feel free to follow it Sane and don't forget to join ours 90k + ml subreddit.

Here is a short opinion of what we build in MarktechPost:


Asphazzaq is a Markteach Media Inc. According to a View Business and Developer, Asifi is committed to integrating a good social intelligence. His latest attempt is launched by the launch of the chemistrylife plan for an intelligence, MarktechPost, a devastating intimate practice of a machine learning and deep learning issues that are clearly and easily understood. The platform is adhering to more than two million moon visits, indicating its popularity between the audience.

Source link

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button