AI Practice Exercises

Updated · 42 min read
mediumPython 3.13aichallengespracticeexercisesassessment

Every lesson in this course ends with a practice exercise: a small task that makes you use what the lesson taught, often by changing one of its programs. This page collects all 186 of them, so you can practice by level, revise before an interview, or find gaps in what you know. Each link opens the lesson's Practice section.

How to Practice

  1. Choose a level with the buttons below.
  2. Do the exercise before rereading the lesson. Many continue the lesson's own example, so run its earlier programs first, in a practice folder.
  3. Predict the result before you run anything, then compare. Being surprised is how you find what to revise.
  4. Mark the ones you found hard and come back to them a few days later.

Level 1: AI Foundations

ExerciseLessonTask
AI in your weekWhat Is Artificial IntelligenceWrite down five AI-powered features you have used in the last seven days. For each one, note what it did for you, what examples it might have learned from, and one mistake it could make. Phone features, apps, websites and services all count.
An AI diaryAI in Everyday LifeFor one day, write down every time a device or app does something "smart" for you. At the end of the day, sort each entry into recognizing, predicting or recommending, and generating. Which kind did you use most?
Myth or fact?AI Is Not MagicFind two news headlines or social media posts about AI from this month. For each one, write down what the AI system actually does, how it was tested (if the article says), and whether the headline is a myth, an exaggeration or a fact.
Then and nowA Short History of AIPick one milestone from the timeline. Write three sentences: what it did, why it was impressive at the time, and what it couldn't do.
Explain it to a 12-year-oldAI, Machine Learning and Deep LearningUsing the family analogy, explain AI, machine learning and deep learning in five sentences or fewer, with one example of each from your own life. Then read it aloud to someone. Did they understand it without any extra help?
Change the examplesTraditional Programming vs Machine LearningRun the house-price program, then add a fourth sale, (1500, 420_000), to the sales list. Does the learned price per square foot go up or down? Why? Then write down one feature, other than area, that would make the prediction better, and explain why.
Name the typeTypes of Machine LearningFor each task, write supervised, unsupervised or reinforcement, and one sentence explaining why:
A data diaryWhat Is DataFor one hour, list every piece of data you create or use: messages, photos, payments, steps, searches. For each one, write the kind of data (text, numbers, image, audio, video or record) and who might store it.
Sort your phoneTypes of DataPick ten things on your phone, such as contacts, photos, a calendar event, a voice note and a downloaded bill. Label each one structured, semi-structured or unstructured, with one sentence explaining why. Which type did you have the most of?
Build a small datasetDatasets, Labels and FeaturesCreate a table of 20 products with the columns name, price, category and rating (1 to 5). Then answer: if an AI system recommended products from it, which columns would be features, and what could be the label? Finally, decide which 14 rows you would train on, which 3 you would use for validation, and which 3 you would keep for the test.
Audit a datasetData Quality and Bias in DataLook at the product dataset you built in "Datasets, Labels and Features", or a list of your own photos. Find one example of each problem you can: a wrong value, a missing value, a duplicate, an inconsistent spelling and a group that is missing. How would each one affect a model trained on it?
Plan a privacy-safe datasetData Privacy BasicsAdvitha's coaching center wants to predict which students need extra help. List the fields you would keep, remove or replace with an ID, from: name, phone number, marks, attendance, health notes, parent's income and city. Then write the one-paragraph consent message you would show students, in plain words.
Input, model, outputWhat Is an AI ModelPick five AI features you use, such as photo search, voice typing or a map's arrival time. For each one, write the input, the kind of model it probably uses, and the output. Which one was hardest to describe, and why?
Change the nudgeParameters: What a Model LearnsRun the program, then change 0.000000125 to 0.00000005. Does the weight reach about 236 faster or slower? Why? Then try 0.0000003 and describe what happens to the weight. Write one sentence about why the size of each nudge matters.
Take apart an AI appModel vs Application vs InterfaceChoose an AI app you use. Using the restaurant table, write down what you think its model, application, interface, data and infrastructure are. Then list two things the app does that the model alone could not do, such as saving your history.
Design with model typesTypes of AI ModelsFor each system, list the model types you would chain, in order:
Advise two businessesOpen and Closed ModelsFor Advitha's clinic and Srihitha's startup, write a short recommendation: open-weight or closed, and why, covering control, privacy, cost and effort. Then name one risk of your recommendation for each business.
Break the loopWhat Is TrainingRun the program, then change the starting threshold to 0.9. How many rounds does it take now, and where does the threshold settle? Then add a seventh example, (0.55, "apple"), and describe what happens. Write one sentence about why the examples matter as much as the loop.
Spot inferenceWhat Is InferenceFor one day, note five moments when an app ran inference for you. For each, write the input, the output, and whether you think it ran on your device or in a data center. What clue told you?
The bicycle testTraining vs InferenceExplain training and inference to a friend using learning to ride a bicycle, in five sentences or fewer. Include what changes during training, what stays fixed during inference, and why the analogy isn't perfect. Then ask your friend to explain it back to you.
Check your settingsDoes AI Learn from Every Conversation?Open the settings of a chat assistant you use. Find out, and write down: whether chats may be used to improve models, whether it has a memory feature and how to view or delete it, and how to delete a conversation. Then ask the assistant about something that happened this week, and note whether it says it doesn't know, guesses, or searches.
Catch the memorizerOverfitting and GeneralizationAdd two more photos to new_photos, such as 0.95: "banana" and 0.1: "apple", and run the program again. Do the scores change? Then add 0.9: "banana" to new_photos, a photo the memorizer has seen, and explain why its new-photo score improves only for that one example.
Draft and checkWhat Is Generative AIUse a generative AI tool to draft a short leave request email and to create an image of "a golden retriever in a park". For each, list everything you had to check or fix: names, dates, tone, strange details in the image. Then write one sentence on what surprised you.
Pick the right toolGenerative AI vs Traditional AIFor each task, write traditional, generative or both, with one reason: (1) flagging duplicate invoices, (2) writing a thank-you note to a customer, (3) predicting next month's sales, (4) explaining a late-delivery refund to a customer, (5) sorting support emails by topic and drafting a first reply. Which tasks needed both?
Compare four outputsText, Image, Audio and Video GenerationUse an image generator to create "a golden retriever in a park" four times with the same prompt. How do the images differ, and why? Then list two details in any of them that a real photo would never have, such as strange paws or text.
Test a multimodal modelFoundation Models and Multimodal AITake a clear photo of a shop receipt or a price label, ask a multimodal assistant to read the item names, quantities and total, and check every number yourself. What did it get right, and what did it misread? Then repeat with a blurry photo and compare.
One model, seven jobsWhat Is a Large Language ModelGive a chat assistant one task from each row of the table above, using your own examples. For each, rate the answer from 1 to 5 and note one thing you checked. Which task did it do best, and which needed the most checking?
Extend the toy modelHow an LLM Generates TextAdd a new starting text, "The capital of Japan is", with its own likely next tokens, and the entries needed to finish the sentence. Run the loop from your new text. Then change one probability so a different token wins, and see how the whole sentence changes.
Count tokensTokensUse a tokenizer tool, or the Python example, to count the tokens in three sentences: one ordinary English sentence, one with your full name, and one in another language you know. Which used the most tokens per word, and why?
Change the meaningTransformers and Attention, SimplyWrite three sentences where "it" refers to something different, such as "The trophy didn't fit in the suitcase because it was too big". For each, write which word "it" means and which other word in the sentence gave it away. Then ask a chat assistant what "it" means in each, and compare.
Test contextContext and Context WindowsIn a new chat, type only "Summarize it in one line." and note the reply. Then paste a short paragraph and ask the same thing. What changed? Finally, in a long chat, ask about a detail from your very first message and see whether it is still known.
Change the temperatureTemperature and RandomnessRun the program, then add 0.5 and 5.0 to the list of temperatures. At which temperature does "orange" first appear in the picks? Then change the seed and run again, and describe what changes and what doesn't.
Catch a hallucinationWhy LLMs HallucinateAsk a chat assistant for three research papers, with authors and years, on a narrow topic you know. Look up every one. How many exist exactly as described? Then repeat with the instruction "If you are not sure a paper exists, say so" and compare.
Improve one promptWhat Is a PromptTake a vague prompt you have used, such as "Help me with my resume". Rewrite it with an audience, a goal, a length and a format. Send both versions to the same assistant. List three differences in the answers.
One prompt per roleThe Five-Part Prompt FrameworkWrite a five-part prompt for each person, then test it and improve one part: a student preparing for an exam, a developer learning Python, a business owner analyzing sales, a product owner preparing requirements, and a professional learning a new technology. Which part did you improve most often?
Build a few-shot classifierZero-Shot and Few-Shot PromptingChoose a sorting task from your life, such as emails into URGENT, LATER and IGNORE. Write a zero-shot prompt and try it on five real examples. Then write a few-shot version with three examples and try the same five. How many answers changed, and were they more consistent?
Turn notes into dataRole, Context and Structured OutputTake five short notes from your week, such as messages, receipts or tasks. Write a prompt that returns JSON with three fields you choose, including one with fixed allowed values. Run it on all five. Did every output follow the format? Was every judgment right?
Chain a real taskBreaking Tasks into Steps and Prompt ChainingPick a task you would normally do in one prompt, such as planning a trip or writing a cover letter. Design a three- or four-step chain, run it, and check each output before the next step. Which step needed fixing, and would you have noticed in a single prompt?
Ground a real documentGrounding Prompts in SourcesTake a document you know well, such as a policy, a manual page or a long email. Ask three questions without pasting it, then three with a grounded prompt. How many answers changed, and how many quotes matched the document exactly? Then ask one question the document can't answer, and check that the model says so.
Refine three timesPrompt Before and AfterPick one real task. Write a first prompt, test it on three inputs, and refine it three times, changing one thing each time. Record each version and the result in a small table. Which single change helped most? Save the final version in your prompt library.
Test the limitsAI LimitationsTry one prompt for four of the limits with an assistant you use, such as a letter count, a question about this week's news, a strict three-bullet request, and the same question worded two ways. Record which limits appeared, and which workaround fixed each one.
Your never-paste listPrivacy: What Not to Share with AIFor one task you do with AI at school or work, write down three things you will never paste, and for each, how you will replace it (for example, "Customer 1" instead of a name). Then find the privacy and retention settings in the AI tool you use and note what they say.
Check for one taskHow to Verify AI AnswersFor one AI-assisted task from your school or work, write down: what you will never paste (from "Privacy: What Not to Share with AI"), the stakes (low, medium or high), and exactly how you will check the answer. Then do the task and the checks, and note anything you caught.
Spot the bias riskAI Bias in Everyday ToolsPick an AI feature that affects people, such as job ads, loan offers, photo tagging or school admissions. Write down what data it likely learned from, which group might be missing or treated unfairly, and who should make the final decision. Then suggest one check that would catch the problem early.
Try the fallacy yourselfWhat AI Cannot Predict, and What Not to Trust BlindlyChange the coin experiment to look at what happens after 8 heads in a row instead of 5. How many times did it happen in a million flips, and what share of next flips were heads?

