准大二学生从0开始学AI——机器学习Day9
---type: learning_notetitle: 前向传播与TensorFlow搭建神经网络date: 2026-07-30course: Andrew Ng — Course 2 高级学习算法phase: C2 Week 1videos: #47-#51---# 2026-07-30 学习笔记## 笔记区学的时候随手记### 核心观点- **前向传播的本质数据从输入层逐层向前传递每层做一个加权求和 激活函数。** 公式为 $a^{[l]} g(W^{[l]}a^{[l-1]} b^{[l]})$其中 $g$ 是激活函数- **TensorFlow 搭神经网络就是堆 Dense 层** Sequential([Dense(...), Dense(...), ...])。- **输入特征维度只写一次** input_shape(特征数,) 只在第一层写后续层的输入维度 TF 自动从上一层的 units 推断- **units 指定的是这一层的输出维度神经元数不是输入维度。**### 关键方法/流程**TensorFlow 搭网络三步法**python# 1. 定义层layer1 Dense(units25, activationsigmoid)layer2 Dense(units1, activationsigmoid)# 2. 组装模型model Sequential([layer1, layer2])**前向传播计算过程2 层网络示例**输入 x (10个特征)→ 第一层: a[1] g(W[1]x b[1]) 输出25个值25个神经元→ 第二层: a[2] g(W[2]a[1] b[2]) 输出1个值1个神经元→ 最终结果### 实战记录- Dense(25) 和 Dense(units25) 是等价的——units 是 Dense 第一个参数参数名可省略- Dense(25) → Dense(10) → Dense(1) 是 3 层网络输出 1 个神经元- TensorFlow tensor 和 NumPy array 的区别TF tensor 需要 input_shape 指定维度NumPy 的形状在数据传入时就确定了。TF tensor 可通过 .numpy() 转为 NumPy---## 线索区学完后合上材料自问自答**Q: Dense(units25, activationsigmoid) 里 units 和 activation 分别代表什么**A: units这一层有多少个神经元输出维度activation激活函数 $g$sigmoid 就是 $g(z)\frac{1}{1e^{-z}}$。**Q: 为什么第一层要写 input_shape**A: TensorFlow 构建计算图时需要提前知道输入维度。input_shape(10,) 表示原始输入有 10 个特征。input_shape 只在第一层写一次。**Q: TensorFlow tensor 和 NumPy array 有什么区别**A: TF tensor 需要 input_shape 显式指定输入维度构建计算图时用NumPy array 的形状在数据传入时就确定了。tensor 可以通过 .numpy() 转化为 numpy**Q: units 能不能省略**A: units 是 Dense 的第一个位置参数可以省略参数名直接写 Dense(25) 等价于 Dense(units25)。**Q: 下面 3 层网络的代码有没有问题**pythonmodel Sequential([Dense(25, activationsigmoid, input_shape(10,)),Dense(10, activationsigmoid),Dense(1, activationsigmoid)])A: 没有问题。3 层网络25 → 10 → 1 个神经元输出层 1 个神经元用于二分类。---## 总结今天学习了前向传播的计算过程加权求和 → 激活函数逐层传递和如何用 TensorFlow 的 Sequential Dense 搭建神经网络。核心在 units 是神经元数输出维度而不是输入维度input_shape 只在第一层写一次TF 自动推断后续层的输入维度。Optional LabNeurons and Layers通过代码验证了这些概念。