Showing posts with label introduccion machine learning. Show all posts
Showing posts with label introduccion machine learning. Show all posts

Sunday, March 23, 2025

Build Your First Interactive Generative AI Website with Meta’s LLaMA Model

Hi friends! 👋

In this tutorial, you’ll create a super simple website where users can type a question and get a response from an AI — just like ChatGPT, but using Meta’s LLaMA model (an open-source AI model) through Hugging Face.

You’ll learn how to:

  • ✅ Use an AI model
  • ✅ Create a basic web page
  • ✅ Connect it all with Python code

🧠 What Are These Tools?

Before we start coding, let’s understand the tools we’re using:

🟣 Hugging Face

Think of this as a giant library of powerful AI models (like LLaMA, GPT, etc.) that you can use in your own apps. It’s like the Netflix of AI models — just log in, choose a model, and go!

🟠 Flask (Python)

This is a mini program that turns your Python code into something that can be used on a website. It’s like the brain behind the scenes — it listens to the user’s question, sends it to the AI, and gives back the answer.


✅ Step-by-Step Tutorial

🔧 Step 1: Open Google Colab

Go to Google Colab and open a new notebook.

📦 Step 2: Install the Tools We Need

!pip install flask flask-ngrok transformers torch pyngrok

🔐 Step 3: Log Into Hugging Face

  1. Go to https://huggingface.co
  2. Sign up/log in → Go to Settings > Access Tokens
  3. Copy your token and paste it into this code:
from huggingface_hub import login
HUGGING_FACE_KEY = "paste-your-key-here"
login(HUGGING_FACE_KEY)

🤖 Step 4: Load Meta’s LLaMA 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)

🧠 Step 5: Let’s Build the Backend (The Brain Behind the Website)

What’s the backend? It’s like the chef in a restaurant. The user places an order (asks a question), and the backend prepares the response using AI.

from flask import Flask, request, jsonify
from flask_ngrok import run_with_ngrok

app = Flask(__name__)
run_with_ngrok(app)

@app.route("/ask", methods=["POST"])
def ask():
    prompt = request.json.get("prompt", "")
    inputs = tokenizer(prompt, return_tensors="pt")
    outputs = model.generate(inputs["input_ids"], max_length=100)
    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return jsonify({"response": response})

🌐 Step 6: Create the Web Page (Frontend)

Now, let’s build the frontend — the part that people see and interact with.

%%writefile index.html
<!DOCTYPE html>
<html>
<head><title>Ask AI</title></head>
<body>
  <h2>Ask the AI</h2>
  <textarea id="prompt" rows="4" cols="50" placeholder="Type your question here..."></textarea><br>
  <button onclick="askAI()">Ask</button>
  <p><strong>Response:</strong> <span id="response"></span></p>

  <script>
    async function askAI() {
      const prompt = document.getElementById("prompt").value;
      const res = await fetch("/ask", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ prompt: prompt })
      });
      const data = await res.json();
      document.getElementById("response").innerText = data.response;
    }
  </script>
</body>
</html>

🧩 Step 7: Connect It All and Run the App

from flask import send_from_directory

@app.route('/')
def serve_frontend():
    return send_from_directory('.', 'index.html')

app.run()

You'll get a link like this: https://xxxxx.ngrok.io
Click it and... 🎉 Your AI-powered website is LIVE!


🏁 Final Words

You just built:

  • A working AI assistant using Meta's LLaMA model
  • A custom web page
  • A backend in Python to power it

You're officially coding with real AI models. That’s amazing. Welcome to the world of AI development!

Wednesday, November 27, 2024

Using Generative AI to Create Sustainable Business Plans: A Mini-Course at the University of Sonora

Last week, we had the incredible opportunity to deliver a mini-course at the University of Sonora on how to use generative AI to craft sustainable business plans. The session was designed to empower students and budding entrepreneurs to integrate cutting-edge AI tools, such as ChatGPT, into their business planning processes. This event showcased the practical applications of AI for innovation and sustainability, offering hands-on experience and collaborative learning.

The Course in Action

The course focused on teaching participants how generative AI can assist in every stage of business planning, including:

  • Brainstorming Ideas: Using AI to refine concepts, identify potential gaps, and generate creative alternatives.
  • Market Research: Employing AI for customer analysis, trend identification, and competitive landscape evaluation.
  • Feasibility Assessments: Exploring cost structures, revenue models, and risk mitigation strategies.
  • Customer Feedback Simulation: Generating insights by simulating customer reactions and improving marketing strategies.
  • SWOT Analysis: Leveraging AI to identify internal strengths and weaknesses and external opportunities and threats.

Participants were encouraged to experiment with AI tools to practice crafting mission statements, vision statements, and value propositions tailored to their sustainable business goals.

Collaborators Making a Difference

The course was a collaborative effort between three instructors, each bringing unique expertise to the table:

  • Dr. Saiph Savage
    A computer scientist and expert in human-centered AI, Saiph provided a technical and strategic perspective on how AI can be applied to the future of work and sustainable business practices.
  • Dr. Rafael Morales
    Originally from Mexico City and a PhD in Political Science from UNAM, Rafael brought a nuanced understanding of how to align AI-driven business strategies with government policies. He highlighted opportunities for collaboration between businesses and governments to promote social good.
  • Jesse Nava
    With extensive experience launching ventures for marginalized communities, including startups supporting low-income Hispanics and formerly incarcerated individuals in the U.S., Jesse shared real-world insights into how AI can help create inclusive, impactful business models.

