
Creating and Verifying a Virtual Environment. Every project in this course depends on libraries, and different projects often need different versions of the same library. A virtual environment keeps each project's packages in a private folder, so that an upgrade for one cannot break another. This lecture creates the environment that all ten projects will share and shows how to prove that it is working.
We begin with the idea of isolation. A virtual environment contains its own Python interpreter and its own installed packages. You will create one with the standard venv module, activate it on your operating system and see how the terminal prompt changes. We explain what activation actually does, which is to place the environment's folders at the front of the search path, so that the commands you type find the right interpreter.
Verification is the second half of the lesson. You will write a short script that prints the interpreter's location, the Python version and whether the active prefix differs from the base prefix, which is the reliable test for being inside an environment. A script like this is quick to run at the start of any session, and it catches the most common beginner problem: installing packages in one place and running code in another.
We also discuss choosing a Python version, naming the folder, keeping it out of version control and selecting the interpreter in your code editor.
By the end of this lecture you will be able to create, activate and verify an isolated environment and explain why every project should have one.
Pinning Dependencies for Reproducible Installs. A project that works today can break next month if a library releases a new version with different behavior. Reproducibility means that you, a colleague or a server can rebuild exactly the same environment later. Pinning dependencies is how you achieve it, and this lecture shows how.
We start by examining the difference between an unpinned requirement, which accepts whatever version is newest, and a pinned one, which names an exact version. You will install the libraries used in the course and then produce a requirements file with pip freeze, reading the output to see both the packages you asked for and the many that were installed alongside them.
We discuss the trade-offs. Exact pins give repeatable builds but can block security updates, while loose ranges allow updates but risk surprises. A common compromise keeps a short file of direct requirements with sensible ranges and a fully pinned file generated for deployment. You will learn how to install from a requirements file in a fresh environment and confirm that the same versions appear.
We cover practical points, including recording the Python version, separating development tools such as test runners from runtime needs and updating pins deliberately, one at a time, with tests.
We also show how to check for conflicts and read the messages pip gives when two libraries demand incompatible versions.
By the end of this lecture you will be able to pin and reinstall dependencies so that a project can be reproduced reliably.
Reading API Keys from Environment Variables Safely. Many AI services require a key, and the way you handle it says a great deal about the quality of your engineering. Keys written into source files end up in version control, screenshots and shared notebooks, and withdrawing them afterward is painful. This lecture shows the safe alternative, which is to read keys from environment variables.
You will start with the os module and learn to read a variable, comparing direct access, which raises an error when the variable is missing, with the get method, which returns a default. For a key, failing early with a clear message is the right behavior, so we write a small function that raises a helpful error naming the missing variable without revealing anything else.
We then address convenience. Typing variables into every terminal is tedious, so we introduce a local settings file that is loaded at start-up and excluded from version control. You will create a sample file listing variable names with placeholder values, which is safe to share and tells colleagues what to supply.
The most important lessons concern leaks. Never print a key, include it in an error message, write it to a log or return it from a function that a model might see. We write a helper that masks all but the last few characters for display.
Finally, we explain that the dry-run exercises in this course need no real key.
By the end of this lecture you will be able to load secrets safely and keep them out of code, logs and repositories.
Building an LLM Chat Request with a Dry-Run Client. Calling a language model costs money, depends on a network and gives slightly different answers each time, which makes it a poor way to test code. A dry-run client builds the complete request and then stops before sending it, so you can inspect exactly what would be sent. This lecture builds that client, and later projects reuse it.
We begin with the anatomy of a chat request: an address, headers that include an authorization value, and a JSON body containing the model name, a list of messages with roles and settings such as temperature and maximum tokens. You will write a function that assembles these from your configuration and returns them as a dictionary.
The client class has a single method for sending a request. In dry-run mode, it returns the prepared request, with the authorization header masked, together with a canned reply, and in live mode it would send the request over the network. Because both modes share the same preparation code, testing the dry run really tests the real path.
You will validate the request before use, checking that messages are present, roles are allowed and numeric settings lie in sensible ranges, and you will write tests that confirm the structure without a key or a connection.
We discuss the benefits: free and instant tests, no accidental charges and a precise record of the application's intentions.
By the end of this lecture you will be able to build and test a chat request using a dry-run client.
Loading and Inspecting a Labeled Text Dataset. The first project is a text classifier, and every machine learning project begins with understanding the data. This lecture loads a small labeled dataset of short texts and examines it carefully before any modeling begins.
You will load the data into a Pandas DataFrame from a file, with one column for the text and one for its label. We inspect it using head, info and shape, and check the data types and the number of rows. We count missing values and duplicates, and discuss what to do about them, because a duplicate that appears in both the training and test sets will inflate the results later.
Next we study the labels. The value_counts method shows how many examples belong to each class, and we discuss why imbalance matters. If ninety percent of examples belong to one class, a model can look accurate while learning nothing useful. We also look at text length, computing and summarizing the number of words in each example, which reveals unusually short or long items.
You will read a sample of the texts yourself, which is a step many people skip. Reading examples shows mislabeled items, inconsistent formatting and ambiguous cases, all of which limit what any model can achieve.
We also discuss recording what you learned in notes, so later results can be interpreted properly.
By the end of this lecture you will be able to load and inspect a text dataset and identify problems before modeling.
Splitting Data into Train and Test Sets. A model judged on the same data it learned from will look better than it really is, because it can memorize the examples. The remedy is to hold back some data that the model never sees during training. This lecture shows how to split the text dataset correctly.
We start with the reasoning. The goal is to estimate how the model will perform on new texts, so the test set must stand in for the future. You will use the train_test_split function to divide the texts and labels, choosing a test proportion of around twenty percent, and you will print the sizes to confirm the result.
Two settings deserve attention. A random state makes the split reproducible, so your results match those of a colleague and can be compared between runs. Stratification keeps the share of each class the same in both parts, which matters greatly when a class is small. We demonstrate the difference on an imbalanced sample, showing a test set that, without stratification, contains almost none of the rare class.
We also discuss discipline. Anything that learns from data, including the text vectorizer you will build next, must be fitted on the training portion only. Fitting it on everything lets information from the test set leak into training and makes the final score optimistic.
We finish by saving the split, so the same division is used in all later steps.
By the end of this lecture you will be able to produce a reproducible, stratified split and explain why the test set must stay untouched.
Turning Text into TF-IDF Features. Machine learning models need numbers, not words. TF-IDF is a classic way to turn text into numerical features, and it remains a strong baseline for many classification tasks. This lecture explains how it works and how to use it.
The name stands for term frequency and inverse document frequency. Term frequency counts how often a word appears in a document. Inverse document frequency reduces the weight of words that appear in many documents, since common words carry little information, and increases the weight of rarer, more distinctive ones. The product of the two highlights words that are frequent in a particular text but uncommon overall. You will compute a tiny example by hand to see the arithmetic.
Then you will use scikit-learn's TfidfVectorizer. We cover its main settings: lowercasing, removing common stop words, including pairs of adjacent words, limiting the vocabulary size and ignoring terms that are too rare or too frequent. You will fit the vectorizer on the training texts and transform both the training and test texts, and we repeat the rule that fitting must use training data only.
The result is a sparse matrix, and we explain why a sparse format is used and how to inspect it. We look at the vocabulary and at the highest-weighted terms in a document, which shows what the model will see.
By the end of this lecture you will be able to convert text into TF-IDF features and interpret the result.
Training and Evaluating a Logistic Regression Classifier. With features ready, we can train the first model of the course. Logistic regression is simple, fast and surprisingly effective on text, and it makes an excellent baseline. This lecture trains it and evaluates the results carefully.
You will create the classifier, fit it on the training features and labels and predict on the test features. We explain what the model learned: a weight for every word, where a positive weight pushes a text toward one class and a negative weight pushes it toward another. Looking at the largest weights shows which words drive the decisions, which is both interesting and a useful check that the model learned something sensible.
Evaluation comes next. You will compute accuracy and then look beyond it. Precision tells you how many of the texts predicted for a class truly belong to it, recall tells you how many of the true members were found and the F1 score combines both. A confusion matrix shows exactly which classes are confused with each other. We use the classification report to see these figures for each class.
We discuss interpreting the results honestly. A high score on a small dataset may not carry over to real data, and we examine misclassified examples to understand the errors.
We also connect the steps into a pipeline, so that vectorizing and classifying happen together, which prevents leakage and simplifies saving the model.
By the end of this lecture you will be able to train, evaluate and interpret a text classifier.
Running a Pretrained Transformer Sentiment Model Offline. Training your own classifier is valuable, but pretrained transformer models have already learned a great deal about language and can be used directly. This lecture runs one for sentiment analysis, and does so in a way that works offline and repeatably.
We begin with what a pretrained model is. A transformer was trained on a vast amount of text, and a version fine-tuned for sentiment has learned to label text as positive or negative. You will use the high-level pipeline interface from the transformers library, which handles tokenizing the text, running the model and converting the output into labels and confidence scores.
Offline use is the practical focus. Models are downloaded once and then cached, so we show how to load a model from a local folder and how to tell the library not to contact the internet. We discuss where the cache lives, how large models can be and how to handle the first download. For reproducibility, we also describe pinning the model's version.
You will run the model on a set of sample sentences, including difficult cases such as negation, sarcasm and mixed opinions, and compare its predictions with your logistic regression model. This shows where each approach is strong.
We discuss limits, including sensitivity to the domain of the text, inherited bias and the cost in speed and memory compared with a small classical model.
By the end of this lecture you will be able to run a pretrained sentiment model offline and compare it with your own.
Turning Documents into Fixed-Length Embedding Vectors. Projects three and four rest on a single idea: that the meaning of a piece of text can be represented as a list of numbers. This lecture introduces embeddings and shows how to turn a set of documents into vectors of the same length.
We begin with the intuition. A keyword search treats the phrases refund policy and getting my money back as unrelated, because they share no words. An embedding model places both near one another in a numerical space, since their meanings are similar. You will see this by embedding a handful of short sentences and examining how the vectors relate.
You will use a sentence embedding model, loading it from a local cache so that the exercise works offline. We encode a list of documents in a single call and inspect the result, which is a two-dimensional array with one row per document and a fixed number of columns, called the dimension. We explain that every text, whether a short phrase or a paragraph, becomes a vector of the same length, and that vectors from different models cannot be compared.
We discuss practical points. Texts longer than the model's limit are truncated, which is why long documents are split first. Embedding is the slow step, so results should be cached and saved. The same model must embed documents and queries. We also examine the effect of normalizing vectors to unit length.
We store the embeddings in a NumPy array alongside a list of identifiers.
By the end of this lecture you will be able to embed documents into fixed-length vectors and store them for later use.
Measuring Meaning Overlap with Cosine Similarity. Once documents are vectors, you need a way to measure how close two of them are. Cosine similarity is the standard choice for embeddings, and this lecture explains it and puts it to work.
The idea is geometric. Each vector is an arrow from the origin, and cosine similarity measures the angle between two arrows. Arrows pointing in the same direction score one, perpendicular arrows score zero and opposite arrows score minus one. Because it considers direction and not length, it is not distorted by differences in the size of the vectors, which makes it well suited to comparing meaning.
You will write the calculation yourself using NumPy. The dot product of two vectors is divided by the product of their lengths. We test it on simple two-dimensional vectors where the answer can be checked by drawing, and then on real embeddings, confirming that sentences about the same topic score higher than unrelated ones. We guard against a zero-length vector, which would cause a division by zero.
You will learn that normalizing all vectors to unit length first turns cosine similarity into a plain dot product, so a single matrix multiplication can compare a query with thousands of documents at once. We use this to build a similarity matrix for a small set of documents and read it as a table, finding the most similar pairs.
We also discuss interpreting scores, which are not probabilities and depend on the model.
By the end of this lecture you will be able to compute and interpret cosine similarity efficiently.
Storing Embeddings in a Vector Index and Retrieving Top-k Matches. Comparing a query with every document works for a handful of items, but a real application needs an organized structure for storing vectors and searching them. This lecture builds a vector index and uses it to retrieve the best matches for a query.
We start with a simple design that you write yourself. The index holds a matrix of normalized embeddings, a list of document identifiers and the original texts. Its add method embeds new documents and appends them, and its search method embeds the query, computes similarities with a matrix multiplication, sorts them and returns the top k results with their scores and identifiers. Writing it yourself makes clear exactly what a vector store does.
You will experiment with the main choices. The value of k controls how many results come back, and a similarity threshold removes weak matches, so that an irrelevant query returns nothing instead of the least bad documents. We test with several queries, including one that shares no words with its best match, to demonstrate semantic retrieval.
We then discuss persistence, saving the matrix and metadata to disk so that documents need not be embedded again, and recording the embedding model's name inside the saved index. We also introduce libraries that provide the same service at scale, using approximate search to stay fast with millions of vectors, and explain when you would move to one.
By the end of this lecture you will be able to build a vector index and retrieve the top matches for a query.
Splitting Private Documents into Overlapping Chunks. Retrieval-augmented generation works with documents that are far too long to embed or place in a prompt as a whole. They must be split into chunks, and the way you split them affects how well questions are answered. This lecture builds a chunker with overlap, designed for private documents such as policies and manuals.
We begin with why chunk size matters. A vector for a whole document blurs every topic together, so a question about one detail matches weakly. Very small chunks, on the other hand, lose the context that gives a sentence its meaning. You will write a function that splits text into pieces of a chosen size, measured in words.
Then we add overlap. Without it, an idea that straddles a boundary is cut in two, and neither half holds the whole thought. With overlap, each chunk begins a set number of words before the previous one ended. We write the loop carefully, so that the step is always positive and the final chunk is handled properly, and we test on small numbers that can be checked by eye.
Each chunk carries metadata, including the source file, its position and its offsets in the original, so that answers can cite where they came from. We discuss privacy too. Private documents should stay on your machine, be chunked locally and never be pasted into services you do not trust.
We compare retrieval with and without overlap on a sample document.
By the end of this lecture you will be able to chunk documents with overlap and attach metadata for citation.
Building a Retrieval-Augmented Prompt with a Dry-Run Client. The final step of the RAG project is to give a language model the retrieved passages and ask it to answer from them. This lecture assembles that prompt and uses the dry-run client from the first section, so everything can be inspected and tested without a live model.
We start with the structure of a grounded prompt. A system message sets the rules: answer only from the provided context, refer to the sources by number and say clearly when the context does not contain the answer. The user message contains the numbered passages followed by the question. You will write a function that takes a question and the results from the vector index and builds this message list.
You will connect the pipeline end to end. The function retrieves the top chunks, discards those below the similarity threshold and, if none remain, returns a clear no-answer response without calling the model at all. Otherwise it builds the prompt and passes it to the dry-run client, which returns the prepared request for inspection. Printing the final prompt lets you check exactly what the model would see.
We discuss the context budget, choosing how many chunks to include and trimming when they exceed the limit, and we explain why retrieved text should be treated as data and not as instructions.
We also return the sources along with the answer, so a reader can check them.
By the end of this lecture you will be able to build and inspect a grounded RAG prompt and connect it to a model client.
Image Tensors and Preprocessing for Vision Models. Vision models do not read image files; they read tensors of numbers, and they are strict about the format. This lecture explains how an image becomes a tensor and how to prepare it correctly for a pretrained model.
We begin with what an image is. A color image is a grid of pixels, each with red, green and blue values, which you can load into an array. You will open an image with the Pillow library, convert it to a NumPy array, and inspect its shape and data type. We explain the common layouts, with channels last for most image libraries and channels first for PyTorch, and why mixing them up is a frequent error.
Preprocessing follows a standard recipe. The image is resized to the size the model expects, converted to a tensor with values scaled between zero and one and normalized using the mean and standard deviation that the model was trained with. You will use the transforms module to build this sequence and apply it, then reverse the normalization to display the result and confirm that it looks right.
We discuss why using the wrong preprocessing silently harms accuracy. A model trained with one normalization performs poorly with another, even though no error appears. We also add a batch dimension, since models expect a batch of images, and discuss converting grayscale images to three channels.
We process several images and stack them into a batch.
By the end of this lecture you will be able to convert images into correctly preprocessed tensors for a vision model.
Running a Pretrained Image Classifier. Training a vision model from scratch takes large amounts of data and computing power. A pretrained classifier has already learned to recognize a thousand common categories, and you can use it immediately. This lecture runs one and teaches you to interpret its output.
You will load a standard pretrained architecture along with its weights, using the cached copy so that the exercise works offline. We put the model into evaluation mode, which turns off behaviors used only in training, and disable gradient tracking, which saves memory and time. The preprocessed image from the previous lecture goes in, and a vector of raw scores for the categories comes out.
We convert those scores into probabilities with softmax, and extract the top few predictions with their labels, using the category list that accompanies the weights. You will classify several sample images and read the results critically. The model is confident about some and unsure about others, and the probabilities show it.
We discuss why a model can be confidently wrong, especially on images unlike its training data or on objects that are not among its categories. A classifier must always choose something, so a picture of an unfamiliar object still receives a label. We discuss thresholds and the value of treating low confidence as unknown.
We also discuss model size, speed on an ordinary processor and the license terms of pretrained weights.
By the end of this lecture you will be able to run a pretrained image classifier and interpret its predictions with appropriate caution.
Fine-Tuning with a Frozen Backbone. A pretrained model recognizes generic categories, but your task may involve different ones, such as particular product types or a small set of custom classes. Transfer learning adapts the model, and the cheapest and most reliable form is to freeze the pretrained backbone and train only a new final layer. This lecture shows how.
We start with the reasoning. The early and middle layers of a vision model detect general features such as edges, textures and shapes, which are useful for almost any image task. The final layer maps those features to the original categories. By replacing only that layer and training it on your small dataset, you reuse everything the model already knows and need far less data and time.
You will load the pretrained model, set the requires_grad flag to false for every backbone parameter and replace the classification layer with a new one that has the right number of outputs. We check which parameters will be trained by counting them, which shows that only a tiny fraction will change.
Then you will write a training loop for the new layer, using a small dataset of images in labeled folders, a data loader, a cross-entropy loss and an optimizer given only the trainable parameters. We track the loss for each epoch and discuss why a modest number of epochs is enough.
We also mention unfreezing deeper layers later with a small learning rate, and saving the trained weights.
By the end of this lecture you will be able to adapt a pretrained vision model to a new task by training only its final layer.
Evaluating a Fine-Tuned Classifier. A fine-tuned model is only useful if you know how well it performs, and an honest measure requires careful evaluation. This lecture evaluates the classifier from the previous lecture on held-out images, looking well beyond a single accuracy figure.
You will run the model in evaluation mode, with gradient tracking disabled, over the test data loader, collecting the predictions and the true labels. From these you compute accuracy, then build a confusion matrix, which shows for each true class how many images were assigned to each predicted class. Reading it row by row reveals which classes are confused with each other, such as two visually similar categories, which accuracy alone would hide.
We calculate precision, recall and F1 for every class, using the classification report, and discuss which matters most for different applications. We also examine individual mistakes by looking at misclassified images and their confidence, which often reveals mislabeled data, poor image quality or genuinely ambiguous cases.
You will compare the fine-tuned model with two reference points: the pretrained model used without adaptation and a trivial baseline that always predicts the most common class. These comparisons show whether fine-tuning actually helped.
We discuss the limits of a small test set, the danger of tuning against it repeatedly and the need to keep a final untouched portion. We also discuss reporting results with an honest description of the data.
By the end of this lecture you will be able to evaluate an image classifier thoroughly and interpret its errors.
Scoring Object Detection with Bounding Boxes and IoU. Detecting objects is different from classifying a whole image. A detector must say what is present and where, by drawing a box around each object. Judging it therefore requires a measure of how well a predicted box matches the true one. This lecture introduces bounding boxes and Intersection over Union, which is the standard measure.
We begin with how boxes are represented. A common format gives the coordinates of the top-left and bottom-right corners, while another gives the top-left corner with a width and height. You will write a function that converts between them, since mixing formats is a classic source of bugs.
Intersection over Union, usually shortened to IoU, is the area where two boxes overlap divided by the area they cover together. A score of one means a perfect match and zero means no overlap. You will implement it step by step: find the overlapping rectangle, compute its area, compute each box's area and combine them, taking care of the case in which the boxes do not overlap at all. We test with simple boxes where the answer is easy to verify.
Next we use IoU to score detections. A prediction counts as correct if its class is right and its IoU with a true box exceeds a threshold, commonly one half. We count true positives, false positives and missed objects and compute precision and recall.
We also discuss the effect of the threshold and why each true box should be matched only once.
By the end of this lecture you will be able to compute IoU and use it to score detections.
Building a Time-Indexed Series and Resampling It. Forecasting begins with data that has a time order, and everything about handling it differs from ordinary tabular work. This lecture creates a time-indexed series in Pandas and shows how to resample it to a different frequency.
We start by building a synthetic series, such as daily sales with a trend, a weekly pattern and some random variation, so that you know exactly what structure it contains. You will convert a date column into a proper datetime type, set it as the index and sort it. A datetime index unlocks selection by date, slicing by month or year and a range of time-aware tools.
Resampling changes the frequency. You will aggregate daily values into weekly or monthly ones with the resample method and a function such as sum or mean, and you will see how the choice of aggregation depends on what the values mean. Sales add up, but a temperature should be averaged. We also go the other way, converting a coarse series to a finer one and filling the new gaps with forward fill or interpolation, noting that this invents values and must be done thoughtfully.
You will learn to detect problems. Missing dates, duplicated timestamps and irregular spacing all cause trouble later, so we check the index, reindex to a complete range and decide how to treat the gaps.
We plot the original and resampled series and read the patterns, including trend and seasonality.
By the end of this lecture you will be able to build a datetime-indexed series, inspect it and resample it correctly.
Lag Features and Leakage-Safe Windows. A forecasting model predicts the future from the past, so its features must be built from earlier values. Lag features provide them. This lecture creates lags and rolling windows, and focuses on the most dangerous mistake in time series work, which is leakage.
A lag feature is the value of the series some steps earlier. You will create lags of one day, seven days and so on with the shift method, and see that the first rows contain missing values because there is no earlier data. We then build rolling window features, such as the mean or standard deviation of the last seven values, with the rolling method.
The key point is leakage, which occurs when a feature accidentally contains information from the time being predicted or from the future. A rolling mean that includes the current value, for example, hands the answer to the model. You will see that the window for predicting day t must end at day t minus one, so we shift the rolling result by one step. We demonstrate the effect by training on a leaky feature and observing a spectacularly good score that collapses in honest evaluation.
We write tests that confirm that no feature uses data from the target's time or later. You will also learn to handle the missing rows created by lags, and to choose lags that fit the pattern, such as a seven-day lag for weekly cycles.
By the end of this lecture you will be able to build lag and rolling features that are safe from leakage.
Chronological Split and a Naive Baseline Forecast. Splitting time series data at random is a serious mistake. It lets the model learn from the future to predict the past, and the resulting scores are meaningless. This lecture shows the correct split and introduces the baselines against which every forecast should be compared.
You will split chronologically. The earlier part of the series becomes the training set, and the later part becomes the test set, with no shuffling. We discuss how much to hold out, usually the most recent period that matches the horizon you care about, and how to confirm that the two parts do not overlap in time. We demonstrate the contrast with a random split, whose scores are unrealistically good.
Baselines come next. The naive forecast predicts that the next value equals the latest one, and the seasonal naive forecast predicts that it equals the value from the same point in the previous cycle, such as the same weekday last week. They are trivial to compute and surprisingly hard to beat. You will implement both and evaluate them on the test period.
For evaluation, we use mean absolute error, root mean squared error and a percentage-based measure, discussing their strengths and weaknesses, including the way percentage errors behave near zero.
The principle is that a complex model is worthwhile only if it clearly beats a simple baseline. We record the baseline results as the number to beat.
By the end of this lecture you will be able to split time series data correctly and compute honest baseline forecasts.
Walk-Forward Backtesting. A single chronological split gives one estimate of forecasting performance, based on one period that may not be typical. Walk-forward backtesting repeats the experiment through time, giving a much more reliable picture of how a model would have performed in practice. This lecture implements it.
The procedure mimics real use. You train on data up to a certain date, forecast the next period, record the error and then move forward: add the newly observed data to the training set and repeat. Each step uses only information that would have been available at that moment. You will write a loop that does this, with a choice between an expanding window, which keeps all history, and a rolling window, which uses only the most recent data.
We apply the loop to a simple model that uses the lag features from earlier lectures, and to the naive baseline, collecting the forecast errors at every step. You will then summarize them with the mean and the spread, and plot the error over time to see whether performance is stable or deteriorates during certain periods, such as unusual seasons.
We discuss the cost, since the model is trained many times, and options for reducing it, such as retraining every few steps. We also compare scikit-learn's time series splitter with a hand-written loop.
The result is a fair comparison between the model and the baseline across many periods.
By the end of this lecture you will be able to run and interpret a walk-forward backtest.
Building a User-Item Interaction Matrix. Recommendation systems learn from behavior: who watched, bought, rated or clicked what. The basic data structure that organizes this behavior is the user-item interaction matrix, and this lecture builds one.
We start with raw interaction records, a table where each row says that a user interacted with an item, perhaps with a rating or a count. You will create a synthetic set of such records with invented users and items, so that the patterns are known. Using Pandas, you pivot the records into a matrix with one row per user and one column per item, with the rating or interaction value in each cell and zeros or missing values where nothing happened.
You will learn that the matrix is usually sparse. Most users interact with a tiny fraction of the items, so most cells are empty. We measure the sparsity and discuss why it makes the problem difficult. We then convert the matrix to a sparse format from SciPy, which stores only the nonzero entries and saves memory.
We discuss design choices. Explicit feedback, such as ratings, differs from implicit feedback, such as clicks, where an absence does not mean dislike. We discuss normalizing ratings by subtracting each user's average, which accounts for generous and strict raters, and mapping user and item identifiers to row and column positions.
We also hold out some interactions for later evaluation.
By the end of this lecture you will be able to build and inspect an interaction matrix and explain sparsity.
Item-Based Collaborative Filtering. Collaborative filtering recommends items by using the behavior of many users. The item-based version rests on a simple idea: if people who liked item A also tend to like item B, then B is a good recommendation for someone who liked A. This lecture implements it using the matrix from the previous lecture.
The first step is to measure how similar items are. Each column of the matrix describes an item by the users who interacted with it, so you can compare two columns with cosine similarity. Computing it for every pair gives an item-by-item similarity matrix. You will build it with a single matrix operation and check a few pairs by hand, setting the diagonal to zero so that an item is not recommended because it resembles itself.
To recommend, you take a user's history and score every item they have not yet seen. The score for a candidate is the weighted sum of its similarities to the items the user liked, weighted by their ratings. You then remove items already seen and return the top ones. We write this as a function and run it for several invented users, reading the results to see whether they make sense.
We discuss the strengths of the approach, including that it is simple, explainable and stable. We also discuss its weaknesses, such as the cold-start problem for new items or users, and a tendency to favor popular items.
By the end of this lecture you will be able to build an item-based recommender and explain its output.
Content-Based Recommendations from Embeddings. Collaborative filtering needs interaction history, which new items do not have. Content-based recommendation uses the properties of the items themselves, such as their descriptions, so that it can recommend an item the moment it exists. This lecture builds one using text embeddings.
We begin with a catalog of invented items, each with a title and a short description. You will embed the descriptions with the sentence embedding model used earlier in the course, giving every item a vector that captures its meaning. Items with similar descriptions will lie close together.
To recommend, you compute the cosine similarity between items and return the nearest neighbors of an item the user liked. For a user with several liked items, you build a profile by averaging their vectors, normalizing the result and finding the items closest to that profile, excluding those already seen. We run the function for several invented users and examine the output.
We compare it with the collaborative approach. Content-based recommendations handle new items and explain themselves well, since you can say that an item was suggested because it is similar to another. However, they tend to stay within a narrow range, recommending more of the same, and they depend on the quality of the descriptions.
We discuss ways to add variety, such as penalizing items that are too similar to those already chosen, and we examine a few surprising results.
By the end of this lecture you will be able to build a content-based recommender using embeddings and describe its trade-offs.
Blending Scores and Evaluating with Precision at K. Collaborative and content-based methods have complementary strengths, and combining them often works better than either alone. This lecture blends their scores into a hybrid recommender, and evaluates the result properly using precision at K.
Blending requires comparable scores. The two methods produce numbers on different scales, so you first normalize each to a common range, for example by scaling each user's scores between zero and one. You then combine them with a weight, so that the final score is a weighted sum. A weight of one gives the collaborative method alone and zero gives the content method alone. We also discuss using more of the content signal when a user or an item has little history, which softens the cold-start problem.
Evaluation uses the interactions you held out earlier. For each user, you produce a ranked list of recommendations from the training data and check how many of the top K appear among the user's held-out items. Precision at K is the fraction of the top K that were relevant, and recall at K is the fraction of the relevant items that were found. You will implement both and average them across users.
You will test several blending weights and plot the results to choose a sensible one. We compare against a baseline that recommends the most popular items, which is a stronger competitor than it appears.
We discuss limits of offline metrics, such as ignoring items that users would have liked but never saw.
By the end of this lecture you will be able to blend recommenders and evaluate them with precision at K.
Describing a Tool with a JSON Schema. An agent is a language model that can use tools, such as a calculator, a lookup function or a search service. For the model to use a tool, it must be told that the tool exists and how to call it. This lecture shows how to describe tools using JSON Schema.
A tool description has a name, a plain-language explanation and a schema for its parameters. The schema is a JSON structure listing each parameter with its type, a description, any permitted values and whether it is required. You will write descriptions for a few tools, such as a function that converts units and one that looks up an order status in a sample table.
We discuss why the wording matters. The model decides whether and how to call a tool from the description alone, so a vague one leads to wrong choices or malformed arguments. A good description says what the tool does, when to use it, what it returns and what it must not be used for. We compare weak and strong examples.
You will learn useful schema features, including enumerations, minimum and maximum values, default values and nested objects. Then you will place the descriptions into a request in the format the API expects, using the dry-run client to inspect it.
We also write a registry that keeps the descriptions and the functions together, so that they cannot drift apart, and discuss versioning and testing the descriptions by observing how a scripted model selects among them.
By the end of this lecture you will be able to write clear, strict tool definitions.
Parsing and Validating a Tool Call. When a model decides to use a tool, it does not run anything. It returns a structured request naming the tool and supplying arguments, and your code must read and check it. This lecture covers parsing and validation, which form the safety boundary of every agent.
We begin with the format of a response that contains tool calls. Each call has an identifier, a function name and an arguments field, which usually arrives as a string of JSON and must be decoded. You will write a function that extracts every call from a response and returns simple records, and that recognizes a response with no calls, which is the final answer.
Model output is untrusted, so validation is essential. The arguments may be malformed JSON, a required field may be missing, a value may have the wrong type or fall outside its allowed range or the model may name a tool that does not exist. You will validate each call against the schema from the previous lecture, writing a clear error for each kind of failure. We use a validation library to do most of the work, and add checks for rules that a schema cannot express.
We discuss what to do on failure. A good agent returns the error to the model as an observation, so that it can correct itself, but only a limited number of times.
We test with a set of valid and broken examples supplied by a scripted model.
By the end of this lecture you will be able to parse tool calls and reject invalid ones safely.
Dispatching Tool Calls and Returning Observations. Having parsed and validated a tool call, the next step is to execute it. Dispatching connects the name chosen by the model to a real Python function, passes the arguments and captures what comes back. The result, called an observation, is returned to the model. This lecture builds the dispatcher.
We begin with a registry, a dictionary that maps tool names to functions. It is the complete list of actions the model can trigger, which makes it an important safety boundary: a name that is not in the registry is rejected. You will write several small tools over sample data, such as an order lookup, a unit converter and a calculator with a restricted set of operations, and register them.
The dispatcher looks up the function, validates the arguments, calls it and converts the result into a short piece of text, which becomes a tool message in the conversation. Observations should be concise, since everything returned consumes the model's context, and they should be clearly labeled with the identifier of the call that produced them, so the model can match results to requests.
Failures need careful handling. If a tool raises an exception, the dispatcher catches it and returns a clear error observation, because a crash would end the whole session while an error message lets the model adapt. We add a time limit for each call and log every invocation with its arguments and outcome.
Safety matters. Never evaluate arbitrary code from the model, and validate anything used for file paths or database queries.
By the end of this lecture you will be able to dispatch tool calls through a registry and return useful observations.
The Agent Loop with a Scripted Model. An agent works by repeating a cycle: ask the model what to do, perform the requested action, show it the result and ask again, until it produces a final answer. This lecture builds that loop, and tests it with a scripted model so that the behavior is repeatable and free.
You will begin by creating the scripted model, a simple object with the same interface as the real client, which returns a prepared sequence of responses. One might request a tool, the next might request another and the last gives a final answer. This lets you test the whole loop deterministically, with no network, no cost and no randomness.
The loop itself is short. Send the messages and tool descriptions to the model. If the response contains tool calls, dispatch them and append both the assistant's message and the observations to the conversation, then repeat. If it contains plain text, return it. You will trace an example that needs two tools, such as looking up an order and then converting a price, printing each step.
We then test the unhappy paths: a call to an unknown tool, invalid arguments, a tool that raises an error and a model that never stops asking for tools. Each shows why the loop must be written defensively.
We discuss recording a trace of every step, since traces are essential for understanding and debugging agent behavior.
Finally, we show how the scripted model can be replaced with a live one through configuration, without changing the loop.
By the end of this lecture you will be able to build and test an agent loop using a scripted model.
Adding Memory and a Step Budget to the Agent. A loop that works on a simple example can still misbehave in practice. It may forget what happened earlier in a long task, or run for ever, repeating the same action. This lecture adds two important features: memory, so the agent keeps track of what it has learned, and a step budget, which keeps it bounded.
We begin with memory. The simplest form is the conversation history itself, which already contains earlier messages and observations. As it grows, it consumes more of the context window, so we discuss limiting it, for example by keeping the system message and the most recent exchanges, or by summarizing older ones. We also add a small key-value store that the agent can write to and read from through tools, for facts that must survive trimming, such as the identifier of the order it is working on.
Next comes the budget. You will add limits on the number of steps, on the total time and on the total tokens used. We detect repetition by recording each call and its arguments and stopping when the same call recurs several times, which usually signals that the model is stuck. When any limit is reached, the agent stops and returns a clear message describing what it completed and what remained.
You will test each limit with a scripted model designed to hit it.
We also discuss what an agent should not do without confirmation, such as actions with real consequences.
By the end of this lecture you will be able to add memory and enforce a step budget.
Wrapping a Model in a Request Handler. A trained model in a notebook helps nobody else. To be useful, it must be reachable by other programs through a well-defined interface. This lecture wraps a model in a request handler, a function that accepts a request, runs the prediction and returns a structured response.
We begin by designing the contract. The request is a JSON document with the input fields the model needs, and the response contains the prediction, a confidence value, the model version and a request identifier. Writing this down first keeps the interface stable and makes the handler easy to test.
You will write a function that takes the request as a dictionary and carries out the steps. It validates the input, checking that required fields are present, types are correct and values fall in sensible ranges, and returns a clear error for anything invalid. It then converts the input into the features the model expects, calls the model and builds the response. Loading the model once, when the service starts, instead of for every request, is an essential performance habit that we demonstrate.
We discuss error handling. Invalid input should produce a client error with a helpful message, while unexpected failures should produce a safe message that reveals no internal details. We add timing information and a simple health check.
You will test the handler directly with valid, invalid and edge-case inputs, without any web server, which keeps tests fast.
By the end of this lecture you will be able to wrap a model in a validated, testable request handler.
Structured Logging for Predictions. Once a model is serving requests, you need to know what it is doing. Which inputs arrive? How long do predictions take? What does the model say, and how often does it fail? Structured logging captures this information in a form that programs can search and analyze. This lecture adds it to the request handler.
We begin by comparing free-text log lines with structured ones. A line such as prediction made is easy to write and hard to analyze, while a JSON record with named fields can be filtered, counted and charted. You will configure Python's logging module to emit one JSON object per event, with fields such as a timestamp, level, request identifier, model version, latency, prediction and outcome.
The request identifier is particularly valuable. You generate one for every request, include it in the response and in every log record for that request, which lets you trace a single call through the system and match a user's report to its log entries.
Privacy needs deliberate attention. Inputs can contain personal or confidential information, so we log summaries, such as the input length or a hash, and not the raw values by default. We discuss redacting sensitive fields, limiting retention and controlling who can read the logs.
You will write a short analysis script that reads the log file and computes the number of requests, the average and highest latency, the error rate and the distribution of predictions. These numbers form the basis for the monitoring in the following lectures.
By the end of this lecture you will be able to log predictions in a structured, privacy-conscious way.
Containerizing the Service with a Dockerfile. A service that runs on your machine may fail on another because of a different operating system, library version or missing file. A container packages the code, its dependencies and its runtime settings into a single unit that behaves the same wherever it runs. This lecture writes a Dockerfile for the prediction service.
A Dockerfile is a recipe of instructions. You begin with a base image, choosing a small one with the right Python version. You set a working directory, copy the requirements file and install the dependencies, then copy the application code. Ordering these steps so that the slow installation comes before the frequently changing code lets Docker reuse cached layers and speeds up rebuilds. You then declare the port and the command that starts the service.
We discuss good practice. Pin the base image version, run as a non-root user, avoid copying unnecessary files by using an ignore file, and keep secrets out of the image entirely, supplying them as environment variables when the container starts. We explain why configuration belongs outside the image.
You will review the finished file line by line and learn the commands for building the image, running a container, mapping a port and viewing its logs. The exercise focuses on writing and understanding the Dockerfile, so you can follow it even if you cannot run containers on your machine.
We also discuss model files, which may be baked into the image or mounted as a volume, and health checks.
By the end of this lecture you will be able to write a clear, secure Dockerfile for an AI service.
Detecting Input Drift with a Reference Window. Models are trained on data from a particular time, and the world changes. When the inputs that a deployed model receives start to differ from those it was trained on, its accuracy can quietly decline. This is called drift, and detecting it early is a core responsibility of machine learning operations. This lecture builds a simple drift detector.
The method uses two windows of data. The reference window is a sample of the inputs that the model was trained or validated on, and the live window holds recent inputs from the logs. For each feature, you compare the two distributions. You will compute simple statistics, such as the mean and standard deviation, and then use the population stability index and a statistical test, such as the Kolmogorov-Smirnov test for numeric features, to quantify the difference. For categories, you compare the proportions.
You will generate synthetic data in which one feature shifts gradually, so that you know the answer, and confirm that the detector flags that feature and leaves the others alone. We choose thresholds and discuss the balance between catching real drift and avoiding false alarms, since with large samples even tiny differences become statistically significant.
We discuss what to do when drift is detected: investigate the cause, check data quality, compare model performance on recent labeled data and retrain if necessary. We also discuss drift in predictions and in the relationship between inputs and outcomes.
By the end of this lecture you will be able to detect input drift by comparing live data with a reference window.
Routing Questions Between Retrieval and Tools. The capstone assistant must answer different kinds of questions. Some can be answered from private documents, some require a calculation or a lookup and some are simply conversation. A router decides which path each question should take. This lecture builds one.
We begin by defining the routes. A document question goes to the retrieval pipeline, a data question goes to a tool and a general question may be answered directly or declined. You will start with a rule-based router that uses keywords and patterns, which is fast, transparent and easy to test, and see where it breaks down on ambiguous phrasing.
Then we add a model-based classifier. A prompt asks the model to choose a route from a fixed list and return it as structured output, which you validate against the allowed values. Using the scripted model keeps the tests deterministic. We also combine both approaches, using rules for clear cases and the model for the rest.
You will learn to handle uncertainty. A router should have an explicit option for questions that fit no route, and a fallback for low confidence, such as asking the user to clarify. Misrouting has costs, because sending a calculation to the document search yields a confusing answer, so we measure routing accuracy on a labeled set of example questions and examine the mistakes.
We record the chosen route in the trace, which helps explain behavior.
By the end of this lecture you will be able to build and evaluate a router that sends questions down the right path.
Wiring Retrieval into the Agent Loop as a Tool. In the earlier projects, retrieval and agents were separate. This lecture joins them by turning the document search into a tool that the agent can call whenever it needs information, which makes the assistant far more flexible than a fixed pipeline.
You will begin by wrapping the retrieval function from the RAG project as a tool. It takes a query and an optional number of results and returns a compact list of passages, each with an identifier, a short excerpt, a source and a score. We write a JSON Schema for it with a clear description that explains when to use it, and register it alongside the calculator and lookup tools.
The agent can now decide for itself. For a question about a policy, the scripted model calls the search tool, reads the passages and writes an answer that cites them. For a question needing both, such as finding a rate in a document and then calculating a total, it calls the search tool and then the calculator. You will trace these runs and read each step.
We discuss design points. Observations from the search should be limited in size, to protect the context. Retrieved text must be treated as data and never as instructions to the agent. Citations should be checked against the passages that were actually returned. We also add a rule that the agent must say so when the search finds nothing relevant.
We test a range of questions, including ones that need no tool.
By the end of this lecture you will be able to expose retrieval as an agent tool and use it within the loop.
Serving the Assistant Behind a Single Endpoint. The assistant now has a router, retrieval, tools and an agent loop. Users and other programs need one simple way to talk to it. This lecture puts everything behind a single endpoint, with a clear contract, sensible limits and safe behavior.
We begin by defining the interface. The request contains a question and an optional session identifier, and the response contains the answer, the sources, the route taken, a request identifier and basic usage information. You will implement the handler by reusing the request handler pattern from the serving section: validate the input, call the assistant, build the response and handle errors cleanly.
Components are created once at start-up, including the index, the tools and the model client, and shared across requests. We discuss keeping conversation memory separate for each session, so that one user's content can never appear in another's answer, and expiring old sessions.
You will add the production concerns covered earlier in the course. Structured logging records each request with its route and latency, input validation limits the length of questions and a step budget keeps the agent bounded. Secrets come from the environment and never appear in responses. Errors return a safe message with the request identifier, so that a report can be traced.
We test the endpoint with a document question, a calculation, a question that needs both, an unanswerable one and invalid input, using the handler directly.
By the end of this lecture you will be able to expose a complete assistant through one validated, observable endpoint.
Evaluating the Assistant with a Golden Question Set. A system with this many parts can fail in many ways, and impressions from a few trials are unreliable. A golden question set gives you a repeatable measurement of quality, and this final lecture builds one for the capstone assistant.
A golden set is a collection of questions, each with the expected outcome. You will write questions of several kinds: document questions with the passage that should be retrieved and the key facts the answer must contain, calculation questions with the correct number, questions needing both, unanswerable questions for which the correct behavior is to say so, and questions that should be routed to a particular path. Variety matters, including easy, hard and ambiguous cases.
You will write an evaluation script that runs every question through the assistant and scores it along several dimensions. Routing accuracy checks the path taken. Retrieval is judged by whether the expected passage appears among the results. Answer quality is judged by whether the required facts are present and whether the assistant correctly declined when it should. Citation checks verify that every cited source was actually supplied. Tool correctness checks that the right tools were used with valid arguments.
The script produces a summary and lists every failure with the question, the expected result and the actual one. We use the scripted model for deterministic runs, and discuss how a rubric-based grader might be added for open-ended answers.
We store the results with the system version, so changes can be compared, and keep some questions aside to avoid tuning only to what you can see.
By the end of this lecture you will be able to build and run a golden-set evaluation and use it to improve a system.
This course contains the use of artificial intelligence.
Are you ready to move beyond AI theory and start building practical, real-world artificial intelligence applications? Welcome to 10 Hands-On AI Projects: Machine Learning to AI Agents, a comprehensive, project-based course designed to help developers, data scientists, machine learning engineers, and AI enthusiasts master modern Artificial Intelligence, Machine Learning, Generative AI, and Agentic AI through practical implementation.
This course takes you through 10 hands-on AI projects using Python programming, covering everything from traditional machine learning algorithms to modern Large Language Models (LLMs), Retrieval-Augmented Generation (RAG), and autonomous AI agents. Instead of focusing exclusively on theoretical concepts, you will develop practical skills through step-by-step coding exercises and reproducible AI development workflows.
Begin by setting up a professional Python development environment, managing dependencies, securing API keys, and constructing LLM requests. Establish a strong foundation in AI software development before moving into increasingly sophisticated artificial intelligence projects.
Explore Natural Language Processing (NLP) by implementing text classification and sentiment analysis pipelines. Learn TF-IDF vectorization, logistic regression, data preprocessing, transformer-based inference, and machine learning model evaluation using accuracy, precision, and recall.
Dive into Generative AI, Semantic Search, and Retrieval-Augmented Generation (RAG). Discover how document embeddings, vector indexes, cosine similarity, document chunking, and contextual retrieval work together to support intelligent question-answering applications grounded in private documents.
Develop practical Computer Vision and Deep Learning skills through image preprocessing, pretrained image classification models, transfer learning, fine-tuning techniques, confusion matrices, and object detection evaluation using bounding boxes and Intersection over Union (IoU).
Master Time Series Forecasting and Predictive Analytics by preparing temporal datasets, engineering lag features, implementing rolling windows, preventing data leakage, and evaluating forecasting models through walk-forward backtesting.
Build intelligent Recommendation Systems using collaborative filtering, content-based filtering, user-item interaction matrices, vector embeddings, hybrid recommendation algorithms, and ranking evaluation techniques.
Explore Agentic AI and Autonomous AI Agents by implementing tool schemas, function calling, tool execution, conversation memory, agent execution loops, argument validation, and execution safety limits using controlled, reproducible examples.
Gain essential AI Engineering, MLOps, and Machine Learning Operations skills through model serving, JSON prediction handlers, structured logging, Docker container configuration, request tracking, and data drift monitoring.
10 Hands-On AI Projects You Will Explore
Project 1: Machine Learning Text Classification
Project 2: Transformer-Based Sentiment Analysis
Project 3: Semantic Document Search Engine
Project 4: Retrieval-Augmented Generation (RAG)
Project 5: Computer Vision and Image Classification
Project 6: Object Detection Evaluation
Project 7: Time Series Forecasting
Project 8: Hybrid Recommendation System
Project 9: Autonomous AI Agent with Tool Calling
Project 10: End-to-End Intelligent AI Assistant
The final capstone project brings multiple technologies together, combining RAG, AI Agents, Query Routing, Tool Integration, Model Serving, and AI Evaluation into a unified AI assistant prototype.
This course is ideal for Python Developers, AI Engineers, Data Scientists, Machine Learning Engineers, Software Engineers, Generative AI Developers, MLOps Engineers, and technology professionals looking to expand their AI development capabilities and build a practical AI portfolio.
Whether you are preparing for an AI engineering career, strengthening your machine learning expertise, exploring LLM application development, or transitioning into generative AI and agentic AI development, this course provides a structured, hands-on learning experience.
Enroll today, strengthen your AI programming and AI application development skills, and start building the intelligent systems that are shaping the future of technology.