An ANN, or NN, consists of "artificial neurons" arranged in layers. DNNs are neural networks that contain "many" layers of neurons or perceptrons. A network is "deep" if it has ≥ 3 layers of neurons (i.e. ≥ 2 hidden layers + output layer).
(1) Weighted summation: z = Σᵢ₌₁ⁿ wᵢxᵢ + b = Σᵢ₌₀ⁿ wᵢxᵢ where wᵢ are weights, b is bias, z is product-sum-plus-bias (w₀ ≡ b, x₀ ≡ 1). (2) Activation: y = a = σ(z) where a is activation (output), σ is activation function.
核心概念每个神经元做两件事:① 加权和 z = Σwᵢxᵢ + b(把偏置看成 w₀,输入 x₀ ≡ 1,就能并进求和号);② 激活 y = a = σ(z)。
详细讲解
这一页是 Unit 2 p18 + Unit 3 p5 的复习,用 σ 统一表示激活函数(本讲 p17–p22 会逐个给出 σ 的具体形式)。
第 ① 步是线性运算(乘加),第 ② 步是非线性运算。没有第 ② 步,多层网络等价于一层(线性叠线性还是线性)——这是激活函数存在的根本原因,p16 会从"训练"角度再补一个理由。
记号:讲义用 a 表示 activation,与 Unit 5 反向传播里的 aⁱ(第 i 层输出)一致;z 叫 "product-sum-plus-bias",即加权求和加偏置。
A "neural network" often means to have multiple layers of neurons. (Figure: 3 input nodes → two hidden layers of 4 neurons each → 2 output neurons, with weights on connections and biases drawn at the bottom of each hidden layer.)
There is 1 input layer, which contains input nodes for forwarding data. Input nodes are placeholders, not neurons. There are 0 or more hidden layers, which contain neurons. The hidden layers are invisible to the outside. A "deep" network has 2 or more hidden layers. There is 1 output layer, which contain neurons.
易错点 · 理解提示考题若问 "how many layers",默认把输入层数进去(Q5a = 4);若问 "how many Dense layers / neuron layers",不含输入层(Q5e = 3)。读题时看清楚问的是哪一种。
p8Dense networks and feed-forward networks:两个容易混的集合定义
A dense neural network (DNN), or dense network, contains only dense layers. A dense layer, or fully-connected layer, is a hidden/output layer in which each neuron is connected to every neuron/node in the preceding layer. A feed-forward neural network (FFNN) is a network whose connections do not form a circle. Data are fed forward through the network in a path without a loop. FFNNs include all DNNs and others, e.g. CNNs. NNs include all FFNNs and others, e.g. RNNs.
核心概念Dense 层(全连接层):每个神经元连到前一层每一个节点;Dense 网络:只含 Dense 层;FFNN:连接不成环、数据单向往前;包含关系 NN ⊃ FFNN ⊃ Dense ⊃ …,CNN 是 FFNN 但不是 Dense,RNN 是 NN 但不是 FFNN。
p9Trainable parameters in dense networks:参数个数公式🧮 必考计算★ 试卷 Q5d
Trainable parameters in a neural network are weights (including biases) to be optimized during training. Number of trainable parameters in a dense layer is n × (m + 1), where n is number of neurons in the dense layer, m is number of nodes in the preceding layer.
必要扩展Course Review p6 特意注明:"When weights and biases are mentioned separately, the term weights refers only to weight values, excluding biases." 即题目若分开问,weights = n×m,biases = n。
Pass training labelled examples to the network for it to learn optimal parameters, i.e. optimal weights and biases. (Figure: Training data → Neural network → Loss/cost function ← Actual target y; Loss → Optimizer → Update weights and biases → Neural network.)
p11Key components in neural network design:设计网络要做的五个选择框架★ 试卷 Q7
Network type and structure (both task specific and for better training) · Activation functions in hidden layers (mainly for better training) · Activation function in the output layer (often task specific) · Type of loss function (often task specific) · Type of optimizer (mainly for better training)
Also called cost function or objective function. A measure of how much the neural network's predictions differ from the actual target values. Mainly contain the prediction errors; may also contain hyperparameter factors for regularizing the network. An example is the mean squared error, or MSE = (1/n) Σᵢ₌₁ⁿ (yᵢ − yᵢ′)².
An optimization algorithm that analyses the loss and updates the weights and biases of the network. E.g. gradient descent iteratively updates parameters: Negative gradient → increase parameter; Positive gradient → decrease parameter. Gradient descent parameter update: p⁺ = p − η G(L,p), where p⁺/p are updated/current parameters, η (eta) is learning rate, G(L,p) is gradient, L is loss function.
易错点 · 理解提示讲义写 "Negative gradient → increase parameter",别背成"负梯度就加"——前提是公式里有减号。记忆方法:p⁺ = p − ηG,代入负 G 自然得加。
p14The learning rate:步子太大还是太小原图Lab 4 E1b
An important hyperparameter in network training. Control how much to change the parameter values. Task specific and often set by trial and error. Too small: parameter update and learning are too slow to be useful practically. Too large: parameter is updated in huge steps, with bouncing and non-converging values. (Figure: three bowls — small slow steps; moderate steps to the bottom; large steps bouncing between the walls.)
p16Importance of activation functions:为什么需要激活函数原理★ 试卷 Q4b
A neuron is characterized by its type of activation function (e.g. a neuron with the sigmoid activation function is called a "sigmoid neuron"). In output layer, the type of activation is determined by the task. In hidden layers, the type of activation is chosen to achieve efficient and effective training: to avoid/reduce the vanishing gradient problem, which happens when activation with small or zero gradient values causes parameter updates to stop. In backprop, error/loss gradients depend on activation gradients and are multiplied through the network layers during training.
Also called the Heaviside step function. Used in the original perceptron. Not used today, no gradient and not working with gradient descent. f(x) = 1 if x > 0; 0 otherwise.
Also called logistic function or logit function. Suffer from the vanishing gradient problem: when input is big, gradients are small and weights are not updated. Useful in output layer for binary classification (as probability values). "sigmoid" or tensorflow.keras.activations.sigmoid. f(x) = eˣ/(eˣ+1) = 1/(1+e⁻ˣ).
Do nothing but simply return the input – no-op! Do not restrict output values of a neuron. Useful in output layer for regression. "linear" or do not specify an activation function. f(x) = x.
The hyperbolic tangent function. Similar to sigmoid, but larger output range (−1 to 1). Work faster, but also have the vanishing gradient problem. "tanh" or tensorflow.keras.activations.tanh. f(x) = tanh(x) = (eˣ − e⁻ˣ)/(eˣ + e⁻ˣ).
Rectified Linear Units. Speed up learning: easy and fast to compute derivative. Widely used in neural networks, default choice for hidden layers. "relu" or tensorflow.keras.activations.relu. f(x) = max(0, x).
p22Leaky ReLU and parametric ReLU:修"dying ReLU"公式原图
The "dying ReLU" problem is similar to the vanishing gradient problem: when many outputs are 0, many gradients are 0 and weights are not updated. Two ReLU variants are Leaky ReLU (fixed a) and Parametric ReLU (trainable a), where a is the leak coefficient, 0 ≤ a ≤ 1. f(x) = max(ax, x).
易错点 · 理解提示讲义原文 "Leaky ReLU (fixed a) and Parametric ReLU (trainable a)"——两者的唯一区别是 a 是否可训练。公式 max(ax, x) 对两者相同。
p23Commonly-used activation, loss functions, and optimizers:任务配置总表★ 必背★ 试卷 Q1 / Q7
(Table) Task | Neurons in hidden layers | Neurons in output layer | Loss function | Optimizer — Regression: ReLU† | Linear (×1) | Mean squared error‡ | Adam, RMSProp, SGD — Binary classification: ReLU† | Sigmoid (×1) | Binary cross-entropy | Adam, RMSProp, SGD — Multiclass classification: ReLU† | Softmax (×n, n is number of classes) | Categorical cross-entropy | Adam, RMSProp, SGD. † In some cases, other activation functions like tanh and leaky ReLU are preferred. ‡ In some cases, other loss functions like mean absolute error are preferred.
必要扩展Unit 1 的线性回归 y = mx + b 是"没有隐藏层的回归网络";本讲的回归网络多了隐藏层,能拟合非线性关系。
易错点 · 理解提示回归任务的标签是连续值,所以输出层不加激活(linear)、损失用 MSE/MAE,而且不需要 one-hot——这三点和 Unit 5 的分类配方刚好相反,试卷 Q1/Q7 就是靠"看标签类型"来选配方的。
p25Regression: neurons in output layer:输出层用 linear配方
For regression, use a linear neuron in the output layer. Generally the predicted numerical label may have any value. The linear activation function allows for any output value. "linear" or do not specify an activation function. f(x) = x.
核心概念回归输出层:1 个 linear 神经元——因为预测的数值标签可以是任意值,linear 激活允许任意输出。
p26Regression: loss function:MSE 与 MAE公式Lab 4 Q1c/Q1d
Mean squared error (MSE) = (1/n) Σ (yᵢ − yᵢ′)² — taking squares removes signs of errors and emphasizes large errors; "mean_squared_error" or tensorflow.keras.losses.MeanSquaredError. Mean absolute error (MAE) = (1/n) Σ |yᵢ − yᵢ′| — less often used, for treating large and small errors similarly; "mean_absolute_error" or tensorflow.keras.losses.MeanAbsoluteError.
核心概念MSE:平方去符号、放大大误差(默认);MAE:绝对值去符号,大小误差一视同仁(较少用)。两者 Keras 名:"mean_squared_error" / "mean_absolute_error"。
易错点 · 理解提示Lab 4 Adam 实验的结论不是"Adam 比 SGD 差",而是"Adam 在默认学习率下比 SGD 差"——notebook 的 markdown 自己也提示了 "setting a suitable learning rate can actually make Adam work very well"(E1b 验证)。
TensorFlow (TF): one of the most popular deep learning frameworks, especially for production deployment. Keras: a high-level API on top of TensorFlow; bundled in TensorFlow 2 – package tensorflow.keras; originally support TensorFlow, Theano, and Microsoft Cognitive Toolkit (CNTK); Keras 3 supports JAX, TensorFlow, and PyTorch.
为什么课程用 Keras 而不是直接写 TF?因为教学重点是概念(结构、激活、损失),不是工程。Keras 一行一个 Dense 层,代码量最少。
题目 / Tut / Lab 关联Lab 4 每个 cell 开头都是 from tensorflow import keras 和 from tensorflow.keras import layers。
必要扩展其他框架:PyTorch(学术界主流)、JAX(Google 新秀)。概念完全相通,换框架只需改 API 名。
易错点 · 理解提示import keras(独立 Keras 3)与 from tensorflow import keras(TF 内置 Keras 2.x)在 2024 年后行为不同——课程代码以后者为准。
p30Regression example – loading data:加载 Boston 数据Lab 4 Cell 8原图
A neural network for regression on the Boston housing dataset. load_data() splits 80% of data to training set, and 20% to test set. Note: boston_housing may be obsoleted in the future; then, try california_housing.load_data(version="small"). Code: from tensorflow import keras; from tensorflow.keras import layers; from tensorflow.keras.datasets import boston_housing; keras.utils.set_random_seed(42); (X_train, y_train), (X_test, y_test) = boston_housing.load_data(). Output: Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/boston_housing.npz 57026/57026 ━━━ 0s 0us/step
Variables in order: CRIM per capita crime rate by town; ZN proportion of residential land zoned for lots over 25,000 sq.ft.; INDUS proportion of non-retail business acres per town; CHAS Charles River dummy variable (= 1 if tract bounds river; 0 otherwise); NOX nitric oxides concentration (parts per 10 million); RM average number of rooms per dwelling; AGE proportion of owner-occupied units built prior to 1940; DIS weighted distances to five Boston employment centres; RAD index of accessibility to radial highways; TAX full-value property-tax rate per $10,000; PTRATIO pupil-teacher ratio by town; B 1000(Bk − 0.63)² where Bk is the proportion of blacks by town; LSTAT % lower status of the population; MEDV Median value of owner-occupied homes in $1000's.
Note that when using the model in production, the same normalizing operation (and any other preprocessing) must be applied to the input features, i.e. perform X_prod = (X_prod − mean) / std. Code: # For demo; Keras Boston dataset has already been normalized. # Normalize input features. mean = X_train.mean(axis=0) # 13 mean values of features; std = X_train.std(axis=0) # 13 SD values of features; X_train = (X_train − mean) / std; X_test = (X_test − mean) / std.
必要扩展另一种缩放 min-max(缩放到 [0, 1]):适合图像像素(试卷 Q6:"features are scaled to the range of 0–1")。标准化更适合无界特征。两者都叫 "scaling"(p35)。
易错点 · 理解提示① 常见错误:X_test = (X_test - X_test.mean()) / X_test.std()——数据泄露;② std 是 Unit 3 p30 的总体标准差(ddof=0),NumPy 默认;③ 讲义注释 "Keras Boston dataset has already been normalized" 不准确——它只是缩放,所以仍需标准化。
p34Scaling data:换单位,"变异"就变了原图
These two plots show the same dataset in different units of height. Which feature – weight or height – is more important or has larger variation in the data points? (Two scatter plots of the same 3 people: top with height in cm (points around 100–150), bottom with height in mm (points around 1000–1200); weight (lb) axis unchanged 0–200.)
核心概念同一批数据,身高用 cm 还是 mm,散点图看起来"变异大小"完全不同——数值范围是单位造成的,不是数据本质。
Features of very different ranges may have adverse effects on some algorithms, e.g. features of larger ranges dominate distance calculations, as in gradient descent, but the large ranges may be "unreal". The safe way not to "confuse" the algorithms is to scale the features to similar and preferably small ranges. Normalizing a feature means to scale feature values to mean 0 and standard deviation 1. Normalize(value) = (value − mean) / stdev.
易错点 · 理解提示本页公式里的 mean / stdev 必须是训练集的(p33 的 axis=0 代码),并且要保存下来给测试集和生产用。
p36Regression example – creating model:三层网络Lab 4 Cell 17原图
Create a Keras model for the neural network. A Sequential model contains a linear sequence of layers of a FFNN. 3 layers of neurons (input layer not specified). (Table: Hidden Dense layer | 16 sigmoid neurons | 13 input features; Hidden Dense layer | 16 sigmoid neurons | 16 neurons in previous layer; Output Dense layer | 1 linear neuron (no activation) | 16 neurons in previous layer.) Code: model = keras.Sequential([layers.Dense(16, activation="sigmoid"), layers.Dense(16, activation="sigmoid"), layers.Dense(1, activation="linear")])
p37Regression example – configuring and training model:compile + fitLab 4 Cell 17
compile() sets up the model to use MSE and SGD. fit() trains the model, specifying training and validation data: epochs=20 for 20 iterations of training; verbose=2 for displaying the results. Code: model.compile(loss="mean_squared_error", optimizer="sgd"); history = model.fit(X_train, y_train, epochs=20, verbose=2, validation_data=(X_test, y_test)).
必要扩展严格说本页用测试集当验证集是不规范的做法(测试集应留到最后)。讲义 p41 的注释也承认 "For simple demo... For more vigorous evaluation, split the whole dataset into 3 sets: training / validation / test"。课程为简化只分两份。
易错点 · 理解提示validation_data 不等于训练数据——它不会更新权重。若看到 val_loss 一直下降而 loss 不动,检查是不是把两者写反了。
p38Regression example – training output:训练输出怎么读Lab 4 Cell 17
必要扩展若 fit 时传了 validation_split=0.2(而不是 validation_data),Keras 会从训练集末尾切 20% 做验证,键名相同。
易错点 · 理解提示history 是 fit() 的返回值,不是 model 的属性——必须写 history = model.fit(...) 接住,否则训练完就拿不到曲线数据。
p40Regression example – training history plot:画曲线原图Lab 4 Cell 21
Validation loss may be lower than training loss in early iterations: some Keras layers work differently during training and validation. Code: import matplotlib.pyplot as plt; plt.plot(history.history["loss"], label="loss"); plt.plot(history.history["val_loss"], label="val_loss"); plt.legend(). (Figure: two curves from epoch 0 to 19, loss starts ~245 and drops steeply to ~16, val_loss starts ~81 and drops smoothly to ~24; they cross around epoch 11; val_loss ends slightly above loss.)
核心概念把 history 的两个列表画成折线图。反常现象:早期 val_loss 低于 loss——因为某些 Keras 层在训练和验证时行为不同(如 Dropout、BatchNorm),且训练 loss 是整轮平均、验证 loss 是轮末计算。
Cell 30 Adam 实验:loss 从 608.8 缓慢降到 ~470,val 469.9。Cell 33 的提示"设置合适学习率可以让 Adam 表现很好"→ E1b 验证。
Q1a(Cell 35–37)tanh 神经元
代码正确:两处 "sigmoid" → "tanh"。输出:第 1 轮 loss 239.3 / val 50.7(比 sigmoid 第 1 轮 val 81.5 低很多——tanh 零中心化 + 导数最大 1 的优势),第 8 轮 val 20.0,最终 ≈16.5。
Q1b(Cell 38–39)你的作答 ✔
"1. The validation loss in the final training epoch is approximately 16.5, which is lower than the baseline model's ~23.9. This indicates that tanh neurons perform better than sigmoid neurons for this regression task. 2. The curve of validation loss is smoother and more stable than the ReLU case. It decreases steadily throughout training without the large fluctuations seen with ReLU. Compared to the baseline (sigmoid), tanh converges faster and to a lower loss value."
代码正确:loss="mean_absolute_error"。输出:第 1 轮 loss 22.70 / val 23.00,缓慢稳定下降(每轮约 0.7),最终 val 8.18。
Q1d(Cell 43–44)你的作答 —— ⚠️ 有一个量纲问题
"1. The loss value of the final round of verification is 8.1797, which is much lower than the 23.9 of the baseline. This indicates that using the MAE loss is much more effective than the original MSE. 2. The verification loss curve is steadily descending throughout the entire process…"
问题:8.18 是 MAE(单位:千美元),23.9 是 MSE(单位:千美元²),两者量纲不同,数值大小没有可比性。正确比较方法:把 baseline 的 MSE 开方 → RMSE = √23.9 ≈ 4.89 千美元,这才是与 MAE 同量纲的"典型误差"。对比 4.89 vs 8.18 → MAE 模型的平均绝对误差其实更大(更差),而不是"much more effective"。
建议改写(第 1 问):"The final validation loss is 8.18 (MAE, in $1000s). This cannot be compared directly with the baseline's 23.9, which is an MSE in ($1000s)². Converting the baseline to RMSE gives √23.9 ≈ 4.9, so the MAE model is actually less accurate after 20 epochs — MAE's constant gradient (±1) makes SGD converge more slowly. The curve is smoother and monotonically decreasing, consistent with MAE not amplifying large errors."
第 2 问"稳步下降、无波动"✔ 正确——这正是 MAE 的特性(绝对值不放大离群点误差,梯度平稳)。
E1a RMSProp:val 463.3,曲线与 Adam 几乎一样(都是默认 η = 0.001 → 太小)。结论"RMSProp performs very poorly"——准确说是"在默认 η 下"。
E1b Adam η = 0.1:adam_opt = keras.optimizers.Adam(learning_rate=0.1) → val 21.2,曲线形状与 baseline 相似。结论"合适 η 下 Adam 优于 SGD"✔——这是本 Lab 最重要的教训:优化器好坏是相对于学习率而言的。
Dense neural network structure (regression and classification tasks) — Determine Input, hidden, and output layers
p4、p6–p8
Q5a–c、Q5e
How to calculate the number of trainable parameters in a Dense layer. Note: When weights and biases are mentioned separately, the term weights refers only to weight values, excluding biases.
p9:n × (m + 1);p42 逐层验证
Q5d;Lab summary 224/272/17
Activation function in hidden and output layers (e.g., linear, sigmoid, tanh, ReLU, softmax)
p16–p23(6 种);p23 表
Q1、Q4、Q5f–g、Q7b–c
Loss function (e.g., mean_squared_error, binary_crossentropy, categorical_crossentropy)
p12、p26;p23 表
Q7b–c;Lab Q1c
Optimizer (adam, rmsprop, sgd)
p13、p27
Lab Adam/RMSProp/E1b
Input shape, output shape of a Dense layer
p31 (404, 13);p42 (None, 16)
Q7a (20000, 8)
Code examples
p30–p42 全部代码
Lab 4 全部
Calculation of updated weights (optional) Units 4 & 5