Why Generative AI?

Generative AI, like ChatGPT, offers a unique advantage for entrepreneurs by providing accessible tools to:

  • Refine business ideas and strategies.
  • Perform rapid iterations to improve outcomes.
  • Enhance collaboration and creativity.
  • Develop sustainable and socially conscious plans.

The session emphasized the importance of human-centered design to ensure that AI tools remain inclusive, adaptable, and aligned with ethical practices.

Gratitude and Looking Ahead

We want to thank the University of Sonora and Dr. Alma Brenda Leyva Carreras for the invitation to deliver this course. It was an honor to collaborate with a multidisciplinary group of students and share knowledge at the intersection of AI, business, and sustainability.

As we move forward, we aim to continue these efforts, fostering a deeper understanding of how AI can empower diverse communities and create a brighter, more sustainable future for all.

Thursday, November 07, 2024

Keynote Speaker at the Mexican AI Conference (MICAI)

Caption: My father, me, and Mexican Professor Beto Ochoa-Ruiz (chair of the Mexican AI Conference) at MICAI in Puebla.

It was an incredible honor to be the keynote speaker at the Mexican AI Conference, a prestigious event with over 40 years of history organized by the Mexican Society for Artificial intelligence. I had the privilege of being a keynote speaker and presenting my research on designing worker-centric AI tools, and it was truly inspiring to see such a vibrant and thriving AI community in Mexico.

Conference Highlights

The conference itself was filled with fascinating talks and discussions. I especially enjoyed the presentation by Professor XX from the University of Toronto, who is pioneering AI systems to quantify and understand smell—an area of AI that I had not previously considered but found fascinating.

I also appreciated reconnecting with Professor Ricardo Baeza Yates, a distinguished researcher at Northeastern University. His work in establishing impactful AI labs in both industry and academia has been transformative, particularly in Latin America. His efforts with Yahoo Research have opened new pathways for research and innovation in the region, creating opportunities for countless researchers.

INAOE: A Unique Setting

The conference took place at the National Institute of Astrophysics, Optics, and Electronics (INAOE), a premier research institution in Mexico. Situated in a serene wooded area, INAOE is home to some stunning telescopes, blending cutting-edge technology with natural beauty. This unique setting added a special touch to the conference, enhancing the overall experience.

Caption: An overview of the speakers, participants, and organizers of the conference.

Special Moments with My Father

One of the most memorable aspects of this experience was attending the conference with my father, who has dedicated much of his career to AI and robotics. We drove together from Mexico City to Puebla, where the conference was held, and this journey gave us the unique opportunity to spend rich quality time together. Our conversations ranged from AI to personal reflections, making this trip a deeply meaningful experience for both of us.

Exploring the City of Puebla

Puebla is an impressive city, renowned for its rich history and architectural beauty. During our visit, I was particularly captivated by its churches, which showcase the Churrigueresque style. This ornate style is a fusion of local Indigenous art and Spanish Baroque, characterized by its elaborate decorations and intricate details. It stands as a testament to the cultural confluence that shaped Puebla’s identity.

Final Reflections

Overall, it was a privilege to be part of such a dynamic and supportive AI research community. The Mexican AI Conference not only provided a platform to share my research but also allowed me to engage with brilliant minds and immerse myself in the rich cultural and scientific landscape of Puebla.

Wednesday, June 08, 2022

Summer: Work in the Age of Intelligent Machines


photos of dr. savage at the conference


I had the honor to start the summer attending and giving a keynote at the Work in the Age of Intelligent Machines (WAIM) Summer Conference. The conference, which is partially funded by the US National Science Foundation aims to create a network of researchers that come together on the topic of work in the age of intelligent machines. In this post I will share a little bit of the discussions and activities we had at WAIM. 


Opening Remarks.

The conference started with opening comments from the conference organizers, whose profiles I share below. Note that I share their profiles because I find interesting how diverse the organizers were (which I think was key for organizing this type of conference):

Dr. Kevin Crowston. Distinguished Professor of Information Science at Syracuse University. He received his Ph.D. in Information Technologies from the Massachusetts Institute of Technology (MIT). His research examines new ways of organizing by the use of information technology. He approaches this issue in several ways: empirical studies of coordination-intensive processes in human organizations (especially virtual organization); theoretical characterizations of coordination problems and alternative methods for managing them; and design and empirical evaluation of systems to support people working together.
Dr. Jeffrey Nickerson. Professor and Associate Dean of research in the School of Business at Stevens Institute of Technology. His research focuses on different aspects of collective creativity, in particular the way crowds and communities design digital artifacts: 3D printing designs, systems designs, source code, and articles. He has a Ph.D. in Computer Science.
Dr. Ingrid Erickson. Associate Professor of Information Science at Syracuse University. Ph.D. from the Center for Work, Technology and Organization in the Department of Management Science and Engineering at Stanford University. She is a scholar of work and technology, currently fascinated by the way that mobile devices and ubiquitous digital infrastructures are influencing how we communicate with one another, navigate and inhabit spaces, and engage in new types of socio-technical practices.

