Showing posts with label analisis inteligente de palabras. Show all posts
Showing posts with label analisis inteligente de palabras. Show all posts

Thursday, December 12, 2024

How to Summon AI Magic with Python: A Fun Guide to Generative AI APIs

Hey there, tech explorers! Ever wanted to whip up some magical AI-generated text, like having robot Shakespeares at your fingertips? Well, today’s your lucky day! We’re here to break down a piece of Python code that lets you chat with a fancy AI model and generate text like pros. No PhDs required, we promise.

First Things First: The Toolbox

Before we can talk to the AI, we need to grab some tools. Think of it like prepping for a camping trip—you need a tent (the model) and some snacks (the tokenizer).

        
pip install transformers
        
    

This command installs the Transformers library, which is like the Swiss Army knife of AI text generation. It’s brought to you by Hugging Face (no, not the emoji—it’s a company!).

Step 1: Unlock the AI Vault

We’ll need to log in to Hugging Face to get access to their cool models. Think of it as showing your library card before borrowing books.

        
from huggingface_hub import login
login("YOUR HUGGING FACE LOGIN")
        
    

Replace "YOUR HUGGING FACE LOGIN" with your actual login token. It’s how we tell Hugging Face, "Hey, it’s us—let us in!"

Step 2: Meet the Model

Now we load the AI brain. In our case, we’re using Meta’s Llama 3.2, which sounds like a cool llama astronaut but is actually an advanced AI model.

        
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch

model_name = "meta-llama/Llama-3.2-1B"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto")
        
    

- Tokenizer: This breaks down your input text into AI-readable gibberish. - Model: The big brain that generates the text.

Step 3: Give It Something to Work With

Now comes the fun part: asking the AI a question or giving it a task.

        
input_text = "Explain the concept of artificial intelligence in simple terms."
inputs = tokenizer(input_text, return_tensors="pt")
        
    

- input_text: This is your prompt—what you’re asking the AI to do. - tokenizer: It converts your input into numbers the model can understand.

Step 4: Let the Magic Happen

Here’s where the AI flexes its muscles and generates text based on your prompt.

        
outputs = model.generate(
    inputs["input_ids"].to("cuda"), 
    max_length=100, 
    num_return_sequences=1, 
    temperature=0.7, 
    top_p=0.9, 
)
        
    

- inputs["input_ids"].to("cuda"): Sends the work to your GPU if you’ve got one. - max_length: How long you want the AI’s response to be. - temperature: Controls creativity. - top_p: Controls how "risky" the word choices are.

Step 5: Ta-Da! Your Answer

Finally, we take the AI’s response and turn it back into human language.

        
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generated_text)
        
    

skip_special_tokens=True tells the AI, "Please don’t include random weird symbols in your answer."

So, What’s Happening Under the Hood?

Here’s a quick analogy for how this works:

  • We give the AI a prompt (our input text).
  • The tokenizer translates our words into numbers.
  • The model (our AI brain) uses these numbers to predict the best possible next words.
  • It spits out a response, which the tokenizer translates back into words.

It’s like ordering a coffee at Starbucks: we place the order, the barista makes it, and voilà—our coffee is ready!

Why Should We Care?

Generative AI APIs like this are the backbone of chatbots, creative writing tools, and even marketing copy generators. Whether we’re developers, writers, or just curious, playing with this code is a great way to dip our toes into the AI ocean.

Ready to Try It?

Copy the code, tweak the prompt, and see what kind of magic we can summon. Who knows? We might create the next big AI-powered masterpiece—or at least have some fun along the way.

Now go forth and generate! 🎉

Sunday, November 20, 2022

List of MIT Tech Review Inspiring Innovators!

We are part of the amazing network of the 35 Innovators under 35 by the MIT Tech Review. We got invited to their EmTech Event and had amazing dinner with other innovators and people having an impact in the field. We are very thankful with Bryan Bryson for the invitation, and we also wanted to congratulate him and his team for all the work done to build such a vibrant innovation ecosystem.



I share below a list of some of the innovators I meet. Keep an eye on them!

*Setor Zilevu (Meta and Virginia Tech). Working at the intersection of human-computer interaction and machine learning to create semi-automated, in-home therapy for stroke patients. After his father suffered a stroke, Zilevu wanted to understand how to integrate those two fields in a way that would enable patients at home to get the same type of therapy, including high-quality feedback, that they might get in a hospital. The semi-­automated human-computer interaction, which Zilevu calls the “tacit computable empower” method, can be applied to other domains both within and outside health care, he says.

Sarah B. Nelson is Chief Design Officer and Distinguished Designer for Kyndryl Vital, Kyndryl’s designer-led co-creation experience. From the emergence of the web through the maturity of user experience practice, Sarah is known throughout the design industry as a thought leader in design-led organizational transformation, participatory, and forward-looking design capability development. At Kyndryl, she leads the design profession, partnering with technical strategists to integrate experience ecosystem thinking into the technical solutions. Sarah is an encaustic painter and passionate surfer.

