
Healthcare AI work has to be repeatable. If a result changes because of a hidden difference in your Python setup, you cannot tell whether a model got better or your environment simply changed. In this opening lecture you will verify a reproducible Python environment so that every later experiment in the course rests on solid ground.
You will begin by inspecting the interpreter. You will print the Python version and the executable path, and confirm whether a virtual environment is active. This avoids the common problem where libraries are installed in one place while the code runs in another.
Next you will look at the packages you will use throughout the course, such as pandas, NumPy, scikit-learn and PyTorch. You will write a short script that reads a pinned requirements file, compares each entry with the installed version and reports anything that is missing or different. You will also set random seeds for Python and NumPy, and see why fixed seeds matter when you want the same split or the same model result on every run.
You will discuss why reproducibility is especially important in health-related work, where results may be reviewed, audited and questioned by others.
The course uses only synthetic and publicly shareable sample data, and nothing in it is medical advice or a clinical tool.
By the end of this lecture you will be able to verify your interpreter and packages, pin versions and fix random seeds for repeatable experiments.
Almost every healthcare AI project begins with data in a table. Patient visits, lab values and diagnoses are commonly exported as CSV files, and pandas is the standard Python tool for working with them. In this lecture you will load clinical data with pandas and take a first look at what you have.
You will begin by looking at a synthetic dataset created for this course. Every row is invented, and none describes a real person. You will open the file in a text editor first so that you know what pandas is about to read, including the header, the separators and how missing values are written.
Next you will use read_csv to create a DataFrame. You will learn useful options, such as choosing the columns to load, parsing date columns as dates, specifying data types and telling pandas which strings mean missing, such as empty text, NA or a placeholder number. Identifiers such as patient numbers should be read as text so that leading zeros are not lost.
You will inspect the result with head, shape, info and dtypes, and learn to notice columns that were read with the wrong type.
You will also handle errors, such as a wrong path or a damaged file, with clear messages.
By the end of this lecture you will be able to load clinical tables into pandas, control types and missing-value markers and check the structure of a dataset.
Before building a model, you need to know whether the data can be trusted. Clinical data is notoriously messy, and a model trained on faulty values will produce faulty predictions. In this lecture you will inspect clinical data quality in a systematic way.
You will begin by defining what quality means. Values should be complete, consistent, plausible and unique. You will translate each idea into a check you can run in code.
For completeness, you will count missing values in each column with isna and sum and calculate the percentage missing, and you will look at whether missingness is clustered in particular rows. For plausibility, you will check ranges, such as an age below zero or above one hundred and twenty, or a heart rate that no living person could have, using simple rules that you define. For consistency, you will find categories that are spelled in several ways and units that are mixed, such as a weight in pounds in a column that should be kilograms. For uniqueness, you will find duplicate patient identifiers and repeated rows.
You will gather the results into a short quality report in the form of a DataFrame, with one row per check, the number of problems and an example. You will think about which issues can be fixed automatically and which need a person to decide.
By the end of this lecture you will be able to write repeatable data quality checks and summarise them clearly.
Patient data is some of the most sensitive information there is. Before data is shared, explored by a wider team or used to train a model, identifying details should be removed or masked. In this lecture you will learn to de-identify patient records safely, working only with synthetic data.
You will begin with the idea of direct and indirect identifiers. Direct identifiers, such as names, phone numbers and record numbers, point to a person on their own. Indirect identifiers, such as a precise date of birth, a postcode and a rare diagnosis, can identify someone when combined. You will list both kinds for the sample dataset.
Next you will apply several techniques with pandas. You will drop columns that are not needed, replace identifiers with random pseudonyms generated by a keyed hash, generalise dates to a year or an age band, reduce the precision of locations and shift dates by a consistent random offset per patient so that intervals are kept. You will see that the key must be kept separate and protected.
You will also search free-text columns for names or numbers using simple patterns, and discuss why pattern matching is only a first step and cannot guarantee that nothing remains.
You will emphasise that de-identification does not remove all risk, that real projects follow legal and organisational rules and that you should work with the minimum data necessary.
By the end of this lecture you will be able to remove and mask identifiers, generalise quasi-identifiers and understand the limits of de-identification.
Healthcare systems exchange information using shared standards, and one of the most important modern ones is FHIR, which stands for Fast Healthcare Interoperability Resources. In this lecture you will parse a FHIR Patient resource from JSON and learn how this standard organises information.
You will begin with the big picture. FHIR describes health data as resources, such as Patient, Observation and Condition, each with a defined structure and each expressed in JSON or XML. Because the structure is standard, different systems can understand each other's data.
Next you will read a synthetic Patient resource stored as a JSON string. You will load it with the json module and explore its structure. You will notice that fields such as name and telecom are lists of objects, that a patient can have several identifiers and that dates follow a specific text format. You will write helper functions that safely extract the family name, given names, gender and birth date, even when some fields are missing.
You will see why defensive access matters, using the get method and sensible defaults rather than direct indexing, since real resources often leave optional parts out.
You will also read the resourceType field to check that a document really is a Patient before processing it.
All data in the lecture is invented for learning.
By the end of this lecture you will be able to read a FHIR Patient resource, navigate nested JSON and extract fields safely.
Reading FHIR data is useful, but a healthcare application also needs to create and check it. Hand-written dictionaries can easily contain misspelled fields or wrong types. In this lecture you will build and validate FHIR resources with Pydantic models.
You will begin by recalling what Pydantic does. You write a class with typed fields, and the library validates data against it, converting types where reasonable and reporting precise errors where not. This is a natural fit for a standard such as FHIR, which has clear rules about structure.
Next you will define models for the parts of a Patient resource that you need: a human name, an identifier, a contact point and the patient itself. You will use optional fields where the standard allows them, lists where several values are permitted and a literal type to fix the resource type. You will add validators that check that a birth date is a real date, is not in the future and that a gender value belongs to the allowed set.
You will create valid models from synthetic data and print them as JSON. You will then feed in broken data, such as a wrong type or a missing required field, and read the errors to see exactly where the problem is.
You will also discuss what a small model does not cover, because a full implementation of the standard is much larger.
By the end of this lecture you will be able to model FHIR structures, validate them and produce standard-shaped JSON.
Although FHIR is growing, a large amount of hospital messaging still uses HL7 version 2, a much older, pipe-delimited text format. If you build healthcare applications, you will meet it. In this lecture you will parse HL7 v2 messages into segments and fields.
You will begin with the structure. A message is a block of text, in which each line is a segment, such as MSH for the header or PID for patient identification. Within a segment, fields are separated by a pipe character, components by a caret and repeats by a tilde. The first segment declares which separators are in use.
Next you will write a parser in plain Python. You will split the message into segments, split each segment into fields and keep the segment name as a key. You will handle the quirk that, in the header segment, the field separator itself counts as the first field, which changes the numbering. You will write a helper that retrieves a value by a path such as PID, field five, component one, and returns an empty value when it is missing.
You will use a short synthetic message with invented details, and extract the sending application, message type, patient identifier and name. You will also handle line endings, which are often carriage returns rather than new lines.
You will test the parser with several variations, including missing fields and extra segments.
By the end of this lecture you will be able to explain HL7 v2 structure, parse messages and extract values by position.
A single FHIR Bundle can contain dozens of resources, such as a patient, several observations and some conditions. To use it, you need a convenient way to pick out the parts you want. In this lecture you will query a FHIR Bundle with FHIRPath-style expressions.
You will begin by looking at a synthetic Bundle. It has a type, an entry list and, inside each entry, a resource with its own resourceType. You will draw out the structure to see where things live.
Next you will learn the idea behind FHIRPath, a language for navigating healthcare resources with simple dotted paths and filters. Rather than installing a full engine, you will write a small query function that supports the most useful features. It will follow dotted names through dictionaries, step into every item of a list and apply a simple filter such as selecting entries where resourceType equals Observation.
You will use it to answer practical questions. Which observations record a heart rate? What are the values and units? Which conditions are marked active? You will return results as lists and handle the empty case without errors.
You will compare your simple approach with a full FHIRPath library, discuss what it does not support and decide when a library is the better choice.
You will test with several expressions on the sample Bundle and check the results by hand.
By the end of this lecture you will be able to navigate Bundles with path expressions and extract observations and conditions reliably.
Once your data is clean enough to load, you need to understand what it contains. Summary statistics give a fast overview of the patients in a dataset and often reveal problems before any model is built. In this lecture you will profile patient records with pandas.
You will begin with the numeric columns. You will use describe to see counts, means, standard deviations, minimums, maximums and quartiles, and learn to read them critically. A mean far from the median suggests skew, a very large maximum suggests an outlier and a count lower than the number of rows reveals missing values.
Next you will examine categorical columns with value_counts and normalised proportions. You will look at the balance of the outcome you might later predict, such as whether a patient was readmitted, and notice how rare outcomes create challenges for modelling. You will also compare groups with groupby, for example the average age and lab value for each outcome.
You will build a short profile function that returns a tidy table for any dataset, with the data type, the number of missing values, the number of unique values and a few summary statistics for each column. You will draw simple histograms and bar charts to see distributions.
You will discuss the care needed when interpreting differences, because a pattern in sample data is not proof of a medical relationship.
By the end of this lecture you will be able to profile numeric and categorical columns, inspect outcome balance and produce a reusable data profile.
Real patient data contains values that disagree with each other. The same diagnosis may be typed five different ways, a temperature might be recorded in Celsius for some patients and Fahrenheit for others and a date may appear in several formats. In this lecture you will clean inconsistent patient values.
You will begin by finding the inconsistencies. You will list the unique values of categorical columns and see variations such as male, Male, M and a trailing space. You will look at numeric columns for clusters that suggest different units.
Next you will apply fixes. You will normalise text by stripping whitespace and lowercasing, and map variants to a standard set using a dictionary and the map method, with a rule for values that do not match any variant. You will convert temperatures with a unit check, using a plausible range to detect which unit a value must be in, and you will parse mixed date formats into one type, turning failures into missing values instead of crashing.
You will keep every change traceable. Instead of overwriting the original columns, you will create cleaned versions and count how many values changed, so that you can report on the work. You will think about which rules are safe to automate and which values should be sent to a clinician or data steward for review.
You will test the cleaning function on synthetic data containing deliberate inconsistencies.
By the end of this lecture you will be able to standardise categories, resolve unit conflicts and parse mixed dates with a record of each change.
Missing values are unavoidable in clinical data, and how you handle them can change the results of a model. In this lecture you will impute missing clinical values and add missingness flags, so that the model can still learn from the fact that a value was absent.
You will begin by thinking about why values are missing. A lab test may not have been ordered because the clinician thought it unnecessary, which is itself informative. A value may be missing because of a recording error. Understanding the reason affects what is appropriate.
Next you will compare simple strategies. You will fill numeric columns with the median, which is less sensitive to outliers than the mean, and categorical columns with the most frequent value or a separate category named unknown. You will use the scikit-learn SimpleImputer so that the same fitted rule can be applied to new data later.
Then you will add indicator columns that mark which values were imputed. You will see how these flags let a model use missingness as a signal, and how they keep a record of what was changed.
You will stress a crucial rule: the imputer must be fitted on the training data only and then applied to the test data, otherwise information leaks from the test set into the training process. You will demonstrate the correct order.
By the end of this lecture you will be able to impute numeric and categorical values, create missingness indicators and avoid leakage by fitting on training data only.
Models do not read patient records the way people do. They need numbers in tidy columns. In this lecture you will engineer model-ready features from patient data, transforming raw clinical fields into inputs that a model can use well.
You will begin with the raw fields: age, sex, a few lab values, a count of previous admissions, a diagnosis category and some dates. You will decide, for each one, how it should be represented.
Next you will create new features that capture meaningful ideas. You will compute length of stay from admission and discharge dates, a body mass index from height and weight, a flag for several previous admissions and age bands. You will take care that every feature uses only information that would be available at the time a prediction is made, since using later information creates leakage and unrealistically good results.
You will then encode categories with one-hot encoding, and scale numeric columns with standardisation where the model needs it. You will combine these steps in a scikit-learn ColumnTransformer and Pipeline, which keeps the whole preparation in one object that can be fitted once and reused for new patients.
You will inspect the resulting matrix, check its shape and feature names and confirm that no missing values remain.
All records used are synthetic.
By the end of this lecture you will be able to create meaningful clinical features, avoid leakage and assemble a reusable preprocessing pipeline.
Many important medical outcomes are rare. Perhaps only a small percentage of patients are readmitted within thirty days. If you split data at random, you might end up with too few positive cases in the test set to say anything useful. In this lecture you will create stratified train and test splits for rare outcomes.
You will begin by seeing the problem on a synthetic dataset in which the outcome occurs in about eight percent of rows. You will use a plain random split several times and observe how the proportion of positive cases varies from one split to the next, sometimes substantially.
Next you will use the stratify argument of train_test_split, which keeps the proportion of each class the same in both parts. You will repeat the experiment and compare the stability. You will also set a random seed so that the split is reproducible.
You will then discuss a more serious issue in health data: patients often appear more than once. If several visits from one patient are spread across training and test sets, the model can recognise the patient and appear to perform better than it really would on new people. You will use a group-aware splitter, such as GroupShuffleSplit, to keep each patient entirely on one side.
You will check the final splits by printing the sizes, the outcome rates and the number of patients in each.
By the end of this lecture you will be able to create stratified, grouped and reproducible splits and verify that they are sound.
Before trying anything complicated, you need a baseline. A simple model gives you a point of comparison and often performs surprisingly well. In this lecture you will train a baseline logistic regression risk model on synthetic patient data.
You will begin with the idea. Logistic regression estimates the probability of an outcome, such as readmission, from a weighted combination of features. Its weights are easy to read, and the model trains quickly, which makes it ideal for a first attempt and for explaining results to non-technical colleagues.
Next you will build a pipeline that includes the preprocessing from the previous lectures and a LogisticRegression estimator. You will fit it on the training data and call predict_proba to get risk probabilities for the test set. You will learn the difference between predicted classes and probabilities, and why probabilities are more informative in healthcare.
You will deal with class imbalance by using the class_weight option, and compare the behaviour with and without it. You will look at the coefficients, tie them back to feature names and discuss which features push risk up or down, remembering that associations in data are not proof of cause.
You will check basic accuracy, and see why accuracy alone is misleading when the outcome is rare, setting up the next lecture on better measures.
This is a teaching exercise and not a clinical tool.
By the end of this lecture you will be able to train a baseline classifier, produce probabilities and interpret its coefficients carefully.
A model that looks good on one number may be failing in ways that matter. For rare medical outcomes, accuracy is especially misleading, because a model that predicts that nobody has the outcome can still be right ninety percent of the time. In this lecture you will evaluate risk models with ROC AUC and precision-recall measures.
You will begin with the confusion matrix, which counts true positives, false positives, true negatives and false negatives for a chosen threshold. You will derive sensitivity, specificity and precision from it and see how moving the threshold trades one against another.
Next you will meet the ROC curve, which plots the true positive rate against the false positive rate across all thresholds, and its summary, the area under the curve, or AUC. You will compute it with scikit-learn's roc_auc_score and roc_curve, and learn how to interpret it. An AUC of 0.5 means the model ranks cases no better than chance, and a value near 1 means it separates the classes well.
You will then learn why ROC AUC can look comfortable on imbalanced data and why precision-recall curves are often more informative. You will compute average precision with average_precision_score and plot the curve, comparing it with the baseline given by the outcome rate.
You will evaluate the logistic regression model from the previous lecture on a synthetic test set and write an honest summary that includes the sample size and the limits of what the numbers can tell you.
By the end of this lecture you will be able to compute and interpret ROC AUC and precision-recall measures and choose sensible thresholds.
A single train and test split can be lucky or unlucky, and a more flexible model needs a more reliable assessment. In this lecture you will use cross-validation to evaluate a gradient boosting model for diabetes risk on synthetic data.
You will begin by understanding gradient boosting. It builds many small decision trees one after another, each one trying to correct the mistakes of the ones before it. It often performs very well on tabular data such as clinical records, handling non-linear patterns and interactions that a linear model would miss.
Next you will create a GradientBoostingClassifier, or the histogram-based version in scikit-learn, and place it in a pipeline with the preprocessing you already built. You will use StratifiedKFold so that each fold keeps the outcome rate, and cross_validate to obtain scores for several folds, including ROC AUC and average precision.
You will read the results as a distribution rather than a single value. The mean shows typical performance and the standard deviation shows how much it varies with the data. You will compare the boosting model with the logistic baseline using the same folds, so that the comparison is fair, and decide whether the extra complexity is justified.
You will also discuss the dangers of tuning many settings against the same folds, which can lead to optimistic results, and the value of keeping a final test set untouched.
By the end of this lecture you will be able to cross-validate models, report variability and compare them fairly.
A risk model does not only rank patients. It also outputs a probability, and people may act on that number. If the model says there is a thirty percent risk, then about thirty out of one hundred such patients should actually have the outcome. In this lecture you will calibrate predicted risk with reliability curves.
You will begin with the idea of calibration. A model can be excellent at ranking, with a high AUC, and still be poorly calibrated, systematically overestimating or underestimating risk. Gradient boosting and some other models are often miscalibrated.
Next you will draw a reliability curve with calibration_curve. It groups predictions into bins and, for each bin, compares the mean predicted probability with the observed rate of the outcome. A perfectly calibrated model follows the diagonal. You will plot the curves for the logistic regression and the boosting model and see how they differ.
You will measure calibration with the Brier score, which combines the quality of the probabilities into one number, and compare it between models.
Then you will improve calibration with CalibratedClassifierCV using sigmoid and isotonic methods. You will fit the calibrator on data not used to train the model, and see the curve move toward the diagonal. You will discuss when isotonic regression needs more data than is available.
All results use synthetic data and are for learning only.
By the end of this lecture you will be able to plot reliability curves, compute Brier scores and apply calibration methods.
Medical images are, to a computer, large arrays of numbers. Before any neural network can learn from a chest X-ray, you must load it and convert it into a tensor with sensible values. In this lecture you will load and normalise a chest X-ray as a tensor using PyTorch.
You will begin with what an image is in memory. A greyscale X-ray is a two-dimensional grid of pixel intensities, and a colour image adds a channel dimension. You will use a small synthetic or openly licensed practice image created for the course, and never any real patient image.
Next you will open the image with Pillow, convert it to greyscale and examine its size and pixel range. You will turn it into a NumPy array and then a PyTorch tensor, and you will learn the shape conventions for deep learning, with channels first, so that a single image has the shape one by height by width.
You will then resize the image to a fixed size, because a network expects consistent dimensions, and scale the values from the range zero to 255 to a range between zero and one. You will go a step further and standardise with a chosen mean and standard deviation, and understand why normalisation helps training.
You will display the image before and after to confirm that nothing has gone wrong, and check the tensor's data type and range.
By the end of this lecture you will be able to load an image, create a tensor with the correct shape and apply resizing and normalisation.
A neural network is not trained on one image at a time. It learns from batches, and the data must be shuffled and delivered efficiently. In this lecture you will batch images with a Dataset and DataLoader in PyTorch.
You will begin with the two abstractions. A Dataset knows how to return one item, an image tensor and its label, given an index, and how many items it holds. A DataLoader wraps a dataset and takes care of batching, shuffling and, optionally, loading in parallel.
Next you will write a custom Dataset class. Its init method will receive a list of file paths and labels and an optional transform. Its len method will return the number of items, and its getitem method will open the image, apply the transform and return the tensor together with the label. You will build a small synthetic collection, generated by code, so that the exercise needs no real data.
You will then create a DataLoader with a batch size, shuffling for training and no shuffling for evaluation, and iterate over it to inspect the shape of a batch, which will be batch size by channels by height by width. You will see what happens at the end of the data when the last batch is smaller.
You will also discuss splitting data by patient before building datasets, so that images from one person do not appear in both training and test sets.
By the end of this lecture you will be able to write a Dataset, create DataLoaders and inspect batches.
Convolutional neural networks are the standard tool for learning from images because they look for local patterns, such as edges and textures, and combine them into more complex ideas. In this lecture you will build a small convolutional network for X-ray classification in PyTorch.
You will begin with the building blocks. A convolutional layer slides small filters across the image and produces feature maps. An activation function such as ReLU adds non-linearity, a pooling layer reduces the size of the maps and a final linear layer turns the learned features into a prediction.
Next you will write a model class that inherits from nn.Module. You will stack a few convolution, ReLU and max pooling blocks, flatten the result and add a fully connected head that outputs a single value for a binary task, such as normal versus abnormal. You will define the forward method and instantiate the model.
You will check the shapes at each step by passing a dummy batch through the network, which is one of the most useful debugging habits in deep learning. You will count the parameters and compare the size of a small network with a large one, and discuss why small networks are appropriate for a teaching prototype and limited data.
You will also discuss why a model like this is not a medical device. It is a learning exercise, and real clinical imaging models require extensive validation and regulation.
By the end of this lecture you will be able to design a small CNN, trace tensor shapes and count parameters.
A network must be trained before it can make useful predictions, and medical datasets are often imbalanced, with far more normal images than abnormal ones. In this lecture you will write a training loop with a class-weighted loss.
You will begin with the loss. For a binary task you will use BCEWithLogitsLoss, which combines a sigmoid and a binary cross-entropy in a numerically stable way. You will see how an imbalanced dataset can lead a network to predict the majority class every time and still appear to do well.
Next you will correct this with class weights. You will calculate the ratio of negative to positive examples and pass it as the pos_weight argument, so that mistakes on the rare class count for more. You will explain the effect in plain terms and compare training with and without the weight.
You will then write the loop itself. For each epoch, you will iterate over the batches, move data to the device, clear gradients, run the forward pass, compute the loss, call backward and take an optimiser step with Adam. You will track the average loss per epoch and print it, and you will switch the model between training and evaluation modes at the right times.
You will run a few epochs on a small synthetic dataset, so that the exercise finishes quickly, and look at the loss curve.
By the end of this lecture you will be able to write a complete training loop and handle class imbalance with a weighted loss.
A model that trains is not necessarily a model that works. You need to measure its performance on data it has not seen, using measures suited to the medical setting. In this lecture you will evaluate the X-ray classifier with ROC AUC.
You will begin by putting the model in evaluation mode and disabling gradient calculation with torch.no_grad, which saves memory and avoids accidental updates. You will loop over a held-out DataLoader, collect the raw outputs, convert them to probabilities with a sigmoid and gather them together with the true labels.
Next you will use scikit-learn to compute the ROC AUC and plot the ROC curve. You will then compute sensitivity and specificity at a chosen threshold and show the confusion matrix. In a screening setting, you may care more about not missing positive cases, so you will see how lowering the threshold increases sensitivity at the cost of more false alarms.
You will discuss why results on a small synthetic test set have wide uncertainty, and use bootstrap resampling to calculate a rough confidence interval for the AUC, which shows how much the number could move.
You will also reflect on the gap between a prototype and a real clinical tool. Real systems need independent data from several sites, subgroup analysis, clinical review and regulatory approval, and a good AUC on practice data does not demonstrate any of that.
By the end of this lecture you will be able to evaluate an image classifier, compute AUC, choose thresholds and express uncertainty.
Clinical notes are written in free text, and before a language model can use them they must be turned into pieces it understands. These pieces are called tokens. In this lecture you will tokenise clinical notes with a subword tokenizer.
You will begin by seeing why simple splitting on spaces is not enough. Medical text contains long technical terms, abbreviations, drug names and numbers, and a fixed vocabulary of whole words would miss many of them. Subword tokenisation solves this by breaking rare words into smaller known pieces, so that nothing is truly out of vocabulary.
Next you will use the Hugging Face transformers library to load a tokenizer for a pretrained model. You will tokenise short synthetic notes, such as a made-up sentence about a patient with chest pain, and print the tokens, the token identifiers and the attention mask. You will notice how a long word becomes several pieces marked with a special prefix, and how special tokens are added at the start and end.
You will learn about padding and truncation, which make all sequences in a batch the same length, and about the maximum length a model can accept. You will also use offset mappings, which tell you which characters in the original text each token came from, an important tool for the entity work that follows.
All notes used here are invented examples without real patient details.
By the end of this lecture you will be able to tokenise text with a subword tokenizer, handle padding and truncation and use offset mappings.
Clinical notes contain valuable facts that are buried in sentences, such as medications, symptoms and conditions. Extracting them as labelled items is called named entity recognition. In this lecture you will extract clinical entities with token classification.
You will begin with the task. Instead of assigning one label to a whole note, the model assigns a label to every token, for example marking a token as the start of a problem, the inside of a problem, a medication or nothing at all. This is commonly written in a scheme with B, I and O prefixes.
Next you will load a pretrained token classification model with the transformers pipeline or the AutoModelForTokenClassification class. To keep the exercise practical, you will use a small publicly available model suited to the task, or a prepared mock output, and run it on invented clinical sentences. You will look at the raw prediction, which contains a label and a score for each token.
You will read the output carefully, noticing that the labels attach to subword pieces rather than to whole words and that the model may be confident in some places and uncertain in others. You will map the label identifiers to names using the model configuration.
You will discuss the importance of checking extracted entities with a clinician or with annotated data before relying on them, because errors, such as missing a negation, can change the meaning.
By the end of this lecture you will be able to run token classification, read per-token labels and scores and understand the BIO scheme.
The output of a token classification model is a label for each subword piece, which is not what a user wants. They want to see phrases, such as a condition or a medication, with a position in the text. In this lecture you will merge subword predictions into entity spans.
You will begin with raw predictions for a short invented sentence. A long drug name might be split into three pieces, each with its own label, and a condition made of two words might be split into four. You will print them side by side with their character offsets.
Next you will write a function that walks through the tokens in order. When it sees a beginning label, it starts a new entity. When it sees an inside label of the same type that directly follows, it extends the current entity, and anything else ends the current entity. You will use the offset mapping to take the start of the first piece and the end of the last, and slice the original text to recover the exact wording.
You will compute an average confidence for each entity, handle special tokens that have no offsets and deal with inconsistent sequences, such as an inside label without a beginning.
You will then print the entities as a clean list with type, text, start, end and score, and check them against the original sentence by eye.
You will also compare your function with the aggregation option built into the library.
By the end of this lecture you will be able to convert token-level predictions into readable entity spans with accurate character positions.
Sometimes the goal is to assign a category to a whole note, such as which department it belongs to, whether it describes an urgent situation or what type of document it is. In this lecture you will classify clinical notes with a transformer model.
You will begin with the idea of sequence classification. The model reads the entire note, produces a summary representation and passes it to a small layer that outputs a score for each category. Pretrained transformers are effective here because they have already learned a great deal about language and need only a small amount of task-specific data.
Next you will load a tokenizer and a model with AutoModelForSequenceClassification. You will prepare a tiny synthetic set of invented notes with labels, tokenise them with padding and truncation and run them through the model to obtain logits. You will convert the logits to probabilities with softmax and read the predicted class.
You will see the difference between using a model as it is and fine-tuning it on your own examples, and outline the steps for fine-tuning with the Trainer or a simple loop. Because training takes time, you will focus on running inference and reading the results, and use prepared outputs where needed.
You will discuss evaluation with a held-out set, class balance and why the output should be treated as a suggestion for a person to review, not as a decision.
By the end of this lecture you will be able to run a transformer text classifier, interpret probabilities and describe how fine-tuning works.
Clinical notes can be long, and reading many of them takes time. A summary that captures the key points can help, as long as it is accurate. In this lecture you will summarise clinical notes with a sequence-to-sequence model.
You will begin with the architecture. A sequence-to-sequence model reads an input text and generates a new text, one token at a time. Models such as T5 and BART were trained for tasks including summarisation. Generation is more open ended than classification, which creates both opportunities and risks.
Next you will load a small pretrained summarisation model with the transformers library, or use prepared outputs if resources are limited. You will give it an invented, multi-sentence note about a made-up patient and generate a short summary. You will explore the generation settings, including the maximum and minimum length, the number of beams in beam search and the repetition penalty, and see how each affects the result.
You will then discuss the main risk in healthcare. A summariser can omit an important detail or state something that the note did not say. You will build a simple check that confirms that numbers and medication names in the summary also appear in the source note, and flags any that do not.
You will emphasise that summaries must be reviewed by a qualified person before anyone relies on them.
By the end of this lecture you will be able to generate summaries, tune generation settings and add a basic consistency check against the source.
A healthcare assistant that answers questions from clinical guidelines needs to find the right passage quickly. Guidelines are long documents, and a model cannot read all of one at once. In this lecture you will chunk clinical guidelines into passages that can be searched and cited.
You will begin with the reasons for chunking. Retrieval works best on focused pieces of text, each about one idea. A chunk that is too large contains a mixture of topics and dilutes the match, and a chunk that is too small loses its context and may be meaningless on its own.
Next you will write a chunking function that works on a short synthetic guideline written for this course, not on any real clinical document. It will split the text first by headings and paragraphs, then merge or divide pieces to reach a target size, and add a small overlap between neighbours so that a sentence on a boundary is not lost. You will keep each chunk's section title, its position and a stable identifier as metadata.
You will check the output by printing the chunks with their lengths and boundaries. You will test unusual cases, such as an empty document, a very long paragraph and a table written as text.
You will also discuss why the source, version and date of a guideline must be stored with each chunk, because clinical advice changes and old guidance should not be presented as current.
By the end of this lecture you will be able to split documents into well-sized, labelled passages with overlap.
To search by meaning rather than keywords, passages are turned into vectors called embeddings. A question about chest pain should find a passage about cardiac symptoms even if the words differ. In this lecture you will turn passages into embedding vectors.
You will begin with the concept. An embedding model maps text to a list of numbers, with the property that texts with similar meanings produce vectors that are close together. This lets you compare a question and a passage mathematically.
Next you will load a small sentence embedding model with the sentence-transformers library, or, if downloads are not possible, use a simple deterministic function based on hashed word counts that follows the same interface. You will embed the passages created in the previous lecture and store the results in a NumPy matrix with one row per passage. You will check the shape and the length of each vector.
You will normalise each vector to unit length, which makes later comparisons simpler and faster, and verify the normalisation. You will embed in batches rather than one at a time for efficiency and save the matrix and the passage identifiers to disk so that unchanged text does not need to be embedded again.
You will discuss that general-purpose models may handle medical terms less well than specialised ones, and that retrieval quality should be measured with example questions instead of assumed.
By the end of this lecture you will be able to create, normalise, store and reuse embeddings for a set of passages.
With passages stored as vectors, finding the best match for a question comes down to measuring closeness. In this lecture you will search a vector index with cosine similarity and return the most relevant passages.
You will begin with the measure. Cosine similarity compares the direction of two vectors and ignores their length. When vectors are normalised, it equals the simple dot product, which NumPy can compute for all passages at once with a single matrix multiplication.
Next you will build a small index class. It will hold the matrix of vectors, the passage texts and the metadata. Its search method will embed the question, compute the scores against every passage, use argsort to select the top results and return them with scores, identifiers and source details. You will add a parameter for how many results to return.
You will try several example questions about the synthetic guideline and examine the results, looking at both the ranking and the scores. You will notice how a question phrased in unfamiliar words can still find the right passage, and how an unrelated question produces uniformly low scores.
You will discuss the scale of the approach. A matrix multiplication is fine for thousands of passages, while larger collections use approximate nearest neighbour indexes, such as those in dedicated vector databases.
You will test the search function with a small set of questions for which you know the correct passage and measure how often it appears in the top results.
By the end of this lecture you will be able to implement similarity search and evaluate it with simple test questions.
Retrieval only helps if the language model actually uses what was retrieved. The way to ensure that is a grounded prompt, one that gives the model the evidence and clear rules about how to use it. In this lecture you will build a grounded prompt with citations.
You will begin with the structure of the prompt. It starts with the role and the rules: answer only from the supplied passages, cite the identifier of each passage that supports a statement, say so when the passages do not contain the answer, never give a diagnosis or personal medical advice and remind the user to consult a qualified professional. These rules are written in plain, specific language.
Next you will write a function that takes the question and the top retrieved passages and assembles the prompt. Each passage is labelled with an identifier and its source details, and the total length is kept within a limit by dropping the lowest-ranked passages first. You will format the prompt carefully so that the boundary between instructions, evidence and question is clear.
You will use a mock model that returns prepared answers, so no paid service is needed, and write a function that finds the citations in the answer and checks that each refers to a passage that was provided.
You will print the complete prompt and one example answer with its citations resolved to titles.
By the end of this lecture you will be able to construct grounded prompts, enforce citation rules and verify that citations are valid.
One of the most important behaviours of a healthcare assistant is knowing when not to answer. If the retrieved passages do not address the question, a confident answer is likely to be invented. In this lecture you will make the assistant refuse when retrieval is weak.
You will begin with the failure. You will ask a question that the guideline does not cover and see that the search still returns its top results, however irrelevant, and a language model may try to answer anyway. This is how unsupported statements appear.
Next you will add a retrieval gate. Using the similarity scores from the previous lecture, you will set a threshold below which a passage is considered not relevant and require a minimum number of relevant passages before the model is called. You will choose the threshold by looking at the scores for questions that the guideline does answer and for those it does not, and finding a value that separates them reasonably.
When the gate closes, the assistant returns a clear, polite message that it could not find supporting information, and suggests consulting a qualified professional or a trusted source. You will log the refusal and the scores so that you can review it later.
You will also add an output check that rejects answers without citations. You will measure the behaviour on a small test set of answerable and unanswerable questions, reporting how often the assistant correctly answers and correctly refuses.
This assistant is for education and is not medical advice.
By the end of this lecture you will be able to set a retrieval threshold, implement abstention and evaluate it.
Wearable devices produce a steady stream of measurements, such as heart rate every few seconds, often with gaps and noise. Before you can analyse them, you must put them on a regular timeline and reduce the noise. In this lecture you will resample and smooth a heart rate stream.
You will begin with a synthetic stream of timestamped heart rate readings generated by code, with irregular intervals, a few missing stretches and some random noise. You will load it into a pandas Series with a datetime index and plot it to see what you are dealing with.
Next you will resample to a regular interval, such as one value per minute, with resample and an aggregation like the mean. You will compare it with the median, which is less sensitive to spikes, and see how gaps appear as missing values. You will decide how to treat them, either by leaving them as missing, interpolating over short gaps only or flagging long ones, because inventing a long stretch of data would be misleading.
You will then smooth the series with a rolling mean and an exponentially weighted mean, and explore how the window size changes the balance between noise reduction and responsiveness. You will see that a window that is too large can hide a real, brief change.
You will plot the raw and smoothed series together and describe the trade-offs.
By the end of this lecture you will be able to resample time series, handle gaps responsibly and apply rolling smoothing.
Sudden or unusual changes in vital signs can indicate a problem, and a monitoring system needs a way to flag them. A simple, transparent method uses rolling statistics. In this lecture you will detect anomalies in vital signs with rolling z-scores.
You will begin with the z-score. It measures how many standard deviations a value is from the mean. A value with a large absolute z-score is unusual compared with the data used to calculate the mean and deviation.
Next you will apply it to a synthetic heart rate series that includes a few injected spikes and drops. A single global mean would be misleading, because a person's heart rate changes naturally during the day. You will therefore compute the mean and standard deviation over a rolling window of recent values, using rolling with a chosen size, and calculate each point's z-score against its own recent past. You will shift the window by one step so that the point being tested is not part of its own baseline.
You will flag points whose score exceeds a threshold, such as three, and plot them on the series. You will explore how the window size and the threshold change the balance between missing real events and raising false alarms.
You will also discuss limits. Rolling methods can be fooled by slow drifts and by the start of the series, and context matters, because exercise can cause a legitimate spike.
This is a teaching example and not a medical alarm system.
By the end of this lecture you will be able to compute rolling z-scores, flag anomalies and tune thresholds thoughtfully.
Looking ahead can be as valuable as looking back. If you can estimate where a patient's measurements are heading, you can provide earlier support. In this lecture you will forecast patient trends with lag features, using a simple and understandable approach.
You will begin with the idea. Instead of using a specialised forecasting model, you turn the time series into an ordinary tabular problem. For each time step, the inputs are the previous few values, called lags, and the target is the next value. Any regression model can then learn the relationship.
Next you will build the lag features with shift in pandas on a synthetic daily series, such as resting heart rate over several months. You will create columns for the previous one, two, three and seven days, plus a rolling mean of recent values and the day of the week, and drop the rows made incomplete by the shifting.
You will split the data by time, with the earlier part for training and the later part for testing, and explain why a random split would be wrong, since it would let the model learn from the future. You will train a linear model or a gradient boosting regressor, predict on the test period and compare it with a naive baseline that simply repeats the last value.
You will compute the mean absolute error for both and discuss whether the model adds any value over the baseline.
By the end of this lecture you will be able to create lag features, split time series correctly and evaluate forecasts against a baseline.
When a model influences decisions about people, it is not enough for it to be accurate. You need to understand what drives its predictions. In this lecture you will explain a risk model with permutation importance.
You will begin with the question: which features does the model rely on? Permutation importance answers it in a simple way. You take a trained model and a held-out dataset, shuffle the values of one feature so that its link with the outcome is broken, and measure how much the performance drops. A large drop means the model relied heavily on that feature.
Next you will apply scikit-learn's permutation_importance to the risk model from earlier in the course, using the test set and a metric such as ROC AUC, with several repeats to measure how stable the results are. You will present the mean importance and the standard deviation for each feature in a sorted table and a bar chart.
You will interpret the results carefully. Importance shows what the model uses, not what causes the outcome, and correlated features can share or hide importance. You will check for features that look suspiciously influential, which can reveal leakage, such as a field that is recorded after the outcome.
You will discuss how explanations support clinical review, because a person can ask whether the drivers make sense.
All data is synthetic and the results are for learning only.
By the end of this lecture you will be able to compute and interpret permutation importance and use it to look for leakage and sanity-check a model.
A model can perform well on average and still serve some groups of patients much worse than others. In healthcare, this can translate into unequal care. In this lecture you will audit model performance across patient groups.
You will begin with the motivation. Differences in performance can arise from unequal representation in the training data, from measurement differences between groups or from outcomes that reflect unequal access to care. Auditing does not fix these problems, but it makes them visible.
Next you will take the predictions from your risk model on a synthetic test set that includes a made-up group attribute, such as an age band or a sex category. You will compute metrics for each group separately, including the number of patients, the outcome rate, the ROC AUC, the sensitivity and false positive rate at a chosen threshold and the calibration. You will gather them into a table with groupby and apply.
You will compare the groups and compute the gaps. You will learn about common fairness ideas, such as equal opportunity, which compares sensitivity, and calibration within groups, and see that they cannot all be satisfied at once when base rates differ, which makes the choice a policy decision.
You will pay attention to small groups, where metrics are noisy, and report sample sizes and rough uncertainty.
You will write a short audit summary that states findings and limitations.
By the end of this lecture you will be able to compute metrics by group, interpret the gaps and report them responsibly.
Sharing patient data can support research, but it carries a risk that someone will be identified from a combination of seemingly harmless fields, such as age, postcode and sex. k-anonymity is a way to measure and reduce that risk. In this lecture you will check k-anonymity before sharing patient data.
You will begin with the definition. A dataset is k-anonymous if every combination of quasi-identifiers appears at least k times, so that each person is indistinguishable from at least k minus one others. You will identify the quasi-identifiers in a synthetic dataset, which are fields that are not direct identifiers but can be linked with outside information.
Next you will compute the size of each group with pandas groupby on those columns. You will find the smallest group, which is the dataset's k value, and list the groups smaller than your chosen target, such as five. You will report the number of records at risk.
Then you will improve the result by generalisation and suppression. You will turn exact ages into ranges, shorten postcodes to a region and group rare categories into an other label, then recompute k. Where small groups remain, you will consider removing those rows. You will see the trade-off between privacy and the detail left in the data.
You will explain the limits of k-anonymity. It does not protect against everyone in a group sharing the same sensitive value, and it is not a complete guarantee, so real sharing requires expert review and governance.
By the end of this lecture you will be able to measure k, generalise data to reach a target and weigh privacy against utility.
A model that stays in a notebook helps nobody. To be used by an application, it must be available through a well-defined interface. In this lecture you will serve risk predictions through a validated API endpoint, using synthetic data and a demonstration model.
You will begin with the design of the interface. A client sends a JSON description of a patient, and the service returns a risk probability, the model version and a clear message about the intended use. You will decide on the input fields, their types and their allowed ranges.
Next you will use Pydantic to define the request and response models, with constraints such as an age between zero and one hundred and twenty and a limited set of values for categorical fields. You will build the endpoint with FastAPI, or an ASGI-style function if you prefer to avoid extra installs, load the trained pipeline once at start-up and call predict_proba for each request.
You will see validation in action. A request with a missing field or an impossible value is rejected with a clear error before it ever reaches the model. You will add a health endpoint and include the model version and a timestamp in every response.
You will test the endpoint in-process with a test client and a handful of synthetic requests, including invalid ones.
You will stress that the output is decision support for education and must never replace professional judgement.
By the end of this lecture you will be able to wrap a model in a validated API, load it efficiently and test it.
Deploying a model is not the end of the work. Over time, the patients who reach the service can change, and a model trained on earlier data can slowly become less reliable. In this final lecture you will monitor deployed predictions for input drift.
You will begin with the concept. Input drift, also called data drift, occurs when the distribution of incoming data differs from the training data. It can result from a new patient population, a change in how a measurement is recorded or a faulty device. Drift is a warning that the model's behaviour should be reviewed.
Next you will record a reference profile from the training data, storing the mean, standard deviation and histogram bins for each numeric feature and the category proportions for each categorical one. You will then simulate a stream of incoming synthetic requests, once drawn from the same distribution and once with a deliberate shift, such as a higher average age.
You will compare the incoming window with the reference using simple measures. For numeric features, you will use the Kolmogorov-Smirnov test from SciPy and the population stability index. For categorical features, you will compare proportions. You will set alert thresholds and produce a drift report that lists the features that triggered them.
You will also log prediction volumes and the distribution of predicted risk, and discuss that true outcomes arrive later and should eventually be used to check performance directly.
By the end of this lecture you will be able to build a reference profile, detect drift with statistical measures and design a simple monitoring report for a deployed clinical decision support application.
This course contains the use of artificial intelligence.
Discover the transformative power of Artificial Intelligence in Healthcare and learn how to build intelligent, data-driven medical applications using Python, Machine Learning, Deep Learning, Natural Language Processing (NLP), and Generative AI.
Healthcare is undergoing a digital revolution, with AI-powered healthcare solutions transforming patient risk assessment, medical imaging, clinical data analysis, remote patient monitoring, and clinical decision support. This comprehensive, hands-on course equips you with practical technical skills to develop innovative Healthcare AI, HealthTech, and Medical AI applications.
Featuring 10 comprehensive modules and 40 hands-on lessons, this course takes you through the complete healthcare AI development lifecycle, from clinical data preparation to model deployment and monitoring.
Master Healthcare Data Science and Clinical Data Processing
Begin your journey by working with Electronic Health Records (EHR), Electronic Medical Records (EMR), clinical datasets, and patient information. Learn how to perform Data Cleaning, Exploratory Data Analysis (EDA), Feature Engineering, Data Preprocessing, Patient Data De-identification, and Missing Value Imputation using Python and pandas.
Explore essential Healthcare Interoperability Standards, including FHIR (Fast Healthcare Interoperability Resources), HL7, FHIRPath, JSON, and Pydantic, to process and validate structured healthcare information.
Build Machine Learning Models for Healthcare
Develop intelligent Predictive Analytics applications for patient readmission prediction and diabetes risk assessment.
Gain practical experience with:
Logistic Regression
Gradient Boosting
Machine Learning Classification
Predictive Modeling
Cross-Validation
Class Imbalance
ROC AUC and Precision-Recall
Probability Calibration
Learn how to evaluate healthcare machine learning models and interpret their performance.
Explore Deep Learning and Medical Imaging
Discover how Deep Learning, Computer Vision, Neural Networks, Convolutional Neural Networks (CNNs), and PyTorch can be applied to medical images.
Build chest X-ray classification prototypes while learning image preprocessing, tensor operations, data loaders, class-weighted loss, neural network training, and medical image classification.
Master Clinical NLP and Generative AI
Explore Clinical Natural Language Processing, Transformer Models, Named Entity Recognition (NER), Text Classification, Clinical Text Summarization, and Tokenization.
Build intelligent healthcare assistants using modern Large Language Models (LLMs), Retrieval-Augmented Generation (RAG), Vector Embeddings, Semantic Search, Cosine Similarity, Prompt Engineering, and Grounded AI Responses.
Learn how to incorporate source citations and abstention mechanisms to reduce unsupported responses and improve AI Reliability.
Analyze Wearable Devices and Patient Health Data
Work with Wearable Technology, Digital Health, Remote Patient Monitoring, Time-Series Analysis, Vital-Sign Analysis, Anomaly Detection, and Predictive Forecasting.
Discover techniques for processing heart-rate streams, detecting abnormal patterns, and forecasting patient health trends using historical data.
Build Responsible and Deployable Healthcare AI
Understand the importance of Responsible AI, Explainable AI (XAI), AI Ethics, Healthcare Data Privacy, Algorithmic Fairness, Bias Detection, and k-Anonymity.
Learn how to develop Clinical Decision Support System prototypes, expose machine learning predictions through FastAPI and REST APIs, validate incoming requests, and implement Model Monitoring, Data Drift Detection, and MLOps fundamentals.
Who Should Take This Course?
This course is ideal for Python Developers, AI Engineers, Machine Learning Engineers, Data Scientists, Healthcare IT Professionals, Biomedical Engineers, Clinical Informatics Specialists, Software Developers, and HealthTech Entrepreneurs.
No medical degree is required. All applications are designed for educational and prototyping purposes rather than clinical use.
Enroll today and start building practical AI-Powered Healthcare Applications with Python, combining artificial intelligence, healthcare data science, and modern software engineering to explore the future of Digital Healthcare and Medical Technology.