CPSC 330 Lecture 20: Survival analysis
Focus on the breath!
Invite everyone to pause for a few slow breaths before starting. Then explain that the recap asks students to choose approaches from the data and task, rather than from the order in which methods were taught.
Recap: What approach would you try? (1/3)
Identify the problem type, suggest an approach, and explain what clues guide your choice.
A. Finding the right product
Suppose the UBC Store wants its online search to match “something to keep my coffee hot on the bus” with products described as “insulated travel mugs.” You have the store’s product titles and descriptions. How could you retrieve relevant products even when the wording differs?
B. What should I watch next?
You are building a YouTube recommendation prototype. You have viewer IDs, video IDs, and records of which videos each viewer clicked, but no ratings or video descriptions. Suggest three videos a returning viewer might enjoy.
Discuss: If someone clicks a video, does that mean they liked it?
Keep the recap brief: ask for an approach and one clue per scenario. Prioritize the click-versus-enjoyment discussion on this slide. The other follow-up questions below are optional.
A — NLP and semantic search (lecture 18): use a pretrained text embedding model designed for retrieval to encode product descriptions and queries into a shared vector space, then retrieve products with high similarity, for example cosine similarity. A pretrained model provides a starting point without labelled query–product matches. Embed new products as they enter the catalogue.
Ask: why might exact keyword matching miss this result? The query describes a need using different words from the product description. Semantic search aims to capture this relationship. An LLM-generated answer is not required to return ranked products; retrieval would become part of RAG if we supplied the retrieved descriptions to an LLM to generate an answer. Check performance on representative queries with human relevance judgments. Exact constraints such as price, dimensions, and availability may need explicit filters rather than embedding similarity alone.
B — Recommender systems (lecture 16): clicks provide implicit feedback. Collaborative filtering can learn viewer–video interaction patterns; an implicit-feedback variant of matrix factorization is one possible approach. The absence of descriptions limits content-based approaches. A popularity baseline is also worth considering, especially for a new viewer.
Use the discussion prompt to distinguish the goal (recommend videos the viewer enjoys) from the observed proxy (clicks). A click might reflect curiosity, an appealing thumbnail, clickbait, or an accident; it does not establish satisfaction. An absent click does not establish dislike: the viewer may never have been shown the video. Do not treat all missing interactions as explicit negative ratings. Exposure and placement also influence what gets clicked.
Ask: what additional evidence would help assess enjoyment? Explicit feedback, watch duration or completion, and satisfaction surveys can help, but each has limitations. Predicting clicks well does not by itself show that recommendations improve satisfaction. This is a simplified prototype, not a description of YouTube’s production system.
Recap: What approach would you try? (2/3)
Identify the problem type, suggest an approach, and explain what clues guide your choice.
C. How much electricity will campus need tomorrow?
UBC facilities staff have two years of hourly electricity-use records for campus buildings. They want to predict demand for each hour tomorrow to plan electricity purchases. They also have weather records and the academic calendar. What information could they use when making the forecast this evening?
D. Who visited the wildlife crossing?
A conservation team has thousands of camera-trap photos, each showing a deer, bear, or coyote, but only 600 have species labels. They want to classify the remaining photos without training a large model from scratch.
Prioritize one follow-up: which weather information is available this evening? Save the additional discussion for spare time.
C — Time-series forecasting (lecture 19): start with a seasonal baseline, such as demand at the same hour last week, then consider regression with lagged demand, calendar features, and weather forecasts. Hour of day, day of week, holidays, and the academic calendar can capture recurring patterns. Evaluate with chronological splits and forecast origins matching the evening decision.
Ask: can we use tomorrow’s actual temperature or electricity demand from earlier tomorrow when making this evening’s forecast? No. Use weather forecasts available this evening; actual future weather would leak information. Predicting all of tomorrow requires a multi-step strategy: some recent-demand lags will be unavailable for later forecast hours. The academic calendar and tomorrow’s hour/day are known in advance.
D — Image classification and transfer learning (lecture 17): use a pretrained image model as a feature extractor with a classifier, or fine-tune it. Many images but few labels motivates reusing learned visual features. Ask: if several near-identical frames come from the same animal visit, should they be split randomly across training and test sets? Keep related frames together; consider held-out cameras or locations if that matches intended use. A model trained on ordinary photos may still need adaptation for night-time camera images.
Recap: What approach would you try? (3/3)
E. When will a telecom customer leave?
A telecom company wants to predict how long a new customer will stay. You have each customer’s observed months since signup and whether they have left the service. Many customers are still subscribed when the data are collected.
Would you frame this as classification or regression?
What target would you assign to a customer who has been subscribed for eight months and is still active ?
Would you keep that customer in the training data? Why?
Let students propose approaches before naming survival analysis or right censoring. The aim is to expose a gap in familiar targets, rather than expect students to name a method they have not learned.
We know the active customer has stayed for at least eight months, but do not know their eventual churn time. Assigning eight months as an exact lifetime invents a departure; dropping the customer discards useful partial information. A snapshot active/churned label does not answer how long a new customer will stay. We could ask, “Will this customer churn within six months of signup?” But if we observed them for only two months and they had not churned, we would not yet know the answer.
Keep this target question open as we continue with the same telecom example for the rest of the lecture and demo. The next slides define the prediction task and contrast completed and incomplete subscriptions before introducing the terminology.
Today’s goals
Recognize what a right-censored outcome tells us.
Represent outcomes using duration and event status.
Explain the limits of familiar classification and regression targets.
Interpret retention curves and model output in the lecture demo.
Connect the last recap scenario to today’s goals: the difficulty is not choosing a more powerful regressor, but deciding what outcome information we actually have. The slides establish the problem; the live notebook demonstrates Kaplan–Meier and Cox. Students should leave able to explain censored records and interpret retention results, rather than derive the estimators.
When will a customer leave?
Churn means a customer stops using a company’s service.
Let’s continue with the telecom company from our recap. Its retention team wants to anticipate time to churn .
Event: a customer leaves the service.
Time origin: the customer’s signup.
What information would we need to learn from past customers?
Ask for signup dates, departure dates where observed, observation end dates, and customer features available at prediction time. Some customers have left; others are still subscribed. Timing can help plan outreach, but predicting departure does not tell us whether an offer will prevent it.
Meet the customer data
Telco Customer Churn : one row per customer. These are six actual records.
7590-VHVEG
1
No
5575-GNVDE
34
No
3668-QPYBK
2
Yes
7795-CFOCW
45
No
9237-HQITU
2
Yes
9305-CDSKC
8
Yes
Other columns include Contract, MonthlyCharges, and InternetService.
Teaching assumption: interpret tenure as months from signup to departure or the end of observation, and Churn as whether departure was observed.
These are the first six CSV records, shown only to introduce the outcome columns; the demo reserves a test set before analysis. This dataset is a snapshot rather than a documented longitudinal cohort. Before operational use, verify sampling, follow-up, and feature availability at prediction time. Current contract and billing information need not be their values at signup.
Could we use classification?
Suppose we train a classifier with Churn as the target.
What question would it learn to answer?
Does that answer how long a new customer will stay ?
Does Churn = No mean the customer will never leave?
Invite answers before moving on. A snapshot classifier distinguishes recorded departures from customers recorded as active; this is different from predicting eventual subscription length. Follow-up lengths differ. No means departure was not observed, not that future departure is impossible.
Will this customer churn within six months?
Classification can answer this question, but do our records tell us the answer for every customer?
Customer left at month 4
Yes
Customer was still subscribed at month 8
No
Customer was still subscribed when observation ended at month 2
We don’t know
For the last customer, we don’t know what happened between months 2 and 6. We cannot label them “No.”
Walk through the three records and ask students to justify each label. Churn at month 4 is positive for the six-month question; active through month 8 is negative because the customer passed the horizon without churn. Observation ending at month 2 leaves the six-month outcome unknown. Classification remains useful with an appropriate horizon and follow-up design. Simply dropping unknown labels can also select a different population, so it is not an automatic repair. Transition: could regression let us keep the durations instead?
Could we predict tenure with regression?
7590-VHVEG
1
No
5575-GNVDE
34
No
3668-QPYBK
2
Yes
7795-CFOCW
45
No
9237-HQITU
2
Yes
9305-CDSKC
8
Yes
Could we use tenure as the target for a regressor?
For the customer with tenure = 34 and Churn = No, do we know their final subscription length ?
Pause before explaining. For an observed departure, tenure is a completed duration. For an active customer, it is only follow-up so far. Ordinary regression expects exact targets; some of these records provide bounds instead. Changing the regressor does not fix this difference.
Right-censoring
Right censoring: observation ends before churn is observed.
Customer B is still subscribed at month 4:
We know their time to churn is greater than 4 months .
Their eventual churn time is unknown .
Give the name only after students have seen the contrast in the table and plot. Right means the unknown event time lies beyond the observed duration on the time axis. For B, we know T > 4; we do not substitute a guess for the eventual departure time. Censoring describes the information available when observation ends, not a claim that churn can never occur. Transition: this is a general data structure, not a telecom-specific problem.
Time-to-event problems
The same structure appears in many settings:
Time until a customer leaves a subscription service
Time until death in a patient study
Time until equipment fails
Duration of unemployment until finding a job
Waiting time until surgery
We care about how long until a defined event occurs , but observation may end before we see it.
Connect each example to right censoring: a customer is still subscribed, a patient is alive, equipment is still working, someone is still looking for work, or a patient is still waiting when follow-up ends. We model a defined event within an observation period; avoid saying events must happen exactly once in general. Some settings also have competing events, such as leaving a surgery waiting list for another reason, which require additional care beyond this introduction.
Approach 1: Use only customers who churned
Keep rows with Churn = Yes and fit a regressor to their completed subscription lengths.
churned = train.loc[train["Churn" ].eq("Yes" )]
# Fit a regressor using churned customers only?
Now every retained row has an observed event time. What did we lose?
Present this as a plausible suggestion: after filtering, every retained tenure is a completed duration, so ordinary regression appears possible. The code is illustrative; train will be created in the demo. Pause at the question and move to the discussion slide before explaining the selection problem. The important choice is which records we keep, not the syntax of the filter.
Your turn: discard active customers?
Customer B is still subscribed when observation ends at month 4.
If we remove their row:
What useful information have we discarded?
If we estimate average time to churn using only customers who have already left, would you expect it to be too short or too long ? Why?
First discuss the lost information: we discard evidence that B stayed at least 4 months. Then ask students to predict the direction of the error. Expected answer: typically too short under independent censoring, because longer subscriptions are more likely to remain incomplete and be excluded. Keeping only observed departures selects events that occurred during follow-up. Under independent censoring, this tends to favor shorter lifetimes, so events-only estimates tend to be too short. Do not present the direction as universal under every possible observation process. The central issue is losing partial information and changing which customers are represented.
Approach 2: Treat every tenure as final
Keep all rows and use recorded tenure as the regression target, regardless of Churn.
A
Left at month 4
4
B
Still subscribed at month 4
4
We have a number for everyone. Does it mean the same thing?
Now try the opposite shortcut: retain everyone, but ignore event status. Compare A and B, whose numerical targets are both 4. Ask whether the regression loss can distinguish their different information; it cannot when both are supplied as exact targets. Move to the next question before giving the answer. Keeping rows is not enough if we change the meaning of their outcomes.
Your turn: did B leave at month 4?
For customer B, setting the target to 4 claims that:
They left at month 4.
They stayed at least 4 months; their departure time is unknown.
They will never leave.
Which claim does an ordinary regression target encode? Which claim does the record support?
The exact numerical regression target encodes A, but the record supports B. We invent a departure at the observation end. Across records, the model learns observed follow-up rather than completed lifetimes. Do not claim that any particular regressor must underpredict every customer’s lifetime; the target is misrepresented regardless of the algorithm.
Why the shortcuts fail
Events only: discards censored customers’ evidence and selects customers whose departures were observed.
Follow-up as lifetime: invents departures when observation ends.
Changing regressors or tuning hyperparameters does not repair the targets.
Customer B tells us \(T>4\) , not \(T=4\) . Discarding B loses that information.
Here, \(T\) is months from signup to churn.
Summarize the two student discussions: removing B loses evidence, while assigning an exact target invents evidence. Define T as the underlying time from signup to churn and read T > 4 aloud as “more than four months.” Ask for a quick verbal check: what must our new method preserve? Both completed durations and the bounds supplied by incomplete records. This motivates survival analysis without needing a more elaborate regression model.
Approach 3: Survival analysis
Survival analysis models time to an event while accounting for censoring.
Use completed durations when departures are observed.
Use lower bounds when observation ends before a departure is observed.
Estimate probabilities of remaining subscribed across time.
In the demo:
Kaplan–Meier: estimate overall and group retention curves.
Cox regression: relate several customer features to time to churn.
These methods use censored records without treating observation ending as a departure. They still require assumptions about the observation process; survival analysis does not automatically correct informative censoring or unsuitable predictors. Discuss the censoring assumption when reading the demo’s overall curve.
Preserve the two-part outcome
A
4
1
Churn at month 4
B
4
0
Stayed beyond month 4
C
12
0
Stayed beyond month 12
event = 1: churn observed (Churn = Yes).
event = 0: churn not observed (Churn = No).
Duration and event status form the outcome , not the predictors.
The demo creates the numeric event column expected by lifelines. Zero means event not observed, not zero future churn risk. Both parts of the outcome matter: B contributes evidence of survival through month 4 even though their eventual churn time is unknown.
What should we predict instead?
Let \(T\) be months from signup to churn . The survival function is:
\[S(t)=P(T>t)\]
If \(S(12)=0.8\) :
80% stay beyond 12 months from signup .
20% churn within 12 months of signup .
This is different from staying another 12 months for a customer who is already subscribed.
T is time from signup to churn. Survival means remaining with the service. We will read estimated survival curves in the demo rather than predicting a completed lifetime for every customer. No Kaplan–Meier calculation is required before the handoff.
Lecture demo
Open the lecture 20 demo
Inspect and clean: can a clean column still be an unsuitable predictor?
Overall retention: estimate and read a Kaplan–Meier curve.
Contract groups: compare curves and discuss what differences mean.
Several features: fit a Cox model and interpret coefficient signs.
If time permits: compare predicted survival curves for different contract profiles.
Open with: “How does customer B contribute despite having no observed churn time?” Revisit this question when fitting Kaplan–Meier: B contributes while still observed, and observation ending is not counted as churn.
Switch to the local lecture-20-survival-analysis-demo.ipynb notebook. Sections 1–4 are the core walkthrough; section 5 is predicted curves if time permits. Remaining sections cover optional group comparisons, remaining survival, and evaluation. Let students predict and discuss before revealing explanations. Explain the independent-censoring assumption while reading the overall curve: observation ending should not signal systematically different future churn prospects among comparable customers.
After the demo: what would you tell the team?
The contract-group curves differ, and the Cox model associates some features with faster churn.
What does a survival curve’s value at 12 months mean?
Do the group curves show that changing a contract would prevent churn?
Is predicted churn risk enough to decide whom to contact?
Return here after the demo. The curve measures survival beyond 12 months from signup, not another 12 months from today. Group differences and model coefficients describe associations. An outreach decision also needs evidence of intervention effectiveness, costs, and customer value; high predicted risk is not the same as high treatment benefit.
What did we learn?
Censored records contain useful partial information .
Preserve duration and event status .
Familiar targets can discard information or invent event times.
Survival curves describe retention across durations.
Group comparisons and model predictions do not establish intervention effects.
Define the event, time origin, and prediction time first.
Return to customer B as a final check: ask students for the two recorded outcome values and what they mean. Expected answer: tenure 4 and event 0; departure was not observed and time to churn exceeds four months. Connect the recap to the lecture: first identify the task and available evidence, then choose a method. Reinforce that retention predictions describe risk, while deciding which action works requires additional evidence. Close by distinguishing time from signup from time remaining for an existing customer.
Further reading
Point students to the chapter for the full explanation and the demo for executable examples. The lifelines pages are implementation references rather than additional material to cover now. Remaining survival and censoring-aware evaluation are available in the optional notebook sections for students who want to continue. No need to walk through the links individually.