The opening remarks began with an overview of what WAIM had become, how the network had grown, and impact obtained through time. The main goals of WAIM was to create a network of researchers that push forward together investigations on work and machines. For instance, what role do machines have in labor? How do they change the work dynamics? What type of new science fiction realities do we create from integrating intelligent machines in the workplace? What type of futures around work and machines do we want to avoid? What new power dynamics emerge from integrating machines in the workplace? Personally, WAIM has become a key space to build key research collaborations. From prior WAIM conferences, I was able to start working with Professor Jarrahi from UNC, Professor Matthew Lease from UT Austin, Professor Steve Sawyer from Sycracruse University, and Professor Michael Dunn from the University of Albany. Overall WAIM became a great place to connect with academics in the United States who also had an interest in the future of work, and wanted to push forward a new future of work reality with machines. I have particularly liked that I have been able to connect with academics who are not just in computer science, but also in economy, information schools, business schools. The diversity has certainly helped bring new perspectives to my research in the space. It was inspiring and energizing way to start the conference with excellent opening statements and remembering all that we had been able to start building together around work and intelligent machines.

Opening Keynote: Saiph Savage.

I then gave the opening keynote. You can access my slides here: XX. Overall, I discussed how to design meta systems that can empower gig workers to be able to design and create their own tools. We had very interesting discussions around how to motivate workers to collaborate with each other to create their own tools (collaborations are hard because gig platforms also promote competition between workers). I also discussed how to facilitate quality data sharing between workers, and how might you engage the other stakeholders to participate in the design process (I use value sensitive design in this front).

Panel: "Illuminating the Human-Technology Frontier" with Bledi Taska (Emsi Burning Glass), Nick Diakopoulus (Northwestern), Sarah Leibovitz (University of Virginia).


Afterwards, we had a panel on "Illuminating the Human-Technology Frontier", with participation from Bledi Taska (Emsi Burning Glass), Nick Diakopoulus (Northwestern), Sarah Leibovitz (University of Virginia), and the moderator was Jeffrey Nickerson. Dr. Bledi works at Emsi Burning Glass which provides the nation’s premier labor market data. Dr. Bledi discussed about how jobs are changing. From the data in his company he has observed that most changes occurs in jobs that involve technology, and what changes the most are the type of key skills that these jobs need (i.e., top 40 skills needed for the job). Professor Diakopoulus then discussed the role that AI plays in journalism and argued for the importance of better understanding the values that exist in each profession, to define how data looks like, what defaults are chosen, what inputs the system has. It is important to understand the tensions that can exist when defining technology for journalists, especially based on their values. For example, you have to think about: Is there sufficient transparency in the AI so that the journalist feels comfortable with the results? Overall, Prof. Diakopoulus argued for the importance of thinking about the intelligent systems and how to design them to match the values of a profession. He also argued for the importance of thinking about the edge that humans have over AI. Journalists have to negotiate with sources to get their information out of them. That is something that AI still cannot do.  Additionally, the journalists need to have creativity in how they communicate and present their story to effectively engage their audience. So, it is important to think about what is the edge that humans have, how might we design technology that does not focus on replacing journalists, but instead, enhances their work. Within this setting of intelligent systems it is also important to think about how intelligent systems have also made the job of journalists more difficult. Particularly, e.g., we have now a number of bots that are contaminating the information ecosystem and journalists have to learn how to navigate and cut through the automated systems that might be spreading political lies. 


Panel: Future of Work at the Human-Technology Frontier,
with NSF Program Director Andruid Kerne.

After the panel we had a fantastic lunch where conversations around the future of work with intelligent machines were common. We then heard insights Federal Government Employee, Dr. Kerne, who currently works at the US National Science Foundation (NSF), and is a Program Director for NSF's Future of Work at the Human-Technology Frontier program. He discussed what makes good research proposals for this program. He argued that good research proposals are proposals that include multiple views: the perspectives of workers, the insights about the new technologies that will be developed, and how it ultimately affects work. The program directors of this program also considered that if your research could go into another program by NSF, then you should just send it there.  This highlight the importance of identifying what research is indeed very unique to the Future of Work at the Human-Technology Frontier. Dr. Kerne also discussed that for this program it was also important for the intellectual merit to involve multiple fields. The program has a commitment to look for proposals that bring together different fields, and that also function across fields, not just the silos of fields. He argued that research across different fields is necessary to address issues around the future of work. 

I also found particularly interesting that Dr. Kerne argued that for the program it was important to also think about and consider the negative broad impacts that can emerge in the research that is proposed. For instance, how might the technologies that researchers want to study, also facilitate the surveillance of workers, the deterioration of their work conditions, and also how might it result in the digital privacy violations of workers. 

Finally, Dr. Kerne presented examples of successful projects that had been funded. The projects were interesting precisely because they combined multiple fields. For example, there were projects around empowering the labor and entrepreneurship of indigenous communities working in computational ceramics. There were also research projects on Occupational Exoskeletons that involved the areas of Mechanical engineering, sociology, and economics. Other funded projects were on the Future of Automation in the Hospitality Industry (which also included academics in healthcare, HCI, and design). Overall, I found the talk from Dr. Kerne useful to better understand the things NSF's program on the future of work might value to further ensure my success when I apply to future grants :)

Panel: WAIM Fellows Presentations.