Level 2: AI at Work

ExerciseLessonTask
Draw an AI productThe AI Ecosystem MapPick an AI product you use. Draw its architecture as boxes and label the model, application, interface, API and data. Add where you think it runs and what it might monitor. Which layer did you know least about?
Map a requestWhat Is an APIPick an app you use that has an AI feature. Write the six steps of one request in your own words, from your tap to the answer on screen, naming what you think the application adds before calling the model. Then list two things the response probably contains besides the answer.
Sort ten toolsAI Assistants, Platforms and Model HubsSearch for ten AI tool names you've heard of, from news, work or friends. Put each in one of the six categories, or note if it spans several. Which category had the most tools? Were any hard to place, and why?
Build your own scorecardChoosing an AI ToolPick a real task, such as summarizing meeting notes or answering customer questions. Choose two options, run five real (de-identified) examples through each, and fill in a seven-row scorecard like the one in the picture. Write your decision in one sentence, and when you would review it.
Learn one hard ideaLearning with AIPick a concept you find hard. Ask an AI to explain it with an everyday example, then to quiz you with five questions, one at a time. Answer without looking anything up. Which questions did you miss, and did a second explanation help? Check your school's AI policy before using this for graded work.
Build and use a two-week planAI for Research and Study PlansChoose one subject. Write a five-part prompt with your real topics, deadline and constraints, and ask an AI for a two-week plan. Check it against your syllabus, adjust it, then follow it for two weeks. At the end, record what worked, what you changed and what you would do differently.
One job, three usesAI for Your First Job: Resumes and InterviewsFind a real job ad you'd apply for. (1) Ask an AI which of its skills your resume shows and which are missing. (2) Rewrite two resume bullets using only your real facts. (3) Do a five-question practice interview and note the feedback. Then plan one small project that would fill your biggest gap.
One real taskAI for Everyday Professional WorkPick a task you do every week, such as a status update or a report summary. Do it once with AI, using a specific prompt, and time it. Compare the time and the quality with your usual way, and list what you had to correct.
Your three trendsAI for Small BusinessesTake three to six months of real numbers from your work, a club or a household budget, with personal details removed. Ask an AI for the three most important trends. Then check every number it quotes, with a spreadsheet or the Python above, and note any it got wrong.
Rank your own tasksFinding and Ranking AI OpportunitiesList five tasks from your work, club or household. For each, estimate how often it happens, minutes saved, risk and effort, and run the Python above with your numbers. Place them on the matrix. Does the top-ranked task match your gut feeling?
Fill in the worksheetEstimating the Cost and Return of AIPick one repetitive task. Fill in all eight lines of the ROI worksheet with your best estimates, and run the Python with your numbers. Then run a one-week pilot and update the worksheet with real numbers. Report time saved, errors found, and your decision: continue, change or stop.
Check a real vendorChoosing an AI VendorPick an AI tool your school, work or business might use. Use its website, terms and privacy policy to fill in as many of the nine checks as you can, marking each pass, check or fail. Which answers could you not find, and who would you ask?
Write your one-page policyWriting an AI Policy for Your TeamFor a team, club or family business you know, write a six-part AI policy in under 250 words, using the example as a model. Then ask one person to read it and tell you, in their own words, what they may and may not do.
Plan a rolloutLeading AI Adoption and ChangeFor a team you know, plan a one-month AI rollout: one training session (which real task?), one champion, three measures, and one conversation about concerns. Write what you would say in that conversation, in three sentences.
Test an AI business ideaStarting an AI-Powered BusinessWrite one AI business idea. Decide whether it is AI-first or AI-assisted, list which of the five advantages it could build, and run the Python with your own guesses for cost per request, requests per user and price. At 10,000 users, does it still make money? What would you change if not?
Write a case studyAI Case Studies by IndustryFind a published AI story from an industry you care about. Rewrite it in the four parts: problem, AI used, result and risk. Which part was hardest to find in the original story, and what does that tell you?
Draft and ownAI for Product OwnersWrite a one-paragraph feature description for a product you use. Ask an AI for user stories, acceptance criteria and edge cases. Then mark each item keep, change or delete, and add one edge case the AI missed.
Sort real feedbackAI for Product ManagersCollect 20 to 30 real comments or requests about a product you know. Ask an AI to group them into themes with counts and pain points. Check two themes by reading every comment in them. Then write one measurable success criterion for the top theme.
Map a featureThe AI Product LifecyclePick an AI feature you'd like to build. For each of the six stages, write one sentence about what you'd do. Then write five questions for its evaluation set, with the expected answers.
Write the Campus Helper spec yourselfWriting an AI Feature Spec, with a Worked ExampleUsing the template, write a spec for Campus Helper's admission deadlines feature. Include users, three examples with ideal outputs, success metrics with thresholds, an evaluation plan, a launch experiment and three risks with mitigations. Ask a friend to find any line they couldn't test.
Redesign an AI screenDesigning AI User ExperiencesTake a screenshot of an AI feature you use, or sketch one. Check it for the five features. Sketch an improved version that adds the missing ones, and test it with someone on one hard question.
Add a week of dataAI Product MetricsAdd five more conversations to the log, including one slow, expensive answer and one more incorrect one. Rerun the program. Which metrics changed, and what would you investigate first? Then write a target for each of the six metrics for a product you know.
Rerun the testLaunching AI Features: Pilots and ExperimentsChange the B result to 168 resolved out of 400 and rerun the program. Is the difference still likely real? Then write a launch plan for an AI feature: who joins the pilot, what the A/B test measures, what result means "go", and the rollout steps.
Campus Helper's full specManaging AI Product RisksCombine this chapter: write the AI feature spec for Campus Helper using the template in "Writing an AI Feature Spec, with a Worked Example", with users, success metrics, an evaluation plan, a launch experiment, and a risk register with at least five risks. Ask someone to challenge your highest-impact risk.
Explain, then confirmAI Coding AssistantsPick a function you didn't write, from an open-source project or your own old code. Ask an assistant to explain it line by line and list what could go wrong. Then run it with two inputs that test one of the risks it named. Was the explanation right?
Break and fixReviewing AI-Generated CodeRun the program. Then try two other attack strings against fees_unsafe, and confirm fees_safe blocks them. Finally, ask an AI assistant to write a function that searches students by grade, and review its answer with the six-point checklist.
Explain, test, find a bugAI for Tests, Docs and DebuggingPick a small function you didn't write. Ask an AI to explain it, then to suggest five tests including edge cases. Check every expected value yourself, and run them. Did you find a real bug? If not, add one deliberately and see whether the tests catch it.
Design your workflowWhat Is an AI WorkflowPick a repetitive task with incoming messages, such as club sign-ups or customer questions. Draw its steps from trigger to final action, mark which are AI steps, where the person reviews, and what happens for urgent cases and failures. Then add a fifth email to the Python example that should go to "other", and check the route.
Build the email workflowBuilding a No-Code AI WorkflowIn a no-code tool you can access (many have free plans), build a workflow that reads incoming emails from a test inbox, classifies them, and drafts replies that a person approves. Test it with ten anonymized emails and record which were classified wrongly.
Classify five systemsWorkflows vs AgentsFor each, decide chatbot, workflow or agent, and say who decides the next step: (1) an assistant that answers homework questions, (2) a system that tags invoices and sends them for approval, (3) an assistant that researches flights and hotels and proposes a trip plan, (4) a tool that summarizes every new support ticket, (5) an assistant that fixes a failing test by reading code, editing it and rerunning tests. Which could be redesigned as a simpler workflow?

