TensorFlow 教程
用张量、一次自动求导和参数更新理解 TensorFlow 在本课程中的作用。
学完这一章,你能够
- 用张量、一次自动求导和参数更新理解 TensorFlow 在本课程中的作用。
从张量到机器学习模型
TensorFlow 是 Google 发起的开源计算与机器学习框架。张量统一表示输入、参数和中间结果,运算既可立即执行,也可追踪为图。课程先做线性回归的小练习,再看神经网络、模型评估和保存。先运行本地 CPU 实例,确认可复算的结果。
学习前需要掌握什么
线性代数用来读张量和矩阵形状。概率与统计帮助理解数据分布、贝叶斯更新、损失与评估指标。微积分解释损失对参数的导数和梯度更新。此处用相同输入核对均方误差和两个参数的梯度。
Python 是本课程主要接口。阅读代码要用到变量、函数、列表、字典、对象、循环和简单递归。可先练习写固定输入、可比较输出的小函数。
学习监督任务时可比较分类和回归,学习无监督任务可从聚类入手。先认识线性模型和神经网络。分类准确率、回归误差与交叉验证适用条件不同,验证数据应和训练数据分开。
NumPy 与 Pandas 常用于整理数组和表格。Matplotlib 与 Seaborn 提供可视化。Scikit-learn 可建立传统模型基线。本站首章实验只需要 TensorFlow 及其安装依赖,后续再按任务选择工具。
按角色选择学习目标
研究者可重点看自定义模型和优化,数据科学家可做图像、文本、音频的数据与评估,软件工程师可练习将模型交给服务或设备运行,初学者可从张量和低维数据开始,硬件与算法工程师则可深入设备放置、算子和性能。
框架概览、学习路线和开源仓库分别用于查功能、跟随逐步教程和查看发布版本。以下实验的具体版本写在下载说明里。
跑一次线性模型的前向、反向和更新
展开查看收起
python
"""Run the TensorFlow CPU example with fixed inputs and one explicit training update."""
import json
import platform
import tensorflow as tf
def observe(cases, name, operation, inputs, expected, actual):
assert actual == expected, (name, expected, actual)
cases.append(dict(name=name, operation=operation, inputs=inputs, expected=expected, actual=actual, passed=True))
def finish(cases):
print(json.dumps(dict(version=platform.python_version(),tensorflow=tf.__version__,
keras=tf.keras.__version__,system=platform.system(),
devices=[d.name for d in tf.config.list_physical_devices()],
cases=cases), ensure_ascii=False))
def main():
cases=[]
with tf.device("/CPU:0"):
x=tf.constant([[-1.],[1.]])
target=tf.constant([[-1.],[3.]])
w=tf.Variable([[0.]])
b=tf.Variable([0.])
use=lambda data: data@w+b
observe(cases,"tensor_shape_and_device","construct a CPU tensor and inspect its metadata",
[[-1.],[1.]], [[2,1],"float32",True],[list(x.shape),x.dtype.name,x.device.endswith("CPU:0")])
observe(cases,"eager_tensor_result","multiply a fixed input and read the numeric result",
{"x":[-1,1],"slope":2},[[1.],[5.]],(2*x+3).numpy().tolist())
with tf.GradientTape() as tape:
start=tf.reduce_mean(tf.square(use(x)-target))
changes=tape.gradient(start,[w,b])
observe(cases,"two_parameter_gradients","differentiate the mean square error",
{"target":[-1,3]},[5.,[[-4.]],[ -2.]],
[float(start.numpy()),changes[0].numpy().tolist(),changes[1].numpy().tolist()])
tf.keras.optimizers.SGD(.25).apply_gradients(zip(changes,[w,b]))
after=tf.reduce_mean(tf.square(use(x)-target))
observe(cases,"one_real_update","apply one SGD step and recompute the objective",
{"learning_rate":.25},[[[1.]],[.5],1.25],[w.numpy().tolist(),b.numpy().tolist(),float(after.numpy())])
data=tf.data.Dataset.from_tensor_slices((x,target)).batch(2)
opts=tf.data.Options()
opts.threading.private_threadpool_size=1
batch_x,batch_y=next(iter(data.with_options(opts)))
observe(cases,"labeled_batch_shape","read a batch of features and the corresponding labels",
{"batch_size":2},[[[-1.],[1.]],[[-1.],[3.]]],[batch_x.numpy().tolist(),batch_y.numpy().tolist()])
layer=tf.keras.layers.Dense(1,kernel_initializer="ones",bias_initializer=tf.keras.initializers.Constant(.5))
observe(cases,"equivalent_keras_layer","run a matching affine layer on a second input batch",
[[2.],[4.]],[[2.5],[4.5]],layer(tf.constant([[2.],[4.]])).numpy().tolist())
finish(cases)
if __name__=="__main__":
main()
初始 MSE 为 5。更新后权重为 1、偏置为 0.5,MSE 降到 1.25。
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 运行本站程序。
本章附件与实例包
课程关联工程包(登记关联24章) · 含当前章节或实例 · mbskycom202612a359.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a375.zip
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
梯度指出每个参数局部改变如何影响损失。