A neat thing from this conference was that they were able to also have fellows! The conference funded the year long research of PhD students who conducted investigations on "Work in the Age of Intelligent Machines" ! The fellows included PhD students from UT Austin, Carnegie Mellon University,  Georgia Tech, among others. It was also inspiring to see that all the PhD students who were funded were women! Their research included:
  • Investigating how AI Can be Integrated in Hiring Decisions (UT Austin). Here the research argued that when people are working with AI based tools, they are not always experts, and they can have very different backgrounds and experiences with AI, which can influence how they use the technology. This research focused on studying how people's  background in AI impacts how they use AI, as well as how they use the information that AI provides to them within the hiring process. 

    The research first focused on understanding people's AI literacy. The work focused first on being able to measure people's literacy in AI and then studying how the literacy that was detected impacted how these individuals made decisions around hiring with AI.  Some challenges within this research is: how do you measure AI literacy? In this particular work,  they ended up using a taxonomy that already exists, that focuses on measuring how much people know certain AI concepts and how much they are able to create new AI applications. The research also found that it was important to study what people's understanding of AI is. People had very different perspectives about what AI was and what AI could do.  Such understanding is important as it affects how much individuals trust and use the results that an AI based hiring system outputs to them. Some of the things the research focused on measuring around people's understanding of AI, was how much people knew that there were humans involved in the process of developing algorithms? Do they have a good idea of how algorithms work? What do people think of AI integrated in the decision process? Do they trust it? Do people have positive/negative opinions of AI? Do they trust it or just don’t like it? Currently the research fellow discussed how she is planning on running a national sample to make better sense of people's opinions and knowledge around AI. She will then run an experiment where people run a Job evaluation task with AI to study how people's knowledge and perceptions around AI affects their behavior with the AI based job evaluation results. Based on her findings she plans to create also educational material on how AI can be best used for hiring given people's different backgrounds.


  • Futures of AI Based Care Work (Georgia Tech).  The research studied how AI based technologies could be integrated for rural nurses to help reduce harms, and help them in their jobs. The research is also looking at the new labor that organizations have to take on when new technology  comes into the picture (new types of indivisible labor!)

  • Peer Tools for Gig Workers (CMU). The research discussed how gig workers are on their own to build their brand and figure out the work they have to do. The research of Yasmine, the Phd student leading the work, focuses on designing peer support systems for gig workers. For instance, she designed "Hire Peer", an interface design that offers new formative feedback on creative entrepreneurship so gig workers can help each other to grow and develop themselves as entreponeurs as well. Her research also focuses on helping workers to better brand themselves, and create an identity for themselves. Her research is heavily based on human centered design and participatory design. Given that her research is also interested in the creation of peer support networks of gig workers (i.e., communities) she has been also studying how can we design solutions that are well integrated into communities. She questions: How do we sustain community driven designs? How do we support community based research,  even when there are  institutional barriers that can hinder the analysis and reaching the communities? 

Overall, it was inspiring to see how the WAIM conference was able to fund and push forward the research of new top researchers in the future of work. I liked learning about the new research directions these scholars were exploring. I think to know where the field will go it is important and critical to listen to the new researchers. 


Panel: The Future Work of the Future of Work: MC Binz-Scharf (CUNY), Katie Pine (Arizona State University), Joel Chan (University of Maryland),
Moderator Ingrid Erickson

This panel involved some of the people I admire the most! So it was a trill and pleasure to hear each panelist and the moderator. Dr. MC Binz-Scharf discussed how the future of work is bright. But not for everyone. It can depend on the privilege of the individual. She discussed how there are matrixes of oppression: we never have just one identity and together our different identities can result in different types of discriminations and harms that we can push onto others. It is thus important to think about what are the consequences that exist from the privilege of certain individuals?  For example, in healthcare many times men get the privilege of being studied fully. While women are sometimes considered to be simply "small men". That privilege that men hold bring several misconceptions around best practices for treating women in the healthcare system. There are currently no standard of care for women. Women are thus likely to be misdiagnosed. Black women are 3 times more likely to die in child birth. Inequality is codified in society and in the workplace. There are a number of structures that permit inequality. What type of jobs do women vs men get? The flexibility of gig work and certain types of jobs benefits some but not everyone. It is important to understand the socio-economic differences that can emerge from privilege.  Technology also permeates inequality. Lots of related research, such as the books: Algorithms of Oppression; In Big Data We Trust. People trust the big data algorithms; but the programmer, the coders influence the design of the algorithms and the biases that exist. People trust algorithms without questioning these biases. MC also discussed how "DEI" is a new buzz word that has substitute "work inequality." However, it has also been different than affirming action. We need to understand the changes these new dynamics generate. MC argued for the following research directions: Studying the impact of technology on behavioral changes  and diversity. She argues it is especially important to measure the effect of the DEI initiatives. An interesting point that MC made was that the people who enjoy privilege should take part in DEI initiatives. If you enjoy some privilege join the party and be part of DEI initiatives. She argues their integration is important as these individuals are who have the current power to push forward change. 

Similarly, Katie Pine (Arizona State University) and  Joel Chang (University of Maryland) discussed about  who gets to design the future of work. People in the neighborhood want to participate in the design of the systems that control the neighborhood. But the problem is: Who actually gets to participate in the design? Workers are many times not able to design their own tools. It is a hard problem. How might we empower workers to design? How do we help workers to be proactive, not reactive in the designs they propose? How do we get there? Katie and Joel argued for the importance of creating coalitions to address the problem, as well as conducting Participatory Design. However, integrating participatory design is NOT as straightforward, especially because Participatory Design requieres a lot of work to really involve people in the design process. It can take a lot of work for the true needs to come out.  It is also hard to know where should the design of tools by participants happen? You can bring people into the lab to design. But who gets to make it to the lab? (Many times it is elites who can travel to the laboratory because they might have more free time, or means of getting to the lab). Additionally, you could argue that researchers should just go to where the people are and do the participatory design where the individuals are. The problem with that approach is that there are a number of different barriers to go to their space, but then once you even arrive you have new issues that you also need to learn how to handle, such as power dynamics. The question then is: How do we create a shared space where people can all co-design? How do we design that space so people can really design together? There is also value in studying how much the designs that were created by gig workers were of any good. How do you evaluate them? No clear sense of quality. Is it time for a Meta-design for the future of work?