Level 3: Building AI Applications

ExerciseLessonTask
Set up your AI workspacePython for AI: SetupCreate a folder called ai-practice, make a virtual environment in it, activate it, install NumPy, pandas and matplotlib, and run the version check. Then save requirements.txt, delete .venv, and recreate it from the file.
Extend the fee programPython Essentials for AIAdd a "sports": 60 fee, write a function most_expensive() that returns the name of the highest fee, and save the fees to fees.json with json.dump. Then read the file back with json.load and print the lab fee.
Student feesNumPy BasicsAdd a fourth student [50, 30] to the students array. Print the total per student, the total per fee type (axis=0), and the students whose total is above $60. Check each result by hand.
The 1,000-payment checkpointPandas BasicsCreate payments.csv with the first program, then load it, clean the missing values, and total payments by item and by method. Which item brings in the most money, and how many payments have an unknown method?
The checkpoint chartVisualizing DataRecreate the chart, then add a second chart of payments by item. Which item brings in the most? Would a bar chart or a pie chart show it more clearly, and why?
Notebook to scriptNotebooksIn a notebook, load payments.csv, clean it and chart payments by month, one step per cell. Restart and run all. Then move the working code into payments_report.py and run it from the terminal.
A new ruleData Pipelines for AIAdd a validation rule that fee amounts must be one of 15, 45, 60 or 250, and report any others. Do any rows fail? Then add a raw fee row with an amount of 450 and run the pipeline again.
Ask about another feeCalling a Model APIChange the question to ask about the library fee, then ask about a fee that isn't listed, such as parking. Does the reply admit it doesn't know? If not, add "If the answer isn't in these facts, say so" to the system prompt.
A three-turn chatMessages, System Prompts and ParametersWrite a loop that reads questions from the keyboard, appends each question and each reply to messages, and prints the reply. Ask about the lab fee, then "when is it due?", and check that the second answer knows what "it" means.
Stream a longer answerStreaming ResponsesAsk Campus Helper for a one-week study plan before exams and stream it. Then add a counter that prints how many text pieces arrived.
Extend the checkpointStructured Output and JSONAdd a language field (Literal["English", "Spanish", "other"]) and test the script with a question in Spanish. Then send questions with needs_staff true to a list called office_queue and print it.
A second toolTool Use and Function CallingAdd a tool next_exam_date(subject) backed by a small dictionary. Ask, "When is the next math exam, and how much is the grade 10 lab fee?" Print every tool request; how many calls does the model make?
Budget Campus HelperTokens, Cost and Rate LimitsSuppose the fee document grows to 4,000 tokens and traffic doubles to 60,000 questions a month. Rerun the estimate for all three models. Which would you test first, and why?
A safe setupAPI Keys and SecretsCreate a .env file containing your key, add .env to .gitignore, and run git status to confirm the file isn't listed. Then run the loading program with and without the variable set.
Your own word groupsWhat Are EmbeddingsEmbed "teacher", "instructor", "professor", "pizza" and "sandwich". Which pairs score highest? Does "pizza" sit closer to "sandwich" or to "teacher"?
Rank three answersSimilarity and Cosine DistanceEmbed the question "What time does school start?" and three FAQ answers of your choice. Rank them by cosine similarity. Does the order match what a person would choose?
The 50-answer checkpointSemantic SearchRun both programs, then try five questions of your own, including one in Spanish. For each, note whether the top answer is right and what its score was. What score seems to separate good matches from poor ones for this model?
Add a date filterVector DatabasesAdd a "month" field to a few timetable answers and let search() filter by it. Then search "When are exams?" with and without the filter.
Weight the fusionHybrid Search and RerankingChange hybrid() so the vector ranking counts twice as much as BM25 (add 2 / (k + rank + 1) for it). Do Recall@1 and MRR improve over plain vector search?
Map a RAG ideaWhat Is RAGPick a document set you know, such as a club's rules or a product manual. Write five questions a person might ask, find each answer in the documents by hand, and note any question the documents can't answer.
Ask the pipeline more questionsBuilding a RAG PipelineChange question to "Is there a test to get into grade 11?" and then "How fast are travel claims paid?". Note the top retrieved chunk and score for each. Is the right paragraph always first?
Chunk by paragraph and by headingChunking DocumentsRun the comparison for the question "Are hotel upgrades paid for?" Which size wins this time? Then try chunking by paragraph and compare the best score.
Break the tieRetrieval Quality and RerankingAdd four questions that use exact terms, such as "What is the $10 charge?" and "Room 104?". Rerun the comparison. Does keyword or hybrid search improve on these?
Test the thresholdAnswers with SourcesAsk five on-topic and five off-topic questions and print the best score for each. Is 0.35 the right threshold for these questions? What would you change it to?
Choose for three casesRAG vs Fine-Tuning vs Long ContextA city library's 20,000 FAQ pages; a law firm that wants replies in its exact letter format; a club with a two-page rulebook. Choose an approach for each and write one sentence explaining why.
A deleted documentAdvanced RAG PatternsAdd a field "deleted": True to the 2025-26 fee schedule and make retrieve skip deleted documents. Then remove the 2026-27 schedule as well: what does a parent get for the lab fee question now?
Agent or workflow?What Is an AI AgentFor each task, decide and explain: sending a monthly fee reminder email; researching three after-school programs and comparing them; resetting a forgotten password. Which one, if any, really needs an agent?
Extend the checkpointThe Agent LoopAdd a third tool, cancel_meeting(confirmation), that also requires confirmation. Ask the agent to book and then cancel a meeting, answering yes and then no. Read the step log: did it do what you expected?
Add a toolGiving Agents ToolsAdd school_hours(day) to the registry, returning opening hours for each weekday. Test it with "Monday", "monday", 5 and "Holiday", and make every error message tell the model what to do next.
A second toolConnecting Tools with MCPAdd next_exam(subject: str) -> str to the server with a docstring. Run the client again: does it discover both tools without any change to the client code?
Design a splitMulti-Agent SystemsCampus Helper must prepare a summary of next year's fee changes from three documents: the fee policy, the board meeting minutes and the budget. Would you use one agent or a lead with helpers? Write the brief each helper would get, or explain why one agent is enough.
Tighten the policyControlling Agent AutonomyAdd a spending limit: send_email costs nothing, but a new pay_invoice tool may never total more than $100 per session and always asks first. Run a sequence with three invoice requests of $40 each and check the audit log.
A budget testAgent State, Memory and ReliabilitySet max_steps=3 and run both cases again. Where does each stop, and what status does it report? Then make the fee service fail three times in a row: what happens?
Map an AI app you useThe Building Blocks of an AI ApplicationPick an AI feature in an app you know, such as a writing assistant or a support chat. Sketch its likely building blocks: what does the frontend do, what must the backend check, and what would it store?
Add a levelBuilding an AI Learning AssistantAdd an "expert" level to Level and LEVELS for graduate students. Run explain() for "compound interest" at all four levels and compare the explanations' length and vocabulary.
A history pageFrontend, Backend and the ModelAdd GET /history/{student} that returns that student's last five topics and ratings. Test it with the test client, then explain why a real app must check that the person asking is that student.
Find the slow answersImproving with FeedbackExtend the analysis to print the median seconds per level and the three slowest topics. Is any group slow enough that students would notice? What could you change to speed it up?
List your casesWhy AI Needs EvaluationFor an AI feature you'd like to build, write ten test questions: six typical, two tricky, and two it should refuse. For each, write what a correct answer must contain or do.
Fix a failureBuilding an Evaluation SetAdd a sentence to the FAQ entry about fee waivers, such as "Help is available if you can't afford the fees." Rerun the evaluation. Does case #8 pass now, and did any other case change?
Try another changeAutomatic and Model-Graded EvaluationLower the threshold to 0.30 in compare.py. Which cases change? Would you accept this version? Update BASELINE only if you do.
Rate with a rubricHuman Evaluation and FeedbackTake ten answers from the evaluation in "Building an Evaluation Set". With a friend, rate each one good or not good using the rubric above, then compute your kappa with kappa.py. Discuss every disagreement and improve one rubric line.
A date guardrailGuardrailsExtend check_output() so that every month name in an answer must also appear in the sources. Test it with "Spring term starts on January 12" and "Spring term starts on February 12".
More casesMeasuring RAG and Agents ProperlyDuplicate the evaluation set with your own 50 reworded questions (same expected answers) and rerun. How much narrower do the intervals get with 100 cases?