*Moses Namara (Meta and Clemson University). Namara co-­created the Black in Artificial Intelligence graduate application mentoring program to help students applying to graduate school. The program, run through the resource group Black in AI, has mentored 400 applicants, 200 of whom have been accepted to competitive AI programs. It provides an array of resources: mentorship from current PhD students and professors, CV evaluations, and advice on where to apply. Namara now sees the mentorship system evolving to the next logical step: helping Black PhD and master’s students find that first job.

*Joanne Jang (OpenAI). Joanne Jang is the product lead of DALL·E, an AI system by OpenAI that creates original images and artwork from a natural language description. Joanne and her team were responsible for turning the DALL·E research into a tool people can use to extend their creative processes and for building safeguards to ensure the technology will be used responsibly. The DALL·E beta was introduced in July 2022 and now has more than 1 million users.

Daniel Salinas (Colombia) Su ‘start-up’ monitoriza las plantas con nanotecnología al conectarlas con ordenadores y facilita la descarbonización. Los humanos tienen 'ceguera a las plantas'. Nuestros sesgos nos impiden percibirlas como sí hacemos con los animales. Esta desconexión planta-humano lleva a que los proyectos de plantar árboles para capturar carbono frente a la crisis climática no sean sostenibles si la reforestación no se mantiene en el tiempo. El estudiante de Emprendimiento colombiano Daniel Salinas descubrió la falta de infraestructuras en la lucha para la descarbonización con una 'start-up' de plantación de árboles. El joven recuerda: "Cada vez que íbamos al terreno teníamos problemas". Para romper esta desconexión entre personas y árboles, Salinas ha creado una interfaz planta-ordenador que permite hacer un seguimiento de la vegetación con su start-up Superplants. Con esta aportación, Salinas ha logrado ser uno de los Innovadores menores de 35 Latinoamérica 2022 de MIT Technology Review en español.
Girl in a jacket
Relevant References:
-https://www.building-up.org/knowledgehub/innovadores-menores-de-35-latinoamrica-2022
-https://event.technologyreview.com/emtech-mit-2022/speakers
-https://www.technologyreview.com/innovator/setor-zilevu/

Monday, October 06, 2008

Why I no longer hate networking, as much as before

Creo, que los algoritmos de deodificación, me agradan bastante. ¿Ya conocían el de Viterbi?
Está bastante interesante como funciona, usa likelihood probabilities, en Aprendizaje o Machine Learning, se usa mucho para diversos métodos de aprendizaje.
No conocía en lo personal yo el de Markov, y de hecho Viterbi se basa en este método para su funcionamiento ,Belive it or no, es bastante straight foward.
Je, veamos sí es tan cierto,intentaré explicarlo:

Viterbi: Es un algoritmo de decodificación, desarrollado a finales de 1960 por Andrew Viterbi. Los decodificadores Viterbi, han sido la manera más efectiva de decodificar comunciaciones de voz inalámbricas en transmisiones satelitales y de celular. Viterbi saca ya sea 0 o 1, dependiendo de lo que estima, que es el bit de entrada.El algoritmo de Viterbi, brinda una manera eficiente de encontrar la secuencia de caracetres con mayor probablidad a posteriori, (MAP)

Para ilustrar como funciona el algorimto de Viterbi, daré un pequeño ejemplo:
Assúmase, que se tiene un alfabeto de 4 letras, A={T,A,C,O}, y que se tiene un Optical Character Readers , un lector de caracteres, el cual intentará leer palabras que sean válidas del inglés. Supónase, que la cadena observada por la maquina OCR es: Z= -CAT-, donde el "-" denota espacios en blanco. Los vectores característicos z1, z2, and z3 son obtenidos cuando el extractor de característica detecta a C,A,T. (GATO en español, y es una palabra válida del idioma inglés.)
La información disponible obtained y relevante que el algoritmo Viterbi utliza para tomar una decisión, se expresa en término de la gráfica direccionada, que se muestra a continuación. Todos los nodos, excpetos los que están en blanco "-", poseen una probablidad ascosciada a ellos.

Denker



Vemos, de la figura , que cualquier camino , de un nodo principio, hasta un nodo final, represneta una secuencia de letras, mas no necesariamente una palabra válida. Se trata de hallar la sequencia de letras que maximizen el producto de probabilidades en su camino. Esto se puede lograr, al porcesar los nodos verticales, paso por paso de izqueirda a derecha. De este modo, si se agregan los logaritmos de las orillas, y las probabildiades de nodo, del camino, obtenemos:

gGAT(z1,Z2,Z3)=logp(z1|C)+logp(z2|A)+ logp(Z3|T)+log[P(C|-)P(A|C)P(T|A)P(-|T)]


Con este modelo, las letras del idioma inglés se visualizan como salidas, de un proceso de M estados de Markov, donde M es el número de caracteres distinguibles, si se trata de letras, el número será de 26, ya que el alfabeto del idioma inglés, pose 26 letras. En cada etapa de la secuencia (palabra), las 26 más probables secuencias se procesarán, la secuencia más probable que terminé en A, la secuencia más probable que termine en B, etc. En la etapa final, la secuencia más probable es seleccionada.
Denker