Keynote 2 Youngjin Yoo (Case Western)

The second keynote was with famous Professor Youngjin Yoo. He is the Elizabeth M. and William C. Treuhaft Professor in Entrepreneurship and Professor of Information Systems at the department of Design & Innovation at the Weatherhead School of Management, Case Western Reserve University. An Association of Information Systems Fellow, he is also WBS Distinguished Research Environment Professor at Warwick Business School, UK. and a Visiting Professor at the London School of Economics, UK. He is the founding faculty director of xLab at Case Western Reserve University. He has worked as Innovation Architect at the University Hospitals in Cleveland, overseeing the digital transformation efforts at one of the largest teaching hospital systems in the country. Before he returns to Case Western Reserve University, he was the Harry A. Cochran Professor of Management Information Systems and the Founding Director of Center for Design+Innovation at the Fox School of Business, Temple University where he was also the founder and Principal Investigator of Urban Apps & Maps Studios, an interdisciplinary initiative for digital urban entrepreneurship in Philadelphia. Previously, he was the Lewis-Progressive Chair of Management at Case Western Reserve University. He has taught digital innovation strategy at Indian School of Business, Aalto University in Finland, and Korean Advanced Institute of Science and Technology. He was a summer research fellow at NASA in summer of 2001 and spent a year as a research associate in 2003 – 2004 at NASA Glenn Research Center. He was also a visiting professor at Chalmers University of Technology in Sweden, Viktoria Institute in Sweden, Hitotsubashi University in Japan, Hong Kong City University, Yonsei University, Korea and Tokyo University of Science, Japan. He holds a PhD in Information Systems from the University of Maryland. His research interests include: digital innovation and entrepreneurship, organizational genetics, societal use of technology and design. He has received over $4.5 million in research grant from National Science Foundation, NASA, James S. and John L. Knight Foundation, the Department of Commerce, National Research Foundation of Korea, and Samsung Electronics. His work was published at leading academic journals such as MIS Quarterly, Information Systems Research, Organization Science, the Communications of the ACM, and the Academy of Management Journal among others. He is Senior Editor of MIS Quarterly, the Journal of AIS, and the Journal Information Technology, and is on the editorial board of Organization Science, Scandinavian Journal of Information Systems, and Information and Organization. He was a former senior editor of the Journal of Strategic Information Systems and an associate editor of Information Systems Research and Management Science. He has worked with leading companies including Samsung Electronics, Samsung Economic Research Institute, American Greetings, Progressive Insurance, Goodyear Tire, Sotera Health, Bendix, Moen, Intel, Ford Motor Company, Andersen Consulting, IDEO, Gehry and Partners, University Hospitals in Cleveland, American Management Systems, Lotus, NASA, Parker Hannifin, Poly One and the Department of Housing and Urban Development. 

These were some of the main activities of the first day. The conference offered amazing breakfast, lunch, and reception events. These social gathering events during the conference were really nice for connecting and networking with other researchers (We also had very nice night walks to the white house! See picture above.) The next day we had in depth discussions on our papers and research proposals. I found this piece of the conference particularly useful for my own work, as I was able to better craft my research contribution in a much better way. I felt I was receiving coaching from top Olympic athletes that were guiding me to also be successful. Overall, it was a fantastic research event.  Very useful for advancing on my papers, proposals, and tools I co-design and create with gig workers.  It also opened new collaborations, and was overall great for pushing forward the network of researchers conducting investigations on Work in the Age of Intelligent Machines :)

Monday, May 16, 2011

LDA is not Ladies Ditching Apes

I have recently been working on Topic Modelling and thought I'd do a brief tutorial on how to automatically divide a text into a series of relevant topics.

Before we dive into our coding, let's give a brief overview of the topic so we are all on the same page:

Topic Modelling is all about automatically finding the thematic structure of a document or a series of documents.

Topic modelling specifies a probabilistic method through which documents can be created. Initially a distribution over topics is selected. For example, the topics of Love and Mexico could be chosen, but each assigned a certain weight or probability. If it was sought for the article to have a greater political inclination, Mexico would be assigned a greater weight than Love. Whereas if the purpose was to write a romantic novel, Love would have a much higher weight or probability assigned than Mexico. Once the topics along with their corresponding probabilities have been assigned, a topic is chosen randomly according to the distribution, and a word from that topic is drawn. This process of randomly choosing a word from a topic is done iteratively until the system has finished "writing" the article.

Besides creating documents automatically ( Hasta la vista estudiantes de Literatura :P) Topic Modelling can also infer the set of topics responsible for generating a collection of documents.
We care about Topic Modelling because it can enhance search in large archives of texts, it also permits for better similarity measures: given two documents exactly how similar are they?

Different algorithms exist for finding the thematic structure of a document. Today we will focus on one particular algorithm called Latent Dirichlet Allocation (LDA). Which is a "...generative probabilistic model for text corpora...".
The intuition behind LDA is that a document is conformed of a series of different topics, and each topic is a probability distribution over words. Each document is a random mixture of corpus-wide topics, where each word of a document is drawn from one of these topics. LDA intents to infer how the documents are divided according to these topics, and what the topics are. The only information LDA has, are the documents.