Level 4: Machine Learning and Deep Learning

ExerciseLessonTask
Try other parametersWhy Math Matters for MLChange w and b to 160 and 60, then to 170 and 40. Which pair gives the smallest loss? What do the signs of the gradient tell you each time?
Add a feeVectors and MatricesAdd a fourth item, sports at $60, to prices, and a fourth column to orders (Srihitha 1, Advitha 0, Navika 1). Predict each total by hand first, then run the code.
A second wordProbability BasicsSuppose "winner" appears in 60 of the 200 spam emails and 4 of the 800 normal ones. Compute P(spam | winner) by hand with Bayes' rule, then check it by changing the program.
A bigger testStatistics for MLChange the A/B test to 400 parents per group with the same rates (208 and 256 paying on time). Rerun the permutation test. What happens to the p-value, and why?
The learning rateDerivatives and GradientsRun gradient descent for 3 steps with learning rates 0.01 and 0.5. What happens to the loss each time? Explain the 0.5 result using the table above.
A different familySupervised LearningPredict for a family with a $45 fee, no late payments, autopay on, 24 months enrolled, reminder opened. Then change one feature at a time until the prediction flips to "likely late". Which feature mattered most?
Drop a featureLinear RegressionFit the model with only size. How do the error and R squared change? What does that tell you about bedrooms and age?
Try thresholdsLogistic Regression and ClassificationPrint accuracy and recall for thresholds 0.2, 0.4 and 0.6. Which would you choose if each missed late payment costs the school $10 in follow-up, and each extra reminder costs nothing?
Find the best depthDecision TreesTry depths 1 to 8 and print train and test accuracy for each. At what depth does the gap between them start to grow?
Tune the forestRandom Forests and Gradient BoostingTry n_estimators of 10, 50 and 500, and min_samples_leaf of 1 and 20. Which setting changes test accuracy most?
Choose kK-Nearest Neighbors and SVMsTry k = 1, 5, 15 and 51 with scaling. Which k gives the best test accuracy? Explain what happens at k = 1 and at k = 51.
A third candidateThe Scikit-Learn WorkflowAdd gradient boosting to candidates, and compare all three with cross-validation using scoring="recall". Does the ranking change when you care about catching late payers instead of accuracy?
A fifth groupUnsupervised Learning and ClusteringFit k-means with n_clusters=5 and print the profile table. Which group splits, and does the new group have a meaning you could name?
Compress, then clusterDimensionality ReductionRun k-means with 4 clusters on the two PCA components instead of the six scaled features, and compare the groups with adjusted_rand_score. Does clustering still find the same groups with a third of the information gone?
A threshold tableEvaluating Models: MetricsExtend the loop to thresholds 0.2, 0.3, 0.4 and 0.5. Which threshold would you choose if each missed late payer costs the school $10 in follow-up, and each false alarm costs $2 in staff time?
A forest's validation curveOverfitting, Underfitting and Cross-ValidationRun validation_curve for RandomForestClassifier(n_estimators=100, random_state=0) over min_samples_leaf values 1, 2, 5, 10 and 20. Where does the gap between training and validation shrink, and does validation improve?
A missing flagFeature EngineeringChange the imputer to SimpleImputer(strategy="median", add_indicator=True) and compare cross-validated scores. Does knowing that months_enrolled was missing help here? Why might it, or might it not?
A costlier puddleReinforcement Learning BasicsChange the puddle reward from −5 to −1, the same as an ordinary step, and rerun. Does the learned route change? Why might the agent now walk through a puddle?
Another baselineReading AI Research and Running Fair ExperimentsAdd KNeighborsClassifier(n_neighbors=3) from "K-Nearest Neighbors and SVMs" as a baseline. How does it compare with the MLP, and would you still recommend the network?
Change the neuronHow Neural Networks WorkIn the first program, try 8 hours studied and 1 day away. Does the neuron still send a reminder? What weighted sum makes sigmoid exactly 0.5?
Count the stepsGradient DescentChange the first program to stop when the loss improves by less than 0.01 between steps. How many steps does learning rate 0.1 need? And 0.01?
Check every gradientBackpropagationExtend the numerical check in the first program to all four entries of W1 and both entries of W2. Do they all match backpropagation to six decimal places?
A deeper networkPyTorch BasicsAdd another nn.Linear(32, 32) and nn.ReLU() in the middle of the nn.Sequential. How many parameters does it have now? Work it out by hand first.
A wider networkTraining a Network in PyTorchChange the hidden layer to 64 neurons, then 128. Does test accuracy improve beyond 97.8%, and does the gap between training and test accuracy grow?
Your own hardwareGPUs and Hardware for AIRun both programs on your computer, and the second with n set to 512 and 8192. At which size does the GPU, if you have one, start to beat the CPU clearly?
Classify your own photosComputer VisionRun the classifier on three photos of your own: one of a common object, one of a pet or food, and one of a document. Which ones does it label well, and what does it say about the document?
A horizontal edgeConvolutional Neural NetworksChange the filter in the first program to [[-1, -1, -1], [0, 0, 0], [1, 1, 1]]. What feature map do you get for the same image, and why? Then make an image with a horizontal edge and try again.
Fewer photosTransfer LearningChange make_notices.py to make only 4 training photos of each kind, then rerun the comparison and the checkpoint. How do the three approaches compare now?
Your own announcementSpeech Recognition and Speech SynthesisChange the text in the text-to-speech program to a sentence of your own with a number, a date and a name, then transcribe it. Which words does Whisper get wrong? Does openai/whisper-base.en, a larger model, do better?
A different promptInside a TransformerChange the prompt in the second program to "The capital of France is" and to "My favorite color is". Which prompt gives one very likely next token, and which spreads the probability over many?
More mergesTokenizationChange range(1, 9) to range(1, 15) in the BPE program. Which new tokens appear, and how does "slowly" split now?
Remove the maskSelf-AttentionComment out scores[mask] = -np.inf in the first program. What happens to the upper triangle of the weights, and why would that be a problem when training a model to predict the next token?
A new kind of announcementPretrainingAdd a second template to the tiny GPT's training text, such as "Bring your {item} on {day}." with a list of items. How many steps does it take before samples use both templates correctly?
Your own preference pairInstruction Tuning and RLHFAdd a pair to the second program, such as a question about homework with a helpful answer and an answer that just gives the result with no explanation. Is the margin positive? Try a pair where you are unsure which answer is better.
Top-k vs top-pSampling and DecodingIn the checkpoint program, replace top_p=0.95 with top_k=5 and run temperature 1.5 again. Does limiting to 5 tokens keep the slogans on topic?
Plan a modelScaling and Context WindowsUsing C ≈ 6ND, estimate the compute to train a 7-billion-parameter model on 2 trillion tokens. How many times more is that than SmolLM2-1.7B? How many tokens would the Chinchilla rule suggest for it?
Change the factWhat Is Fine-TuningChange the document in the program to say the fee is $18. Does the answer follow the document? What would you need to do if the fee had been fine-tuned into the model instead?
More declinesPreparing Fine-Tuning DataAdd 12 more unanswerable questions to UNANSWERABLE, so training has 20 declines. Rerun both programs. How does the balance change? After the checkpoint in the next lesson, does the model decline better?
Rank and layersLoRA and Efficient Fine-TuningChange r=8 to r=2 and then r=32, and try adding "up_proj", "down_proj" to target_modules. How do the trainable parameters and the test scores change?
TemperatureDistillation and Smaller ModelsChange T = 4.0 to T = 1.0 and then T = 10.0. How does the distilled student's accuracy change? Print the teacher's soft answer at each temperature to see why.
Guidance scaleDiffusion ModelsAdd guidance_scale=2.0 and then guidance_scale=12.0 to the pipe(...) call for the apple at 25 steps. How closely does each image follow the prompt, and how natural does it look?
Your own captionsMultimodal ModelsChange CLIP's captions to five that are all about dogs: "a puppy", "a sleeping dog", "a dog in the snow", "a dog playing fetch", "a dog's face up close". Which wins, and do the shares make sense for this photo?
A wider moveAudio and Video GenerationIn the video program, change k * 0.05 to k * 0.2 in the smooth animation. How does the average change between frames compare now, and what does the GIF look like?

