Course Overview & Software Setup
STAT3009 · Recommender Systems
Ben Dai
CUHK · Department of Statistics and Data Science
The semester moves from baselines to neural recommenders
COURSE MAP
FOUNDATIONS
Frame the problem
Interaction data Evaluation Mean baselines
LATENT STRUCTURE
Learn hidden preferences
Cross-validation SVD and matrix factorization MovieLens
NEURAL RS
Add expressive models
Neural networks Neural matrix factorization Side information
STATISTICS × MACHINE LEARNING × CODE
[Sources] - Course sequence is condensed from the top-level sections of the user-provided STAT3009_nb/STAT3009_nb_Fall2025.ipynb.
How this course works
02
Understand the expectations before we begin the technical work.
[Sources] - Section framing adapted from the teaching modes and assessment design in the user-provided slides/Lec-overview/S.tex.
You will learn, build, and compete
01
LEARN
Concepts in slides and notes
02
BUILD
Live Python in Colab and Jupyter
03
COMPETE
In-class practice and Kaggle
Course homepage ↗ · GitHub repository ↗
Bring foundations—not prior recommender-system experience
WHAT HELPS
You do not need to arrive as a recommender-systems expert.
Python-library tutorials are provided when we need them.
01 Statistics Linear and ridge regression; hypothesis testing
02 Programming Python, NumPy, Pandas, basic scikit-learn
03 Mathematics Linear algebra, calculus, probability
Assessment rewards implementation
15% Homework
40% Open-book in-class Kaggle Approximately mid-semester
45% Final in-class coding quiz Last class of the semester
[Sources] - Instructor-updated assessment weights and timing: homework 15%; open-book in-class Kaggle 40%, approximately mid-semester; final in-class coding quiz 45%, in the last class of the semester.
Use AI as a tutor—not a substitute for understanding
AI-ASSISTED · STUDENT-OWNED
USE IT TO Question · compare · debug
Ask for an explanation of an error, compare two approaches, or improve the clarity of your Markdown.
VERIFY IT Run · inspect · test
Execute every cell, read the output, check assumptions, and test the suggestion on the actual data.
OWN IT Explain · modify · reproduce
You remain responsible for every submitted result and should be able to adapt the code yourself.
Not evidence of learning: submitting generated work that you cannot reproduce, justify, or debug.
Follow each assessment’s stated tool and disclosure rules. During an assessment, use only the tools explicitly permitted.
[Sources] - This slide states the course’s working principle for responsible AI assistance. Assessment-specific instructions remain authoritative.
Building a knowledge landscape
Know where an idea fits, what it depends on, and what you need to learn next.
Foundation
Connection in this course
A question you can ask
Linear algebra Vectors and inner products
Matrix factorization Represents users and items with vectors
What does the predicted score represent?
Probability and statistics Sampling and uncertainty
Model evaluation Uses held-out data as evidence
Will this result extend to new ratings?
Coding Arrays, indexing, functions
Computational experiments Turns a model into data operations
Does the program implement the intended experiment?
A model needs a representation, an implementation, and evidence about its predictions.
Use this map to locate an AI suggestion and identify the knowledge you need to use it.
Teaching notes:
这张知识版图把数学和 coding 的基础概念与课程方法连接起来。学生要逐渐理解概念的位置、依赖关系和适用条件,也要识别自己理解中的空白。
例如 AI 建议 matrix factorization:线性代数帮助理解用户和电影的向量表示,coding 帮助实现索引和内积,统计帮助评价对未参与训练的评分的预测能力。
这些基础并非各自孤立。研究一个模型时,需要同时考虑它怎样表示数据、怎样计算,以及怎样获得评价证据。
遇到陌生术语时,可以先定位,再检查先修概念。知道“训练表现与新数据表现”有区别,才会意识到需要追问评价数据的来源。
AI 可以辅助解释概念和寻找学习材料。课堂中的推理、小例子和代码修改,让学生逐渐能够自己复述并使用这些关系。
不要求一开始精通所有节点。先建立结构,再逐步把关键连接学深。
[Sources] - The instructor’s teaching priority of building a knowledge landscape, connected to the linear algebra, evaluation, and programming topics in this course.
Mathematics and coding in the AI era
Mathematics and coding turn your knowledge landscape into something you can reason with and use.
Mathematics
Define the problem and judge the evidence.
Connect models to their assumptions and objectives.
Understand what an evaluation result supports.
Does a lower rating error imply a better recommendation list?
Coding
Understand and adapt the computation.
Trace how a modeling idea becomes an experiment.
Modify the workflow when data or requirements change.
Which observations went into fitting and evaluation?
Use these foundations to guide your questions and extend your understanding with AI.
Teaching notes: - 建议讲解约 2 分钟。先承认学生的问题:既然 AI 可以解释公式、写代码,为什么还要学基础? - 承接上一页:数学和 coding 帮助学生把知识版图中的连接建立起来。通过推导理解假设如何影响结论,通过小规模实验理解数据处理和模型行为。 - 学习目标是形成自己的理解和判断。数学让我们能把“推荐得好”说清楚:预测什么、采用哪些假设、什么结果算证据。Coding 让我们能追踪实际计算,并在数据格式或任务要求改变时调整程序。 - 即使一段 AI 给出的代码完全正确,我们仍需要理解它实现的目标是否适合当前问题。准确实现一个目标,与选择一个合适的目标,是不同的判断。 - 基础知识也让提问更具体。例如“为什么分组后的数组长度变了?”比“代码不对,帮我修”更容易定位问题。学生需要能够根据回答继续检查。 - 本课会练习读懂关键代码、预测小例子的结果,并亲手修改和验证。API 的细节可以查文档,也可以请 AI 解释。 - 本页的两个问题会在后面的评分预测、排序和 held-out evaluation 中再次出现。
[Sources] - Instructor teaching rationale connecting the course’s programming foundations, rating-prediction task, and evaluation examples. No claim about a particular AI system’s measured performance is intended.
The best way to learn code is to wrestle with it
Bring a laptop. Read code, run it, break it, fix it—and make it yours.
[Sources] - Advice and illustrations are from the user-provided slides/Lec-overview/S.tex and figs/ directory.
Software preparation
03
Use notebooks to keep executable code and readable reasoning together.
Three layers make a Colab notebook work
ONE COMPUTATIONAL WORKFLOW
LANGUAGE Python
The instructions and objects we write.
lives inside
DOCUMENT Jupyter Notebook
An .ipynb file containing code, text, and saved output.
runs through
SERVICE Google Colab
A hosted notebook interface and computational runtime.
Colab is based on Jupyter; Python is the primary language executed by its kernel.
[Sources] - Google describes Colab as a hosted Jupyter Notebook service and Jupyter as the open-source project on which Colab is based: https://research.google.com/colaboratory/faq.html. - Jupyter notebook documents contain executable inputs, outputs, and accompanying narrative text: https://jupyter-notebook.readthedocs.io/.
A notebook mixes Python and Markdown
JUPYTER NOTEBOOK
PYTHON Compute
Import packages, define objects, run models, and create output.
MARKDOWN Explain
Write headings, equations, links, interpretation, and task status.
Open the course notebook in Colab ↗
[Sources] - The Colab link uses the Google Drive notebook linked from the course homepage. The downloaded file was verified as a Jupyter notebook (nbformat 4). - Jupyter documentation describes code cells and Markdown cells as core notebook cell types: https://jupyter-notebook.readthedocs.io/. - Screenshot: user-provided figs/labpreview.png.
Use Colab on the web or in VS Code
SAME NOTEBOOK · SAME COLAB COMPUTE
COLAB WEB
Browser first
Open the course notebook below
Sign in with Google
Save a copy in your Drive
Run a cell with Shift + Enter
Open the course notebook ↗
COLAB FOR VS CODE
Editor first
Install the official Colab extension
Download the course notebook as .ipynb
Open it in VS Code
Choose Select Kernel → Colab
Select Auto Connect and sign in
Install the VS Code extension ↗
In Colab: File → Download → Download .ipynb gives you a local notebook file.
[Sources] - Colab Web workflow is adapted from cells 1–3 of the user-provided notebook and the official Colab site: https://colab.research.google.com/. - Official Colab for VS Code installation and connection steps: https://marketplace.visualstudio.com/items?itemName=google.colab. - Google announcement explaining that local notebooks can connect to Colab runtimes from VS Code: https://developers.googleblog.com/ja/meeting-developers-where-they-are-google-colab-is-coming-to-vs-code/. - The Colab extension user guide marks its connected terminal as experimental: https://github.com/googlecolab/colab-vscode/wiki/User-Guide.
Notebook, kernel, and Python environment
AN ANALOGY: MIXING A GLASS OF SUGAR WATER
Notebook
Instructions & experiment log
The .ipynb file stores code, explanations, and saved results.
Kernel
The person doing the experiment
Runs the code and holds variables in memory, like the current mixture.
Python environment
Workbench & available tools
Provides the Python interpreter and installed packages the kernel uses.
Restart the kernel
Start again with an empty cup. Variables disappear. Saved notebook contents remain.
%pip install pandas
Add a tool to the active workbench. The package goes into the kernel’s environment.
先讲一个调配糖水的小实验,再逐一对应三个技术概念。
Notebook 是配方和实验记录:写下“加水、加糖、搅拌”,也可以保存观察结果。把配方复制给别人,并不会把眼前这杯糖水或实验器材一起复制过去。
Kernel 是正在操作的实验员:收到某一步指令后,才实际执行。当前杯中糖水的状态,对应 kernel 内存中的变量。只是把配方上的糖量改了,杯里的糖水不会自己改变,这正好引出下一页的“编辑”和“执行”区别。
Python environment 是实验台和可用工具:对应 Python 解释器、已安装的包及其版本。实验员使用这套工具执行指令。不同实验台的工具可能不同,所以相同 notebook 在不同环境下可能报错或产生不同结果。
Restart kernel 像清空杯子,重新开始操作:变量需要通过运行代码重新建立。保存到 notebook 的代码、文字和输出仍然在;保存的输出只是实验记录,不能替代内存中的当前对象。普通的 kernel 重启通常保留环境中已安装的包。
%pip install pandas 像给当前实验台添置工具。它安装到当前 kernel 使用的环境,而不是把整个包塞进 .ipynb 文件。
Colab 的 runtime 包含托管的计算环境,范围比 kernel 进程更广。若 Colab 回收并新建虚拟机,自行安装的包也可能需要重装。保留 notebook 顶部的安装单元格。Local Jupyter / VS Code 则要选择指向所需 Python 环境的 kernel。
[Sources] - Original water-mixing analogy and editable SVG illustrations prepared for this slide. - Jupyter kernels are separate processes that run code and communicate with the notebook interface: https://docs.jupyter.org/en/latest/projects/kernels.html. - Python virtual environments contain a Python installation and its packages: https://docs.python.org/3/tutorial/venv.html. - IPython’s %pip runs pip within the current kernel: https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-pip. - Colab virtual machines and custom libraries are separate from the saved notebook and can be deleted after inactivity: https://research.google.com/colaboratory/faq.html.
A notebook remembers execution—not visual order
THE KERNEL HOLDS INVISIBLE STATE
01 · RUN CELL discount = 0.10
kernel memory → discount = 0.10
02 · EDIT, BUT DO NOT RUN discount = 0.20
screen → 0.20 · memory → 0.10
03 · RUN THE NEXT CELL 100 * (1 - discount)
output → 90.0 , not 80.0
ON SCREEN Saved cells
What the notebook currently displays.
IN MEMORY Executed state
What the kernel will actually use.
BEFORE SHARING OR SUBMITTING Restart session → Run all → Verify outputs
A fresh Colab runtime may also require the package-setup cells again.
[Sources] - Jupyter’s execution model uses a kernel process that holds the current computational state: https://docs.jupyter.org/en/latest/projects/kernels.html. - Colab notes that code runs in a private virtual machine and that the runtime state is temporary: https://research.google.com/colaboratory/faq.html. - The discount example is instructor-authored to demonstrate the difference between visible cell contents and executed kernel state.
Markdown turns plain text into structure
WHAT YOU TYPE
## Preparation
**Goal:** verify the software setup.
- [x] install the packages
- [ ] finish the practice
[ Python docs ](https://docs.python.org/)
Inline code: `print(version)`
Equation: $y = \beta_0 + \beta_1 x$
WHAT THE NOTEBOOK RENDERS
Preparation
Goal: verify the software setup.
Python docs
Inline code: print(version)
y = β₀ + β₁x
[Sources] - Markdown examples follow CommonMark block and inline conventions: https://spec.commonmark.org/. - Checklist and auditability examples are adapted from cell 4 of the user-provided notebook. Use the text cell to explain results and record unfinished work. - Markdown reference: https://www.markdownguide.org/cheat-sheet/.
Markdown also handles technical notation
### Prediction error
Use `predict(...)` to obtain predictions.
$$
\operatorname{RMSE}
= \sqrt{\frac{1}{n}\sum_{i=1}^{n}
(y_i-\hat y_i)^2}
$$
| symbol | meaning |
|---|---|
| y | observed rating |
| y_hat | predicted rating |
inline code wrap a short expression in backticks
display math wrap an equation in double dollar signs
pipe table use vertical bars to separate columns
blank lines separate blocks and prevent rendering surprises
[Sources] - Quarto Markdown supports inline code, equations, lists, and pipe tables: https://quarto.org/docs/authoring/markdown-basics.html. - The example is instructor-authored for this course.
Python refresher
04
Review the small set of patterns we will use from the first lab onward.
Packages extend what Python can do
% pip install - q numpy pandas seaborn rehline
import numpy as np
import pandas as pd
import seaborn as sns
import rehline
print ("NumPy:" , np.__version__)
print ("Pandas:" , pd.__version__)
%pip install installs into the current notebook environment
import loads a package in the current session
as np · as pd creates conventional short aliases
seaborn · rehline match the dependencies listed in the combined course notebook
[Sources] - Package installation and verification steps are adapted from cells 5–10 of the user-provided notebook.
Assignment connects a name to an object
course = "STAT3009"
week = 1
threshold = 3.5
ready = True
# inspect and compare
print (type (course))
print (week == 1 )
name = value assigns an object to a name
str · int · float · bool are common scalar types
== compares two values
# starts a comment
[Sources] - Examples are instructor-authored and follow the official Python tutorial: https://docs.python.org/3/tutorial/introduction.html.
Lists and dictionaries organize values
ratings = [4 , 5 , 3 , 4 ]
student = {"name" : "Ada" , "ready" : True }
print (ratings[0 ]) # first item
print (ratings[- 1 ]) # last item
print (ratings[1 :3 ]) # positions 1 and 2
print (student["name" ]) # look up a key
list ordered values indexed by position
dict key–value pairs indexed by key
[start:stop] includes start, excludes stop
-1 refers to the last item
[Sources] - List indexing, slicing, and dictionary key access follow the official Python tutorial: https://docs.python.org/3/tutorial/introduction.html and https://docs.python.org/3/tutorial/datastructures.html.
A for loop visits each value once
liked = []
for rating in ratings:
if rating >= 4 :
liked.append(rating)
for index, rating in enumerate (ratings):
print (index, rating)
for item in values iterates over a sequence
if condition runs a block only when true
.append(…) adds one item to a list
enumerate(…) provides both position and value
[Sources] - for, if, enumerate, and loop patterns follow the official Python tutorial: https://docs.python.org/3/tutorial/controlflow.html. - List methods follow the official Python data-structures tutorial: https://docs.python.org/3/tutorial/datastructures.html.
Indentation is part of Python syntax
for rating in ratings:
if rating >= 4 :
label = "liked"
else :
label = "other"
print (label)
print ("finished" )
: starts an indented block
4 spaces is the recommended indentation
same level means the same block
dedent leaves the current block
Do not mix tabs and spaces. Python uses indentation to decide which statements belong together.
[Sources] - Python uses indentation to group statements, and lines in one basic block must use the same indentation: https://docs.python.org/3/tutorial/introduction.html. - The official Python tutorial recommends four spaces and no tabs: https://docs.python.org/3/tutorial/controlflow.html. - Inconsistent mixing of tabs and spaces can raise TabError: https://docs.python.org/3/reference/lexical_analysis.html#indentation.
Functions package repeated logic
def select_liked(values, threshold= 4 ):
liked = []
for value in values:
if value >= threshold:
liked.append(value)
return liked
select_liked(ratings)
def name(…): defines a function
parameters receive inputs
local names exist inside the function
return sends one result back
[Sources] - Function, loop, and conditional syntax follows the official Python tutorial: https://docs.python.org/3/tutorial/controlflow.html. - The example is instructor-authored and prepares students for the array operations in cell 12 of the user-provided notebook.
NumPy arrays have shape and dtype
ratings = np.array([4 , 5 , 3 , 4 ], dtype= float )
print ("ndim:" , ratings.ndim)
print ("shape:" , ratings.shape)
print ("size:" , ratings.size)
print ("dtype:" , ratings.dtype)
matrix = np.arange(12 ).reshape(3 , 4 )
print ("matrix shape:" , matrix.shape)
ndarray stores homogeneous values efficiently
ndim counts the number of axes
shape · size describe dimensions and element count
dtype records the common value type
[Sources] - NumPy array attributes and reshaping follow the official beginner guide: https://numpy.org/doc/stable/user/absolute_beginners.html. - Examples are condensed from the in-class practice in cell 12 of the user-provided notebook.
Axis tells NumPy which direction to summarize
matrix = np.arange(12 ).reshape(3 , 4 )
print (matrix.mean()) # one overall mean
print (matrix.mean(axis= 0 )) # one mean per column
print (matrix.mean(axis= 1 )) # one mean per row
column_totals = matrix.sum (axis= 0 )
row_totals = matrix.sum (axis= 1 )
print (column_totals, row_totals)
axis omitted summarizes all elements
axis=0 collapses rows; keeps columns
axis=1 collapses columns; keeps rows
check shape predicts the size of the result
[Sources] - Array axes and aggregation patterns follow the official NumPy beginner guide: https://numpy.org/doc/stable/user/absolute_beginners.html. - The example is instructor-authored for this course.
Boolean masks filter NumPy arrays
ratings = np.array([4 , 5 , 3 , 4 , 2 ])
mask = ratings >= 4
liked = ratings[mask]
middle = ratings[
(ratings >= 3 ) & (ratings <= 4 )
]
share_liked = mask.mean()
print (mask, liked, middle, share_liked, sep= " \n " )
comparison creates an array of True and False
array[mask] keeps values where the mask is True
& · | combine array conditions element by element
mask.mean() computes the share of True values
[Sources] - Boolean indexing and combined conditions follow the official NumPy beginner guide: https://numpy.org/doc/stable/user/absolute_beginners.html. - The example is instructor-authored for this course.
Pandas adds labels to tabular objects
df = pd.DataFrame({
"student" : ["A" , "B" , "C" ],
"score" : [82 , 95 , 74 ],
})
selected = df[["student" , "score" ]]
high_scores = df.loc[df["score" ] >= 80 ]
df["centered" ] = (
df["score" ] - df["score" ].mean()
)
display(selected, high_scores, df)
DataFrame a labeled table
columns select named variables
.loc filters rows explicitly
assignment creates or updates a column
[Sources] - Pandas operations are condensed from cells 13–17 of the user-provided notebook; the tiny in-memory table is instructor-authored to avoid introducing a course dataset in this deck.
Pandas can sort and summarize groups
df["tutorial" ] = ["A" , "A" , "B" ]
ordered = df.sort_values(
"score" , ascending= False
)
summary = (
df.groupby("tutorial" )
.agg(n= ("score" , "size" ),
mean_score= ("score" , "mean" ))
.reset_index()
)
display(ordered, summary)
.sort_values(…) orders rows by one or more columns
.groupby(…) splits rows into meaningful groups
.agg(…) calculates several summaries at once
method chain reads as a sequence of transformations
[Sources] - Sorting and grouped summary patterns follow the official Pandas getting-started tutorials: https://pandas.pydata.org/docs/getting_started/intro_tutorials/06_calculate_statistics.html. - The example extends the instructor-authored table on the preceding slide.
Missing values require an explicit decision
scores = pd.DataFrame({
"student" : ["A" , "B" , "C" , "D" ],
"score" : [82 , None , 74 , 91 ],
})
print (scores.isna().sum ())
complete = scores.dropna(subset= ["score" ])
scores["score" ] = scores["score" ].fillna(
scores["score" ].median()
)
display(complete, scores)
.isna() locates missing entries
.dropna(…) removes rows under a stated rule
.fillna(…) replaces missing entries
document the choice because it changes the analysis
[Sources] - Missing-value detection, removal, and replacement follow the official Pandas user guide: https://pandas.pydata.org/docs/user_guide/missing_data.html. - The example is instructor-authored for this course.
Recommendation setup
05
Turn observed user–item interactions into predictions for unseen pairs.
[Sources] - Section framing is adapted from the recommendation-system overview and formal setup in the user-provided slides/Lec-baseline/note.tex. - The progression into the Netflix exercise follows cells 19–32 of the user-provided STAT3009_nb/STAT3009_nb_Fall2025.ipynb.
The recommendation feedback loop
A recommender learns from actions produced by earlier recommendations.
1
Observe behavior Clicks, purchases, and ratings reveal user preferences.
2
Record events The tracker stores interactions for later learning.
3
Learn preferences The model turns interaction history into scores.
4
Serve recommendations The system returns selected items to each user.
New actions become the next round of training data.
[Sources] - The diagram is the user-provided image old/Lec1/figs/overview.png, copied into this deck as figs/overview.png. - The original course slide attributes the diagram to “A Simple Way to Explain the Recommendation Engine in AI,” Voice Tech Podcast: https://medium.com/voice-tech-podcast/a-simple-way-to-explain-the-recommendation-engine-in-ai-d1a609f59d97. - The four labels summarize the numbered stages already shown in the supplied diagram.
Recommendation serving and learning
ONLINEEach request
Retrieve
Reduce the catalog to a candidate pool
→
Rank
Score the smaller pool with a richer model
→
Re-rank + display
Apply eligibility and diversity constraints
Outcomes become training data ↓ Updated models return to serving ↑
OFFLINEPeriodic updates
Prepare data
Log events and construct features
→
Train + validate
Fit models and compare their predictions
→
Deploy + monitor
Publish models and check service quality
Training and serving must use consistent feature definitions.
Teaching notes:
线上路径需要及时响应一次用户请求,离线路径按周期或事件触发更新模型。
Retrieval 先缩小候选集合,再对候选使用较复杂的评分模型。最终展示还要考虑是否可用、是否已经看过、以及多样性等条件。
本页合并介绍服务漏斗和训练/服务关系,帮助学生定位课程中的模型部分。工程细节将在需要时展开。
[Sources] - Retrieval, scoring, and re-ranking: https://developers.google.com/machine-learning/recommendation/dnn/scoring and https://developers.google.com/machine-learning/recommendation/dnn/re-ranking. - Offline training, deployment, monitoring, and training/serving consistency: https://docs.cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning.
This course focuses on rating prediction
Data
Sparse user–item ratings
Identify the observed feedback and the missing pairs.
Models
Baselines, factorization, neural models
Learn a function that predicts a rating for a user–item pair.
Evaluation
Prediction on held-out ratings
Compare models on validation data and report final test performance.
The predicted scores can then support candidate ranking in the wider system.
[Sources] - Course scope follows the baseline, matrix-factorization, and neural-recommender sequence of the course materials. - The wider serving context follows the preceding recommendation-system overview.
Real datasets use different names for the same roles
THREE DATASETS · ONE ABSTRACTION
Dataset
Fields in user / item / rating order
Actual record (u, i, r)
Netflix
user_id · movie_id · rating
(1960, 670, 4)
CiaoDVD
userID · itemID · rating
(FA8D7A, 79CBAD, 5.0)
Book-Crossing
User-ID · ISBN · Book-Rating
(276726, 0155061224, 5)
(u, i, rui ) is a modeling vocabulary: IDs identify who and what; feedback records the observed preference.
[Sources] - The Netflix record is reproduced from the train.head() output stored in the user-provided STAT3009_nb/STAT3009_nb_Fall2025.ipynb. - The CiaoDVD record is reproduced from dataset/proj2/2022Fall/train.csv; the original data format is documented in dataset/proj2/2022Fall/raw/readme.txt. - The Book-Crossing record is reproduced from dataset/proj2/2021Fall/Ratings.csv. - The mapping to user, item, and rating follows slides/Lec-baseline/note.tex, frames “Dataset: Netflix Prize” and “Formal Model: Recommender Systems”.
Load the table, then inspect the rows
import pandas as pd
base = (
"https://raw.githubusercontent.com/"
"statmlben/CUHK-STAT3009/main/"
"dataset/netflix/"
)
fields = ["movie_id" , "user_id" , "rating" ]
train = pd.read_csv(
base + "train.csv" , usecols= fields
)
test = pd.read_csv(
base + "test.csv" , usecols= fields
)
train.head()
train.head()
movie_id
user_id
rating
0
670
1960
4
1
152
1346
4
2
1741
785
4
3
3032
686
5
4
536
1894
4
One row records one observed user–movie rating.
[Sources] - The loading code is condensed from cell 22 of the user-provided STAT3009_nb/STAT3009_nb_Fall2025.ipynb. - The displayed rows reproduce the three modeling fields in the train.head() output stored in cell 23 of that notebook.
A few checks reveal the dataset structure
# rows and columns
print ("shape:" , train.shape)
# storage types
display(train.dtypes)
# users and movies across both splits
both = pd.concat([train, test])
ids = ["user_id" , "movie_id" ]
display(both[ids].nunique())
# response scale
display(train["rating" ].agg(["min" , "max" ]))
SHAPE 51,161 × 3
training observations × selected fields
CATEGORIES 2,000 users · 3,568 movies
unique IDs across train and test
RATING RANGE 1–5
integer-valued explicit feedback
MODEL TABLE 2 IDs · 1 target
the columns needed for rating prediction
[Sources] - The inspection questions and the reported 51,161 training rows, 2,000 users, and 3,568 movies come from cells 27–29 of the user-provided notebook. - The Netflix rating scale is documented in slides/Lec-baseline/note.tex, frame “Dataset: Netflix Prize”.
Netflix data separates IDs from ratings
STORAGE TYPE ≠ MODELING ROLE
Field
Example
Pandas
Meaning
user_id
1960
int64
categorical user identifier
movie_id
670
int64
categorical item identifier
rating
4
int64
ordered score and prediction target
NETFLIX Explicit feedback
A 1–5 star rating directly states a preference.
CONTRAST Implicit feedback
A click, view, or purchase only suggests a preference.
An integer ID is a label—not a quantity. User 1960 is not “larger” than user 20.
[Sources] - Column names and sample values come from cells 21–23 of the user-provided STAT3009_nb/STAT3009_nb_Fall2025.ipynb. - The 1–5 rating scale and Netflix field definitions are also described in slides/Lec-baseline/note.tex, frame “Dataset: Netflix Prize”.
Most user–movie pairs are unobserved
Movie 0
Movie 1
Movie 2
Movie 3
User 0
4
?
5
?
User 1
?
2
?
4
User 2
5
?
4
?
User 3
?
3
?
5
OBSERVED (u, i) ∈ Ω
We know r ui . Split observed ratings before model selection.
UNKNOWN (u, i) ∉ Ω
We estimate the missing preference as r̂ ui .
Missing ≠ zero. A blank cell means “not observed,” not “disliked.”
[Sources] - The sparse rating-matrix representation and prediction question are adapted from slides/Lec-baseline/note.tex, frames “Data: Recommender Systems” and “Formal Model: Recommender Systems”. - The small matrix is instructor-authored to illustrate the notation; it does not reproduce actual Netflix users or ratings.
New pairs and new IDs are different problems
Test case
What training provides
In this Netflix split
Known IDs, new pair
History for both IDs, but no rating for this pair
Use the learned user and movie information
New user
No training history for this user
74 test users are absent from training
New movie
No training ratings for this movie
584 test movies are absent from training
For an unseen ID, define a fallback such as the training-set mean. Later models can use side information.
Teaching notes:
“未观察到这对用户和电影的评分”与“完全没见过这个用户或电影”是不同的预测情况,后两种属于 cold start。
不要求学生现在实现复杂的冷启动模型。先明确每个方法遇到陌生 ID 时怎么处理,避免报错或使用未经训练的个人参数。
全局训练均值可作为简单的后备预测。不能用验证或测试评分去计算这个均值。
随机切分 train.csv 得到验证集时,也应检查是否产生未见过的 ID。
[Sources] - Computed from local dataset/netflix/train.csv and test.csv: 1,926 training users and 2,984 training movies; 74 test-only users and 584 test-only movies. There are 1,002 test rows with at least one unseen ID, and no user–movie pair overlaps between the supplied train and test files.
Three minutes: make the data contract explicit
first = train.iloc[0 ][
["user_id" , "movie_id" , "rating" ]
]
features = ["user_id" , "movie_id" ]
X = train[features].to_numpy()
y = train["rating" ].to_numpy()
display(first)
print ("X:" , X.shape, "y:" , y.shape)
01
Write the first observation as (u, i, rui ) .
02
Report the shapes of X and y .
03
Explain why an integer ID is a label , not a continuous measurement.
04
Complete the sentence: “A missing rating means ___, not zero.”
Run it · compare with a neighbor · explain one answer aloud
[Sources] - The code uses the Netflix table and feature–target split introduced in cells 22–25 of the user-provided STAT3009_nb/STAT3009_nb_Fall2025.ipynb.
Answer key: - First observation: (1960, 670, 4) when ordered as user, movie, rating. - X.shape == (51161, 2) and y.shape == (51161,). - User and movie IDs identify categories; arithmetic distances between their integer codes have no substantive meaning. - A missing rating means “not observed,” not zero.
Training, validation, and test ratings
Training
Ωtr
Fit model parameters.
Use the fitting portion of train.csv.
Validation
Ωval
Choose the method and its settings.
Reserve a portion of train.csv.
Test
Ωte
Report final predictive performance.
Keep test.csv untouched during model selection.
After choosing settings, refit on all of train.csv, then evaluate once on test.csv.
Teaching notes:
本课程文件中的 train.csv 是可用于模型开发的数据。比较模型时从中保留验证评分,或在其中做 cross-validation。
切分后的三个集合互不重叠。特征处理、均值、模型参数等都只能从当前训练部分学习,再应用到验证数据。
选择完模型与超参数后,可在完整 train.csv 上重新拟合。此时 Ω^tr 指最终重新拟合使用的全部训练评分。test.csv 仅用于最终评价。
反复根据测试误差改模型,会让测试集参与模型选择,因此不再提供独立的最终评价。
[Sources] - scikit-learn cross-validation guide: https://scikit-learn.org/stable/modules/cross_validation.html.
The task is to predict held-out ratings accurately
INPUT (u, i)
a candidate user–movie pair
→
MODEL fθ
fitted using training ratings Ωtr
→
PREDICTION r̂ui
an estimated preference score
EVALUATE ON HELD-OUT PAIRS
Compare predictions with known ratings in Ωte .
[Sources] - The map from user–item inputs to predicted ratings and the held-out RMSE objective are adapted from slides/Lec-baseline/note.tex, frame “Formal Model: Recommender Systems”. - The competition-style contract X_train, y_train, X_test → y_pred and the RMSE exercise are adapted from cells 24–32 of the user-provided notebook.
Training error and prediction on new ratings
This code measures training fit. What evidence would support prediction on new ratings?
# X_train: user and movie IDs
# y_train: observed ratings
model.fit(X_train, y_train)
pred = model.predict(X_train)
rmse = np.sqrt(
np.mean((y_train - pred) ** 2 )
)
print (rmse)
Read the code Fitting and evaluation use the same observations.
Interpret the number This is training RMSE, measuring fit to the training ratings.
Identify the missing evidence Training RMSE alone does not establish accuracy on new ratings.
Change the experiment Use validation ratings to choose settings. Keep test ratings for the final report.
Coding reveals which data was used. Mathematics explains what the result can support.
Teaching notes: - 建议讲解约 2 分钟。先问:如果这段代码顺利运行,而且打印出来的误差很小,我们能说模型会预测新评分了吗? - 回顾开头“练习题与新题”的例子。现在学生已经见过 X/y 和 RMSE,可以找出重复出现的 X_train 和 y_train,检查评价使用了哪些数据。 - 这段代码正确计算了训练 RMSE。问题在于:仅凭这个量,不能判断对未参与训练的评分的预测能力。 - 回到知识版图:这段代码位于“评价”部分,而且评价的是训练拟合。有了这一区分,学生才能主动追问:对新评分的证据在哪里? - 数学和统计基础帮助区分拟合已有数据与推广到新数据。Coding 基础帮助检查这个区分是否真的落实在程序里。 - 修正时先保留评价数据,所有模型拟合仅使用训练部分,再用 model.predict(X_test) 与 y_test 计算评价误差。调整模型时使用 validation set,最终 test set 留到最后评价。 - 同样的判断也适用于人写的代码。这里使用假设的 AI 回答,是为了讨论学生怎样评价建议,并非展示某个 AI 系统的实际错误。 - 这是用于讨论的代码片段,假定 np、model、X_train 和 y_train 已定义。本页用于阅读评价代码,具体模型将在后续课程中实现。
[Sources] - Instructor-authored hypothetical example connecting the feature/target arrays and held-out RMSE evaluation later in this deck.
Ranking unrated candidates by predicted score
RATING PREDICTION → CANDIDATE SCORES → RANKED LIST
01 · PREDICT For user 1960
r̂ui = fθ (u, i)
Score candidate movies that this user has not rated.
→
02 · SCORE CANDIDATES Illustrative predictions
Movie 13
4.2
Movie 14
4.8
Movie 3032
3.9
→
03 · SORT DESCENDING Recommendation ranking
1
Movie 14
4.8
2
Movie 13
4.2
3
Movie 3032
3.9
COURSE FOCUS Learn the scoring function
Estimate ratings accurately from sparse observations and evaluate with held-out RMSE.
SYSTEM USE Turn scores into an ordered list
Rank candidates by predicted preference, then apply later serving constraints.
Observed ratings → rating model → predicted scores → ranked list → user actions → new observations
[Sources] - The rating-prediction function and held-out RMSE objective are adapted from slides/Lec-baseline/note.tex, frame “Formal Model: Recommender Systems”. - The connection from model scores to ranking follows Google’s official recommendation scoring guide: https://developers.google.com/machine-learning/recommendation/dnn/scoring. - The return from user actions to new observations reconnects this scoring sequence to the feedback loop introduced at the start of the section. - Movies 13, 14, and 3032 occur in the training data but have no rating from user 1960 in either supplied split. Candidates were checked against local train.csv and test.csv. In a deployed system, filter using the history available at recommendation time. The displayed predicted ratings are instructor-authored illustrative values, not output from a fitted model.
Offline accuracy is a gate—not the final outcome
MODEL → SYSTEM → PRODUCT
01 · MODEL Held-out RMSE
Can predicted ratings generalize to unseen user–item pairs?
02 · SYSTEM Latency · reliability · coverage
Can the service respond quickly and consistently for real users?
03 · PRODUCT Satisfaction · engagement · retention
Does the full experience improve the intended user outcome?
OFFLINE VALIDATION → ONLINE EXPERIMENT → MONITOR AFTER LAUNCH
The objective shapes the behavior of the system. A better model metric does not automatically imply a better product.
[Sources] - Google’s scoring guide explains that the chosen scoring objective can materially change recommendation behavior and user experience: https://developers.google.com/machine-learning/recommendation/dnn/scoring. - Offline validation, online validation through canary or A/B testing, and production monitoring follow the Google Cloud MLOps guide: https://docs.cloud.google.com/architecture/mlops-continuous-delivery-and-automation-pipelines-in-machine-learning. - This opening lecture uses held-out RMSE because it matches the explicit-rating task introduced in the Netflix example; ranking metrics are deferred to a later lecture.
Ready for the first lab?
01 Bring a laptop 02 Open the notebook 03 Run the setup cell 04 Trace ratings → scores → ranked list → new feedback
bendai.org/CUHK-STAT3009 ↗
[Sources] - Closing actions synthesize cells 0–32 of the user-provided notebook and the original course-overview deck.