In the following, we will use THE FORMAL notation of LDA, (mathematical style!) to make things a bit more clearer:
P(z) denotes the topic distribution z of a particular document. P( w | z ) is the probability distribution of words w given topic z. LDA assumes each word wi in a document (where the index refers to the ith word token) is generated by first sampling a topic from the topic distribution, then choosing a word from the topic-word distribution. We write P( zi = j ) as the probability that the jth topic was sampled for the ith word token and P( wi | zi = j ) as the probability of word wi under topic j.

LDA assumes that the topics present a Dirichlet distribuition, i.e. the mixture weights θ are generated by a Dirichlet prior on θ. Each topic is modelled as a multinomial distribution
over words.
Hopefully this brief overview will allow us to have some Python coding fun for our next post!

Saturday, March 05, 2011

How to use Machine Learning to boost up your Parallel Computing

In the past, programmers would find reassurance to their problems of running extremely large programs in the yearly speed up of computer processors. Every year or so, the speed of computers would double and a faster computer would be in the market which would be able to rapidly execute their large sized code. But, in today's world this is not the case, analysing the GHz speed of the processors in a desktop computer of 2 years ago, versus the speed new desktop computers present, proves that it has barely, if any, increased, this mainly due to the fact that it is very difficult to build reliable low-cost processors that run significantly faster. This is the reason why, the solution to running faster code has focused on doubling the number of processors that exist on a single chip. Actually researchers believe, that in the following years we will have systems, which present twice the number of cores with every new technology generation.

It is important to note, that these multi-processors have laid the road for using parallel computing, in which a large program can be divided into smaller programs, each of which is then assigned to a processor with shared or independent resources. Parallelism is what is generally used today, for providing Performance improvement.

This approach although generally highly functional, has shown in some cases to degrade the performance considerably! The problem is that the scheduling of parallel jobs is a very complicated task which is highly dependent on a series of different factors: the workload, the blocking algorithm being utilised, the local operating system, the parallel programming language and the machine architecture. Expert humans are who tend to make the design specifications for these highly complicated tasks,and as a result they tend to be somewhat rigid and unsophisticated [1].

Because of this, machine learning techniques have in recent years provided a solution to this problem. Machine learning is a field which intends to build computer systems that automatically improve with experience. Researchers have been applying machine learning algorithms to problems of resource allocation, scheduling, load balancing, and design space exploration, among other things.

Such is the work done, in Cost-Aware Parallel Workload Allocation Approach based on Machine Learning Techniques. Here the authors tackle the problem of finding adequate workload allocations in a cost-aware manner, by learning from training examples how to allocate parallel workload among Java threads.
Given a program, their system computes its feature vectors, and utilising a nearest neighbour approach finds from the training examples, the best parallel scheme for this new program.

One may initially wonder, what type of training examples were utilised for this problem and how were they generated?
The training examples came from a series of programs coded in java, which presented different for loops. From each for loop its corresponding feature vector was calculated along with its associated label, this conformed each training example. In this case, the feature vector corresponded simply to the workload the for loop presented, and the label to the optimal number of threads that should be utilised with that specific workload.
The programs which were utilised for the training examples were manually selected, each had the purpose of bringing a certain workload variety to the training pool.The labels were set by an automatic program, which tested each workload (loop description) with a different number of threads, and then calculated what was the optimal thread number required for that specific workload to achieve optimal performance. It is important to note, that in this approach the computation cost of calculating the feature vectors was diminished by calculating an implicit estimate of the workload, the features which conformed the workload were: 1) loop depth; 2) loop size; 3) number of arrays used; 4) number of statements within the loop body, and 5) number of array references.

Since not all program features play an equal role in workload estimation different weights were assigned to different features during classification, with higher weights given to feature 1), 2) and 4). Within the paper it was not clearly explained how the values of these weights were assigned or what their values were. It might have been adequate to also utilise a learning algorithm which was capable of finding the most adequate weights given a certain training example, because it might be the case that under certain conditions a feature might be weaker for classification than an other, and therefore other weights need to be utilised. A broader explanation on the weight manner could have provided more insight and restricted this speculation, but it is interesting to ponder none the less.

On the other hand, in this example the authors opted for a supervised learning approach, where each training example that was handed to the system was manually selected and labelled. This is clearly a tedious task to do, and at times may not be the most optimal, since manually finding which examples provide more information for the learning process in comparison to other possible training examples is difficult and non-trivial. One therefore wonders if an unsupervised learning algorithm could have provided better results. In this type of approach, the machine can be "thrown into the wild" and through observations discover previously unknown structures or relationships between instances or their components, this could eliminate the problems mentioned previously, but has the shortcoming that if the learning phase is done online the algorithm might take much longer than if an instance based learning approach had been taken.



Furthermore it does not seem that their approach accounts for any long-term consequences. Each decision within a for loop was done independently of what had been decided for the other for loops within the program, this might mean, the decision to use X amount of threads for that workload might be locally optimal but not globally optimal, this could in the long run deteriorate the performance. This situation seems to suggest that for this problem instead of using instant based learning, a better approach would have been to use Reinforcement Learning. In Reinforcement Learning, the machine is not told which actions to take, but rather must infer them, by analysing what yields the best reward. The following figure presents an overview of how reinforcement learning works