Level 5: Production, Responsibility and Careers

ExerciseLessonTask
A stricter gateMLOps and LLMOpsChange min_gain to 0.01. Which version ends up in production now? When would a stricter gate be the right choice?
A version endpoint and a limitDeploying Models and AI AppsAdd max_length=100 to Question, and send a 150-character question. What status and message come back? Then add a /version endpoint that returns only the version string.
A cost alertMonitoring Quality, Cost and LatencyAdd a check after the dashboard that prints an ALERT when a day's cost per 1,000 requests is more than 20% above day 1's. Then make version 1.1 add 800 extra input tokens instead of 400. Does the alert fire?
Your own numbersHosted, Open and Local ModelsChange the example prices and token counts in the first program to those of a real provider and model you might use, and set tokens_in to match your own app. Where is the break-even now?
Group sizeQuantization and Running Models LocallyChange the 4-bit group size from 32 to 8, then to 128. How do the size and perplexity change, and which would you choose?
A third fallbackTracing, SLOs and Incident ResponseAdd a case where retrieval finds nothing for the question (for example "Is there a swimming pool?") and the model is down. What should the user see, and what should the trace record?
Threat-model an appThreats to AI ApplicationsPick an AI app you use or are building. List every place text enters the model and every place its output goes. For each, which OWASP risk applies, and which defense would you add first?
Break it againPrompt Injection and JailbreaksWrite two new attacks that get past the input filter in the second program, for example by translating "ignore previous instructions" into Spanish, or by asking for the tuition "in words, not numbers". Does the output check still catch them? What would you add?
Better redactionData Leakage and Privacy AttacksAdd a pattern for student numbers (five digits after the words "student number") and one for US street addresses. Test them on five sentences of your own, including two that should not be changed.
A payment toolSecuring Agents and ToolsAdd a refund_fee tool that is allowed only for amounts up to $50, only to the parent's own account, and always needs approval. Write three requests that should be denied and one that should wait for approval, and check them.
Add two threatsAI Threat Modeling and Supply Chain SecurityAdd rows for "a malicious MCP server tool description" and "a model provider changes the model without notice", with likelihood, impact, control and test. Where do they rank?
Your own reviewResponsible AI PrinciplesWrite a one-page review, in the table format above, for an AI feature you use or are building. Which line has the weakest evidence, and what test would strengthen it?
A stronger proxyBias and FairnessChange 0.8 to 0.95 in the line that makes area, so where people live matches their group more closely. How do the ratio and the qualified acceptance rates of the first model change?
A review sampleKeeping Humans in the LoopChange the program so that, in addition to the middle band, a person also reviews every declined question. How many more reviews does that take, and does the overall score reach 50/50?
Classify three systemsAI Laws and FrameworksChoose three AI systems you know (for example a resume screener, a movie recommender and a customer-service chatbot). Which EU AI Act tier is each in, and what are its main duties? Note the date you checked.
Check your toolsCopyright and AI-Generated ContentList three AI tools or models you use. For each, find its license or terms of service. Can you use its output commercially? Who owns the output? Does it use your inputs for training?
Your system recordAI Governance in PracticeAdd an AI tool you use at school or work to the inventory, with an owner, risk class and last review date. Is it overdue? Then write its model card in the same seven lines.
Your own matchAI Career PathsAdd yourself to people with your real skills, and add a role you are curious about to ROLES. Which role matches best, and which two skills would you learn first?
Your planLearning Paths by BackgroundChange the program for yourself: your path, your hours per week and your project. Does it fit in six months? If not, what will you cut or move to the next six months?
Four questionsThe Future of AIChoose one trend from the table and apply the four questions to an app or job you know. What would you need before you trusted it?
Fix the draftHow to Plan an AI ProjectAdd the three missing sections to the draft in the program, and rewrite the three thin ones so the checker reports nothing. Then write the evaluation criteria for a project of your own.
Your own summary checkBeginner AI ProjectsAsk an AI assistant to summarize a real document you have permission to use, then paste the source and the summary into the program. Which facts does it flag? Were they really wrong?
A baselineIntermediate AI ProjectsWrite a keyword rule (for example: "password", "log in" or "locked" means login; "charged", "fee" or "refund" means billing) and score it on the same 60 test tickets. How does it compare with the classifier's 0.95?
A stricter gateAdvanced AI ProjectsChange the gate so a pull request must score at least as high as the main branch, not just 42. Which of the two proposed changes passes now?
Grade your own projectPresenting Your AI ProjectScore your own project (or one you know) with the rubric in the program. Which criterion is lowest, and what is the single change that would raise it most?

Was this tutorial helpful?