For this particular case, if they authors had used this other learning method, it could have been possible for the machine to analyse the program as a whole, and decide then what the best long-term thread allocation for each workload would be. In specific, the machine would have interacted with the "environment" (in this case the supplied java program) over a discrete set of time steps. In each step the machine would have "sensed" the environment's current state (which would match the number of threads being used in each for loop) and executed an action(an action would correspond to assigning or removing more threads to certain for loops). This action would modify the environment’s state (which the machine could sense in the next time step) and produced an immediate reward (The reward would be the overall performance obtained for that particular thread assignation).
The machine’s objective would be to maximise its long-term cumulative reward by learning an optimal policy that maps states to actions.
In its most basic form, Reinforcement Learning brings a knowledge-free trial-and-error methodology in which the machine intents various actions in numerous system states, and learns from the consequences of each action.
From this, it is clear that the advantage of using this learning method is that no explicit model of either the computing system being managed or of the external process that generates workload or traffic are necessary.Additionally, Reinforcement Learning is capable of treating dynamical phenomena in the environment, as mentioned before, it can analyse how current decisions may have delayed consequences in both future rewards and future observed states.

Now, while this can sound very promising, it is necessary to also take into consideration, the challenges which Reinforcement Learning faces in the real world. Firstly, Reinforcement Learning can suffer from poor scalability in large state spaces, furthermore in times the performance obtained during online training can be below average, due to the lack of domain knowledge or good heuristics. In addition, because reinforcement learning procedures need to include "exploration" of actions, the selection of actions can be exceedingly costly to implement in a live system. This is the reason why, many modern applications that utilise reinforcement learning in order to address the above practical limitations,take a hybrid approach. Such an example, is the work done in A Hybrid Reinforcement Learning Approach to Autonomic Resource Allocation. Here the authors propose for the machine to have an offline training phase. They suggest that given enough training examples which follow a certain optimisation policy , the learner (machine) using reinforcement learning will be able to converge to the correct value function, it will be able to find a new policy which greedily maximises the value function and is able to improve the original policy that was given. In this form, the poor performance that is obtained by using live online training is avoided. Another benefit of their method is that multiple iterations can be done: Through training a new policy, which is the improved version of the original policy, is obtained. This improved policy can then be feed into the system again, acting as the original non-optimal policy, with this second policy a second data set is collected, which can then be used to train a further improved policy. This enables the possibility of running the algorithm iteratively till a desired "reward" is obtained.

It was mentioned before that reinforcement learning, presents the problem of having expensive exploration of actions, the authors tackled this problem by replacing the generally used lookup table for representing the value function with a nonlinear function approximator, in particular a neural network. A function approximator provides a solution to the mentioned issue, because it is mechanism for generalising training experience across states, therefore it is no longer necessary to visit every state in the state space. It also allows for generalisation across actions, so that the need for exploratory off-policy actions is also greatly reduced.

Their hybrid Reinforcement Learning approach was tested on realistic prototype Data Center, which dynamically allocates servers among multiple web applications so as to maximise the expected sum of SLA (service level agreement) payments in each application.

Although their proposed solution resolves most of the problems encountered with reinforcement learning, we can observe an aspect of their work, that might call for improvement: In their algorithm with each iteration, the model of the system is modified. They always assume the model "learned" from the use of a certain set of policies can never be applied to a set conformed of other policies. The authors never explored if this is always the case, could a model learned with certain policies still be valid under other policies which hold a degree of similarity to the original policies, or is it always necessary to learn from scratch the model, as a result of changes to an active set of policies?
Additionally, the authors utilised a neural network for finding the states to explore, and although this did solve the exploratory problem mentioned before, because the neural network has hidden states it is not possible to determine beforehand exactly how many states will be explored given the current used policies, knowing beforehand this number could improve computational costs as better planning can be done. In the work done in "An Adaptive Reinforcement Learning Approach to Policy-driven Automatic Management", the authors addressed this problems and show how a Reinforcement Learning Model can be adapted to accommodate this.
The authors analysed how previously learned information about the use of policies can be effectively used in a new scenario. For this, they consider policy modifications as well as the amount of time used to form the model before the changes. Similarly to the work in Hybrid Reinforcement Learning Approach to Autonomic Resource Allocation, a state transition model, which uses a set of active expectation policies is defined, but in difference to Hybrid Reinforcement Learning Approach to Autonomic Resource Allocation, instead of using a neural network, the authors capture the management system's behaviour through a state-transition graph, what their system is lacking and could be beneficial in the future is mapping directly how changes in policies effect the state-transition models

Monday, February 02, 2009

¿Cómo aprendería una máquina un concepto?

Cuando hablamos de aprendizaje, nos referimos al hecho de mejorar alguna tarea usando la experiencia .
Esto es:
  • Mejorar en la tarea T
  • Con respecto a la medida de rendimiento P
  • basándose en la experiencia E.

    Por ejemplo, aprender a jugar ajedrez:

  • *T:Jugar ajedrez
  • *P: % de juegos ganados en torneos.
  • *E:Opportunidad de jugar contra uno mismo.

Es fácil de entender esto, ya que en la vida cotidiana cuando un individuo aprenda un concepto nuevo, es muy común que utilice una serie de ejemplos específicos que le sirven de entrenamiento. Si el individuo está aprendiendo lo que es una vaca, los ejemplos de entrenamiento que podría tener son fotos diversas de vacas, donde se le indique que esas fotos son efectivamente de vacas, también se podría tener como entrenamiento fotos de otros animales, y se le podría indicar que esas fotos NO representan una vaca.
Con esto podemos observar, que se puede definir que un concepto es una función booleana valuada sobre un conjunto mayor. Es decir, es una función definida sobre TODOS los animales, cuyo valor será verdadero para las vacas y falso para cualquier otro tipo de animal.
Un problema interesante que existe, es obtener un método mediante el cual se pueda inferir de manera automática la definición general de un concepto, dados unos ejemplos que muestran miembros o no-miembros del concepto. Este tipo de tarea se suele llamar Aprendizaje de conceptos o Concept Learning.
Aprendizaje de Conceptos
El Aprendizaje de Conceptos se refiere al hecho de inferir una función booleana apartir de ejemplos que muestran sus entradas y salidas .
Para entender mejor, todo esto, empezaré por definir unas cosas:
El conjunto de elementos o instancias sobre el cual un concepto es definido se llama el conjunto de instancias, el cual será denotado por la letra X.
El concepto ó función a ser aprendido se llama el concepto meta,el cual será denotado por una c.
En general, la c puede ser cualquier función booleana definida sobre las instancias X.
Esto es c: X ->{0,1}
Ahora bien, como se mencionó antes usualmente cuando una persona aprende un concepto se le presentan una serie de ejemplos que facilitan el aprendizaje. Cada ejemplo consiste en una instancia de x que pertenece a X, así como su concepto objetivo valuado,c(x) Ya que se presentaron estos ejemplos, el individuo debe tratar de estimar cual es el concepto meta. Se usará el símbolo H para denotar todas las posibles hipótesis ó estimaciones de c que el aprendiz genere en su búsqueda por definirla.
Con esto, es claro que la tarea del aprendiz, es encontrar una hipótesis h, que sea idéntica al concepto c.
Para aterrizar más esto, considerese el ejemplo de aprender el concepto objetivo de “Días en los que mi amado disfruta besarme bajo la luna”.
La siguiente tabla muestra un conjunto de ejemplos de días, cada uno representado por un conjunto de atributos.

Ejemplo

Cielo

Temperatura

Viento

GustaBesarme

1

Estrellado

Caliente

Fuerte

Sí

2

Estrellado

Caliente

Fuerte

Sí

3

Nublado

Frío

Fuerte

No

4

Estrellado

Caliente

Fuerte

Sí


El atributo de GustaBesarme indica si a mi amante le gusta besarme bajo la luna en ese día. La tarea es aprender a predecir el valor de GustaBesarme para un día arbitrario, basándose en los valores de los otros atributos.

Lo primero que se deberá hacer, es definir como se quiere representar a las hipótesis.
En este caso, podemos definir a h, como una conjuncion de restricciones sobre los atributos.
Cada una de las restricciones puede ser:
  • Un valor especifico. Esto es: Cielo=Estellado
  • Sin importancia . Cualquier valor es aceptado para este atributo. Esto es Cielo=?
  • Un valor no aceptado. Esto es Cielo=0
Por ejemplo, se podría tener:
Cielo Temp Viento
Estrelallado ? Alto

Si una instancia x satisface todas las restricciones de la hipótesis h, entonces la hipótesis h clasifica a x como un ejemplo positivo (h(x)=1)
Por ejemplo, la hipótesis que dice que a mi amante le gusta besarme bajo la luna en días con temperatura alta y cielo estrellado, independientemente de como esté el viento, se representa por la expresión:
(estrellado,alta,?)
En resumen, en la tarea de aprender el concepto de GustaBesarme, se requiere aprender el conjunto de días para los cuales GustaBesarme=sí, este conjunto de días se puede describir mediante una conjunción de restricciones sobre las instancias de atributos. Como por ejemplo, el cielo deberá estar estrellado, y la temperatura deberá ser alta, para que a mi amante le guste besarme bajo la luna.

La hipótesis de aprendizaje inductiva
Es importante notar que aunque la tarea en el aprendizaje es encontrar la hipótesis h que es igual al concepto objetivo c sobre un conjunto de instancias X, la única información disponible sobre c, es el valor que posee dentro de los ejemplos de entrenamiento. Dicho más fácilmente, la única información que se tiene con respecto a los días en que a mi amante no le gusta besarme bajo la luna, está en los ejemplos de entrenamiento.
Ahora bien, debido a que no poseemos más información, se asume que la mejor hipótesis para instancias no vistas, es la hipótesis que mejor le queda a nuestros ejemplos.
Si encontramos con los ejemplos de entrenamiento, que la mejor hipotesis que explica en que días a mi amante le gusta besarme bajo la luna, es cuando la temperatura es alta, ,entonces usaremos esta hipótesis para clasificar instancias de días no vistas en los entrenamientos. Si tuvieramos un día, que fuera estrellado con temperatura baja y viento fuerte , diríamos que en este día a mi amante no le gusta besarme bajo la luna, ya que temperatura=baja.

La hipótesis del aprendizaje inductivo : Cualquier hipótesis que se encuentre que aproxima bien la función ó el concepto objetivo sobre un conjunto suficientemente grande de ejemplos de entrenamiento, también se aproximará bien a la función ó concepto objetivo en ejemplos no vistos durante el entrenamiento.

El Aprendizaje de un concepto como una búsqueda
El aprendizaje de conceptos se puede ver como la tarea de buscar, a través de un espacio grande de hipótesis, a la que mejor representa a los ejemplos de aprendizaje.
Es importante notar que las hipótesis que se encunetran en el espacio, están definidas bajo una cierta representación, que está a manos del diseñador, debido a esto, el diseñador está implicitamente declarando el espacio de todas las hipótesis que el program puede represnetar, y por ende aprender.