📘 Tutorial 1(= Lab 1)· Python collections 与 NumPy basics(t01-s13903054.ipynb,92 cells)

Lab = Tutorial,每周交(15%)。本 notebook 不涉及 TensorFlow,全部是后续十周代码的"语法底座":list / tuple / range / 列表推导式 / NumPy 数组 / axis 的含义。每行代码按 notebook 原序逐行精讲;练习题(Q1a–c、Q2a–d、E1a–b)按你的作答逐行核对。
怎么用这份精讲:每个 Cell 先给原代码,再用六列表格逐行拆解——作用(这行做什么)· 机制·语法(为什么能这样做 / Python 或 NumPy 的规则)· 关联·结果(和上下文变量的关系、跑出来的值)· 易错点。标 重点展开 的 Cell 下方有"深挖"段落。本讲 5 个最重要的点:① 切片 [start:stop:step] 的 stop 永远不包含;② -1 索引与 [::-1] 反转;③ 列表推导式 = for + append 的语法糖;④ reshape() 返回新数组、-1 自动推断;⑤ axis=0 沿行向下(按列聚合)、axis=1 沿列向右(按行聚合)——这就是后面 axis=-1 softmax、Dense 作用在最后一维的根源。

In this lesson, you'll work on:


  • Python collections and comprehension, and
  • NumPy basics.
  • Student name: Yin Bang
    Student ID: 13903054

    Python collections


    In Python, some commonly-used collections types are lists, tuples, sets, and dictionaries.

    Lists and tuples


    A list is a sequence, or an ordered collection, of items. The len() function returns the number of items in a list.

    ↳ 本节 4 个 Cell 建立 "序列 → 索引 → 切片 → 可变" 四个概念。
    Cell 7创建 list:三种类型混装、type()、len()基础
    ls = [1, 2.0, "three"]
    print(ls)
    print(type(ls))
    print(len(ls))
    #代码作用机制·语法关联·结果易错点
    1ls = [1, 2.0, "three"]新建变量 ls,一个含 3 项的 list方括号 [ ] 构造 list;Python list 可混装 int / float / str——它只是"指向对象的指针数组",不要求元素同类型ls 后续被 C9/C11/C13 反复使用;输出 [1, 2.0, 'three']打印显示单引号,是 repr 形式,不是内容变了
    2print(ls)打印整个列表print 对 list 调用其 __repr__,所以显示方括号结果 [1, 2.0, 'three']想看元素不带括号要循环打印
    3print(type(ls))查看类型type() 返回对象的类型对象;Python 一切皆对象<class 'list'>type 只看"外壳",不看元素类型
    4print(len(ls))求长度(项数)len() 是内置函数,返回 list 的 item 数输出 3len 不等于"最大下标",最大下标 = len−1 = 2
    运行结果 [1, 2.0, 'three'] <class 'list'> 3

    An individual item in a list can be accessed by integer indexing, with syntax a_list[index]. Note the f-string syntax: f"{exp}" displays the value of exp; f"{exp=}" displays the expression exp, an equal symbol, and the value of exp -- very useful for debugging and exploring code!

    Cell 9索引:0-based、负索引、f-string 的 {exp=}重点展开
    print(ls)
    print(f"{ls[0]=}, {ls[1]=}")  # index is 0-based; index 0 -> first item
    print(f"{ls[2]=}, {ls[-1]=}")  # index -1 -> last item
    #代码作用机制·语法关联·结果易错点
    1print(ls)再次打印 ls与 C7 L2 相同[1, 2.0, 'three']—
    2print(f"{ls[0]=}, {ls[1]=}") # index is 0-based; index 0 -> first item取第 1、2 项索引从 0 开始:ls[0] 第一项;f"{x=}"(Python 3.8+)同时打印表达式文本、等号、值ls[0]=1, ls[1]=2.0ls[1] 是第 二 项,不是第一项
    3print(f"{ls[2]=}, {ls[-1]=}") # index -1 -> last item取第 3 项与最后一项负索引从尾部数:ls[-1] 最后一项、ls[-2] 倒数第二两者相同 → 'three'ls[-0] 不是最后一项!-0 == 0 是第一项
    运行结果 [1, 2.0, 'three'] ls[0]=1, ls[1]=2.0 ls[2]='three', ls[-1]='three'
    深挖 · f-string {exp=}:这是调试利器,等价于 f"ls[0]={ls[0]!r}"——自动把表达式原文写出来再写 repr 值。后面 Keras 代码不常用,但做手算验证(如 Unit 3 的矩阵乘法)时非常方便。注意 {x = }(带空格)输出会保留空格:ls[2:6] = [...](C11 就是这样),不是 bug。

    Multiple items in a list can be accessed by slicing, with syntax a_list[start:stop:step]. Note that the item at the stop index is excluded.

    Cell 11切片 [start:stop:step]:六种写法重点展开
    ls = [0, 1, 2, 3, 4, 5, 6]
    print(ls)
    print(f"{ls[2:6] = }")  # from index 2 (included) to index 6 (excluded)
    print(f"{ls[:6] = }")  # start index 0 by default here
    print(f"{ls[2:] = }")  # stop index len+1 (=7) by default here
    print(f"{ls[:] = }")  # all items, i.e. making a copy
    print(f"{ls[::2] = }")  # steps of 2, i.e. every other items
    print(f"{ls[::-1] = }") # all items in reversed order
    #代码作用机制·语法关联·结果易错点
    1ls = [0, 1, 2, 3, 4, 5, 6]重建 ls 为 0–6用连续整数初始化;覆盖 C7 的 ls之后所有切片基于这个新列表变量被整体重新赋值,旧 list 不受影响
    2print(ls)打印原列表—[0, 1, 2, 3, 4, 5, 6]—
    3print(f"{ls[2:6] = }") # from index 2 (included) to index 6 (excluded)ls[2:6]stop 不包含:取下标 2,3,4,5 → 4 个元素;元素个数 = stop−start = 4[2, 3, 4, 5]数长度时别把 stop 算进去
    4print(f"{ls[:6] = }") # start index 0 by default herels[:6]start 省略 → 默认 0[0,1,2,3,4,5]—
    5print(f"{ls[2:] = }") # stop index len+1 (=7) by default herels[2:]stop 省略 → 默认到末尾(len)[2,3,4,5,6]—
    6print(f"{ls[:] = }") # all items, i.e. making a copyls[:]两端都省 → 全部;产生一个新 list(浅拷贝)[0..6]ls[:] 与 ls.copy() 等价,但 ls2 = ls 只是起别名
    7print(f"{ls[::2] = }") # steps of 2, i.e. every other itemsls[::2]step=2:隔一个取一个,从 0 开始[0,2,4,6]step 为负时 start 默认变成末尾
    8print(f"{ls[::-1] = }") # all items in reversed orderls[::-1]step=−1:start/stop 自动取 len−1 与 "开头之前" → 反转[6,5,4,3,2,1,0]常见题:ls[::-1] 反转字符串同样适用
    运行结果 [0, 1, 2, 3, 4, 5, 6] ls[2:6] = [2, 3, 4, 5] ls[:6] = [0, 1, 2, 3, 4, 5] ls[2:] = [2, 3, 4, 5, 6] ls[:] = [0, 1, 2, 3, 4, 5, 6] ls[::2] = [0, 2, 4, 6] ls[::-1] = [6, 5, 4, 3, 2, 1, 0]
    深挖 · 切片长度公式:max(0, ceil((stop−start)/step))。例 ls[2:6] → ceil(4/1)=4;ls[6::2] → ceil(1/2)=1 个;ls[11::-3] → start=11, stop 省略(=−1 之前, 即"到头"), step=−3 → 11,8,5,2 共 4 个(Q1b 第三问就是这个)。stop 超界不报错(ls[2:100] 正常返回),但索引超界报 IndexError(ls[100] 错)——切片是"区间",索引是"点"。

    Lists are mutable, meaning that their contents may be changed during code execution.

    Cell 13list 可变:赋值改元素、append 追加基础
    ls = [1, 2, 3]
    print(ls)
    ls[0] = 10  # modify the 1st item, i.e. with index 0
    print(ls)
    ls.append(40)  # append item at the end
    print(ls)
    #代码作用机制·语法关联·结果易错点
    1ls = [1, 2, 3]新建 3 项 list—ls=[1,2,3]—
    2print(ls)打印—[1, 2, 3]—
    3ls[0] = 10 # modify the 1st item, i.e. with index 0把第 1 项改成 10可变(mutable):ls[0] = 10 是"原地替换第 0 格的内容",list 对象本身 id 不变之后 ls=[10,2,3]对 tuple 做同样操作会报 TypeError(C15)
    4print(ls)打印—[10, 2, 3]—
    5ls.append(40) # append item at the end末尾追加 40append 是 list 的方法,原地修改,返回 Nonels=[10,2,3,40]ls = ls.append(40) 会把 ls 变成 None!
    6print(ls)打印—[10, 2, 3, 40]—
    运行结果 [1, 2, 3] [10, 2, 3] [10, 2, 3, 40]

    A tuple is similar to a list, but immutable. That is, once created you cannot modify the contents of a tuple. A tuple has no append() method and so on.

    Cell 15tuple:不可变序列基础
    t = (1, 2.0, "three")
    print(t)
    print(type(t))
    # t.append(40)  # no such method!
    #代码作用机制·语法关联·结果易错点
    1t = (1, 2.0, "three")用圆括号创建 tupletuple 字面量用 ( );元素同样可混装;不可变(immutable)t=(1, 2.0, 'three')单元素 tuple 必须写 (42,) —— 见 E1a
    2print(t)打印print 用 tuple 的 repr → 圆括号(1, 2.0, 'three')—
    3print(type(t))查看类型——
    4# t.append(40) # no such method!注释掉的 appendtuple 没有 append 方法——这行若取消注释会 AttributeError;作者保留它作"反面教材"无输出tuple 不可变指的是"长度和每格的指向"不可改;若某格是 list,那个 list 内部仍可改
    运行结果 (1, 2.0, 'three') <class 'tuple'>

    Ranges


    A range generates a sequence of consecutive, or equally-spaced, integers. It is often used with the for loop. The syntax is range(start, stop, step), where start and step are optional. The meanings of the three parts are similar to those of list slicing syntax a_list[start:stop:step]. Again, note that the item of stop is excluded.

    Cell 17range(10):0 到 9,print 的 end 参数基础
    for i in range(10):  # from 0 (included) to 10 (excluded)
        print(i, end=" ")  # print " " instead of "\n" at the end
    #代码作用机制·语法关联·结果易错点
    1for i in range(10): # from 0 (included) to 10 (excluded)循环 0..9range(stop) 只给一个参数 → start=0, step=1;stop 不包含(与切片一致);range 是惰性对象,不占内存i 依次取 0…9 共 10 个值range(10) 不含 10;想含 10 写 range(11)
    2 print(i, end=" ") # print " " instead of "\n" at the end同一行打印print(i, end=" ") 把默认的换行 \n 换成空格,所以数字在同一行输出 "0 1 2 … 9 "忘写 end 会打 10 行;Python 的 for 块靠缩进界定
    运行结果 0 1 2 3 4 5 6 7 8 9
    Cell 18range(5, 10):从 5 到 9基础
    for i in range(5, 10):  # from 5 (included) to 10 (excluded)
        print(i, end=" ")
    #代码作用机制·语法关联·结果易错点
    1for i in range(5, 10): # from 5 (included) to 10 (excluded)循环 5..9range(start, stop):包含 start、不包含 stop5 个值range(5,10) 长度 = 10−5 = 5
    2 print(i, end=" ")同行打印同 C17"5 6 7 8 9 "—
    运行结果 5 6 7 8 9
    Cell 19range(5, 10, 2):步长 2基础
    for i in range(5, 10, 2):  # in steps of 2
        print(i, end=" ")
    #代码作用机制·语法关联·结果易错点
    1for i in range(5, 10, 2): # in steps of 2循环 5,7,9range(start, stop, step):从 5 起每次 +2,直到 <103 个值step 为 0 报 ValueError;step 负数要 start > stop 才有值
    2 print(i, end=" ")同行打印同 C17"5 7 9 "—
    运行结果 5 7 9

    Comprehension


    List comprehension is a "Pythonic" way of generating a new list from an existing sequence of items. The basic syntax is shown below, where if condition is optional:


    [expr_using_item for item in sequence_of_items if condition]
    

    Consider generating the squares of the numbers in an existing list. This can be done using a new list for storing the result and a for loop.

    为什么先教 for-append 再教推导式?因为推导式只是把右边三行(建空列表 → for → append)压成一行。先看懂"展开版",推导式的 [表达式 for 项 in 序列 if 条件] 读法就自然了:表达式对应 item*item,for 项 in 序列对应 for item in ls,if 条件是可选过滤器(放在 for 之后、表达式之前执行)。
    Cell 21平方:for + append 的"展开版"基础
    ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # an existing sequence
    squares = []  # for keeping result
    for item in ls:
        squares.append(item * item)  # put to result
    print(squares)
    #代码作用机制·语法关联·结果易错点
    1ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # an existing sequence0–9 的序列—ls—
    2squares = [] # for keeping result建空列表存结果必须先建容器,再往里放squares=[]忘建空列表 → NameError
    3for item in ls:遍历每一项for item in ls:item 依次绑定每个元素——
    4 squares.append(item * item) # put to result计算并追加item*item 是表达式;append 原地放入squares 增长—
    5print(squares)打印结果—[0,1,4,9,…,81]—
    运行结果 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    Using a list comprehension, the code is more concise and probably easier to read.

    Cell 23列表推导式:一行等价重点展开
    ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # an existing sequence
    squares = [item * item for item in ls]
    print(squares)
    #代码作用机制·语法关联·结果易错点
    1ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # an existing sequence同上—ls—
    2squares = [item * item for item in ls]推导式[表达式 for 项 in 序列]:先执行 for,对每个 item 求表达式,收集为新 list与 C21 结果完全相同方括号不能少——少了变成生成器表达式(惰性)
    3print(squares)打印—[0,1,4,9,…,81]—
    运行结果 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    深挖 · 推导式求值顺序:读的时候从 for 开始读——"对 ls 里的每个 item,取 item*item,组成列表"。if 在 for 之后(C27)。它比 for+append 快(C 层循环),也是 Keras 里写 [Dense(64) for _ in range(3)] 这种"重复堆层"的基础(Unit 8/9 就会见到)。

    A range can be used as the existing sequence of items.

    Cell 25以 range 为源的推导式基础
    print([n * n for n in range(10)])
    #代码作用机制·语法关联·结果易错点
    1print([n * n for n in range(10)])直接在 print 内推导range 可迭代,推导式可直接作为 print 的参数;省去中间变量[0,1,4,…,81]—
    运行结果 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

    An optional if clause can be added to select items in the existing sequence based on a condition. For example, the squares of only odd numbers (i.e. n % 2 == 1 is true when n is odd) are obtained as follows.

    Cell 27带 if 过滤:只留奇数的平方基础
    print([n * n for n in range(10) if n % 2 == 1])
    #代码作用机制·语法关联·结果易错点
    1print([n * n for n in range(10) if n % 2 == 1])推导式 + ifn % 2 == 1 为 True 才保留;if 写在 for 之后(先取 n 再筛选)[1, 9, 25, 49, 81]若写 [n*n if n%2==1 else 0 for n in …] 是"三元表达式",不过滤而是映射成 0——两者不同
    运行结果 [1, 9, 25, 49, 81]

    Practice - Question 1 of 2

    Q1a


    Lists can be nested; that is, a list can contain another list as an item. The following list ls contains three nested lists. Note that the lists may have different lengths. Multiple indexing operations may be used to access items in the nested lists. For example, ls[0] refers to the first (index 0) nested list, i.e. [1, 2, 3, 4]; ls[0][2] refers to the third (index 2) item in the nested list ls[0], i.e. 3.

    Cell 30Q1a 示例:嵌套列表的二维索引练习·作答
    ls = [
        [1, 2, 3, 4],
        [5, 6],
        [7, 8, 9, 10]
    ]
    print(ls[0][2])
    #代码作用机制·语法关联·结果易错点
    1ls = [定义 3 个子列表list 里放 list = 二维结构;子列表长度可不同(4/2/4),不是矩阵ls = [[1,2,3,4],[5,6],[7,8,9,10]]用 np.array 建这种"不等长"结构会报错或变成 object 数组
    2 [1, 2, 3, 4],定义 3 个子列表list 里放 list = 二维结构;子列表长度可不同(4/2/4),不是矩阵ls = [[1,2,3,4],[5,6],[7,8,9,10]]用 np.array 建这种"不等长"结构会报错或变成 object 数组
    3 [5, 6],定义 3 个子列表list 里放 list = 二维结构;子列表长度可不同(4/2/4),不是矩阵ls = [[1,2,3,4],[5,6],[7,8,9,10]]用 np.array 建这种"不等长"结构会报错或变成 object 数组
    4 [7, 8, 9, 10]定义 3 个子列表list 里放 list = 二维结构;子列表长度可不同(4/2/4),不是矩阵ls = [[1,2,3,4],[5,6],[7,8,9,10]]用 np.array 建这种"不等长"结构会报错或变成 object 数组
    5]定义 3 个子列表list 里放 list = 二维结构;子列表长度可不同(4/2/4),不是矩阵ls = [[1,2,3,4],[5,6],[7,8,9,10]]用 np.array 建这种"不等长"结构会报错或变成 object 数组
    6print(ls[0][2])ls[0][2]两次索引:先取第 0 个子列表 [1,2,3,4],再取其第 2 项3ls[0,2] 是 NumPy 写法,对纯 list 不行
    运行结果 3

    Write code to print the value 8 in ls using two positive indices; i.e. write a statement like print(ls[0][2]) but replace the indices 0 and 2 with other positive indices to display the value 8.


    Write code to print the value 8 in ls using two negative indices; i.e. write a statement like print(ls[0][2]) but replace the indices 0 and 2 with two negative indices to display the value 8.

    Cell 32Q1a 你的作答:正、负索引取 8练习·作答
    print (ls [2][1])
    print (ls [-1][-3])
    #代码作用机制·语法关联·结果易错点
    1print (ls [2][1])正索引取 8ls[2] 是第三个子列表 [7,8,9,10],其 [1] 是 88 ✔—
    2print (ls [-1][-3])负索引取 8ls[−1] 最后一个子列表,[−3] 倒数第三项 = 88 ✔两处都能用负索引;ls[−1][−3] 与 ls[2][1] 等价
    运行结果 8 8
    核对:两行都正确。写法 print (ls [2][1]) 括号内多了空格,PEP 8 不推荐但完全合法。

    Q1b


    Write 4 lines of code to do the following:


  • Create a list of integers from 0 to 11, with code `ls = list(range(12))`.
  • Using `print()`, `ls`, and slicing, print the slice result `[6, 7, 8, 9, 10, 11]`.
  • Using `print()`, `ls`, and slicing, print the slice result `[6, 8, 10]`.
  • Using `print()`, `ls`, and slicing, print the slice result `[11, 8, 5, 2]`.
  • Cell 34Q1b 你的作答:三组切片练习·作答
    ls=list(range(12))
    print (ls [6:12])
    print (ls [6::2])
    print (ls [11::-3])
    #代码作用机制·语法关联·结果易错点
    1ls=list(range(12))建 0–11list(range(12)):把 range 转成真正的 list(0…11)ls 长度 12range(12) 不含 12;含 11
    2print (ls [6:12])取 6..11ls[6:12]:下标 6–11(stop=12 不含)[6,7,8,9,10,11] ✔写 ls[6:11] 会少一个 11
    3print (ls [6::2])取 6,8,10ls[6::2]:从 6 起步长 2 到末尾[6,8,10] ✔stop 省略 → 到末尾
    4print (ls [11::-3])倒序隔 3 取ls[11::-3]:start=11、stop 省略、step=−3 → 11,8,5,2[11,8,5,2] ✔step 为负时不能写 ls[11:0:-3],那会漏掉 0 但此处恰好不需要
    运行结果 [6, 7, 8, 9, 10, 11] [6, 8, 10] [11, 8, 5, 2]

    Q1c


    The following is_prime(n) function returns True if n is a prime number or False otherwise. Using this function and a list comprehension, write code to print the list of prime numbers between 2 and 1000, i.e. [2, 3, 5, 7, ... 997]. Hint: in a list comprehension, the expression using the item may be just the item, i.e. [n for n in ...].

    Cell 36Q1c 你的作答:is_prime + 推导式列出 1000 内质数练习·作答
    def is_prime(n):
        for i in range(2, int(n ** 0.5 + 1)):
            if n % i == 0:
                return False
        return True
    
    
    print ([n for n in range (2,1001) if is_prime (n)])
    #代码作用机制·语法关联·结果易错点
    1def is_prime(n):定义函数def 定义;参数 n;函数体缩进——
    2 for i in range(2, int(n ** 0.5 + 1)):只需试到 √nrange(2, int(n**0.5+1)):若 n 有大于 √n 的因子,必有一个小于 √n 的配对因子,所以试到 √n 即可循环上界 int(√n)+1 保证包含 √n(如 n=9 → 试到 3)int() 是向下取整;+1 让 range 包住 √n
    3 if n % i == 0:整除判断n % i == 0:余数为 0 即 i 整除 n——
    4 return False返回 False找到一个因子 → 不是质数,立即返回(函数结束)——
    5 return True返回 True循环结束都没返回 → 没有因子 → 质数—此函数对 n=0,1 也返回 True(题目的"边界"),n=2 循环不执行也 True
    8print ([n for n in range (2,1001) if is_prime (n)])推导式调用函数[n for n in range(2,1001) if is_prime(n)]:表达式就是 n 本身;if 里可以调用函数[2, 3, 5, 7, …, 997],共 168 个range(2,1001) 不含 1001 → 覆盖到 1000;写成 range(2,1000) 会漏 997
    运行结果 [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701

    &#x2766;

    NumPy basics


    The NumPy library implements efficient multi-dimensional arrays and related operations. It is heavily used in machine learning libraries such as Scikit-learn and TensorFlow.

    Array creation and properties


    By convention, NumPy is often imported as the name np. A NumPy array can be created using the np.array() function.

    Cell 40NumPy 入场:np.array 与 ndarray重点展开
    import numpy as np
    arr = np.array([[1, 2, 3], [4, 5, 6]])
    print(arr)
    print(type(arr))
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入并起别名惯例 import numpy as np——所有教程/教材/官方文档都用 np之后所有 np.xxx 可用忘 import → NameError: np
    2arr = np.array([[1, 2, 3], [4, 5, 6]])嵌套 list 建 2D 数组np.array 把"列表的列表"解释为矩阵:外层 2 个 → 2 行,内层各 3 个 → 3 列;元素被统一成同一 dtype(这里 int64)arr shape (2,3)内层长度不等 → 报错(NumPy 要求是矩形)
    3print(arr)打印NumPy 的打印不带逗号、用空格对齐[[1 2 3]\n [4 5 6]]—
    4print(type(arr))类型—ndarray = n-dimensional array,一个类,不是 list
    运行结果 [[1 2 3] [4 5 6]] <class 'numpy.ndarray'>

    The following code examines various properties of an array.

    Cell 42数组五个属性:size / shape / ndim / dtype / itemsize重点展开
    print(f"{arr.size=}")  # number of items in array
    print(f"{arr.shape=}")  # dimensions of array
    print(f"{arr.ndim=}")  # number of dimensions, 1D or 2D etc
    print(f"{arr.dtype=}")  # data type of items
    print(f"{arr.itemsize=}")  # byte size of an item
    #代码作用机制·语法关联·结果易错点
    1print(f"{arr.size=}") # number of items in arraysize元素总个数(所有维相乘:2×3)6size ≠ len;len(arr) 返回第 0 维长度 = 2
    2print(f"{arr.shape=}") # dimensions of arrayshape每一维的长度组成的 tuple(2, 3)shape 是 tuple 不是 list;(3,) 才是"一维 3 个",(3) 只是 3
    3print(f"{arr.ndim=}") # number of dimensions, 1D or 2D etcndim维数 = len(shape)2一维数组 ndim=1、标量 np.array(5).ndim=0
    4print(f"{arr.dtype=}") # data type of itemsdtype元素类型:创建时从 Python int 推断为 int64(macOS/Linux 64 位)dtype('int64')Windows 上可能推断为 int32 → 与 Colab 的 int64 不同
    5print(f"{arr.itemsize=}") # byte size of an itemitemsize每个元素字节数:int64 → 88size×itemsize = nbytes = 48 字节
    运行结果 arr.size=6 arr.shape=(2, 3) arr.ndim=2 arr.dtype=dtype('int64') arr.itemsize=8
    深挖 · 为什么这五个属性重要:Keras 里 X_train.shape 决定 input_shape(Unit 4:`(13,)`、Unit 5:`(28,28)`、Unit 8 加通道维 `(28,28,1)`);dtype 影响归一化——int 的 /255 会得到 float64,所以 MNIST 代码都写 astype("float32")(t05)。记住 shape 是 tuple、size 是 int、len() 只看第 0 维。

    In NumPy, a dimension is often called an axis; e.g. axis-0 means the first or most dominant dimension of an array.


    We can change the dimensions, or shape, of an array using the reshape() method or function. Specifying -1 as a dimension lets NumPy calculate that dimension according to the number of items in the array. reshape() would not modify the provided array but return a new array.

    ↳ reshape 的三条规则在 C44–C46 逐一演示:-1 自动算 / 返回新数组 / (6,) 与 (6,1) 不同。
    Cell 44reshape (3,-1):-1 自动推断,原数组不变重点展开
    arr2 = arr.reshape((3, -1))  # -1 becomes 6/3=2
    print(arr2, arr2.shape)
    print(arr, arr.shape)  # arr is not changed!
    #代码作用机制·语法关联·结果易错点
    1arr2 = arr.reshape((3, -1)) # -1 becomes 6/3=2方法形式 reshape方法 arr.reshape(...);形状 (3,−1):只给一个 −1,NumPy 用 总数/已知维 自动算出 6/3=2arr2 shape (3,2)−1 只能出现一次;(−1,−1) 报错
    2print(arr2, arr2.shape)打印新数组与形状—[[1 2]\n [3 4]\n [5 6]] (3, 2)—
    3print(arr, arr.shape) # arr is not changed!打印原数组reshape 不修改原数组,返回新视图/新数组(能共享内存时是 view)arr 仍 (2,3)arr.reshape(...) 单独一行不赋值 = 白做
    运行结果 [[1 2] [3 4] [5 6]] (3, 2) [[1 2 3] [4 5 6]] (2, 3)
    Cell 45np.reshape 函数形式 → (6,1) 列向量基础
    arr3 = np.reshape(arr, (6, 1))  # 2D array of 6x1 items
    print(arr3, arr3.shape)
    #代码作用机制·语法关联·结果易错点
    1arr3 = np.reshape(arr, (6, 1)) # 2D array of 6x1 items函数形式np.reshape(arr, shape) 与 arr.reshape(shape) 完全等价;(6,1) 是 6 行 1 列的二维数组arr3 shape (6,1)(6,1) ≠ (6,):前者 2D、后者 1D;sklearn 的 y 常要求 (n,1) 或 (n,) 之一,混用会报 "bad input shape"
    2print(arr3, arr3.shape)打印—6 行 1 列—
    运行结果 [[1] [2] [3] [4] [5] [6]] (6, 1)
    Cell 46np.reshape → (6,) 一维基础
    arr4 = np.reshape(arr, (6,))  # 1D array of 6 items
    print(arr4, arr4.shape)
    #代码作用机制·语法关联·结果易错点
    1arr4 = np.reshape(arr, (6,)) # 1D array of 6 items压平为一维(6,) 是单元素 tuple——逗号不能少,否则 (6) 只是整数 6 会被当成... 实际 reshape(6) 也合法(int 视为一维)arr4 shape (6,)arr.reshape((6,)) 与 arr.reshape(-1) 等价;与 arr.flatten() 结果相同但 flatten 返回拷贝
    2print(arr4, arr4.shape)打印—[1 2 3 4 5 6] (6,)—
    运行结果 [1 2 3 4 5 6] (6,)

    More ways of creating arrays


    There are many other ways of creating NumPy arrays. Some are shown below.

    Cell 48np.zeros((2,5))基础
    a = np.zeros((2, 5)) # 2D array of 2x5 zeros
    print(a)
    #代码作用机制·语法关联·结果易错点
    1a = np.zeros((2, 5)) # 2D array of 2x5 zeros全零数组np.zeros(shape):shape 必须是 tuple(二维时),默认 dtype float64 → 显示 0.a shape (2,5)np.zeros(2,5) 报错——两个位置参数会被当成 dtype
    2print(a)打印—2×5 的 0.—
    运行结果 [[0. 0. 0. 0. 0.] [0. 0. 0. 0. 0.]]
    Cell 49np.ones(5) 与 Colab 自动显示末行表达式基础
    a = np.ones(5) # 1D array of 5 ones, same as np.ones((5,))
    a  # Colab automatically displays the last expression in a code cell
    #代码作用机制·语法关联·结果易错点
    1a = np.ones(5) # 1D array of 5 ones, same as np.ones((5,))全 1 数组一维 shape 可直接给 int:np.ones(5) ≡ np.ones((5,))a = array([1.,1.,1.,1.,1.])dtype 仍 float64;要 int 写 np.ones(5, dtype=int)
    2a # Colab automatically displays the last expression in a code cell裸表达式Colab/Jupyter 自动显示 cell 最后一行表达式的 repr,不需要 printarray([1., 1., 1., 1., 1.])只在"最后一行"且"是表达式"时触发;赋值语句不显示
    运行结果 array([1., 1., 1., 1., 1.])
    Cell 50np.arange(0,5,0.5)基础
    # No need to keep the array for later use; let's just display it
    np.arange(0, 5, 0.5)  # 0 (included) to 5 (excluded) in steps of 0.5
    #代码作用机制·语法关联·结果易错点
    1# No need to keep the array for later use; let's just display it注释说明不保存结果只显示——
    2np.arange(0, 5, 0.5) # 0 (included) to 5 (excluded) in steps of 0.5等差数列np.arange(start, stop, step) 与 range 同规则(stop 不含),但支持小数步长、返回 ndarray[0. , 0.5, …, 4.5] 共 10 个浮点累加有误差:np.arange(0,1,0.1) 长度可能是 10 或 11 不确定——要精确个数用 np.linspace
    运行结果 array([0. , 0.5, 1. , 1.5, 2. , 2.5, 3. , 3.5, 4. , 4.5])

    Array indexing


    An item in an array can be accessed using indexing, with index values specified for the dimensions separated by commas, as arr[r_index, c_index] for a 2D array.

    Cell 52np.arange(12).reshape((3,4)):链式调用重点展开
    a = np.arange(12).reshape((3, 4))
    a
    #代码作用机制·语法关联·结果易错点
    1a = np.arange(12).reshape((3, 4))生成 0–11 再整形链式:arange 返回 ndarray → 立刻调用其 reshape 方法;0–11 按行填充(row-major / C order)a = [[0,1,2,3],[4,5,6,7],[8,9,10,11]]NumPy 默认 C order(先填最后一维);order='F' 是按列填,几乎不用
    2a显示同 C49 的自动显示3×4 矩阵—
    运行结果 array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])
    Cell 53a[1,2]:二维索引基础
    a[1, 2]  # index 1 -> second row, index 2 -> third column
    #代码作用机制·语法关联·结果易错点
    1a[1, 2] # index 1 -> second row, index 2 -> third column取一个元素NumPy 用逗号分隔多维索引:a[1,2] = 第 1 行第 2 列(0-based)→ 值 6np.int64(6)a[1][2] 也可以但慢(两次索引);纯 list 只能 a[1][2]
    运行结果 np.int64(6)

    A row is accessed using arr[r_index], while a column using arr[:, c_index]. You may think of : to mean "all items" in a dimension or along an axis.

    Cell 55a[1]:取整行基础
    a[1]  # index 1 -> second row, all columns; same as a[1, :]
    #代码作用机制·语法关联·结果易错点
    1a[1] # index 1 -> second row, all columns; same as a[1, :]行索引只给一个下标 → 第 0 维(行);其余维默认全取 → a[1] ≡ a[1,:][4,5,6,7]a[1] 返回的是视图(view),改它会改 a
    运行结果 array([4, 5, 6, 7])
    Cell 56a[:,2]:取整列重点展开
    a[:, 2]  # : -> all rows; index 2 -> third column
    #代码作用机制·语法关联·结果易错点
    1a[:, 2] # : -> all rows; index 2 -> third column列索引: 表示该维"全取";所以 a[:,2] = 所有行、第 2 列[2,6,10]常见错:写 a[2] 得到的是行 [8,9,10,11],不是列
    运行结果 array([ 2, 6, 10])
    深挖 · 视图 vs 拷贝:基本切片(a[:,2]、a[1:3])返回 view——共享内存,改 view 会改原数组;花式索引(a[[0,2]]、布尔掩码)返回拷贝。做归一化 X[:, 0] = X[:, 0]/255 能生效正是因为切片是 view。

    Multiple consecutive columns of an array can be accessed using a slice, i.e. start:stop:step, as the column index. The code below accesses the region of all rows and the second and third columns in the array.

    Cell 58a[:,1:3]:切片取多列基础
    a[:, 1:3]  # : -> all rows, slice 1:3 -> second & third columns
    #代码作用机制·语法关联·结果易错点
    1a[:, 1:3] # : -> all rows, slice 1:3 -> second & third columns子区域每一维都可以用切片:行全取,列取 1:3(第 1、2 列)3×2 子矩阵 [[1,2],[5,6],[9,10]]stop 不含:1:3 是两列不是三列
    运行结果 array([[ 1, 2], [ 5, 6], [ 9, 10]])

    Practice - Question 2 of 2

    Q2a


    Write code to do the following:


  • Import NumPy as the name `np`.
  • Create a 2D array of 4x5 items from 10 (included) to 30 (excluded). Use the `np.arange()` function and the `reshape()` method. Keep it in a variable called `arr`.
  • Write `arr` in the last line of the code cell so that it is displayed in execution.
  • Cell 61Q2a 你的作答:arange(10,30).reshape(4,5)练习·作答
    import numpy as np
    arr = np.arange (10,30).reshape (4,5)
    arr
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2arr = np.arange (10,30).reshape (4,5)建 4×5 的 10–29arange(10,30) 20 个数 → reshape(4,5) = 20 个格子,刚好;行优先填充arr = [[10..14],[15..19],[20..24],[25..29]]arange(10,31) 会 21 个数 → reshape(4,5) 报 "cannot reshape"
    3arr末行表达式显示同 C49显示矩阵题目要求 "Write arr in the last line" 就是为了触发自动显示
    运行结果 array([[10, 11, 12, 13, 14], [15, 16, 17, 18, 19], [20, 21, 22, 23, 24], [25, 26, 27, 28, 29]])

    Q2b


    This part continues to use the arr variable above. Write code to display each of the following using print(), arr and array indexing:


  • The value `15` in the array.
  • The value `27` in the array.
  • The last row, i.e. `[25, 26, 27, 28, 29]`.
  • The second column, i.e. `[11, 16, 21, 26]`.
  • The middle six numbers, i.e. `[[16, 17, 18], [21, 22, 23]]`.
  • Cell 63Q2b 你的作答:五个索引/切片练习·作答
    print (arr [1,0])
    print (arr [3,2])
    print (arr [3])
    print (arr [:,1])
    print (arr [1:3,1:4])
    #代码作用机制·语法关联·结果易错点
    1print (arr [1,0])取 15arr[1,0]:第 1 行第 0 列15 ✔—
    2print (arr [3,2])取 27arr[3,2]27 ✔—
    3print (arr [3])最后一行arr[3](≡ arr[3,:] 或 arr[-1])[25 26 27 28 29] ✔—
    4print (arr [:,1])第二列arr[:,1][11 16 21 26] ✔—
    5print (arr [1:3,1:4])中间六格arr[1:3,1:4]:行 1–2、列 1–3[[16 17 18],[21 22 23]] ✔行 1:3 两行、列 1:4 三列 → 2×3 = 6 个
    运行结果 15 27 [25 26 27 28 29] [11 16 21 26] [[16 17 18] [21 22 23]]
    核对:五问全部正确。

    Q2c


    Write code to do the following with proper NumPy API:


  • Seed the random number generator, with code `np.random.seed(42)`.
  • Create an array of 10000 random numbers normally distributed with mean 0.0 and standard deviation 1.0. Use the `np.random.randn()` function, and keep the array in a variable called `xs`.
  • Display the mean of the numbers in `xs`.
  • Display the standard deviation of the numbers in `xs`.
  • Display the number of elements (i.e. how many numbers) in `xs`.
  • Cell 65Q2c 你的作答:seed / randn / mean / std / size重点展开
    np.random.seed (42)
    xs = np.random.randn (10000)
    print (xs.mean ())
    print (xs.std ())
    print (xs.size)
    #代码作用机制·语法关联·结果易错点
    1np.random.seed (42)固定随机种子np.random.seed(42):让之后的伪随机数可复现——同一种子同一机器产生同一序列;与 Keras 的 set_random_seed 是不同 RNG(t04 起)—seed 要在生成之前调用;只影响 NumPy 的全局 RNG
    2xs = np.random.randn (10000)标准正态 10000 个np.random.randn(n):均值 0、标准差 1 的高斯;返回 float64 ndarrayxs shape (10000,)randn 与 rand 不同:rand 是 [0,1) 均匀;np.random.normal(0,1,10000) 与 randn 等价
    3print (xs.mean ())样本均值.mean() 方法;理论 0,样本 −0.0021−0.00213598…n 越大越接近 0(大数定律)
    4print (xs.std ())样本标准差.std()(默认总体 std,ddof=0);理论 1,样本 1.00341.0034122…—
    5print (xs.size)元素个数.size 属性(不是方法)10000xs.size() 报错——它是属性
    运行结果 -0.002135983368426207 1.0034122061299875 10000
    深挖 · 为什么 DL 代码都要 seed:权重初始化( glorot / he )与 Dropout 掩码都是随机的;固定 seed 才能比较"改一个超参数"到底有没有用。本课 notebook 全部 np.random.seed(42) / tf.random.set_seed(42)(t06+),Lab 报告写 "results reproducible" 靠的就是它。

    Q2d


    This part continues to use the xs variable above. Write code to do the following:


  • Import the matplotlib library, with code `import matplotlib.pyplot as plt`.
  • Plot a histogram of the numbers in `xs` using 100 bins, with code `plt.hist(xs, bins=100);`. Note that the trailing semicolon `;` is specified so that the last expression value is not displayed.
  • Cell 67Q2d 你的作答:matplotlib 直方图与末尾分号基础
    import matplotlib.pyplot as plt
    plt.hist (xs, bins=100);
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入绘图库惯例别名 plt——
    2plt.hist (xs, bins=100);画 100 桶直方图plt.hist(xs, bins=100):把数值范围切成 100 个区间统计频数;末尾 ; 抑制 Jupyter 对返回值((n, bins, patches) 元组)的显示钟形直方图(标准正态)不加分号会在图上方多出一行 (array([...]), array([...]), <BarContainer>)
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    &#x2766;

    Extras

    More list operations


    Items can be removed from a list using the del operator or the pop() method.

    Cell 71del 与 pop()基础
    ls = [1, 2, 3, 4, 5]
    print(ls)
    del ls[1]  # remove the 2nd item, i.e. with index 1
    print(ls)
    ls.pop()  # remove item at the end
    print(ls)
    #代码作用机制·语法关联·结果易错点
    1ls = [1, 2, 3, 4, 5]建 1–5 并打印—[1,2,3,4,5]—
    2print(ls)建 1–5 并打印—[1,2,3,4,5]—
    3del ls[1] # remove the 2nd item, i.e. with index 1按下标删除del ls[1]:语句,删除该项,后面的元素前移—del 不返回值
    4print(ls)打印—[1,3,4,5]—
    5ls.pop() # remove item at the end弹出末项pop() 默认弹出最后一项并返回它(这里没接返回值)—pop(i) 可弹任意位置;对空 list pop 报 IndexError
    6print(ls)打印—[1,3,4]—
    运行结果 [1, 2, 3, 4, 5] [1, 3, 4, 5] [1, 3, 4]

    Some list functions modify list contents in-place (e.g. extend()); usually the return values of such functions are not used. Other functions and operations return copies or new lists (e.g. +), which are typically assigned to variables for later uses.

    Cell 73extend():原地拼接基础
    ls = [1, 2, 3]
    print(ls)
    ls.extend([40, 50])  # add two items in-place
    print(ls)  # ls is modified!
    #代码作用机制·语法关联·结果易错点
    1ls = [1, 2, 3]建并打印—[1,2,3]—
    2print(ls)建并打印—[1,2,3]—
    3ls.extend([40, 50]) # add two items in-place追加多个extend 原地把另一个可迭代对象的每个元素追加进来;返回 Nonels 被修改ls = ls.extend(...) → None;ls.append([40,50]) 会变成嵌套 [[…],[40,50]]
    4print(ls) # ls is modified!打印—[1,2,3,40,50]—
    运行结果 [1, 2, 3] [1, 2, 3, 40, 50]
    Cell 74+ 运算符:返回新列表基础
    ls = [1, 2, 3]
    print(ls)
    ls2 = ls + [40, 50]  # add two items and put result to ls2
    print(ls)  # ls is not modified!
    print(ls2)  # result is in ls2
    #代码作用机制·语法关联·结果易错点
    1ls = [1, 2, 3]建并打印—[1,2,3]—
    2print(ls)建并打印—[1,2,3]—
    3ls2 = ls + [40, 50] # add two items and put result to ls2拼接并赋给 ls2ls + [40,50] 创建新 list,ls 不变ls2=[1,2,3,40,50]与 extend 对比:+ 不改原列表、extend 改
    4print(ls) # ls is not modified!打印两者—ls 仍 [1,2,3],ls2 含新项—
    5print(ls2) # result is in ls2打印两者—ls 仍 [1,2,3],ls2 含新项—
    运行结果 [1, 2, 3] [1, 2, 3] [1, 2, 3, 40, 50]

    Sets and dictionaries


    A set is an unordered collection of unique items. If an item already exists in a set, adding another item of an equal value has no effect.

    Cell 76set:无序、去重基础
    s = {1, 2, "three", 1, 2.0, 1, 1}  # equal item skipped
    print(s)
    print(type(s))
    print(len(s))
    #代码作用机制·语法关联·结果易错点
    1s = {1, 2, "three", 1, 2.0, 1, 1} # equal item skipped字面量建集合花括号 { };重复的相等元素只保留一个:1 与 1.0 与 True 在 Python 中两两相等(1 == 1.0 == True),所以只剩 1{1, 2, 'three'}{} 是空 dict 不是空 set!空集合要 set()(E1a 考点);输出顺序不保证
    2print(s)打印 / 类型 / 长度— / 3—
    3print(type(s))打印 / 类型 / 长度— / 3—
    4print(len(s))打印 / 类型 / 长度— / 3—
    运行结果 {1, 2, 'three'} <class 'set'> 3

    Use the add() method to add an item to a set, and the in operator to check if an item exists in a set.

    Cell 78in 与 add()基础
    s = {1, 2, 3}
    print(40 in s)
    s.add(40)
    print(40 in s)
    #代码作用机制·语法关联·结果易错点
    1s = {1, 2, 3}建集合—{1,2,3}—
    2print(40 in s)成员测试x in s:set 用哈希查找,O(1)False—
    3s.add(40)添加add 原地添加;若已存在则无事发生—add 一个 list 会报 TypeError(list 不可哈希)
    4print(40 in s)再测—True—
    运行结果 False True

    A dictionary is a collection of key-value pairs with unique keys.

    Cell 80dict:键值对、键唯一基础
    d = {"one": 1, "two": 2, "three": 3, "two": 2.0}  # equal key overriding item
    print(d)
    print(type(d))
    print(len(d))
    #代码作用机制·语法关联·结果易错点
    1d = {"one": 1, "two": 2, "three": 3, "two": 2.0} # equal key overriding item字面量建字典{key: value, …};重复键 "two" 出现两次 → 后者覆盖前者(值变 2.0){'one': 1, 'two': 2.0, 'three': 3}键必须可哈希(str/int/tuple);list 不能做键
    2print(d)打印 / 类型 / 长度len(d) = 键的个数 / 3—
    3print(type(d))打印 / 类型 / 长度len(d) = 键的个数 / 3—
    4print(len(d))打印 / 类型 / 长度len(d) = 键的个数 / 3—
    运行结果 {'one': 1, 'two': 2.0, 'three': 3} <class 'dict'> 3
    ↳ Keras 的 history.history 就是 dict(t02 起):{"loss": [...], "val_loss": [...]},用 history.history["loss"] 取训练曲线。

    Values in a dictionary can be accessed or added by indexing with the keys. Use the in operator to check if a key exists.

    Cell 82按键取值、in、新增键基础
    print(d["one"])
    print("four" in d)
    d["four"] = 4  # add an item as the key doesn't exist
    print("four" in d, d["four"])
    #代码作用机制·语法关联·结果易错点
    1print(d["one"])按键取值d[key]:键不存在会 KeyError(与 set 的 in 不同)1安全取值用 d.get(key, 默认)
    2print("four" in d)键是否存在in 检查的是键不是值False—
    3d["four"] = 4 # add an item as the key doesn't exist新增键值给不存在的键赋值 = 添加—给存在的键赋值 = 覆盖
    4print("four" in d, d["four"])打印—True 4—
    运行结果 1 False True 4
    E1a

    For each of the following expressions, write a statement to print the value of the expression, and the type of the value. For example, for an expression set(), the statement is print(set(), type( set() )).


  • `{}`
  • `()`
  • `(42)`
  • `(42,)`
  • NumPy operations along axes


    Some NumPy operations can be applied to the whole array or along a certain axis of the array. E.g. in a 2D array, along axis-0 means across the rows downwards, while along axis-1 means across the columns towards the right.


    The following code use max() to display the maximum value of an array, the maximum value of every column (along axis-0 or across rows downwards), and the maximum value of every row (along axis-1 or across columns towards the right). Note that the array contents are shuffled for more observable results.

    axis 是 DL 代码里最常见的混淆点。记法:axis=k 就是"把第 k 个下标消掉"——形状 (3,4) 的数组,max(axis=0) 得到 4 个数(消掉第 0 维),max(axis=1) 得到 3 个数(消掉第 1 维)。后面 Unit 5 的 softmax(axis=-1)、Unit 7 的 BatchNormalization(axis=-1)、Unit 10 的 axis=1 都是这条规则。
    Cell 85E1a 示例:shuffle + max 沿 axis重点展开
    import numpy as np
    arr = np.arange(12)
    np.random.seed(42)  # reproducible random results
    np.random.shuffle(arr)  # shuffle in-place, i.e. modify arr
    arr = arr.reshape((3, 4))
    print(arr)
    print(f"{arr.max() = }")  # max of whole array; same as np.max(arr)
    print(f"{arr.max(axis=0) = }")  # max of every column; np.max(arr, axis=0)
    print(f"{arr.max(axis=1) = }")  # max of every row; np.max(arr, axis=1)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2arr = np.arange(12)0–11—arr 一维—
    3np.random.seed(42) # reproducible random results固定种子让 shuffle 结果可复现——
    4np.random.shuffle(arr) # shuffle in-place, i.e. modify arr原地打乱shuffle 原地修改(返回 None)arr 变为随机排列arr = np.random.shuffle(arr) → None!
    5arr = arr.reshape((3, 4))整形 3×4—[[10 9 0 8],[5 2 1 11],[4 7 3 6]]—
    6print(arr)打印———
    7print(f"{arr.max() = }") # max of whole array; same as np.max(arr)整体最大arr.max() 无 axis → 所有元素;≡ np.max(arr)np.int64(11)—
    8print(f"{arr.max(axis=0) = }") # max of every column; np.max(arr, axis=0)axis=0:每列最大沿第 0 维(行方向向下)聚合 → 消掉行维,剩 4 个值[10, 9, 3, 11]axis=0 结果长度 = 列数(shape[1])
    9print(f"{arr.max(axis=1) = }") # max of every row; np.max(arr, axis=1)axis=1:每行最大沿第 1 维(列方向向右)聚合 → 消掉列维,剩 3 个值[10, 11, 7]axis=1 结果长度 = 行数(shape[0])
    运行结果 [[10 9 0 8] [ 5 2 1 11] [ 4 7 3 6]] arr.max() = np.int64(11) arr.max(axis=0) = array([10, 9, 3, 11]) arr.max(axis=1) = array([10, 11, 7])
    E1b

    Write code to create a 2D array of 3x3 integers from 0 (included) to 9 (excluded) in a random order (i.e. with contents shuffle). Display the array, the mean of the whole array, the mean of every column (along axis-0), the mean of every row (along axis-1); use the np.mean(arr, axis=n) function.

    Solutions to extra exercises

    E1a
    Cell 89E1a 解答:四种字面量的类型练习·作答
    # Solution
    print({}, type({}))
    print((), type(()))
    print((42), type((42)))
    print((42,), type((42,)))
    #代码作用机制·语法关联·结果易错点
    1# Solution注释———
    2print({}, type({})){} 是 dict空花括号被 Python 解析为字典{} <class 'dict'>想要空 set:set()
    3print((), type(()))() 是 tuple空圆括号是空元组() <class 'tuple'>—
    4print((42), type((42)))(42) 是 int括号只是分组,没有逗号就不是 tuple42 <class 'int'>单元素 tuple 必须带逗号
    5print((42,), type((42,)))(42,) 是 tuple逗号才决定 tuple(42,) <class 'tuple'>shape 写 (6,) 不写 (6) 同理
    运行结果 {} <class 'dict'> () <class 'tuple'> 42 <class 'int'> (42,) <class 'tuple'>
    E1b
    Cell 91E1b 解答:mean 沿 axis练习·作答
    # Solution
    import numpy as np
    arr = np.arange(9)
    np.random.seed(42)  # reproducible random results
    np.random.shuffle(arr)  # shuffle in-place, i.e. modify arr
    arr = arr.reshape((3, 3))
    print(arr)
    print(f"{np.mean(arr) = }")  # mean of whole array; same as arr.mean()
    print(f"{np.mean(arr, axis=0) = }")  # mean of every column; arr.mean(axis=0)
    print(f"{np.mean(arr, axis=1) = }")  # mean of every row; arr.mean(axis=1)
    #代码作用机制·语法关联·结果易错点
    1# Solution同 C85 结构arange(9) → shuffle → reshape(3,3);打印[[7 1 5],[0 8 2],[4 3 6]]seed 42 下 9 个数打乱的结果与 12 个数不同
    2import numpy as np同 C85 结构arange(9) → shuffle → reshape(3,3);打印[[7 1 5],[0 8 2],[4 3 6]]seed 42 下 9 个数打乱的结果与 12 个数不同
    3arr = np.arange(9)同 C85 结构arange(9) → shuffle → reshape(3,3);打印[[7 1 5],[0 8 2],[4 3 6]]seed 42 下 9 个数打乱的结果与 12 个数不同
    4np.random.seed(42) # reproducible random results同 C85 结构arange(9) → shuffle → reshape(3,3);打印[[7 1 5],[0 8 2],[4 3 6]]seed 42 下 9 个数打乱的结果与 12 个数不同
    5np.random.shuffle(arr) # shuffle in-place, i.e. modify arr同 C85 结构arange(9) → shuffle → reshape(3,3);打印[[7 1 5],[0 8 2],[4 3 6]]seed 42 下 9 个数打乱的结果与 12 个数不同
    6arr = arr.reshape((3, 3))同 C85 结构arange(9) → shuffle → reshape(3,3);打印[[7 1 5],[0 8 2],[4 3 6]]seed 42 下 9 个数打乱的结果与 12 个数不同
    7print(arr)同 C85 结构arange(9) → shuffle → reshape(3,3);打印[[7 1 5],[0 8 2],[4 3 6]]seed 42 下 9 个数打乱的结果与 12 个数不同
    8print(f"{np.mean(arr) = }") # mean of whole array; same as arr.mean()整体均值np.mean(arr) 函数形式 ≡ arr.mean();0–8 的均值恒为 4.0 与顺序无关np.float64(4.0)—
    9print(f"{np.mean(arr, axis=0) = }") # mean of every column; arr.mean(axis=0)每列均值axis=0 → 3 个值[3.667, 4., 4.333]—
    10print(f"{np.mean(arr, axis=1) = }") # mean of every row; arr.mean(axis=1)每行均值axis=1 → 3 个值[4.333, 3.333, 4.333]每列/每行均值再取均值都回到 4.0(等长)
    运行结果 [[7 1 5] [0 8 2] [4 3 6]] np.mean(arr) = np.float64(4.0) np.mean(arr, axis=0) = array([3.66666667, 4. , 4.33333333]) np.mean(arr, axis=1) = array([4.33333333, 3.33333333, 4.33333333])

    &#x2766;

    📘 Tutorial 2(= Lab 2)· Matplotlib 画图 + 第一次跑 Keras:感知机 vs MLP(OR / XOR / AND)

    t02-s13903054.ipynb,61 cells。前半:plot / scatter / subplot / 标签 / legend / ylim / show;后半:四段几乎相同的 Keras "单神经元" 程序,只有 y 和网络结构不同——这是整门课所有 Keras 代码的母版(数据 → seed → Sequential → compile → fit → predict → history 画图)。把 C26 这 16 行吃透,后面 t04–t11 只是往里面加层、加回调、换数据。
    本讲三个核心对照:① OR / AND 线性可分 → 单个 sigmoid 神经元 300 轮后预测 [0,1,1,1] / [0,0,0,1] 全对,loss → 0;② XOR 线性不可分 → 同样的单个神经元卡在预测 ≈ [0.49,0.48,0.48,0.46]、loss ≈ 0.69 = ln2(等于瞎猜)、acc ≈ 0.5;③ 加一个 Dense(2) 隐藏层(MLP)→ XOR 预测 [0,1,1,0] 全对,但需要约 200 轮。这就是 Unit 2 讲义 p16–p33 "感知机 → 多层感知机" 的实验证据。
    Cell 2关闭 TensorFlow 的 C++ 层日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2设置环境变量%env 是 IPython 魔术命令(只有 notebook 里能用):在内核进程里设置环境变量;TF_CPP_MIN_LOG_LEVEL=2 表示只显示 ERROR 及以上(1=过滤 INFO,2=再过滤 WARNING,3=全部过滤)输出 env: TF_CPP_MIN_LOG_LEVEL=2必须在 import tensorflow 之前执行才生效——它是 C++ 后端启动时读的;.py 脚本里要改用 os.environ[...]
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • creating plots using Matplotlib, and
  • running Keras code and plotting history.
  • Student name: Yin Bang
    Student ID: 13903054

    Creating plots using Matplotlib

    Matplotlib is a Python library for creating charts, or plots. By convention, we import the matplotlib.pyplot module as the name plt.

    Line plots


    The following is a very simple example of creating a line graph, or line plot. It uses the plot() function to plot a few y values stored in a list. The x values are by default the index values of the y list, i.e. [0, 1, 2, 3]. Since the plot() function call is the last expression in the code cell, Colab displays its return value.

    Cell 8最简线图:plot(y),x 默认为下标基础
    import matplotlib.pyplot as plt
    y = [1, 3, 2, 4]
    plt.plot(y)  # x data default to indices, i.e. [0, 1, 2, 3]
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入绘图模块惯例 import matplotlib.pyplot as plt;pyplot 是"状态机式"接口——后面的 plot/xlabel 都作用在"当前图"上—不是 import matplotlib
    2y = [1, 3, 2, 4]y 数据普通 list 即可,不必转 ndarray[1, 3, 2, 4]—
    3plt.plot(y) # x data default to indices, i.e. [0, 1, 2, 3]画线plt.plot(y) 只给 y → x 自动取 0..len−1;返回 Line2D 对象列表显示折线 + 多一行 [<Line2D>]加 ; 或最后 plt.show() 可抑制那行对象文本
    运行结果 [<matplotlib.lines.Line2D at 0x7b18fffc2c10>] <Figure size 640x480 with 1 Axes> [image/png]

    The next example plots the sine function. In order to obtain a smooth curve, we create 1000 x values from 0 to 2$\pi$ using the NumPy np.linspace() function. Then, the sine values of these x values are computed using the np.sin(x) function; this application of an operation (here sine) to all items in a NumPy array (here x) is called vectorization. After that, we set the x-axis label, y-axis label, and plot title. The semicolon ; suppresses the last expression value in Colab.

    Cell 10正弦曲线:linspace、向量化、标签与标题、末尾分号重点展开
    import numpy as np
    x = np.linspace(0, 2 * np.pi, 1000)
    y = np.sin(x)  # NumPy vectorization
    plt.plot(x, y)
    plt.xlabel("x")
    plt.ylabel("sin(x)")
    plt.title("The sine function");  # trailing ; to hide last expression value
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入 NumPy———
    2x = np.linspace(0, 2 * np.pi, 1000)生成 1000 个等距 xnp.linspace(start, stop, num):两端都包含,精确 num 个点(与 arange 不同:arange 是按步长、stop 不含、浮点有误差)x shape (1000,),0 到 2π要"刚好 n 个点"用 linspace;要"固定步长"用 arange
    3y = np.sin(x) # NumPy vectorization向量化算 sinnp.sin(x) 对数组每个元素逐一运算(C 层循环),不用写 for——这就是向量化y shape (1000,)对 list 用 np.sin 会先转成数组;math.sin 只接受标量
    4plt.plot(x, y)画 x-y给出 x 时按 (x[i], y[i]) 连线平滑正弦—
    5plt.xlabel("x")轴标签与标题xlabel / ylabel / title 都是字符串;作用在当前 axes—ylabel 写 "sin(x)" 带括号没问题
    6plt.ylabel("sin(x)")轴标签与标题xlabel / ylabel / title 都是字符串;作用在当前 axes—ylabel 写 "sin(x)" 带括号没问题
    7plt.title("The sine function"); # trailing ; to hide last expression value末尾分号notebook 中表达式后加 ; 抑制显示返回值(否则显示 [...])无多余输出; 在 .py 脚本里无意义,只是无害
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Multiple curves can be drawn on the same plot. The code below invokes the plot() function two times to draw the sine and cosine curves. The label parameters in plot() specify the labels of the curves; to show these labels in a legend box, we call the legend() function.

    Cell 12同一图画两条曲线 + legend基础
    import numpy as np
    x = np.linspace(0, 2 * np.pi, 1000)
    plt.plot(x, np.sin(x), label="sin(x)")
    plt.plot(x, np.cos(x), label="cos(x)")
    plt.legend()  # show the legend of labels
    plt.xlabel("x")
    plt.title("The sine and cosine functions");
    #代码作用机制·语法关联·结果易错点
    1import numpy as np同 C10———
    2x = np.linspace(0, 2 * np.pi, 1000)同 C10———
    3plt.plot(x, np.sin(x), label="sin(x)")第一条带 labellabel="sin(x)" 只是登记名字,不会自动显示—忘了调用 legend 则 label 无效
    4plt.plot(x, np.cos(x), label="cos(x)")第二条带 label同一 axes 上再 plot → 叠加,颜色自动换成第二种——
    5plt.legend() # show the legend of labels显示图例plt.legend() 读取所有已登记的 label 画图例框;默认自动找空白位置图例出现label 含下标线可用 r"$\sin x$" LaTeX 语法
    6plt.xlabel("x")x 标签、标题 + 分号同 C10——
    7plt.title("The sine and cosine functions");x 标签、标题 + 分号同 C10——
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Scatter plots


    A scatter plot shows data points as dots (or other markers) without line segments joining the dots. In Matplotlib, two ways of creating scatter plots are specifying the "o" marker in the plot() function, and using the scatter() function. These are demonstrated below.


    Here, 20 (instead of 1000) x values are used so that the dots can be seen clearly. In the plot() function call, the third argument "or" achieves two purposes: "o" for drawing big dots without joining line segments, and "r" for using the red color. The scatter() function draws the big dots using the default blue color.

    Cell 14散点图两种画法:"or" 格式串 与 scatter()基础
    import numpy as np
    x = np.linspace(0, 2 * np.pi, 20)  # 20 points for better view
    plt.plot(x, np.sin(x), "or", label="sin(x)")  # "o" --> big dots; "r" -> red
    plt.scatter(x, np.cos(x), label="cos(x)")
    plt.legend()  # show the legend of labels
    plt.xlabel("x")
    plt.title("The sine and cosine functions");
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2x = np.linspace(0, 2 * np.pi, 20) # 20 points for better view20 个点散点要少点才看得清每个点——
    3plt.plot(x, np.sin(x), "or", label="sin(x)") # "o" --> big dots; "r" -> redplot + 格式串第三个位置参数 "or" = marker "o"(大圆点、不连线)+ color "r"(红);格式串顺序任意 "ro" 也行红色圆点"o" 本身就不连线;"-" 才是线;"-o" 是线+点
    4plt.scatter(x, np.cos(x), label="cos(x)")scatterplt.scatter(x, y) 专用散点函数;默认实心蓝点蓝色圆点scatter 点大小用 s=,plot 用 markersize=
    5plt.legend() # show the legend of labelslegend / xlabel / title / 分号L5 legend 显示图例;L6 x 轴标签;L7 标题 + 分号抑制 Out[]
    分号 = notebook 专有:抑制 Out[] 输出
    6plt.xlabel("x")legend / xlabel / title / 分号L5 legend 显示图例;L6 x 轴标签;L7 标题 + 分号抑制 Out[]
    分号 = notebook 专有:抑制 Out[] 输出
    7plt.title("The sine and cosine functions");legend / xlabel / title / 分号L5 legend 显示图例;L6 x 轴标签;L7 标题 + 分号抑制 Out[]
    分号 = notebook 专有:抑制 Out[] 输出
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Practice - Question 1 of 2

    Q1a


    Write code to create a line graph of the tangent function as follows:


  • Import the `matplotlib.pyplot` and `numpy` modules.
  • Create an array of 1000 `x` values from 0 to 2$\pi$.
  • Create an array called `y` to contain the tangent values of `x`. Use the `np.tan()` function.
  • Plot the `x` and `y` values in a line graph.
  • Set the x-axis label to "x", y-axis label to "tan(x)", the plot title to "The tangent function".
  • Set the y limits of the plot to `[-10, 10]`, by calling `plt.ylim([-10, 10])`. This is done because Matplotlib tries to cater for huge tangent values, which makes the plot difficult to view; setting the y limits omits the effects of the huge tangent values.
  • Cell 17Q1a 你的作答:正切曲线 + ylim练习·作答
    import numpy as np
    import matplotlib.pyplot as plt
    x = np.linspace(0, 2 * np.pi, 1000)
    y = np.tan (x)
    plt.plot (x,y)
    plt.xlabel ("x")
    plt.ylabel ("tan (x)")
    plt.title ("The tangent function")
    plt.ylim (-10, 10)
    plt.show ()
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入两个库顺序无关——
    2import matplotlib.pyplot as plt导入两个库顺序无关——
    3x = np.linspace(0, 2 * np.pi, 1000)1000 个 xlinspace 0–2π——
    4y = np.tan (x)np.tantan 在 π/2、3π/2 处趋向 ±∞,1000 个采样点附近会出现巨大值y 含极大值—
    5plt.plot (x,y)画线———
    6plt.xlabel ("x")标签、标题plt.ylabel ("tan (x)") 函数名与括号之间多了空格——合法但不符 PEP 8—建议 plt.ylabel("tan(x)")
    7plt.ylabel ("tan (x)")标签、标题plt.ylabel ("tan (x)") 函数名与括号之间多了空格——合法但不符 PEP 8—建议 plt.ylabel("tan(x)")
    8plt.title ("The tangent function")标签、标题plt.ylabel ("tan (x)") 函数名与括号之间多了空格——合法但不符 PEP 8—建议 plt.ylabel("tan(x)")
    9plt.ylim (-10, 10)限制 y 轴范围plt.ylim([-10, 10]):否则 Matplotlib 为容纳 ±10¹⁵ 的值把曲线压成一条竖线看到标准正切形状ylim 要在 plot 之后、show 之前
    10plt.show ()show显式渲染当前图并"清空"状态;之后的 plot 会开新图显示图像末行有 show 则不需要分号
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]
    核对:满足题目全部 6 条要求 ✔。

    Q1b


    Write code to create a line graph of the hyperbolic tangent, or tanh, function as follows.


  • Use 1000 `x` values from -5 to 5.
  • Compute the `y` values using the `np.tanh()` function.
  • Plot the `x` and `y` values in a line graph.
  • Set the x-axis and y-axis labels and the plot title properly.
  • Cell 19Q1b 你的作答:tanh 曲线练习·作答
    x = np.linspace (-5, 5, 1000)
    y = np.tanh (x)
    plt.plot (x, y)
    plt.xlabel ("x")
    plt.ylabel ("tanh (x)")
    plt.title ("Hyperbolic Tangent Function")
    plt.show ()
    #代码作用机制·语法关联·结果易错点
    1x = np.linspace (-5, 5, 1000)x 从 −5 到 5题目要求;tanh 在 ±5 已接近 ±1(饱和)—np、plt 已在 C17 导入,notebook 内核里仍可用——但"Restart & Run All"时必须按顺序
    2y = np.tanh (x)np.tanhtanh(x) = (eˣ−e⁻ˣ)/(eˣ+e⁻ˣ),值域 (−1,1),零点中心——Unit 4 激活函数一节的明星S 形曲线—
    3plt.plot (x, y)画图 / 标签 / 标题 / show同 C17——
    4plt.xlabel ("x")画图 / 标签 / 标题 / show同 C17——
    5plt.ylabel ("tanh (x)")画图 / 标签 / 标题 / show同 C17——
    6plt.title ("Hyperbolic Tangent Function")画图 / 标签 / 标题 / show同 C17——
    7plt.show ()画图 / 标签 / 标题 / show同 C17——
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Q1c


    Repeat the tanh plot in part b but using a scatter plot instead of a line graph. Specifically, copy the above program and make these changes:


  • Use 50 `x` values (instead of 1000).
  • Create a scatter plot (instead of a line graph). You may use either `plot()` or `scatter()`.
  • Cell 21Q1c 你的作答:tanh 散点(50 点)练习·作答
    x = np.linspace (-5, 5, 50)
    y = np.tanh (x)
    plt.scatter (x, y)
    plt.xlabel ("x")
    plt.ylabel ("tanh (x)")
    plt.title ("Hyperbolic Tangent Scatter Plot")
    plt.show ()
    #代码作用机制·语法关联·结果易错点
    1x = np.linspace (-5, 5, 50)50 个点题目要求改 1000 → 50——
    2y = np.tanh (x)tanh———
    3plt.scatter (x, y)scatter题目允许 plot 或 scatter 二选一,你选了 scatter ✔——
    4plt.xlabel ("x")标签 / 标题 / show———
    5plt.ylabel ("tanh (x)")标签 / 标题 / show———
    6plt.title ("Hyperbolic Tangent Scatter Plot")标签 / 标题 / show———
    7plt.show ()标签 / 标题 / show———
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    &#x2766;

    Running Keras code and plotting history

    In this section, some Keras programs are provided to you for execution and plotting of history. Note that it is not required that you fully understand the Keras code, which is not the goal of this lesson.

    Perceptron and OR gate


    The program below simulates a perceptron (which has output of either exactly 0 or 1) by a Keras sigmoid neuron (which has output of a floating point number between 0.0 and 1.0). The program trains the neuron, i.e. the model, to predict the OR gate outputs, and then displays the actual outputs and predicted outputs for the 4 training examples.

    先看清结构:C26 / C35 / C42 / C47 四段代码逐行同构,差异只有三处——y = X[:,0] | X[:,0] 的运算符(| OR、^ XOR、& AND)和 Sequential([...]) 里是 1 层还是 2 层。读 C26 时把每行看懂,后面三段只需看"差异列"。
    Cell 26感知机 = 单个 sigmoid 神经元 学 OR 门(★ 全课 Keras 母版)重点展开
    # Simulate a perceptron by a sigmoid neuron,
    # with a float output between 0.0 and 1.0.
    import numpy as np
    from tensorflow import keras
    X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
    y = X[:, 0] | X[:, 1]
    keras.utils.set_random_seed(42)
    model = keras.models.Sequential([
        keras.layers.Dense(1, activation="sigmoid")
    ])
    opt = keras.optimizers.RMSprop(learning_rate=.1)
    model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])
    history = model.fit(X, y, epochs=300, verbose=0)
    y_pred = model.predict(X, verbose=0)
    print("Actual y:", y)
    print("Predicted y:", y_pred.round(2).ravel())
    #代码作用机制·语法关联·结果易错点
    1# Simulate a perceptron by a sigmoid neuron,注释说明用 sigmoid 神经元(输出 0.0–1.0 的浮点)模拟感知机(输出恰为 0 或 1)——
    2# with a float output between 0.0 and 1.0.注释说明用 sigmoid 神经元(输出 0.0–1.0 的浮点)模拟感知机(输出恰为 0 或 1)——
    3import numpy as np导入 NumPy———
    4from tensorflow import keras导入 Kerasfrom tensorflow import keras:Keras 已内置于 TensorFlow 2.x;统一用 keras.xxx 前缀—单独 import keras 会装独立的 Keras 3 包,API 有差异——本课一律从 tensorflow 导入
    5X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])输入矩阵 X4 个样本 × 2 个特征,形状 (4, 2);np.array 把 list-of-lists 变矩阵X = [[0,0],[0,1],[1,0],[1,1]]Keras Dense 的 input_shape 从这里推断为 (2,),不用手写 InputLayer
    6y = X[:, 0] | X[:, 1]标签 y = ORX[:,0] 取第 0 列(t01 C56),| 是按位或 → [0,1,1,1]y shape (4,)int 类型的 0/1 正好配 binary_crossentropy;不需要 one-hot
    7keras.utils.set_random_seed(42)统一随机种子keras.utils.set_random_seed(42) 一次设 Python random / NumPy / TensorFlow 三个 RNG → 权重初始化可复现—只在开头设一次;t01 的 np.random.seed 只管 NumPy
    8model = keras.models.Sequential([定义模型keras.models.Sequential([...]):层按顺序堆叠;Dense(1, activation="sigmoid"):1 个神经元、权重 W 形状 (2,1)、偏置 b 形状 (1,)、输出 σ(w·x+b) ∈ (0,1)。参数共 2+1 = 3 个model 是 Sequential 对象,尚未编译activation 写在层里等价于后面加 keras.layers.Activation("sigmoid")
    9 keras.layers.Dense(1, activation="sigmoid")定义模型keras.models.Sequential([...]):层按顺序堆叠;Dense(1, activation="sigmoid"):1 个神经元、权重 W 形状 (2,1)、偏置 b 形状 (1,)、输出 σ(w·x+b) ∈ (0,1)。参数共 2+1 = 3 个model 是 Sequential 对象,尚未编译activation 写在层里等价于后面加 keras.layers.Activation("sigmoid")
    10])定义模型keras.models.Sequential([...]):层按顺序堆叠;Dense(1, activation="sigmoid"):1 个神经元、权重 W 形状 (2,1)、偏置 b 形状 (1,)、输出 σ(w·x+b) ∈ (0,1)。参数共 2+1 = 3 个model 是 Sequential 对象,尚未编译activation 写在层里等价于后面加 keras.layers.Activation("sigmoid")
    11opt = keras.optimizers.RMSprop(learning_rate=.1)优化器RMSprop(learning_rate=.1):默认 ρ=0.9;lr 0.1 比常见 0.001 大 100 倍——因为只有 4 个样本、3 个参数,大步长才快opt 对象lr 太大在真实数据上会震荡——这里只是教学
    12model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])编译compile 把 loss、optimizer、metrics 绑定进计算图;binary_crossentropy = 二分类交叉熵(配 sigmoid 单输出);metrics=["acc"] 让 history 里多一个 "acc" 键("acc" 是 "accuracy" 的旧别名,仍可用)model 可训练fit 之前必须 compile,否则报 "You must compile your model";loss 名字符串自动映射到 keras.losses
    13history = model.fit(X, y, epochs=300, verbose=0)训练fit(X, y, epochs=300, verbose=0):每轮用全部 4 个样本算一次梯度(batch_size 默认 32 > 4,所以每轮就是 1 步);300 轮 = 300 步;verbose=0 静默(1=进度条,2=每轮一行);返回 History 对象history = History没有 validation_split → history 里只有 loss/acc 没有 val_*;verbose=0 时 fit 不打印任何东西
    14y_pred = model.predict(X, verbose=0)预测model.predict(X, verbose=0):前向传播算 σ 输出,形状 (4,1)y_pred [[0.00],[1.00],[1.00],[1.00]]predict 输出是概率不是 0/1;要 0/1 需 (y_pred>0.5).astype(int)
    15print("Actual y:", y)打印真实标签—Actual y: [0 1 1 1]—
    16print("Predicted y:", y_pred.round(2).ravel())打印预测.round(2) 保留两位;.ravel() 把 (4,1) 拉平成 (4,) 便于阅读Predicted y: [0. 1. 1. 1.] ✔不 ravel 会显示 [[0.],[1.],[1.],[1.]]
    运行结果 WARNING:tensorflow:5 out of the last 5 calls to <function TensorFlowTrainer.make_predict_function.<locals>.one_step_on_data_distributed at 0x7b191c51bd80> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorfl Actual y: [0 1 1 1] Predicted y: [0. 1. 1. 1.]
    深挖 · 这 16 行是整门课的骨架:把 C26 与 t04–t11 的任何一段 Keras 代码对照,都是这五步:
    ① 数据 (X, y) → ② set_random_seed → ③ Sequential([...]) 堆层 → ④ compile(loss, optimizer, metrics) → ⑤ fit 返回 history → ⑥ predict / 画 history。
    参数计算:Dense(1) 输入 2 维 → W (2×1) + b (1) = 3。OR 门的真值表在 (x₁,x₂) 平面上是四个点,y=1 的三个点可以用一条直线把它们与 (0,0) 分开 → 线性可分 → 3 个参数就够。
    为什么用 RMSprop 而不是 SGD:讲义 Unit 7 p33+ 讲优化器时你会再见到它——RMSprop 对每个参数自适应步长,在tiny 数据上收敛快;这里只是沿用课程模板。
    WARNING:tensorflow ... retracing:predict 在 fit 之后第一次调用会重新追踪(trace)tf.function,只是性能提示,不是错误;可忽略。

    As the actual outputs equal the predicted outputs, the model seems to be able to predict the OR gate outputs. Let's plot the performance of the model when it is trained. The training history is returned by model.fit(); note that history.history is a dictionary with two keys: "loss" and "acc".

    Cell 28看 history 的类型和键基础
    print(type(history.history))
    print(history.history.keys())
    #代码作用机制·语法关联·结果易错点
    1print(type(history.history))类型History 对象的 .history 属性是 dict(t01 C80)history 本身是 keras.callbacks.History,history.history 才是字典
    2print(history.history.keys())查看键keys() 返回所有指标名;compile 里的 metrics=["acc"] 决定了有 "acc"dict_keys(['acc', 'loss'])若写 metrics=["accuracy"] 键名就是 "accuracy"——画图时写错键名会 KeyError
    运行结果 <class 'dict'> dict_keys(['acc', 'loss'])

    All in all, history.history["loss"] is a list of loss, or error, values for different epochs. history.history["acc"] is a list of accuracy values for different epochs.

    This is a plot of the training loss, which decreases steadily to about 0 in 200 epochs.

    Cell 31画 OR 的训练 loss基础
    import matplotlib.pyplot as plt
    plt.plot(history.history["loss"])
    plt.xlabel("Epochs")
    plt.ylabel("Loss");
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入———
    2plt.plot(history.history["loss"])画 300 个 losshistory.history["loss"] 是长度 300 的 list,plot(y) 自动以轮次为 xloss 在约 200 轮内稳定降到 ≈0—
    3plt.xlabel("Epochs")轴标签 + 分号———
    4plt.ylabel("Loss");轴标签 + 分号———
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    This is a plot of the training accuracy, which becomes 1.0 in a smaller number (<50) of epochs.

    Cell 33画 OR 的训练 acc基础
    plt.plot(history.history["acc"])
    plt.xlabel("Epochs")
    plt.ylabel("Accuracy");
    #代码作用机制·语法关联·结果易错点
    1plt.plot(history.history["acc"])画 accacc 在 <50 轮内就到 1.0——比 loss 快,因为 acc 只看 >0.5 的阈值是否正确曲线迅速到 1.0acc=1.0 不代表 loss=0:loss 还在继续把概率从 0.6 推向 1.0
    2plt.xlabel("Epochs")标签 + 分号———
    3plt.ylabel("Accuracy");标签 + 分号———
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Perceptron and XOR gate


    The following program simulates a perceptron by a sigmoid neuron for predicting the XOR gate outputs.

    Cell 35同一个神经元学 XOR:失败重点展开
    # Simulate a perceptron by a sigmoid neuron,
    # with a float output between 0.0 and 1.0.
    import numpy as np
    from tensorflow import keras
    X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
    y = X[:, 0] ^ X[:, 1]
    keras.utils.set_random_seed(42)
    model = keras.models.Sequential([
        keras.layers.Dense(1, activation="sigmoid")
    ])
    opt = keras.optimizers.RMSprop(learning_rate=.1)
    model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])
    history = model.fit(X, y, epochs=300, verbose=0)
    y_pred = model.predict(X, verbose=0)
    print("Actual y:", y)
    print("Predicted y:", y_pred.round(2).ravel())
    #代码作用机制·语法关联·结果易错点
    1# Simulate a perceptron by a sigmoid neuron,注释同 C26——
    2# with a float output between 0.0 and 1.0.注释同 C26——
    3import numpy as np导入重复导入无害——
    4from tensorflow import keras导入重复导入无害——
    5X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])X 同上—(4,2)—
    6y = X[:, 0] ^ X[:, 1]y = XOR^ 按位异或:不同为 1 → [0,1,1,0]y关键差异 #1:这四个点不能被一条直线分开((0,0) 和 (1,1) 是 0,(0,1) 和 (1,0) 是 1——两类在对角)
    7keras.utils.set_random_seed(42)seed同 C26——
    8model = keras.models.Sequential([仍是 1 个神经元Dense(1) = 线性决策边界 σ(w₁x₁+w₂x₂+b)3 个参数关键差异 #2:模型没变,所以注定学不会
    9 keras.layers.Dense(1, activation="sigmoid")仍是 1 个神经元Dense(1) = 线性决策边界 σ(w₁x₁+w₂x₂+b)3 个参数关键差异 #2:模型没变,所以注定学不会
    10])仍是 1 个神经元Dense(1) = 线性决策边界 σ(w₁x₁+w₂x₂+b)3 个参数关键差异 #2:模型没变,所以注定学不会
    11opt = keras.optimizers.RMSprop(learning_rate=.1)优化器 / 编译同 C26——
    12model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])优化器 / 编译同 C26——
    13history = model.fit(X, y, epochs=300, verbose=0)训练 300 轮同 C26loss 停在 ≈0.69—
    14y_pred = model.predict(X, verbose=0)预测输出全部 ≈ 0.5y_pred ≈ [0.49,0.48,0.48,0.46]round(2) 后四舍五入显示 0.49 等;没有一个 >0.5 或 <0.5 有把握
    15print("Actual y:", y)打印真实 vs 预测对比Actual [0 1 1 0] vs Pred [0.49 0.48 0.48 0.46]预测若四舍五入到整数是 [0,0,0,0] → acc 0.5
    16print("Predicted y:", y_pred.round(2).ravel())打印真实 vs 预测对比Actual [0 1 1 0] vs Pred [0.49 0.48 0.48 0.46]预测若四舍五入到整数是 [0,0,0,0] → acc 0.5
    运行结果 WARNING:tensorflow:6 out of the last 6 calls to <function TensorFlowTrainer.make_predict_function.<locals>.one_step_on_data_distributed at 0x7b191c5dca40> triggered tf.function retracing. Tracing is expensive and the excessive number of tracings could be due to (1) creating @tf.function repeatedly in a loop, (2) passing tensors with different shapes, (3) passing Python objects instead of tensors. For (1), please define your @tf.function outside of the loop. For (2), @tf.function has reduce_retracing=True option that can avoid unnecessary retracing. For (3), please refer to https://www.tensorfl Actual y: [0 1 1 0] Predicted y: [0.49 0.48 0.48 0.46]
    深挖 · 单个神经元为什么学不会 XOR:神经元输出 σ(w₁x₁+w₂x₂+b),决策边界是平面上一条直线 w₁x₁+w₂x₂+b=0。要让 (0,1)、(1,0) 在直线一侧、(0,0)、(1,1) 在另一侧——任何直线都做不到(画一下就知道)。于是模型只能"和稀泥":让所有输出尽量靠近 0.5,此时交叉熵 = −ln 0.5 = 0.693,正好是 C37 图里的平台值。这就是 Minsky & Papert 1969 年《Perceptrons》对感知机的经典批评,也是"AI 寒冬"的导火索——解法就是 Unit 2 p29+ 的多层感知机(C47)。

    The differences between the actual outputs and predicted outputs indicate that a perceptron cannot predict the XOR gate outputs.


    In the plot of the training loss below, the loss decreases initially but note that all the loss values are about 0.7! This is not good!


    Note that the code cell below must be executed after executing the preceding code cell, so that the history variable refers to the correct data. history refers to different objects throughout this notebook!

    为什么 loss 卡在 0.69:二分类交叉熵 −[y·ln p + (1−y)·ln(1−p)],当模型对每个样本都输出 p ≈ 0.5 时,−ln 0.5 = 0.693,这就是"模型什么都没学到"的理论值。讲义 Unit 2 p24–p28 用感知机的几何解释(一条直线分不开 XOR 的四个点),这里是数值证据。
    Cell 37画 XOR 的 loss:卡在 0.69基础
    plt.plot(history.history["loss"])
    plt.xlabel("Epochs")
    plt.ylabel("Loss");
    #代码作用机制·语法关联·结果易错点
    1plt.plot(history.history["loss"])画 loss注意 history 此刻指的是 C35 的对象(M36 的提醒:同一变量名在 notebook 中反复指向不同对象)loss 从 ≈0.75 快速降到 0.69 后水平若先跑 C26 再跑 C37 不跑 C35,画的是 OR 的曲线——顺序错了图就错
    2plt.xlabel("Epochs")标签 + 分号———
    3plt.ylabel("Loss");标签 + 分号———
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    In the plot of the training accuracy below, the accuracy values are mostly 0.5 -- not a good result.

    Cell 39画 XOR 的 acc:卡在 0.5基础
    plt.plot(history.history["acc"])
    plt.xlabel("Epochs")
    plt.ylabel("Accuracy");
    #代码作用机制·语法关联·结果易错点
    1plt.plot(history.history["acc"])画 acc输出 ≈0.5 → 阈值 0.5 附近随机翻转 → acc 在 0.25–0.75 抖动,均值 0.5—"not a good result"—
    2plt.xlabel("Epochs")标签 + 分号———
    3plt.ylabel("Accuracy");标签 + 分号———
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Practice - Question 2 of 2

    Q2a (Perceptron and AND gate)


    The following program simulates a perceptron by a sigmoid neuron for predicting the AND gate outputs.

    Cell 42Q2a 同一个神经元学 AND:成功练习·作答
    # Simulate a perceptron by a sigmoid neuron,
    # with a float output between 0.0 and 1.0.
    import numpy as np
    from tensorflow import keras
    X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
    y = X[:, 0] & X[:, 1]
    keras.utils.set_random_seed(42)
    model = keras.models.Sequential([
        keras.layers.Dense(1, activation="sigmoid")
    ])
    opt = keras.optimizers.RMSprop(learning_rate=.1)
    model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])
    history = model.fit(X, y, epochs=300, verbose=0)
    y_pred = model.predict(X, verbose=0)
    print("Actual y:", y)
    print("Predicted y:", y_pred.round(2).ravel())
    #代码作用机制·语法关联·结果易错点
    1# Simulate a perceptron by a sigmoid neuron,同 C26注释 / 导入 / X——
    2# with a float output between 0.0 and 1.0.同 C26注释 / 导入 / X——
    3import numpy as np同 C26注释 / 导入 / X——
    4from tensorflow import keras同 C26注释 / 导入 / X——
    5X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])同 C26注释 / 导入 / X——
    6y = X[:, 0] & X[:, 1]y = AND& 按位与 → [0,0,0,1]只有 (1,1) 为 1AND 与 OR 对称:把 OR 的权重取负就是 AND,所以同样线性可分
    7keras.utils.set_random_seed(42)seed / 单神经元 / RMSprop / compile / fit与 C26 完全相同——
    8model = keras.models.Sequential([seed / 单神经元 / RMSprop / compile / fit与 C26 完全相同——
    9 keras.layers.Dense(1, activation="sigmoid")seed / 单神经元 / RMSprop / compile / fit与 C26 完全相同——
    10])seed / 单神经元 / RMSprop / compile / fit与 C26 完全相同——
    11opt = keras.optimizers.RMSprop(learning_rate=.1)seed / 单神经元 / RMSprop / compile / fit与 C26 完全相同——
    12model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])seed / 单神经元 / RMSprop / compile / fit与 C26 完全相同——
    13history = model.fit(X, y, epochs=300, verbose=0)seed / 单神经元 / RMSprop / compile / fit与 C26 完全相同——
    14y_pred = model.predict(X, verbose=0)预测 + 打印—Pred [0. 0. 0. 1.] ✔ 全对—
    15print("Actual y:", y)预测 + 打印—Pred [0. 0. 0. 1.] ✔ 全对—
    16print("Predicted y:", y_pred.round(2).ravel())预测 + 打印—Pred [0. 0. 0. 1.] ✔ 全对—
    运行结果 Actual y: [0 0 0 1] Predicted y: [0. 0. 0. 1.]

    Write code to create a plot of the training loss and a plot of the training accuracy. Make sure that you execute the above code cell and then your code cells of plotting.

    Cell 44Q2a 你的作答:画 AND 的 loss(用 show)练习·作答
    import matplotlib.pyplot as plt
    plt.plot (history.history ['loss'])
    plt.title ('Training Loss')
    plt.ylabel ('Loss')
    plt.xlabel ('Epochs')
    plt.show ()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入———
    2plt.plot (history.history ['loss'])画 losshistory.history ['loss'] 键前多空格——合法loss → 0—
    3plt.title ('Training Loss')标题 / y / x 标签你加了 title,题目没要求但更好——
    4plt.ylabel ('Loss')标题 / y / x 标签你加了 title,题目没要求但更好——
    5plt.xlabel ('Epochs')标题 / y / x 标签你加了 title,题目没要求但更好——
    6plt.show ()show显式显示—用了 show 就不需要分号
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]
    Cell 45Q2a 你的作答:画 AND 的 acc练习·作答
    plt.plot (history.history ['acc'])
    plt.title ('Training Accuracy')
    plt.ylabel ('Accuracy')
    plt.xlabel ('Epochs')
    plt.show ()
    #代码作用机制·语法关联·结果易错点
    1plt.plot (history.history ['acc'])画 acc—acc → 1.0—
    2plt.title ('Training Accuracy')标签 + show———
    3plt.ylabel ('Accuracy')标签 + show———
    4plt.xlabel ('Epochs')标签 + show———
    5plt.show ()标签 + show———
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Q2b (MLP and XOR gate)


    The following program simulates a MLP of perceptrons by a MLP of sigmoid neurons for predicting the XOR gate outputs.

    Cell 47Q2b MLP(2 隐神经元)学 XOR:成功重点展开
    # Simulate perceptrons in a MLP by sigmoid neurons,
    # with a float output between 0.0 and 1.0.
    import numpy as np
    from tensorflow import keras
    X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
    y = X[:, 0] ^ X[:, 1]
    keras.utils.set_random_seed(42)
    model = keras.models.Sequential([  # MLP
        keras.layers.Dense(2, activation="sigmoid"),
        keras.layers.Dense(1, activation="sigmoid")
    ])
    opt = keras.optimizers.RMSprop(learning_rate=.1)
    model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])
    history = model.fit(X, y, epochs=300, verbose=0)
    y_pred = model.predict(X, verbose=0)
    print("Actual y:", y)
    print("Predicted y:", y_pred.round(2).ravel())
    #代码作用机制·语法关联·结果易错点
    1# Simulate perceptrons in a MLP by sigmoid neurons,注释"perceptrons in a MLP"——多个感知机堆成多层——
    2# with a float output between 0.0 and 1.0.注释"perceptrons in a MLP"——多个感知机堆成多层——
    3import numpy as np导入 / X / y=XOR与 C35 完全相同——
    4from tensorflow import keras导入 / X / y=XOR与 C35 完全相同——
    5X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])导入 / X / y=XOR与 C35 完全相同——
    6y = X[:, 0] ^ X[:, 1]导入 / X / y=XOR与 C35 完全相同——
    7keras.utils.set_random_seed(42)seed———
    8model = keras.models.Sequential([ # MLPSequential 开始# MLP 注释标记:接下来是两层——
    9 keras.layers.Dense(2, activation="sigmoid"),隐藏层 Dense(2, sigmoid)2 个神经元,输入 2 维 → W (2×2)=4 + b (2)=2 → 6 个参数;输出 2 维,可理解为"把输入映射到平面上另一个 2 维表示"隐藏层输出 h ∈ (0,1)²关键差异:有隐藏层 = 有非线性变换 = 决策边界可以是曲线
    10 keras.layers.Dense(1, activation="sigmoid")输出层 Dense(1, sigmoid)输入 2 维(隐藏层输出)→ W (2×1)=2 + b 1 = 3 个参数总参数 6+3 = 9第二层不用写 input_shape,Keras 自动从上一层输出推断
    11])RMSprop同 C26 lr=.1——
    12opt = keras.optimizers.RMSprop(learning_rate=.1)compile同 C26——
    13model.compile(loss="binary_crossentropy", optimizer=opt, metrics=["acc"])fit 300 轮同 C26;但 9 个参数比 3 个难优化——需要约 200 轮 loss 才接近 0(Q2c)history—
    14history = model.fit(X, y, epochs=300, verbose=0)预测 / 打印—Pred [0. 1. 1. 0.] ✔显示 "1." 和 "0." 是 round(2) 后的浮点格式
    15y_pred = model.predict(X, verbose=0)预测 / 打印—Pred [0. 1. 1. 0.] ✔显示 "1." 和 "0." 是 round(2) 后的浮点格式
    16print("Actual y:", y)预测 / 打印—Pred [0. 1. 1. 0.] ✔显示 "1." 和 "0." 是 round(2) 后的浮点格式
    17print("Predicted y:", y_pred.round(2).ravel())预测 / 打印—Pred [0. 1. 1. 0.] ✔显示 "1." 和 "0." 是 round(2) 后的浮点格式
    运行结果 Actual y: [0 1 1 0] Predicted y: [0. 1. 1. 0.]
    深挖 · 为什么加一层就会了:隐藏层两个 sigmoid 神经元各自画一条直线,例如 h₁ ≈ OR(x)、h₂ ≈ NAND(x);输出层对 (h₁,h₂) 再画一条直线,等价于 AND → NAND ∧ OR = XOR。两层直线折起来就能围出对角区域——这就是"多层"的意义:用多个线性边界组合成非线性边界。参数 9 个(6+3),是 C35 的 3 倍,所以优化更慢(Q2c 答 ≈200 轮)。
    与本讲义的对应:Unit 2 p16–p28 感知机(= C26/C35/C42 的单个神经元)、p29–p33 多层感知机(= C47)、p34–p38 讲为什么需要非线性激活——如果把 C47 的 sigmoid 都去掉,两层 Dense 叠加仍是线性的(W₂W₁x + ...),XOR 照样学不会。

    Write code to create a plot of the training loss and a plot of the training accuracy. Make sure that you execute the above code cell and then your code cells of plotting.

    Cell 49Q2b 你的作答:画 MLP 的 loss练习·作答
    import matplotlib.pyplot as plt
    plt.plot (history.history ['loss'])
    plt.title ('Training Loss')
    plt.xlabel ('Epochs')
    plt.ylabel ('Loss')
    plt.show ()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt画 loss / 标题 / show同 C44;注意此 history 是 C47 的loss:前 50 轮慢、100–200 轮快降、之后 ≈0—
    2plt.plot (history.history ['loss'])画 loss / 标题 / show同 C44;注意此 history 是 C47 的loss:前 50 轮慢、100–200 轮快降、之后 ≈0—
    3plt.title ('Training Loss')画 loss / 标题 / show同 C44;注意此 history 是 C47 的loss:前 50 轮慢、100–200 轮快降、之后 ≈0—
    4plt.xlabel ('Epochs')画 loss / 标题 / show同 C44;注意此 history 是 C47 的loss:前 50 轮慢、100–200 轮快降、之后 ≈0—
    5plt.ylabel ('Loss')画 loss / 标题 / show同 C44;注意此 history 是 C47 的loss:前 50 轮慢、100–200 轮快降、之后 ≈0—
    6plt.show ()画 loss / 标题 / show同 C44;注意此 history 是 C47 的loss:前 50 轮慢、100–200 轮快降、之后 ≈0—
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]
    Cell 50Q2b 你的作答:画 MLP 的 acc练习·作答
    plt.plot(history.history['acc'])
    plt.title('Training Accuracy')
    plt.xlabel('Epochs')
    plt.ylabel('Accuracy')
    plt.show()
    #代码作用机制·语法关联·结果易错点
    1plt.plot(history.history['acc'])画 acc / 标题 / show这次没有空格——PEP 8 风格 ✔acc 阶梯式上升到 1.0—
    2plt.title('Training Accuracy')画 acc / 标题 / show这次没有空格——PEP 8 风格 ✔acc 阶梯式上升到 1.0—
    3plt.xlabel('Epochs')画 acc / 标题 / show这次没有空格——PEP 8 风格 ✔acc 阶梯式上升到 1.0—
    4plt.ylabel('Accuracy')画 acc / 标题 / show这次没有空格——PEP 8 风格 ✔acc 阶梯式上升到 1.0—
    5plt.show()画 acc / 标题 / show这次没有空格——PEP 8 风格 ✔acc 阶梯式上升到 1.0—
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Q2c


    In part b above, the data and model are simple, and more training epochs achieve better performance. Referring to the plot of training loss in part b, answer the following questions.


    1. Is the training loss close to zero in 50 epochs?

    1. Is the training loss close to zero in 200 epochs?

    1. What is the smallest number of epochs that achieves a training loss close to zero?

    Solution:



    <div class='alert alert-warning' role='alert'><b>1.No. 2.Yes. 3.Around 200 epochs</b></div>
    Q2c 你的作答核对:1. No ✔(50 轮时 loss 仍在 0.3–0.4);2. Yes ✔(200 轮后接近 0);3. "Around 200 epochs" ✔——与 C49 的 loss 曲线吻合(前 50 轮缓慢,100–200 轮快速下降,之后趋平)。

    &#x2766;

    Extras

    Creating multiple subplots in a figure


    Matplotlib supports putting multiple subplots in a figure, with a layout of a table or grid. Subplots can be created using the subplot(nrows, ncols, index) function, where the 3 parameters specify the number of rows of subplots, the number of columns of subplots, and the index of the current subplot to work on.


    In the example below, subplot(1, 2, 1) specifies to use 2 subplots in 1 row and 2 columns and to work on the first subplot subsequently; after that, we plot a sine curve in the first subplot using the plot() function and so on. Similarly, subplot(1, 2, 2) specifies to use 2 subplots again but then to work on the second subplot subsequently; after that, we plot the cosine curve in the second subplot.


    The call to figure(figsize=[8, 4]) near the beginning sets a figure size of 8 inches by 4 inches; this fits the two subplots to a better aspect ratio. The call to tight_layout() near the end sets a tight layout to avoid overlapping of the subplots.

    Cell 56subplot(1,2,k):一张图两个子图基础
    import matplotlib.pyplot as plt
    import numpy as np
    x = np.linspace(0, 2 * np.pi, 1000)
    plt.figure(figsize=[8, 4])
    plt.subplot(1, 2, 1)  # 1 row, 2 columns, do 1st plot; same as subplot(121)
    plt.plot(x, np.sin(x))
    plt.xlabel("x")
    plt.ylabel("sin(x)")
    plt.title("The sine function")
    plt.subplot(1, 2, 2)  # 1 row, 2 columns, do 2nd plot; same as subplot(122)
    plt.plot(x, np.cos(x))
    plt.xlabel("x")
    plt.ylabel("cos(x)")
    plt.title("The cosine function")
    plt.tight_layout()  # fit layout and spacing
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入———
    2import numpy as np导入———
    3x = np.linspace(0, 2 * np.pi, 1000)xlinspace 1000 点——
    4plt.figure(figsize=[8, 4])设图幅大小plt.figure(figsize=[宽, 高]),单位英寸;默认 (6.4, 4.8)8×4 英寸要在 subplot 之前调用,否则会开新图
    5plt.subplot(1, 2, 1) # 1 row, 2 columns, do 1st plot; same as subplot(121)定位第 1 个子图subplot(nrows, ncols, index):1 行 2 列的第 1 格(index 从 1 数起);之后 plot/xlabel 都画在这一格当前 axes = 左子图三位数简写 subplot(121) 等价,但 nrows>9 时不能简写
    6plt.plot(x, np.sin(x))左图画 sin———
    7plt.xlabel("x")左图画 sin———
    8plt.ylabel("sin(x)")左图画 sin———
    9plt.title("The sine function")左图画 sin———
    10plt.subplot(1, 2, 2) # 1 row, 2 columns, do 2nd plot; same as subplot(122)定位第 2 个子图切到右格当前 axes = 右子图忘记切换会把两条线画在同一格
    11plt.plot(x, np.cos(x))右图画 cos———
    12plt.xlabel("x")右图画 cos———
    13plt.ylabel("cos(x)")右图画 cos———
    14plt.title("The cosine function")右图画 cos———
    15plt.tight_layout() # fit layout and spacingtight_layout自动调整子图间距,防止标题/标签重叠—建议习惯性加在最后
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    E1a

    Create a figure of 3 subplots: the sine, cosine, and tangent functions. Refer to the above example of 2 subplots and remember to set the y limits of the tangent subplot to [-10, 10].

    Solutions to extra exercises

    E1a
    Cell 60E1a 解答:1×3 子图(sin / cos / tan)练习·作答
    # Solution
    import matplotlib.pyplot as plt
    import numpy as np
    x = np.linspace(0, 2 * np.pi, 1000)
    plt.figure(figsize=[9, 3])
    plt.subplot(1, 3, 1)  # same as subplot(131)
    plt.plot(x, np.sin(x))
    plt.xlabel("x")
    plt.ylabel("sin(x)")
    plt.title("The sine function")
    plt.subplot(1, 3, 2)  # same as subplot(132)
    plt.plot(x, np.cos(x))
    plt.xlabel("x")
    plt.ylabel("cos(x)")
    plt.title("The cosine function")
    plt.subplot(1, 3, 3)  # same as subplot(133)
    plt.plot(x, np.tan(x))
    plt.xlabel("x")
    plt.ylabel("tan(x)")
    plt.title("The tangent function")
    plt.ylim([-10, 10])
    plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1# Solution导入 / x / 图幅 9×3更宽的图容纳 3 格——
    2import matplotlib.pyplot as plt导入 / x / 图幅 9×3更宽的图容纳 3 格——
    3import numpy as np导入 / x / 图幅 9×3更宽的图容纳 3 格——
    4x = np.linspace(0, 2 * np.pi, 1000)导入 / x / 图幅 9×3更宽的图容纳 3 格——
    5plt.figure(figsize=[9, 3])第 1 格 sinsubplot(1,3,1)——
    6plt.subplot(1, 3, 1) # same as subplot(131)第 1 格 sinsubplot(1,3,1)——
    7plt.plot(x, np.sin(x))第 1 格 sinsubplot(1,3,1)——
    8plt.xlabel("x")第 1 格 sinsubplot(1,3,1)——
    9plt.ylabel("sin(x)")第 1 格 sinsubplot(1,3,1)——
    10plt.title("The sine function")第 2 格 cossubplot(1,3,2)——
    11plt.subplot(1, 3, 2) # same as subplot(132)第 2 格 cossubplot(1,3,2)——
    12plt.plot(x, np.cos(x))第 2 格 cossubplot(1,3,2)——
    13plt.xlabel("x")第 2 格 cossubplot(1,3,2)——
    14plt.ylabel("cos(x)")第 2 格 cossubplot(1,3,2)——
    15plt.title("The cosine function")第 3 格 tansubplot(1,3,3)——
    16plt.subplot(1, 3, 3) # same as subplot(133)第 3 格 tansubplot(1,3,3)——
    17plt.plot(x, np.tan(x))第 3 格 tansubplot(1,3,3)——
    18plt.xlabel("x")第 3 格 tansubplot(1,3,3)——
    19plt.ylabel("tan(x)")第 3 格 tansubplot(1,3,3)——
    20plt.title("The tangent function")第 3 格 tansubplot(1,3,3)——
    21plt.ylim([-10, 10])tan 的 ylim只对当前(第 3)子图生效——ylim 作用于当前 axes第 3 格 y 轴 ±10若放在 subplot 之前会错位到别的格
    22plt.tight_layout()tight_layout———
    运行结果 <Figure size 900x300 with 3 Axes> [image/png]

    &#x2766;

    📘 Tutorial 3(= Lab 3)· NumPy 线性代数(点积 / 矩阵乘)· 手算 sigmoid 神经元 · 整数数组与布尔数组索引

    t03-s13903054.ipynb,83 cells。对应 Unit 3 讲义 p1–p50 的"数学工具":向量点积、矩阵乘法、形状规则;Q2 用 Keras 的 set_weights 把一个 Dense 神经元的参数固定下来,再用 NumPy 手算 z = w·x + b → σ(z),验证与 model.predict 完全一致(0.6899745)——这就是 Unit 5 反向传播手算的预备动作。后半:整数数组索引(选行、重排)、argsort 排序平行数组、布尔掩码筛选。
    本讲三个必会:① 矩阵乘法形状规则 (n,k) @ (k,m) → (n,m):相邻维度必须相等——这是 Dense 层 W (in, out) 的来源,也是 C23 那条 "size 5 is different from 3" 报错的根源;② 神经元的两步:线性部分 z = w·x + b(点积 + 偏置)→ 激活 σ(z),Keras 的 Dense 层做的就是这个;③ 平行数组(特征 + 标签)必须用同一个索引数组去取(argsort / 布尔掩码),各自 sort 会打散对应关系——这是 t06+ 做 train/validation 切分和 t09 做数据增强时反复用到的原则。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同 t02 C2IPython 魔术命令设环境变量,过滤 INFO/WARNINGenv: TF_CPP_MIN_LOG_LEVEL=2须在 import tensorflow 之前
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • basic linear algebra using NumPy, and
  • more NumPy array indexing.
  • Student name: Yin Bang
    Student ID: 13903054

    Basic linear algebra using NumPy

    Linear algebra is an important topic in the implementation of neural networks. In this section, we examine dot product and matrix product using the NumPy library.

    Dot product of vectors


    Let's begin with basic vector operations. The code below creates two vectors as 1D NumPy arrays, a and b, both with shape (3,).

    Cell 8两个一维向量 a、b,shape (3,)基础
    import numpy as np
    a = np.array([1, 2, 3])
    b = np.array([10, 20, 30])
    print(a, a.shape)
    print(b, b.shape)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2a = np.array([1, 2, 3])a一维数组 shape (3,)——t01 C46 强调过 (3,) 是 tuple[1 2 3](3,) 不是 (3,1):前者是向量,后者是 3×1 矩阵
    3b = np.array([10, 20, 30])b—[10 20 30]—
    4print(a, a.shape)打印同时打印形状,确认都是一维(3,) (3,)—
    5print(b, b.shape)打印同时打印形状,确认都是一维(3,) (3,)—
    运行结果 [1 2 3] (3,) [10 20 30] (3,)

    NumPy supports element-wise operations, such as using the +, -, , and / operators. In the following, a + 100 adds 100 to each element of a; a + b adds the corresponding elements in a and b, and a b multiplies the corresponding elements in a and b. In all 3 cases, the results are 1D arrays with shape (3,).

    Cell 10逐元素运算:标量广播、向量加、向量乘基础
    print(a + 100)
    print(a + b)
    print(a * b)
    #代码作用机制·语法关联·结果易错点
    1print(a + 100)a + 100广播:标量 100 被视为与 a 同形,逐元素相加[101 102 103]这其实就是 z = w·x + b 里加偏置 b 的 NumPy 版本(b 是标量/长度 1)
    2print(a + b)a + b同形数组逐元素相加[11 22 33]形状不同会广播或报错
    3print(a * b)a * b* 是逐元素乘(Hadamard),不是点积![10 40 90]最常见的混淆:a*b = [10,40,90],a@b = 140
    运行结果 [101 102 103] [11 22 33] [10 40 90]

    Dot product of vectors can be obtained in several ways: the @ operator, the dot() method, the np.dot() function, and the np.matmul() function. In all 4 cases below, the result is 140 (= 1&times;10 + 2&times;20 + 3&times;30).

    点积的几何意义:a·b = |a||b|cosθ。两个向量越"同向"点积越大。神经元的 w·x 就是在问"输入 x 和权重 w 有多像"——这是 Unit 3 讲义 p3 的核心比喻。
    Cell 12向量点积的四种写法 → 140重点展开
    print(a @ b)
    print(a.dot(b))
    print(np.dot(a, b))
    print(np.matmul(a, b))
    #代码作用机制·语法关联·结果易错点
    1print(a @ b)@ 运算符a @ b(Python 3.5+)= 矩阵乘法运算符,对一维向量即点积:1×10+2×20+3×30 = 140140最推荐,可读性最好
    2print(a.dot(b)).dot() 方法a.dot(b):ndarray 方法,等价140—
    3print(np.dot(a, b))np.dot 函数np.dot(a, b):对 2D 是矩阵乘,对 1D 是点积140np.dot 对高维数组语义与 matmul 略有差异(batch 维处理),DL 里用 @ 或 matmul 更安全
    4print(np.matmul(a, b))np.matmul 函数np.matmul(a, b):严格矩阵乘(把 1D 当 1×n 和 n×1)140(标量)matmul 不允许标量乘(np.matmul(a, 3) 报错),np.dot 可以
    运行结果 140 140 140 140
    深挖 · 点积 = 神经元:一个 Dense 神经元对输入 x 的计算就是 weights @ inputs + bias——Q2b 的 C35 用的正是 weights.dot(inputs) + bias。多个神经元并排 → weights 变成 (in, out) 矩阵 → 点积变成矩阵乘(C16)。所以 Dense 层 = 矩阵乘 + 偏置(+ 激活),没有任何别的东西。

    Matrix product


    Let's turn to matrix product. The code below creates two matrices: a 2&times;3 matrix called c and a 3&times;2 matrix called d. Recall that the matrix product operation requires that the last dimension of the first matrix (here 3 in 2&times;3 of c) equals the first dimension of the second matrix (here 3 in 3&times;2 of d).

    Cell 14矩阵 c (2×3)、d (3×2)、三维数组 e (2,3,2)基础
    import numpy as np
    c = np.array([[1, 2, 3], [4, 5, 6]])
    d = np.array([[10, 20], [30, 40], [50, 60]])
    e = np.array([[[10, 20], [30, 40], [50, 60]],[[10, 20], [30, 40], [50, 60]]])
    print(c, c.shape)
    print(d, d.shape)
    print(e, e.shape)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2c = np.array([[1, 2, 3], [4, 5, 6]])c = 2×3外层 2 个 list → 2 行;每行 3 个 → 3 列(2, 3)—
    3d = np.array([[10, 20], [30, 40], [50, 60]])d = 3×2—(3, 2)c 的列数 3 = d 的行数 3 → 可乘
    4e = np.array([[[10, 20], [30, 40], [50, 60]],[[10, 20], [30, 40], [50, 60]]])e = 三维数组再套一层 list → 3 个维度 (2, 3, 2):可理解为"2 个 3×2 矩阵叠在一起"(batch of 2)(2, 3, 2)这是 CNN 里 (batch, H, W) 或 RNN 里 (batch, T, D) 的形状雏形;shape 元组从左到右 = 从外到内
    5print(c, c.shape)打印NumPy 打印三维数组时用空行分隔第 0 维的各"页"——
    6print(d, d.shape)打印NumPy 打印三维数组时用空行分隔第 0 维的各"页"——
    7print(e, e.shape)打印NumPy 打印三维数组时用空行分隔第 0 维的各"页"——
    运行结果 [[1 2 3] [4 5 6]] (2, 3) [[10 20] [30 40] [50 60]] (3, 2) [[[10 20] [30 40] [50 60]] [[10 20] [30 40] [50 60]]] (2, 3, 2)

    Matrix product is obtained using the same NumPy APIs as vector product: the @ operator, the dot() method, the np.dot() function, and the np.matmul() function. In all 4 cases below, the result is a 2&times;2 matrix. For example, the first number in the resulting matrix, 220, is calculated using the first row of c and the first column of d (i.e. 220 = 1&times;10 + 2&times;30 + 3&times;50).

    矩阵乘法怎么算(手算规则):结果第 i 行第 j 列 = c 的第 i 行 与 d 的第 j 列的点积。220 = 1×10 + 2×30 + 3×50(c 第 0 行 · d 第 0 列);280 = 1×20+2×40+3×60;490 = 4×10+5×30+6×50;640 = 4×20+5×40+6×60。自己算一遍再对输出。
    Cell 16矩阵乘法 c @ d → 2×2,元素 220 怎么来重点展开
    print(c @ d)
    print(c.dot(d))
    print(np.dot(c, d))
    print(np.matmul(c, d))
    #代码作用机制·语法关联·结果易错点
    1print(c @ d)c @ d(2,3) @ (3,2) → (2,2):结果 [i][j] = c 第 i 行 · d 第 j 列;220 = 1×10+2×30+3×50[[220 280] [490 640]]d @ c 则是 (3,2)@(2,3) → (3,3),结果完全不同——矩阵乘法不满足交换律
    2print(c.dot(d))三种等价写法.dot / np.dot / np.matmul 对 2D 完全等价同上—
    3print(np.dot(c, d))三种等价写法.dot / np.dot / np.matmul 对 2D 完全等价同上—
    4print(np.matmul(c, d))三种等价写法.dot / np.dot / np.matmul 对 2D 完全等价同上—
    运行结果 [[220 280] [490 640]] [[220 280] [490 640]] [[220 280] [490 640]] [[220 280] [490 640]]
    深挖 · 形状规则是 Keras 的通用语言:Dense(units, input_dim=in) 的权重形状是 (in, units),前向计算 output = input @ W + b:input (batch, in) @ W (in, units) → (batch, units)。所以 Unit 4 讲义说 Dense(13→64) 有 13×64+64 = 896 个参数。记住:相邻维度相等才能乘、结果取两端——考卷上 "determine the output shape" 全靠这一句。

    The code below computes the matrix product of c and d, adds 9000 to it (i.e. adds 9000 to each element of the matrix product). The contents and shape of the result are displayed.

    Cell 18矩阵乘 + 标量 9000:又是广播基础
    result = c @ d + 9000
    print(result, result.shape)
    #代码作用机制·语法关联·结果易错点
    1result = c @ d + 9000result = c @ d + 9000运算优先级:@ 先于 +;c@d 得 (2,2),再加标量 → 逐元素加[[9220 9280] [9490 9640]]写成 c @ (d + 9000) 结果不同——括号位置决定语义
    2print(result, result.shape)打印内容与形状—(2, 2)—
    运行结果 [[9220 9280] [9490 9640]] (2, 2)

    Practice - Question 1 of 3

    The code below creates two arrays a1 and a2 of random values (0.0 to 1.0), with shapes (2, 3) and (5, 3).

    Cell 21Q1 数据:随机 a1 (2,3)、a2 (5,3),round(2)导入·绘图·输出
    import numpy as np
    np.random.seed(42)
    a1 = np.random.random((2, 3)).round(2)
    a2 = np.random.random((5, 3)).round(2)
    print(a1, a1.shape)
    print(a2, a2.shape)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2np.random.seed(42)seed 42让随机结果可复现(t01 C65)——
    3a1 = np.random.random((2, 3)).round(2)a1np.random.random(shape):[0,1) 均匀分布;.round(2) 保留两位便于阅读(2, 3)round 后数值变了,之后矩阵乘的结果是基于 round 后的值
    4a2 = np.random.random((5, 3)).round(2)a2—(5, 3)a2 有 5 行 3 列
    5print(a1, a1.shape)打印———
    6print(a2, a2.shape)打印———
    运行结果 [[0.37 0.95 0.73] [0.6 0.16 0.16]] (2, 3) [[0.06 0.87 0.6 ] [0.71 0.02 0.97] [0.83 0.21 0.18] [0.18 0.3 0.52] [0.43 0.29 0.61]] (5, 3)

    Q1a


    Write code to try to compute the matrix product of a1 and a2 inside a try-except statement as:


    try:
        result = a1 @ a2
    except Exception as e:
        print("Error:", e)
    
    Cell 23Q1a 你的作答:try a1 @ a2 → 形状不匹配报错重点展开
    try:
        result = a1 @ a2
    except Exception as e:
        print("Error:", e)
    #代码作用机制·语法关联·结果易错点
    1try:try:try: 块:若内部抛异常则跳到 except—冒号后缩进
    2 result = a1 @ a2a1 @ a2(2,3) @ (5,3):a1 最后一维 3 ≠ a2 第一维 5 → 无法相乘抛 ValueErrorKeras 里同样的错会报 "MatMul op ... dimension mismatch"
    3except Exception as e:except Exception as e捕获所有异常并绑定到变量 e—裸 except: 不捕获变量、也吞掉 KeyboardInterrupt——不推荐
    4 print("Error:", e)打印错误e 的 str() 是 NumPy 的详细提示Error: matmul: Input operand 1 has a mismatch ... (size 5 is different from 3)读错误信息的方法:看最后括号 "size 5 is different from 3"——立刻知道是 a2 的第 0 维 5 对不上 a1 的最后一维 3
    运行结果 Error: matmul: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (n?,k),(k,m?)->(n?,m?) (size 5 is different from 3)
    深挖 · 这条报错就是 "相邻维度必须相等":a1 (2,3) 的最后一维 3,a2 (5,3) 的第 0 维 5。解决办法有二:转置 a2 → (3,5),让 3 对 3(Q1c);或者 a2.T @ a1 → (3,5)@(5,3) = (3,3)。考试 "modify code" 题最爱出这种形状错——看到 "dimension mismatch" 先写出两边的 shape 再对相邻两数。

    Q1b


    Write code to print the contents and shape of a2.T (i.e. the transpose of a2).

    Cell 25Q1b 你的作答:a2.T 转置 → (3,5)练习·作答
    print(a2.T, a2.T.shape)
    #代码作用机制·语法关联·结果易错点
    1print(a2.T, a2.T.shape)打印转置.T 属性:行列互换 (5,3) → (3,5);第 i 行变第 i 列3×5 矩阵.T 是属性不是方法(不加括号);返回 view,不占新内存
    运行结果 [[0.06 0.71 0.83 0.18 0.43] [0.87 0.02 0.21 0.3 0.29] [0.6 0.97 0.18 0.52 0.61]] (3, 5)

    Q1c


    Write code to compute the matrix product of a1 and a2.T, and keep the result in a variable called result. Print the contents and shape of result.

    Cell 27Q1c 你的作答:a1 @ a2.T → (2,5)练习·作答
    result = a1 @ a2.T
    print(result, result.shape)
    #代码作用机制·语法关联·结果易错点
    1result = a1 @ a2.T相乘(2,3) @ (3,5) → (2,5):result[i][j] = a1 第 i 行 · a2 第 j 行(因为转置后 d 的列 = a2 的行)—这个 "每一行对每一行做点积" 的结果在 ML 里叫 gram 矩阵 / 相似度矩阵——注意力机制(Transformer)的 QKᵀ 就是这个形状
    2print(result, result.shape)打印—(2, 5)验证 1.2867 = 0.37×0.06 + 0.95×0.87 + 0.73×0.6 ≈ 1.2867 ✔
    运行结果 [[1.2867 0.9898 0.638 0.7312 0.8799] [0.2712 0.5844 0.5604 0.2392 0.402 ]] (2, 5)

    &#x2766;

    Practice - Question 2 of 3

    The Keras program below is written for studying the operations of a sigmoid neuron. Note that you're not required to fully understand its code (in this lesson). In brief, the neuron has weights in the weights variable, and bias in the bias variable. It performs prediction from the values in the inputs variable and displays the predicted value.

    Q2 的设计:C31 用 model.set_weights() 把 Dense 层的 W、b 固定成已知值,这样 predict 的输出是确定的 0.6899745;然后 Q2a/Q2b 让你用 NumPy 从零算出同一个数。能从零算出 Dense 层的输出,就说明你理解了 Dense 层在做什么——Unit 5 的反向传播手算(讲义 p31–p38)从这里出发。
    Cell 31Q2 题干:用 set_weights 固定一个 sigmoid 神经元重点展开
    # A sigmoid neuron for studying its operations
    import numpy as np
    from tensorflow import keras
    
    weights = np.array([-0.1, -0.2, 0.3])
    bias = np.array([0.4])
    inputs = np.array([10, 11, 12])
    
    model = keras.models.Sequential([
        keras.layers.Dense(1, activation="sigmoid", input_shape=inputs.shape)
    ])
    model.set_weights([weights.reshape((3, 1)), bias])
    y_pred = model.predict(inputs.reshape((1, -1)), verbose=0)
    print(y_pred)
    #代码作用机制·语法关联·结果易错点
    1# A sigmoid neuron for studying its operations注释———
    2import numpy as np导入———
    3from tensorflow import keras导入———
    5weights = np.array([-0.1, -0.2, 0.3])权重3 个权重 → 一维 (3,):对应 3 个输入w = [−0.1, −0.2, 0.3]顺序对应输入 [10, 11, 12] 的每一维
    6bias = np.array([0.4])偏置长度 1 的数组(不是标量)——因为 set_weights 要求是数组b = [0.4]若 bias=0.4 标量,set_weights 会报错
    7inputs = np.array([10, 11, 12])输入3 维输入向量[10, 11, 12]—
    9model = keras.models.Sequential([建一个 Dense(1)input_shape=inputs.shape=(3,) → 告诉 Keras 输入 3 维;sigmoid 激活;参数 W (3,1) + b (1)模型 4 个参数,此时是随机初始化的WARNING 提示 input_shape 参数已过时——Keras 3 推荐写 keras.Input(shape=(3,)) 作为第一层;本课沿用旧写法,功能正常
    10 keras.layers.Dense(1, activation="sigmoid", input_shape=inputs.shape)建一个 Dense(1)input_shape=inputs.shape=(3,) → 告诉 Keras 输入 3 维;sigmoid 激活;参数 W (3,1) + b (1)模型 4 个参数,此时是随机初始化的WARNING 提示 input_shape 参数已过时——Keras 3 推荐写 keras.Input(shape=(3,)) 作为第一层;本课沿用旧写法,功能正常
    11])建一个 Dense(1)input_shape=inputs.shape=(3,) → 告诉 Keras 输入 3 维;sigmoid 激活;参数 W (3,1) + b (1)模型 4 个参数,此时是随机初始化的WARNING 提示 input_shape 参数已过时——Keras 3 推荐写 keras.Input(shape=(3,)) 作为第一层;本课沿用旧写法,功能正常
    12model.set_weights([weights.reshape((3, 1)), bias])手动设权重model.set_weights([W, b]):按层的顺序传 list;Dense 的权重 list 是 [kernel, bias];kernel 形状必须是 (3,1) 所以 reshape模型参数被固定 → 输出可预测形状必须严格匹配:(3,) 会报错,必须 (3,1);顺序也必须 [W, b] 不是 [b, W]
    13y_pred = model.predict(inputs.reshape((1, -1)), verbose=0)predictinputs.reshape((1, −1)):把 (3,) 变成 (1,3)——Keras 要求 batch 维,即使只有一个样本y_pred = [[0.6899745]] 形状 (1,1)直接传 (3,) 会被当成 3 个样本各 1 维 → 报错
    14print(y_pred)打印—[[0.6899745]]两层方括号 = (1,1) 形状
    运行结果 /usr/local/lib/python3.13/dist-packages/keras/src/layers/core/dense.py:106: UserWarning: Do not pass an `input_shape`/`input_dim` argument to a layer. When using Sequential models, prefer using an `Input(shape)` object as the first layer in the model instead. super().__init__(activity_regularizer=activity_regularizer, **kwargs) [[0.6899745]]
    深挖 · 手算 0.6899745(Q2b 要你做的事,这里先演示):
    z = w·x + b = (−0.1)(10) + (−0.2)(11) + (0.3)(12) + 0.4 = −1 − 2.2 + 3.6 + 0.4 = 0.8
    σ(0.8) = 1 / (1 + e⁻⁰·⁸) = 1 / (1 + 0.4493) = 1 / 1.4493 = 0.68997 ✔ 与 Keras 输出一致。
    意义:model.predict 做的事 = 这两行 NumPy。Unit 5 讲义 p32–p37 的反向传播手算(讲义数字 [[19,25],[79,85]])第一步就是把 Dense 前向写成 w·x+b 再过 sigmoid——这个 Lab 就是在为那一步打基础。

    Q2a


    Write a sigmoid(x) Python function that takes a parameter x to implement the sigmoid/logistic function: $$\text{sigmoid}(x) = 1 / (1 + e^{-x})$$


    Use np.exp(-x) for $e^{-x}$.

    Cell 33Q2a 你的作答:手写 sigmoid(x)重点展开
    def sigmoid(x):
        return 1 / (1 + np.exp(-x))
    #代码作用机制·语法关联·结果易错点
    1def sigmoid(x):def参数 x 可以是标量或 ndarray(np.exp 支持广播)——
    2 return 1 / (1 + np.exp(-x))return 1 / (1 + np.exp(-x))σ(x) = 1/(1+e⁻ˣ):x→+∞ 时 e⁻ˣ→0 → 1;x→−∞ → 0;x=0 → 0.5σ(0.8)=0.68997必须用 np.exp 不是 math.exp(后者不支持数组);写 1/(1+np.exp(-x)) 对大正数 x 有数值溢出风险(e⁻ˣ 下溢为 0 没问题,但大负数 x 时 e⁻ˣ 溢出 → inf → 结果 0,实际 Keras 用更稳定的实现)
    深挖 · sigmoid 的导数:σ'(x) = σ(x)(1−σ(x)),在 x=0 处最大 = 0.25,|x|→∞ 时趋于 0——这就是梯度消失(Unit 5 p37–p38)的根源:饱和区导数接近 0,深层网络传不回去。所以 Unit 4 引入 ReLU,Unit 7 讲初始化要保持方差。

    Q2b


    Write 3 lines of code to do the following:


  • Compute the dot product of `weights` and `inputs`, and add `bias` to the product. Keep the result in a variable called `z`.
  • Apply the `sigmoid()` function to `z`. Keep the result in a variable called `y`.
  • Print the value of `y`.
  • Cell 35Q2b 你的作答:z = w·x + b → y = σ(z)重点展开
    z = weights.dot(inputs) + bias
    y = sigmoid(z)
    print(y)
    #代码作用机制·语法关联·结果易错点
    1z = weights.dot(inputs) + bias线性部分weights.dot(inputs) + bias:点积得标量 −1−2.2+3.6 = 0.4,加 bias 数组 [0.4] → 广播成数组 [0.8]z = [0.8]因为 bias 是 (1,) 数组,z 也是 (1,) 而非标量——形状"传染"
    2y = sigmoid(z)激活sigmoid(z) 对数组逐元素 → [0.68997448]y = [0.68997448]与 C31 的 0.6899745 一致(打印精度不同)
    3print(y)打印—[0.68997448]—
    运行结果 [0.68997448]
    核对:手算结果与 Keras 完全一致 ✔——你已能从零复现一个 Dense 层的前向传播。

    &#x2766;

    Integer array indexing


    We've learned basic ways of indexing NumPy arrays using integers and slices. For instance, the example below shows an array a of 5 strings. a[0] uses an integer 0 in indexing the array and results in the first item "a". a[0:2] uses a slice 0:2 in indexing the array and results in the first two items in a new array ["a", "b"].

    Cell 38字符串数组 + 整数索引 + 切片(回顾)基础
    import numpy as np
    a = np.array(list("abcde"))  # array of 5 strings
    print(a)
    print(a[0])  # use an integer in indexing
    print(a[0:2])  # use a slice in indexing
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2a = np.array(list("abcde")) # array of 5 strings建字符串数组list("abcde") 把字符串拆成字符 list → np.array 得 dtype '['a' 'b' 'c' 'd' 'e']dtype 由内容推断;数字数组会推断 int/float
    3print(a)打印———
    4print(a[0]) # use an integer in indexinga[0]单个整数索引 → 取一个元素(标量)'a'—
    5print(a[0:2]) # use a slice in indexinga[0:2]切片 → 取一段(新数组)['a' 'b']—
    运行结果 ['a' 'b' 'c' 'd' 'e'] a ['a' 'b']

    1D data arrays


    In NumPy, integer array indexing uses an integer array to select arbitrary items in another array (the data array). The integer array contains indices that refer to items in the data array.


    The following shows two examples of integer array indexing. Note that in a[ix], ix is an integer array; in a[[0, 1, 2]], [0, 1, 2] is an integer array. (Technically ix and [0, 1, 2] are lists, not arrays; but lists can be used in integer array indexing so we call them integer arrays here.) In both examples, [0, 1, 2] selects the items in a at indices 0, 1, and 2, i.e. "a", "b", and "c".

    Cell 40整数数组索引:a[ix] 与 a[[0,1,2]]重点展开
    ix = [0, 1, 2]
    print(a[ix])  # use an integer array in indexing
    print(a[[0, 1, 2]])  # use an integer array in indexing
    #代码作用机制·语法关联·结果易错点
    1ix = [0, 1, 2]ix = [0,1,2]一个普通 list,当作"整数数组"使用(NumPy 接受 list)——
    2print(a[ix]) # use an integer array in indexinga[ix]用一个数组做索引:按 ix 中的每个下标去 a 取元素,组成新数组;长度 = len(ix)['a' 'b' 'c']结果长度由索引数组决定,不由 a 决定
    3print(a[[0, 1, 2]]) # use an integer array in indexinga[[0,1,2]]直接写 list 字面量,效果相同;注意双层方括号同上a[0,1,2](单层)会被解释为多维索引 → 报错 "too many indices"
    运行结果 ['a' 'b' 'c'] ['a' 'b' 'c']

    The indices in the integer array may have repeated values, which select an item in the data array multiple times. In the integer array below, the three 0's select the item "a" at index 0 of a three times; the two -1's select the item "e" in index -1 of a two times.

    Cell 42索引可重复、可为负基础
    print(a[[0, 2, 0, 0, -1, -1]])
    #代码作用机制·语法关联·结果易错点
    1print(a[[0, 2, 0, 0, -1, -1]])a[[0,2,0,0,-1,-1]]同一元素被选多次(0 出现 3 次 → 'a' 3 次);−1 = 最后一个 → 'e' 2 次['a' 'c' 'a' 'a' 'e' 'e']这正是 Keras 里 X[idx] 做 batch 采样的机制(有放回采样 / bootstrap)
    运行结果 ['a' 'c' 'a' 'a' 'e' 'e']

    2D data arrays


    When integer array indexing is applied to a multiple-dimensional data array (2D or above), the indices in the integer array refer to axis-0 of the data array. For a 2D data array, it means selecting the rows. Let's see some examples using a 2D data array with shape (5, 10).

    Cell 44b = arange(50).reshape(5,10)基础
    b = np.arange(50).reshape((5, 10))
    print(b, b.shape)
    #代码作用机制·语法关联·结果易错点
    1b = np.arange(50).reshape((5, 10))建 5×100–49 按行填充(5, 10)—
    2print(b, b.shape)打印———
    运行结果 [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [20 21 22 23 24 25 26 27 28 29] [30 31 32 33 34 35 36 37 38 39] [40 41 42 43 44 45 46 47 48 49]] (5, 10)

    In the code below, b[[1, 3]] selects the second (index 1) row and the fourth row (index 3) row of b.

    Cell 46b[[1,3]]:用整数数组选行重点展开
    print(b[[1, 3]])  # use an integer array in indexing
    #代码作用机制·语法关联·结果易错点
    1print(b[[1, 3]]) # use an integer array in indexing选第 1、3 行整数数组索引作用在 axis-0(行):结果 = 第 1 行和第 3 行堆叠 → (2,10)[[10..19],[30..39]]务必双层括号;b[1,3] 是标量 13(C48)
    运行结果 [[10 11 12 13 14 15 16 17 18 19] [30 31 32 33 34 35 36 37 38 39]]

    Take extra care in the use of brackets, i.e. [ and ], in integer array indexing. Omitting brackets would give you a totally different result, such as b[[1, 3]] in the above example versus b[1, 3] in the next example (which is the item 13 at the second row and the fourth columns).

    易错:b[[1, 3]] vs b[1, 3]——只差一层方括号,意义完全不同。前者是"整数数组索引"(选第 1、3 两行 → 2×10 矩阵),后者是"多维索引"(第 1 行第 3 列 → 标量 13)。考试改代码题常在这里设陷阱。
    Cell 48b[1,3]:两个整数 → 一个元素基础
    print(b[1, 3])  # use two integers in indexing
    #代码作用机制·语法关联·结果易错点
    1print(b[1, 3]) # use two integers in indexing取 (1,3)逗号分隔的多维索引(t01 C53)→ 第 1 行第 3 列13与 C46 对比:差一层 [],结果从 2×10 矩阵变成一个数
    运行结果 13

    When the integer array contains all indices of the data array exactly once (along axis-0), all items in the data array are selected once. This has the effect of reordering the items in the data array according to the index order in the integer array. For example, the following index_order integer array selects, in that order, the rows at indices 3, 0, 1, 4, 2 of the data array b.

    Cell 50b[index_order]:用整数数组重排行重点展开
    index_order = [3, 0, 1, 4, 2]
    print(b[index_order])
    #代码作用机制·语法关联·结果易错点
    1index_order = [3, 0, 1, 4, 2]定义顺序每个下标恰好出现一次 → 这是"排列"[3,0,1,4,2]—
    2print(b[index_order])按顺序取行结果 = 第 3、0、1、4、2 行依次堆叠 → 实现了按任意顺序重排5×10 重排矩阵np.random.permutation 生成随机排列后做 X[perm] 就是 shuffle;sklearn 的 train_test_split 内部正是如此
    运行结果 [[30 31 32 33 34 35 36 37 38 39] [ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19] [40 41 42 43 44 45 46 47 48 49] [20 21 22 23 24 25 26 27 28 29]]

    Sorting parallel arrays


    Parallel arrays refer to the use two or more arrays to store a dataset such that the items at the same index of the arrays are associated to a record. They are frequently used in machine learning to store the features (prediction inputs) and labels (prediction outputs) of training/test examples.


    In the example below, the names array contains 5 names and the marks array contains 5 marks. Note that names and marks are associated by the indices in the arrays: Peter gets 77 (both at index 0), Paul gets 45 (both at index 1), Mary gets 80 (both at index 2), David gets 62 (both at index 3), and Ann gets 50 (both at index 4).

    Cell 52平行数组 names / marks基础
    import numpy as np
    names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])
    marks = np.array([77, 45, 80, 62, 50])
    print(names)
    print(marks)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入———
    2names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])namesdtype '5 个名字—
    3marks = np.array([77, 45, 80, 62, 50])marksint 数组[77 45 80 62 50]names[i] 与 marks[i] 是同一个人的记录——"平行"的含义
    4print(names)打印———
    5print(marks)打印———
    运行结果 ['Peter' 'Paul' 'Mary' 'David' 'Ann'] [77 45 80 62 50]

    Now, let's say we want to sort the marks in the increasing order. NumPy has a np.sort() function for sorting an array. The code below attempts to sort both names and marks arrays using np.sort(). While both arrays are sorted, the association between the arrays is lost! E.g. the result indicates that Ann gets 45, but this is not correct as in the original data Ann gets 50.

    Cell 54反面教材:各自 np.sort 打散对应关系重点展开
    sorted_names = np.sort(names)
    sorted_marks = np.sort(marks)
    print(sorted_names)
    print(sorted_marks)
    #代码作用机制·语法关联·结果易错点
    1sorted_names = np.sort(names)sort namesnp.sort(a) 返回排好序的新数组(不改原数组;ndarray.sort() 是原地)['Ann' 'David' 'Mary' 'Paul' 'Peter']—
    2sorted_marks = np.sort(marks)sort marks—[45 50 62 77 80]—
    3print(sorted_names)打印现在 Ann 对 45——但原始数据 Ann 是 50!关联被破坏错误配对这是静默错误:不报错,但数据已经错了
    4print(sorted_marks)打印现在 Ann 对 45——但原始数据 Ann 是 50!关联被破坏错误配对这是静默错误:不报错,但数据已经错了
    运行结果 ['Ann' 'David' 'Mary' 'Paul' 'Peter'] [45 50 62 77 80]
    这就是为什么 fit(X, y) 之前不能分别 shuffle X 和 y。正确做法:生成一个排列 idx,然后 X[idx] 和 y[idx] 用同一个 idx(C60/C62 的 argsort 是同一思路)。

    Sorting the arrays individually breaks the association. To maintain the association, a single integer array is used to index both arrays, as you'll do in the question below.

    平行数组(parallel arrays):Keras 的 fit(X, y) 里 X 和 y 就是平行数组——X[i] 是第 i 个样本的特征,y[i] 是它的标签。所以任何对 X 的行重排/筛选都必须用同一个索引作用到 y,否则特征和标签错位,模型学到的就是垃圾(而且不会报错!)。

    Practice - Question 3 of 3


    Here are the original parallel arrays again:

    Cell 57Q3 数据:原始平行数组再来一次导入·绘图·输出
    import numpy as np
    names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])
    marks = np.array([77, 45, 80, 62, 50])
    print(names)
    print(marks)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np同 C52———
    2names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])同 C52———
    3marks = np.array([77, 45, 80, 62, 50])同 C52———
    4print(names)同 C52———
    5print(marks)同 C52———
    运行结果 ['Peter' 'Paul' 'Mary' 'David' 'Ann'] [77 45 80 62 50]

    To maintain the association between the two arrays: (1) we need an integer array for ordering the data in both arrays; (2) the integer array should contain the indices of the marks array, each index once; (3) the indices in the integer array should be in the order of the increasing values in marks. The integer array fulfilling these is [1, 4, 3, 0, 2], where 1 is the index of the smallest item 45 (i.e. marks[1]) in marks, 4 is the index of the next smallest item 50 (i.e. marks[4]), 3 is the index of the next smallest item 62 (i.e. marks[3]), followed by the index 0 of 77 (i.e. marks[0]) and index 2 of 80 (i.e. marks[2]).


    This integer array can be obtained using the NumPy function np.argsort(). That is, calling np.argsort(marks) returns [1, 4, 3, 0, 2].

    Q3a


    Write code to do the following:


  • Invoke `np.argsort(marks)` and keep the result in a variable called `order`.
  • Print the contents of `order`.
  • Cell 60Q3a 你的作答:order = np.argsort(marks)重点展开
    order = np.argsort(marks)
    print(order)
    #代码作用机制·语法关联·结果易错点
    1order = np.argsort(marks)argsortnp.argsort(a) 返回的不是排好的值,而是"按值升序排列时的下标顺序":marks 最小值 45 在下标 1 → order[0]=1;次小 50 在下标 4 → 2;以此类推order = [1 4 3 0 2]argsort 返回 int 数组;np.sort 返回值本身——两者一字之差
    2print(order)打印—[1 4 3 0 2]降序:np.argsort(-marks) 或 [::-1]
    运行结果 [1 4 3 0 2]

    Q3b


    Write code to do the following:


  • Use the `order` integer array to index the `names` array. Keep the result in a variable called `sorted_names`.
  • Use the `order` integer array to index the `marks` array. Keep the result in a variable called `sorted_marks`.
  • Print the contents of `sorted_names`.
  • Print the contents of `sorted_marks`.

  • Note that you should see the sorted_marks contains the sorted marks, and the association between the names and marks are maintained, i.e. in the same way as the original data.

    Cell 62Q3b 你的作答:用同一个 order 索引两个数组重点展开
    sorted_names = names[order]
    sorted_marks = marks[order]
    print(sorted_names)
    print(sorted_marks)
    #代码作用机制·语法关联·结果易错点
    1sorted_names = names[order]names[order]整数数组索引(C50)→ 按下标 1,4,3,0,2 取名字['Paul' 'Ann' 'David' 'Peter' 'Mary']关键:同一个 order
    2sorted_marks = marks[order]marks[order]同样的 order 作用于 marks → 升序且与 names 对齐[45 50 62 77 80]Paul 45、Ann 50 ✔ 关联保持
    3print(sorted_names)打印———
    4print(sorted_marks)打印———
    运行结果 ['Paul' 'Ann' 'David' 'Peter' 'Mary'] [45 50 62 77 80]
    核对:正确 ✔。这个"一个索引数组作用于多个平行数组"的模式,在 t06(train/valid 切分)、t09(文件名列表与标签同步 shuffle)、t11(文本与标签同步)里反复出现。

    &#x2766;

    Extras

    Boolean array indexing


    In NumPy, Boolean array indexing uses a Boolean array to decide whether or not to include each item in a data array. A data item is included once if the corresponding Boolean value in the Boolean array is True, or not included if it is False. Note that the Boolean array must have the same size as the data array (or the first dimension of the data array).


    The a array below contains 10 integers. The mask array is a Boolean array obtained by a % 2 == 0, which gives True for even numbers in a and False for odd numbers in a. E.g. the first item a[0] (i.e. 10) is even so the first Boolean value mask[0] is True; a[1] (i.e. 11) is odd so mask[1] is False.

    Cell 66E1 数据:a = arange(10,20)导入·绘图·输出
    import numpy as np
    a = np.arange(10, 20)
    print(a)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入 / 建 10–19 / 打印arange(start, stop) stop 不含[10..19]—
    2a = np.arange(10, 20)导入 / 建 10–19 / 打印arange(start, stop) stop 不含[10..19]—
    3print(a)导入 / 建 10–19 / 打印arange(start, stop) stop 不含[10..19]—
    运行结果 [10 11 12 13 14 15 16 17 18 19]
    Cell 67mask = a % 2 == 0:布尔数组重点展开
    mask = a % 2 == 0
    print(mask)
    #代码作用机制·语法关联·结果易错点
    1mask = a % 2 == 0比较运算向量化a % 2 逐元素取余 → [0 1 0 1 …];== 0 逐元素比较 → 布尔数组;运算符优先级:%(高) 先于 ==(低),不用加括号mask = [True False True …]布尔数组长度必须等于 a 的长度;a % 2 == 0 若写成 a % (2 == 0) 就是 a % False = a % 0 → 除零
    2print(mask)打印———
    运行结果 [ True False True False True False True False True False]

    To perform Boolean array indexing, we use the mask Boolean array when indexing the a array, i.e. a[mask] in the example below. The Boolean array can also be directly created and used in indexing an array, as in a[a % 2 == 0]. In both cases, the even numbers in a are obtained according to the True values in the Boolean arrays. The Boolean array is sometimes called a mask.

    Cell 69a[mask]:布尔索引只留 True 位置重点展开
    print(a[mask])
    print(a[a % 2 == 0])
    #代码作用机制·语法关联·结果易错点
    1print(a[mask])用 mask 索引布尔数组索引:mask 为 True 的位置被保留,结果长度 = True 的个数(这里 5)[10 12 14 16 18]返回拷贝不是 view(与切片不同)
    2print(a[a % 2 == 0])内联写法直接把比较表达式放进 []——最常用的写法同上—
    运行结果 [10 12 14 16 18] [10 12 14 16 18]
    深挖 · 布尔掩码在 DL 里的用处:y[mask] 筛选某一类样本(如只看错分样本:X[y_pred.ravel() != y]);X[X[:,0] > 0.5] 按特征筛选;Pandas 的 df[df["col"] > 3] 同源。记住"长度相等"这条硬规则(E1a 第三问考它)。
    E1a

    You are given an array of 5 integers called a as follows.

    Cell 71E1a 数据:a = [1..5]导入·绘图·输出
    import numpy as np
    a = np.array([1, 2, 3, 4, 5])
    print(a)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入 / 建 / 打印—[1 2 3 4 5]—
    2a = np.array([1, 2, 3, 4, 5])导入 / 建 / 打印—[1 2 3 4 5]—
    3print(a)导入 / 建 / 打印—[1 2 3 4 5]—
    运行结果 [1 2 3 4 5]

    Write code to do the following:


  • Index the `a` array using the Boolean array `[False, False, False, False, False]`, and print the result.
  • Index the `a` array using the Boolean array `[True] * 5`, and print the result.
  • Use a `try-except` statement and try to index the `a` array using the Boolean array `[True, True]`. Display the error for any exception that occurs.
  • E1b

    Boolean array indexing is also useful in manipulating parallel arrays. You're given the names and marks arrays again below.

    Cell 74E1b 数据:names / marks导入·绘图·输出
    import numpy as np
    names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])
    marks = np.array([77, 45, 80, 62, 50])
    print(names)
    print(marks)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np同 C52———
    2names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])同 C52———
    3marks = np.array([77, 45, 80, 62, 50])同 C52———
    4print(names)同 C52———
    5print(marks)同 C52———
    运行结果 ['Peter' 'Paul' 'Mary' 'David' 'Ann'] [77 45 80 62 50]

    Write code to do the following:


  • Create a Boolean array as `marks >= 70` and keep the result in a variable called `mask`. This Boolean array contains `True` for marks above or equal to 70, and `False` otherwise.
  • Index the `names` array using `mask`, and keep the result in a variable called `high_names`.
  • Index the `marks` array using `mask`, and keep the result in a variable called `high_marks`.
  • Print the contents of `high_names`.
  • Print the contents of `high_marks`.

  • Note that the resulting high_names and high_marks are parallel arrays containing high marks (&ge;70) and the associated names.

    Solutions to extra exercises

    E1a
    Cell 78E1a 解答环境导入·绘图·输出
    import numpy as np
    a = np.array([1, 2, 3, 4, 5])
    print(a)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np同 C71———
    2a = np.array([1, 2, 3, 4, 5])同 C71———
    3print(a)同 C71———
    运行结果 [1 2 3 4 5]
    Cell 79E1a 解答:全 False → 空;全 True → 全部;长度不等 → 报错练习·作答
    # Solution
    print(a[[False, False, False, False, False]])
    print(a[[True] * 5])
    try:
        print(a[[True, True]])
    except Exception as e:
        print("Error:", e)
    #代码作用机制·语法关联·结果易错点
    1# Solution注释———
    2print(a[[False, False, False, False, False]])全 False没有 True → 空数组(长度 0,dtype 同 a)[]空数组不是 None
    3print(a[[True] * 5])全 True[True] * 5:list 重复 → 5 个 True → 全选[1 2 3 4 5]相当于 a.copy()
    4try:try———
    5 print(a[[True, True]])长度 2 ≠ 5布尔索引要求长度匹配 → IndexError抛异常——
    6except Exception as e:捕获并打印—Error: boolean index did not match indexed array along axis 0; size of axis is 5 but ... 2读错误:"size of axis is 5 but ... 2"——a 长 5、mask 长 2
    7 print("Error:", e)捕获并打印—Error: boolean index did not match indexed array along axis 0; size of axis is 5 but ... 2读错误:"size of axis is 5 but ... 2"——a 长 5、mask 长 2
    运行结果 [] [1 2 3 4 5] Error: boolean index did not match indexed array along axis 0; size of axis is 5 but size of corresponding boolean axis is 2
    E1b
    Cell 81E1b 解答环境导入·绘图·输出
    import numpy as np
    names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])
    marks = np.array([77, 45, 80, 62, 50])
    print(names)
    print(marks)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np同 C52———
    2names = np.array(["Peter", "Paul", "Mary", "David", "Ann"])同 C52———
    3marks = np.array([77, 45, 80, 62, 50])同 C52———
    4print(names)同 C52———
    5print(marks)同 C52———
    运行结果 ['Peter' 'Paul' 'Mary' 'David' 'Ann'] [77 45 80 62 50]
    Cell 82E1b 解答:marks >= 70 → mask → 同步筛选两个数组练习·作答
    # Solution
    mask = marks >= 70
    high_names = names[mask]
    high_marks = marks[mask]
    print(high_names)
    print(high_marks)
    #代码作用机制·语法关联·结果易错点
    1# Solution注释———
    2mask = marks >= 70mask>= 向量化比较 → [True, False, True, False, False]mask>70 与 >=70 不同:77 ≥ 70 True
    3high_names = names[mask]names[mask]布尔索引选名字['Peter' 'Mary']—
    4high_marks = marks[mask]marks[mask]同一个 mask 作用于 marks[77 80]关联保持:Peter 77、Mary 80 ✔
    5print(high_names)打印———
    6print(high_marks)打印———
    运行结果 ['Peter' 'Mary'] [77 80]

    &#x2766;

    📘 Tutorial 4(= Lab 4)· 神经网络组件实验(激活 / 损失 / 优化器 / 归一化)+ 回归网络设计(Boston → Wine Quality)

    t04-s13903054.ipynb,76 cells。对应 Unit 4 讲义 p12–p14(损失、优化器、学习率)、p15–p23(激活函数)、p24–p43(回归配方 + Boston 代码)。方法是控制变量:同一数据、同一种子、同一 16-16-1 结构,每次只换一个组件,看 val_loss 怎么变。结果速览:sigmoid+SGD(基线)23.9 → ReLU 16.6 → tanh 16.5 → MAE 8.18(注意:MAE 与 MSE 不可直接比大小)→ Adam 默认 469.9(学习率 0.001 配 sigmoid 太小)→ Adam lr=0.1 21.2 → RMSprop 463.3 → 不归一化 79.5(几乎学不动)。
    读法:本 notebook 有 8 个结构完全相同的"实验 Cell"(Baseline#1 / ReLU / Adam / Q1a tanh / Q1c MAE / E1a RMSprop / E1b Adam-lr0.1 / E1c no-norm),每个都是 18 行:导入 → seed → 载入 → 归一化 → Sequential(3 层) → compile → fit(20 轮, validation_data)。Baseline#1 逐行精讲一遍,后面 7 个实验只讲"变化的那 1–2 行"和"输出怎么读"——但每一行仍列出,保持 notebook 原序。
    三条结论(考试 "comment on the curve" 题的答题模板):① 激活函数:ReLU/tanh ≈ 16.5 优于 sigmoid 23.9(sigmoid 两端饱和、梯度小);② 优化器没有绝对好坏,学习率才是关键——Adam 默认 0.001 配 sigmoid 几乎不动(469.9),改成 0.1 就到 21.2;③ 特征归一化是前提:不归一化 val_loss 卡在 79.5(Boston 的特征尺度从 0.0x 到 700,梯度被大尺度特征主导)。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同前IPython 魔术命令;须在 import tensorflow 前env: TF_CPP_MIN_LOG_LEVEL=2每个 notebook 第一个 cell
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • exploring components in neural networks, and
  • designing a neural network for regression.
  • Student name: Yin Bang
    Student ID: 13903054

    Exploring components in neural networks

    A neural network is built using various components. Having critical effects on performance, the types of components are chosen largely based on the type and nature of the task, the dataset to be used, among others.


    Some key components and their commonly-used types are:


  • Activation functions: ReLU, sigmoid, tanh, etc;
  • Loss functions: (for regression) mean squared error, absolute squared error, etc; and
  • Optimizers: Adam, RMSProp, SGD, etc.
  • 三类组件各自管什么:激活函数决定网络的"表达力"(能拟合什么形状)和梯度大小;损失函数决定"什么叫好"(MSE 惩罚大误差更重、MAE 对离群点更鲁棒);优化器 + 学习率决定"怎么走"。本 Lab 就是把它们逐个拧一遍。

    The dataset


    Before building a neural network, let's look at the dataset to be used -- the Boston housing dataset. This code loads the dataset.

    Cell 8载入 Boston Housing 数据集导入·绘图·输出
    from tensorflow import keras
    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()
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入 kerasfrom tensorflow import keras——
    2from tensorflow.keras.datasets import boston_housing导入数据集模块tensorflow.keras.datasets 内置 Boston/MNIST/CIFAR/IMDb/Reuters;首次调用自动下载到 ~/.keras/datasets—Keras 3 可能移除 boston_housing(伦理原因)——Colab 的 TF 2.x 仍可用
    4keras.utils.set_random_seed(42)seed在 load_data 之前设也行,load_data 的切分是固定的——
    5(X_train, y_train), (X_test, y_test) = boston_housing.load_data()解包load_data() 返回 ((X_train, y_train), (X_test, y_test)) 两层 tuple;按位置解包—顺序固定:先 train 后 test,先 X 后 y

    Then, we briefly explore the dataset by displaying its dimensions, and the first three examples as follows. Note that the training set contains 404 examples and the test set contains 102 examples. Each example has 13 features (inputs) and 1 label (output).

    Cell 10看形状:(404,13) (404,) (102,13) (102,)基础
    print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
    #代码作用机制·语法关联·结果易错点
    1print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)四个形状X 是 2D (样本数, 特征数),y 是 1D (样本数,)——回归的 y 不需要 one-hot、不需要 reshape404 训练 / 102 测试 / 13 特征与分类对比:MNIST 的 y 是 (60000,) 的整数标签(t05),20ng 的 y 是 (n,20)(t11)
    运行结果 (404, 13) (404,) (102, 13) (102,)
    Cell 11看前 3 个样本基础
    print(X_train[:3])
    print(y_train[:3])
    #代码作用机制·语法关联·结果易错点
    1print(X_train[:3])X_train[:3]切片取前 3 行 → (3,13);科学计数法显示(1.23247e+00)说明特征尺度差异大13 列数值从 0.0x 到 396.9这就是为什么必须归一化:第 12 个特征 ≈ 396、第 2 个 ≈ 0——不归一化时梯度被大尺度特征主导(E1c 证明)
    2print(y_train[:3])y_train[:3]标签是房价(千美元)[15.2, 42.3, 50.0]回归标签是连续值
    运行结果 [[1.23247e+00 0.00000e+00 8.14000e+00 0.00000e+00 5.38000e-01 6.14200e+00 9.17000e+01 3.97690e+00 4.00000e+00 3.07000e+02 2.10000e+01 3.96900e+02 1.87200e+01] [2.17700e-02 8.25000e+01 2.03000e+00 0.00000e+00 4.15000e-01 7.61000e+00 1.57000e+01 6.27000e+00 2.00000e+00 3.48000e+02 1.47000e+01 3.95380e+02 3.11000e+00] [4.89822e+00 0.00000e+00 1.81000e+01 0.00000e+00 6.31000e-01 4.97000e+00 1.00000e+02 1.33250e+00 2.40000e+01 6.66000e+02 2.02000e+01 3.75520e+02 3.26000e+00]] [15.2 42.3 50. ]

    Some basic information of the dataset is shown below. Further details can be found at <http://lib.stat.cmu.edu/datasets/boston>.


    The Boston house-price data of Harrison, D. and Rubinfeld, D.L. 'Hedonic prices and the demand for clean air', J. Environ. Economics & Management, vol.5, 81-102, 1978. Used in Belsley, Kuh & Welsch, 'Regression diagnostics ...', Wiley, 1980. N.B. Various transformations are used in the table on pages 244-261 of the latter.
    
     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)^2 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
    

    The baseline model


    The following functions are utilities to normalize input features and plot the training history. They are used several times in the programs below.

    Cell 14两个工具函数:normalize_features / plot_history重点展开
    import matplotlib.pyplot as plt
    
    # For demo and general use
    # Keras Boston dataset has already been normalized
    # Normalize input features
    def normalize_features(X_train, X_test):
        mean = X_train.mean(axis=0)  # 13 mean values of features
        std = X_train.std(axis=0)    # 13 SD values of features
        X_train_normalized = (X_train - mean) / std
        X_test_normalized = (X_test - mean) / std
        return X_train_normalized, X_test_normalized
    
    # Plot training history
    def plot_history(history):
        plt.plot(history.history["loss"], label="loss")
        plt.plot(history.history["val_loss"], label="val_loss")
        plt.legend()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入 plt———
    3# For demo and general use注释说 Keras 的 Boston 已"部分归一化"——实际只是部分列标准化过,仍需再做—注释与事实有出入,以 E1c 的实验结果为准:不做归一化效果差很多
    4# Keras Boston dataset has already been normalized注释说 Keras 的 Boston 已"部分归一化"——实际只是部分列标准化过,仍需再做—注释与事实有出入,以 E1c 的实验结果为准:不做归一化效果差很多
    5# Normalize input features注释说 Keras 的 Boston 已"部分归一化"——实际只是部分列标准化过,仍需再做—注释与事实有出入,以 E1c 的实验结果为准:不做归一化效果差很多
    6def normalize_features(X_train, X_test):定义归一化函数参数是 train 和 test 两组特征;返回两组新数组——
    7 mean = X_train.mean(axis=0) # 13 mean values of features按列求均值X_train.mean(axis=0):沿第 0 维(跨所有样本)聚合 → 13 个均值(t01 C85:axis=0 消掉行维)mean shape (13,)只用训练集的统计量——测试集不能参与,否则是数据泄露
    8 std = X_train.std(axis=0) # 13 SD values of features按列求标准差同理 axis=0 → 13 个 stdstd shape (13,)std 为 0 的列(常数特征)会导致除零——Boston 没有,但真实数据要防
    9 X_train_normalized = (X_train - mean) / std标准化训练集(X − mean) / std:逐列 (13,) 广播到 (404,13);每列均值 0、std 1X_train_normalized这是 z-score 标准化;Unit 5 MNIST 用的是 /255 的 min-max 缩放——两种都叫"归一化"
    10 X_test_normalized = (X_test - mean) / std用训练集的 mean/std 处理测试集关键:测试集用同一组 mean、std——因为部署时不知道测试分布X_test_normalized常见错:对测试集单独算 mean/std → 训练/测试分布不一致
    11 return X_train_normalized, X_test_normalized返回———
    13# Plot training history注释标明下面是画图函数——
    14def plot_history(history):定义画图函数参数 history(fit 的返回值)——
    15 plt.plot(history.history["loss"], label="loss")画训练 losshistory.history["loss"]:每轮训练集上的平均损失蓝线—
    16 plt.plot(history.history["val_loss"], label="val_loss")画验证 loss"val_loss" 只在 fit 时给了 validation_data/validation_split 才存在橙线没给验证集却画 val_loss → KeyError
    17 plt.legend()显示图例——label 要先在 plot 里登记
    深挖 · 为什么 axis=0:X_train 形状 (404, 13),axis=0 是样本维。按样本聚合 → 每个特征一个均值(13 个)→ 正确。若写 axis=1 会得到 404 个"每个样本 13 个特征的均值"——完全错误,而且不报错。记忆法:axis=k 就是把第 k 个下标消掉,(404,13) 消掉 404 → 剩 13。
    Cell Baseline#1

    The code below loads and prepares the dataset; creates, compiles, and trains a Keras model. Note the sigmoid neurons of the hidden layers, the mean squared error loss function, and the SGD optimizer. This neural network is used as a baseline model for comparing to other models with different components.

    Cell 17Baseline#1:16-16-1 sigmoid + MSE + SGD(★ 逐行精讲,后面 7 个实验同构)重点展开
    # Cell Baseline#1
    
    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()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(1, activation="linear")     # output layer
    ])
    
    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))
    #代码作用机制·语法关联·结果易错点
    1# Cell Baseline#1标记注释作者用注释给 cell 编号,方便题目引用 "Cell Baseline#1"——
    3from tensorflow import keras三个导入keras(模型/工具)、layers(层)、boston_housing(数据)—每段实验都重新导入——重复导入无害
    4from tensorflow.keras import layers三个导入keras(模型/工具)、layers(层)、boston_housing(数据)—每段实验都重新导入——重复导入无害
    5from tensorflow.keras.datasets import boston_housing三个导入keras(模型/工具)、layers(层)、boston_housing(数据)—每段实验都重新导入——重复导入无害
    7keras.utils.set_random_seed(42)固定种子同一段实验里 seed 必须在建模型之前——权重初始化用 RNG—8 个实验都用 seed 42 → 初始权重相同 → 结果可比(控制变量)
    8(X_train, y_train), (X_test, y_test) = boston_housing.load_data()载入数据同 C8——
    10X_train, X_test = normalize_features(X_train, X_test)归一化调用 C14 的函数,用训练集统计量标准化两组X_train/X_test 被覆盖为归一化版本这一行删掉就是 E1c → val_loss 79.5
    12model = keras.Sequential([Sequential 开始———
    13 layers.Dense(16, activation="sigmoid"), # hidden layer隐藏层 1Dense(16, activation="sigmoid"):输入维由数据推断为 13 → W (13,16) 208 + b 16 = 224 参数;输出 σ(·) ∈ (0,1)(None, 16)第一层自动从 X_train 的形状推断 input_dim,不用写 input_shape
    14 layers.Dense(16, activation="sigmoid"), # hidden layer隐藏层 2输入 16 → W (16,16) 256 + 16 = 272(None, 16)两层同宽是常见做法;宽度 16 对 404 个样本足够
    15 layers.Dense(1, activation="linear") # output layer输出层Dense(1, activation="linear"):回归输出 1 个连续值;linear = 恒等 = 不激活 → 输出可为任意实数;17 参数(None, 1)回归输出层不用 sigmoid/tanh(会把输出限制在 (0,1)/(−1,1));可以不写 activation(默认 linear)
    16])闭合 Sequential右括号结束层列表—漏掉 ] 或 ) 会 SyntaxError
    18model.compile(loss="mean_squared_error", optimizer="sgd")compileloss="mean_squared_error"(= "mse"):回归标准损失,(1/n)Σ(ŷ−y)²;optimizer="sgd":随机梯度下降,默认 lr=0.01—没有 metrics——回归的 loss 本身就是指标(不像分类要看 acc)
    19history = model.fit(X_train, y_train, epochs=20, verbose=2,fitepochs=20:20 轮;verbose=2:每轮一行(1=进度条,0=静默);validation_data=(X_test, y_test):每轮结束在测试集上算 val_losshistory 含 loss 和 val_loss 两条各 20 个值严格说这里把测试集当验证集用——教学上方便比较,但不规范(真实项目应三分);404 样本 / batch 32 = 13 步/轮(输出里的 13/13)
    20 validation_data=(X_test, y_test))fitepochs=20:20 轮;verbose=2:每轮一行(1=进度条,0=静默);validation_data=(X_test, y_test):每轮结束在测试集上算 val_losshistory 含 loss 和 val_loss 两条各 20 个值严格说这里把测试集当验证集用——教学上方便比较,但不规范(真实项目应三分);404 样本 / batch 32 = 13 步/轮(输出里的 13/13)
    运行结果 Epoch 1/20 13/13 - 1s - 64ms/step - loss: 245.0043 - val_loss: 81.4963 Epoch 2/20 13/13 - 0s - 9ms/step - loss: 75.2090 - val_loss: 65.2667 Epoch 3/20 13/13 - 0s - 9ms/step - loss: 63.9005 - val_loss: 55.3988 Epoch 4/20 13/13 - 0s - 11ms/step - loss: 56.0047 - val_loss: 48.2542 Epoch 5/20 13/13 - 0s - 9ms/step - loss: 49.7193 - val_loss: 42.2513 Epoch 6/20 13/13 - 0s - 9ms/step - loss: 43.9004 - val_loss: 36.7998 Epoch 7/20 13/13 - 0s - 9ms/step - loss: 38.3883 - val_loss: 32.1486 Epoch 8/20 13/13 - 0s - 9ms/step - loss: 33.7758 - val_loss: 28.6943 Epoch 9/20 13/13 - 0s - 11ms/step - loss: 30.
    深挖 · 读 fit 的输出行:13/13 - 1s - 64ms/step - loss: 245.0043 - val_loss: 81.4963
    ① 13/13:本轮 13 个 batch(404/32 = 12.6 → 13,最后一批 20 个样本);② 1s:本轮耗时(第一轮含图编译所以慢);③ loss:训练集上的平均 MSE;④ val_loss:测试集上的 MSE。
    loss 245 → val_loss 81:第 1 轮训练 loss 高是因为它包含了初始化后前几个 batch 的巨大误差;val_loss 在整轮训练结束后才算,用的是已更新 13 步的权重,所以更低。
    基线 20 轮 → val_loss ≈ 23.9(M18)。MSE 23.9 → RMSE ≈ 4.9 千美元;房价均值 ≈ 22、std ≈ 9 → 比瞎猜(MSE ≈ 80)好很多。Unit 4 讲义 p28–p43 的回归代码实例就是这一段。

    In the final (20th) epoch, the validation loss is about 23.9 (with some variations in the few nearby epochs).

    Cell Baseline#2

    The following is a plot of the training history.

    Cell 21Baseline#2:画训练曲线基础
    # Cell Baseline#2
    
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Cell Baseline#2标记注释———
    3plot_history(history)调用画图函数传入 Baseline#1 的 history(必须先跑 C17)两条下降曲线,val_loss 在 20 轮 ≈ 23.9若 history 是别的实验的 → 画错图;"Restart & Run All" 后 history 是最后跑的那个
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Model summary


    The summary below shows the layers of the model. Note that the input layer with 13 features (i.e. 13 input nodes) is not shown.


    The first (hidden) layer contains 16 neurons; each neuron is connected to 13 input nodes with 13 weights, and has 1 bias, so each neuron has 13+1 trainable parameters. Thus, the first layer has 16 &times; (13 + 1) = 224 trainable parameters. Similarly, the second layer has 16 &times; (16 + 1) = 272 trainable parameters; the third layer has 1 &times; (16 + 1) = 17 trainable parameters.

    参数手算(Course Review "determine the # of trainable parameters" 题型):Dense(16) on 13 维 → 16×(13+1) = 224;Dense(16) on 16 维 → 16×(16+1) = 272;Dense(1) on 16 维 → 1×(16+1) = 17;总 224+272+17 = 513 ✔ 与 summary 的 Trainable params 一致。通用公式:Dense 参数 = (输入维 + 1) × 单元数。Total 515 = 513 + 2:多出的 2 是 SGD 的 iterations 计数器(Unit 8 讲义 "Optimizer=2×Trainable+2" 是 Adam 的情形,SGD 只有 1 个变量但这里显示 2 个——不同 Keras 版本的计数差异,记 Trainable 即可)。
    Cell 23model.summary():看层、形状、参数重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()打印模型摘要列出每层名字(dense_15 这种自动编号)、类型、输出形状、参数数;末尾汇总 Total / Trainable / Non-trainable / Optimizer params224 + 272 + 17 = 513 Trainable;Total 515输入层不显示(Keras 没有显式 InputLayer 时);(None, 16) 的 None 是 batch 维——可变
    运行结果 Model: "sequential_5" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ dense_15 (Dense) │ (None, 16) │ 224 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ dense_16 (Dense) │ (None, 16  Total params: 515 (2.02 KB)  Trainable params: 513 (2.00 KB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 2 (12.00 B)

    Experimenting with ReLU neurons


    Instead of sigmoid neurons, the model below uses ReLU neurons in the hidden layers.

    Cell 25实验 2:隐藏层改 ReLU(只差 L13–L14 的 activation)重点展开
    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()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="relu"),  # hidden layer
        layers.Dense(16, activation="relu"),  # hidden layer
        layers.Dense(1, activation="linear")  # output layer
    ])
    
    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))
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入同 C17(没有 # Cell 注释行)——
    2from tensorflow.keras import layers导入同 C17(没有 # Cell 注释行)——
    3from tensorflow.keras.datasets import boston_housing导入同 C17(没有 # Cell 注释行)——
    5keras.utils.set_random_seed(42)seed 42同 C17 → 初始权重相同—控制变量:只有激活函数不同
    6(X_train, y_train), (X_test, y_test) = boston_housing.load_data()载入数据同 C17——
    8X_train, X_test = normalize_features(X_train, X_test)归一化———
    10model = keras.Sequential([Sequential(———
    11 layers.Dense(16, activation="relu"), # hidden layerhidden → reluReLU(x) = max(0, x):正半轴恒等、负半轴 0;参数数不变(激活不加参数)(None,16)与 C17 唯一的差异
    12 layers.Dense(16, activation="relu"), # hidden layerhidden → reluReLU(x) = max(0, x):正半轴恒等、负半轴 0;参数数不变(激活不加参数)(None,16)与 C17 唯一的差异
    13 layers.Dense(1, activation="linear") # output layer输出层 linear不变(None,1)—
    14])闭合 Sequential———
    16model.compile(loss="mean_squared_error", optimizer="sgd")compile:MSE + sgd不变——
    17history = model.fit(X_train, y_train, epochs=20, verbose=2,fit 20 轮—val_loss 第 2 轮 31.4、第 5 轮 21.9、…、第 20 轮 ≈ 16.6曲线抖动:第 4 轮 67.9、第 7 轮 37.0(ReLU + 固定 lr SGD 容易过冲)
    18 validation_data=(X_test, y_test))fit 20 轮—val_loss 第 2 轮 31.4、第 5 轮 21.9、…、第 20 轮 ≈ 16.6曲线抖动:第 4 轮 67.9、第 7 轮 37.0(ReLU + 固定 lr SGD 容易过冲)
    运行结果 Epoch 1/20 13/13 - 1s - 71ms/step - loss: 298.4414 - val_loss: 81.0497 Epoch 2/20 13/13 - 0s - 9ms/step - loss: 123.3473 - val_loss: 57.7686 Epoch 3/20 13/13 - 0s - 10ms/step - loss: 38.1984 - val_loss: 31.3694 Epoch 4/20 13/13 - 0s - 10ms/step - loss: 24.6823 - val_loss: 67.8733 Epoch 5/20 13/13 - 0s - 10ms/step - loss: 19.2731 - val_loss: 21.9302 Epoch 6/20 13/13 - 0s - 9ms/step - loss: 12.2381 - val_loss: 20.2436 Epoch 7/20 13/13 - 0s - 9ms/step - loss: 10.9269 - val_loss: 37.0116 Epoch 8/20 13/13 - 0s - 9ms/step - loss: 14.1966 - val_loss: 21.7943 Epoch 9/20 13/13 - 0s - 10ms/step - loss:

    The final validation loss is about 16.6, which is quite lower than 23.9 of the baseline model. ReLU neurons perform better than sigmoid neurons for this task.

    为什么 ReLU 比 sigmoid 好:① sigmoid 在 |x|>4 时导数 ≈ 0(饱和),两层 sigmoid 叠加后前层几乎收不到梯度;ReLU 正半轴导数恒为 1,梯度能直接传回去。② sigmoid 输出均值 0.5 不是 0 中心,下一层输入偏置;ReLU 输出 ≥0 但稀疏。③ 但 ReLU 的 val_loss 曲线抖动大(M28 观察到)——因为 ReLU 不可导点在 0、且 lr 固定的 SGD 配 ReLU 容易过冲。这正是 Unit 4 讲义 p17–p22 的对比实验。
    Cell 27画 ReLU 实验曲线基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)画图—val_loss 快速下降但有抖动与 M28 的文字描述对照看
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    As shown in the above plot of training history, the curve of the validation loss fluctuates slightly and is less smooth than the baseline model. The validation loss lowers quite quickly in early epochs (around epoch 2). Overall, training is effective relatively early but is not very steady.

    Experimenting with the Adam optimizer


    Instead of SGD, the model below uses the Adam optimizer.

    Cell 30实验 3:优化器改 Adam(默认 lr=0.001)重点展开
    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()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(1, activation="linear")     # output layer
    ])
    
    model.compile(loss="mean_squared_error", optimizer="adam")
    history = model.fit(X_train, y_train, epochs=20, verbose=2,
                        validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    2from tensorflow.keras import layers同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    3from tensorflow.keras.datasets import boston_housing同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    5keras.utils.set_random_seed(42)同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    6(X_train, y_train), (X_test, y_test) = boston_housing.load_data()同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    8X_train, X_test = normalize_features(X_train, X_test)同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    10model = keras.Sequential([同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    11 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    12 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    13 layers.Dense(1, activation="linear") # output layer同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    14])同 C17(少一行注释,其余相同)sigmoid 两层 + linear—控制变量:只换优化器
    16model.compile(loss="mean_squared_error", optimizer="adam")optimizer="adam"字符串 → Keras 用默认参数:lr=0.001、β₁=0.9、β₂=0.999—关键:Adam 自适应步长但仍受基准 lr 控制;0.001 对"sigmoid×2 + 归一化输入"太小
    17history = model.fit(X_train, y_train, epochs=20, verbose=2,fit—loss 608 → 20 轮后 ≈ 470,每轮只降约 7,线性下降val_loss ≈ 469.9(M31)
    18 validation_data=(X_test, y_test))fit—loss 608 → 20 轮后 ≈ 470,每轮只降约 7,线性下降val_loss ≈ 469.9(M31)
    运行结果 Epoch 1/20 13/13 - 2s - 162ms/step - loss: 608.8168 - val_loss: 633.0062 Epoch 2/20 13/13 - 0s - 24ms/step - loss: 597.8104 - val_loss: 621.9338 Epoch 3/20 13/13 - 0s - 15ms/step - loss: 587.2410 - val_loss: 611.2977 Epoch 4/20 13/13 - 0s - 17ms/step - loss: 577.0776 - val_loss: 601.0325 Epoch 5/20 13/13 - 0s - 13ms/step - loss: 567.2542 - val_loss: 591.0727 Epoch 6/20 13/13 - 0s - 10ms/step - loss: 557.7200 - val_loss: 581.3816 Epoch 7/20 13/13 - 0s - 10ms/step - loss: 548.4493 - val_loss: 571.9428 Epoch 8/20 13/13 - 0s - 10ms/step - loss: 539.4313 - val_loss: 562.7525 Epoch 9/20 13/13 - 0s -

    The final validation loss is about 469.9, which is much higher than 23.9 of the baseline model. In these 20 epochs of training, Adam performs very poorly compared to SGD.

    Adam 为什么"很差"?不是 Adam 差,是学习率配错了。Adam 默认 lr=0.001;sigmoid 在输入 ≈ 0 附近输出 ≈ 0.5、导数 ≈ 0.25,两层相乘梯度 ≈ 0.06,再乘 0.001 → 每步几乎不动。E1b 把 lr 改成 0.1(大 100 倍)→ 21.2 优于 SGD。所以看到"loss 缓慢线性下降、20 轮只降了 25%"的第一反应应该是学习率太小,而不是"优化器不行"。
    Cell 32画 Adam 实验曲线基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)画图—两条近乎平行、缓慢下降的直线形状诊断:"线性慢降" = 学习率过小
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    As shown in the above plot of training history, the losses are reducing and the model is actually learning, even though the learning may be too slow.


    Note that specifying "adam" lets Keras use its default parameters (settings) for the Adam optimizer. As you will see in the Extras section, setting a suitable learning rate can actually make Adam it work very well for the task.

    Practice - Question 1 of 2

    Q1a (Experimenting with tanh neurons)


    Modify the baseline model to use tanh neurons instead of sigmoid neurons in the hidden layers. Specifically, copy the two code cells Baseline#1 and Baseline#2 below, and then change "sigmoid" to "tanh" in the two Dense hidden layers. Remember to execute the two cells in order.

    Cell 36Q1a 你的作答:隐藏层改 tanh练习·作答
    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()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="tanh"),  # hidden layer
        layers.Dense(16, activation="tanh"),  # hidden layer
        layers.Dense(1, activation="linear")  # output layer
    ])
    
    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))
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras同 C17(少注释行)导入 / seed / 载入 / 归一化 / Sequential(——
    2from tensorflow.keras import layers同 C17(少注释行)导入 / seed / 载入 / 归一化 / Sequential(——
    3from tensorflow.keras.datasets import boston_housing同 C17(少注释行)导入 / seed / 载入 / 归一化 / Sequential(——
    5keras.utils.set_random_seed(42)同 C17(少注释行)导入 / seed / 载入 / 归一化 / Sequential(——
    6(X_train, y_train), (X_test, y_test) = boston_housing.load_data()同 C17(少注释行)导入 / seed / 载入 / 归一化 / Sequential(——
    8X_train, X_test = normalize_features(X_train, X_test)同 C17(少注释行)导入 / seed / 载入 / 归一化 / Sequential(——
    10model = keras.Sequential([同 C17(少注释行)导入 / seed / 载入 / 归一化 / Sequential(——
    11 layers.Dense(16, activation="tanh"), # hidden layerhidden → tanhtanh(x) ∈ (−1,1),0 中心;最大导数 1(在 x=0),比 sigmoid 的 0.25 大 4 倍 → 梯度条件更好(None,16)题目要求的改动 ✔
    12 layers.Dense(16, activation="tanh"), # hidden layerhidden → tanhtanh(x) ∈ (−1,1),0 中心;最大导数 1(在 x=0),比 sigmoid 的 0.25 大 4 倍 → 梯度条件更好(None,16)题目要求的改动 ✔
    13 layers.Dense(1, activation="linear") # output layer输出层 linear不变—回归输出仍 linear
    14])闭合 Sequential———
    16model.compile(loss="mean_squared_error", optimizer="sgd")compile:MSE + sgd不变——
    17history = model.fit(X_train, y_train, epochs=20, verbose=2,fit—val_loss 第 2 轮 37.3 → 第 8 轮 20.0 → 第 20 轮 ≈ 16.5比 sigmoid 基线低 7 个点
    18 validation_data=(X_test, y_test))fit—val_loss 第 2 轮 37.3 → 第 8 轮 20.0 → 第 20 轮 ≈ 16.5比 sigmoid 基线低 7 个点
    运行结果 Epoch 1/20 13/13 - 1s - 59ms/step - loss: 239.2959 - val_loss: 50.7421 Epoch 2/20 13/13 - 0s - 9ms/step - loss: 50.0710 - val_loss: 37.3396 Epoch 3/20 13/13 - 0s - 10ms/step - loss: 36.5242 - val_loss: 30.6123 Epoch 4/20 13/13 - 0s - 11ms/step - loss: 28.3350 - val_loss: 26.7989 Epoch 5/20 13/13 - 0s - 10ms/step - loss: 22.1514 - val_loss: 24.5174 Epoch 6/20 13/13 - 0s - 9ms/step - loss: 18.3745 - val_loss: 23.3035 Epoch 7/20 13/13 - 0s - 9ms/step - loss: 15.6651 - val_loss: 23.3815 Epoch 8/20 13/13 - 0s - 9ms/step - loss: 13.6340 - val_loss: 20.0022 Epoch 9/20 13/13 - 0s - 9ms/step - loss: 12
    Cell 37Q1a 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)画图—val_loss 平滑稳定下降Q1b 第 2 问的依据
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Q1b


    Refer to the outputs of Q1a and answer the following questions. Write your answers in a text cell below.


    1. State the validation loss in the final training epoch, and compare this loss to that of the baseline model.

    1. Comment on the curve of validation loss; you may compare the curve to that of the baseline model or develop other comments.

    Q1b 你的作答核对:1. ≈16.5 < 23.9 ✔(tanh 是 0 中心的 sigmoid,梯度条件更好);2. "smoother and more stable than ReLU" ✔——你正确地把它和 ReLU 的抖动做了对比,这正是题目要的 "develop other comments"。

    Solution:


    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.

    Q1c (Experimenting with mean absolute error)


    Modify the baseline model to use mean absolute error as the loss function instead of mean squared error. Specifically, copy the two code cells Baseline#1 and Baseline#2 below, and then change "mean_squared_error" to "mean_absolute_error" in the compile() method call. Remember to execute the two cells in order.

    Cell 41Q1c 你的作答:损失改 MAE练习·作答
    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()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(1, activation="linear")     # output layer
    ])
    
    model.compile(loss="mean_absolute_error", optimizer="sgd")
    history = model.fit(X_train, y_train, epochs=20, verbose=2,
                        validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras同 C17(sigmoid 两层)——控制变量:只换损失
    2from tensorflow.keras import layers同 C17(sigmoid 两层)——控制变量:只换损失
    3from tensorflow.keras.datasets import boston_housing同 C17(sigmoid 两层)——控制变量:只换损失
    5keras.utils.set_random_seed(42)同 C17(sigmoid 两层)——控制变量:只换损失
    6(X_train, y_train), (X_test, y_test) = boston_housing.load_data()同 C17(sigmoid 两层)——控制变量:只换损失
    8X_train, X_test = normalize_features(X_train, X_test)同 C17(sigmoid 两层)——控制变量:只换损失
    10model = keras.Sequential([同 C17(sigmoid 两层)——控制变量:只换损失
    11 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17(sigmoid 两层)——控制变量:只换损失
    12 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17(sigmoid 两层)——控制变量:只换损失
    13 layers.Dense(1, activation="linear") # output layer同 C17(sigmoid 两层)——控制变量:只换损失
    14])同 C17(sigmoid 两层)——控制变量:只换损失
    16model.compile(loss="mean_absolute_error", optimizer="sgd")loss="mean_absolute_error"MAE = (1/n)Σ|ŷ−y|:梯度恒为 sign(ŷ−y)(±1),不会被大误差主导—MAE 与 MSE 数值不可比(见 M44 的纠错)
    17history = model.fit(X_train, y_train, epochs=20, verbose=2,fit—val_loss 22.99 → 8.18,单调平滑下降平滑的原因:梯度幅度恒定、没有平方放大
    18 validation_data=(X_test, y_test))fit—val_loss 22.99 → 8.18,单调平滑下降平滑的原因:梯度幅度恒定、没有平方放大
    运行结果 Epoch 1/20 13/13 - 1s - 68ms/step - loss: 22.7048 - val_loss: 22.9954 Epoch 2/20 13/13 - 0s - 11ms/step - loss: 21.9905 - val_loss: 22.2819 Epoch 3/20 13/13 - 0s - 10ms/step - loss: 21.2722 - val_loss: 21.5587 Epoch 4/20 13/13 - 0s - 11ms/step - loss: 20.5393 - val_loss: 20.8154 Epoch 5/20 13/13 - 0s - 10ms/step - loss: 19.7817 - val_loss: 20.0423 Epoch 6/20 13/13 - 0s - 10ms/step - loss: 18.9898 - val_loss: 19.2302 Epoch 7/20 13/13 - 0s - 10ms/step - loss: 18.1549 - val_loss: 18.3709 Epoch 8/20 13/13 - 0s - 10ms/step - loss: 17.2750 - val_loss: 17.4683 Epoch 9/20 13/13 - 0s - 10ms/step - loss
    Cell 42Q1c 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)画图—两条平滑直线Q1d 的依据
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    Q1d


    Refer to the outputs of Q1c and answer the following questions. Write your answers in a text cell below.


    1. State the validation loss in the final training epoch, and compare this loss to that of the baseline model.

    1. Comment on the curve of validation loss; you may compare the curve to that of the baseline model or develop other comments.

    Solution:


    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. It does not have the situation of being high in the early stage and fluctuating in the later stage like the baseline. The convergence is more stable and the generalization performance is also better.

    Q1d 你的作答——有一个概念性问题要纠正:你写 "MAE 8.18 much lower than MSE 23.9, so MAE is more effective"。MAE 和 MSE 的数值不可直接比较:MSE 的单位是"目标单位的平方"、对大误差平方放大;MAE 的单位与目标相同。Boston 房价 std ≈ 9 → 随机猜的 MSE ≈ 80+、MAE ≈ 7 左右——所以 8.18 甚至可能比基线更差。正确的说法是:"曲线稳步下降、无波动(因为 MAE 的梯度恒为 ±1,不会被大误差主导),但要与 MSE 模型比较需在同一指标下重新 evaluate"——可以 model.compile(loss="mse"); model.evaluate(X_test, y_test) 换算。考试 "compare" 题若遇到不同损失函数,一定要写这一句。

    &#x2766;

    Designing a neural network model

    In this section, you develop a neural network model for a TensorFlow Dataset. TensorFlow Datasets (tfds) are a collection of datasets ready to use with TensorFlow. For more information, see https://www.tensorflow.org/datasets and https://www.tensorflow.org/datasets/api_docs/python/tfds.


    We will use the wine_quality dataset (default config, white wine). In this dataset, the features are objective measures of wine (e.g. PH values) and the label is an evaluation score by experts. You can find a description of this dataset at https://www.tensorflow.org/datasets/catalog/wine_quality. The following load_wine_quality() function loads the dataset.

    Cell 48Q2 数据加载函数:load_wine_quality(红+白葡萄酒,pandas)重点展开
    import pandas as pd
    import numpy as np
    def load_wine_quality(train_ratio=0.8):
        red_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
        white_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
    
        df = pd.concat([
            pd.read_csv(red_url, sep=';'),
            pd.read_csv(white_url, sep=';')
        ], ignore_index=True)
    
        LABEL_COL = "quality"
    
        # split
        n_train = int(len(df) * train_ratio)
        train_df = df.iloc[:n_train]
        test_df  = df.iloc[n_train:]
    
        X_train = train_df.drop(columns=[LABEL_COL]).values
        y_train = train_df[LABEL_COL].values
        X_test  = test_df.drop(columns=[LABEL_COL]).values
        y_test  = test_df[LABEL_COL].values
    
        return X_train, y_train, X_test, y_test
    #代码作用机制·语法关联·结果易错点
    1import pandas as pd导入 pandas / numpypandas 读 CSV 并做表格操作——
    2import numpy as np导入 pandas / numpypandas 读 CSV 并做表格操作——
    3def load_wine_quality(train_ratio=0.8):定义函数参数 train_ratio=0.8 默认 8:2 切分——
    4 red_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"两个 CSV 的 URLUCI 葡萄酒质量数据集:红 1,599 行 + 白 4,898 行;分号分隔—pd.read_csv(url, sep=';') 直接从网络读——离线会失败
    5 white_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"两个 CSV 的 URLUCI 葡萄酒质量数据集:红 1,599 行 + 白 4,898 行;分号分隔—pd.read_csv(url, sep=';') 直接从网络读——离线会失败
    7 df = pd.concat([读取并纵向拼接pd.concat([...], ignore_index=True):两个 DataFrame 叠成一个,重排行号 0..6497df 6,497 行 × 12 列(红 1,599 + 白 4,898)ignore_index=False 会保留两套 0..1598 的索引 → iloc 仍按位置但 loc 会混乱
    8 pd.read_csv(red_url, sep=';'),读取并纵向拼接pd.concat([...], ignore_index=True):两个 DataFrame 叠成一个,重排行号 0..6497df 6,497 行 × 12 列(红 1,599 + 白 4,898)ignore_index=False 会保留两套 0..1598 的索引 → iloc 仍按位置但 loc 会混乱
    9 pd.read_csv(white_url, sep=';')读取并纵向拼接pd.concat([...], ignore_index=True):两个 DataFrame 叠成一个,重排行号 0..6497df 6,497 行 × 12 列(红 1,599 + 白 4,898)ignore_index=False 会保留两套 0..1598 的索引 → iloc 仍按位置但 loc 会混乱
    10 ], ignore_index=True)读取并纵向拼接pd.concat([...], ignore_index=True):两个 DataFrame 叠成一个,重排行号 0..6497df 6,497 行 × 12 列(红 1,599 + 白 4,898)ignore_index=False 会保留两套 0..1598 的索引 → iloc 仍按位置但 loc 会混乱
    12 LABEL_COL = "quality"标签列名常量字符串"quality"—
    14 # split训练样本数int(len(df)*0.8) = 5,198n_train = 5197注意:题目说 3918/980——那是只用白葡萄酒;你的函数把红白合并了 → 5198/1300(C50 输出)。两种都满足 "wine_quality dataset",但数字与 M49 文字不符
    15 n_train = int(len(df) * train_ratio)训练样本数int(len(df)*0.8) = 5,198n_train = 5197注意:题目说 3918/980——那是只用白葡萄酒;你的函数把红白合并了 → 5198/1300(C50 输出)。两种都满足 "wine_quality dataset",但数字与 M49 文字不符
    16 train_df = df.iloc[:n_train]iloc 位置切分前 80% 训练、后 20% 测试;没有 shuffle——红酒在前、白酒在后,所以训练集含全部红酒+部分白酒,测试集全是白酒—分布偏移风险:测试集只含白葡萄酒。更规范:df = df.sample(frac=1, random_state=42) 后再切(t06 会教 validation_split / shuffle)
    17 test_df = df.iloc[n_train:]iloc 位置切分前 80% 训练、后 20% 测试;没有 shuffle——红酒在前、白酒在后,所以训练集含全部红酒+部分白酒,测试集全是白酒—分布偏移风险:测试集只含白葡萄酒。更规范:df = df.sample(frac=1, random_state=42) 后再切(t06 会教 validation_split / shuffle)
    19 X_train = train_df.drop(columns=[LABEL_COL]).values分离特征与标签drop(columns=["quality"]) 去掉标签列 → 11 列特征;.values 把 DataFrame 转 ndarray(Keras 接受 ndarray)X (5198,11) y (5198,)标签 quality 是 3–9 的整数(但按回归处理,不是分类)
    20 y_train = train_df[LABEL_COL].values分离特征与标签drop(columns=["quality"]) 去掉标签列 → 11 列特征;.values 把 DataFrame 转 ndarray(Keras 接受 ndarray)X (5198,11) y (5198,)标签 quality 是 3–9 的整数(但按回归处理,不是分类)
    21 X_test = test_df.drop(columns=[LABEL_COL]).values分离特征与标签drop(columns=["quality"]) 去掉标签列 → 11 列特征;.values 把 DataFrame 转 ndarray(Keras 接受 ndarray)X (5198,11) y (5198,)标签 quality 是 3–9 的整数(但按回归处理,不是分类)
    22 y_test = test_df[LABEL_COL].values分离特征与标签drop(columns=["quality"]) 去掉标签列 → 11 列特征;.values 把 DataFrame 转 ndarray(Keras 接受 ndarray)X (5198,11) y (5198,)标签 quality 是 3–9 的整数(但按回归处理,不是分类)
    24 return X_train, y_train, X_test, y_test返回四个数组顺序同 Keras 的 load_data——

    This code loads the dataset and displays its dimensions. The training set contains 3918 examples, and the test set contains 980 examples. An example has 11 features and a label.

    Cell 50Q2 载入并看形状基础
    X_train, y_train, X_test, y_test = load_wine_quality()
    print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
    #代码作用机制·语法关联·结果易错点
    1X_train, y_train, X_test, y_test = load_wine_quality()调用函数使用默认 train_ratio——
    2print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)打印形状—(5197,11) (5197,) (1300,11) (1300,)6497×0.8 = 5197.6 → int = 5197 ✔;测试 1300
    运行结果 (5197, 11) (5197,) (1300, 11) (1300,)

    Practice - Question 2 of 2

    Q2a


    Write code to train a model for the wine_quality dataset. Specifically:


  • load the wine_quality dataset,
  • normalize the features,
  • create a Keras model,
  • compile the model,
  • train the model, and
  • plot the training history.

  • Try different components in the model design in order to improve the model performance. An MSE loss <= 0.5 is acceptable; you are not required to search extensively for the lowest loss. Submit the best model of your choice, and keep its execution output.


    These are some suggestions, but not requirements, of possible components that you may try:


  • 1 to 3 hidden layers,
  • 8 to 64 neurons in a hidden layer,
  • ReLU, sigmoid, or tanh neurons in the hidden layers,
  • SGD, Adam, or RMSProp optimizer, and
  • 10 to 50 training epochs.
  • Q2a 你的模型核对:64-32-1 ReLU + Adam lr=0.005 + 30 轮 → val_loss 第 3 轮就到 0.4929 < 0.5 ✔ 达标(题目要求 ≤0.5)。最终约 0.45。参数:Dense(64) on 11 → 64×12 = 768;Dense(32) on 64 → 32×65 = 2,080;Dense(1) on 32 → 33;总 2,881。Wine 的标签是 3–9 的整数评分,MSE 0.45 意味着 RMSE ≈ 0.67 分——C57 的预测对比能看到误差多在 ±0.5。
    Cell 53Q2a 你的作答:64-32-1 ReLU + Adam lr=0.005,30 轮重点展开
    import pandas as pd
    import numpy as np
    from tensorflow import keras
    from tensorflow.keras import layers
    import matplotlib.pyplot as plt
    
    # Load data
    X_train, y_train, X_test, y_test = load_wine_quality()
    
    # Normalize features (important!)
    def normalize_features(X_train, X_test):
        mean = X_train.mean(axis=0)
        std = X_train.std(axis=0)
        X_train_norm = (X_train - mean) / std
        X_test_norm = (X_test - mean) / std
        return X_train_norm, X_test_norm
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    # Set random seed for reproducibility
    keras.utils.set_random_seed(42)
    
    # Create model
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),  # hidden layer 1
        layers.Dense(32, activation="relu"),  # hidden layer 2
        layers.Dense(1, activation="linear")  # output layer
    ])
    
    # Compile with Adam optimizer
    opt = keras.optimizers.Adam(learning_rate=0.005)
    model.compile(loss="mean_squared_error", optimizer=opt)
    # Train
    history = model.fit(X_train, y_train, epochs=30, verbose=2,
                        validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1import pandas as pd导入pandas/numpy/keras/layers/plt—pd、np 实际没用到但无害
    2import numpy as np导入pandas/numpy/keras/layers/plt—pd、np 实际没用到但无害
    3from tensorflow import keras导入pandas/numpy/keras/layers/plt—pd、np 实际没用到但无害
    4from tensorflow.keras import layers导入pandas/numpy/keras/layers/plt—pd、np 实际没用到但无害
    5import matplotlib.pyplot as plt导入pandas/numpy/keras/layers/plt—pd、np 实际没用到但无害
    7# Load data载入调用 C48 的函数——
    8X_train, y_train, X_test, y_test = load_wine_quality()载入调用 C48 的函数——
    10# Normalize features (important!)重新定义 normalize_features与 C14 相同逻辑,只是变量名 X_train_norm—重复定义覆盖了 C14 的版本——功能相同所以无影响;但若改了逻辑会悄悄影响后面的 cell
    11def normalize_features(X_train, X_test):重新定义 normalize_features与 C14 相同逻辑,只是变量名 X_train_norm—重复定义覆盖了 C14 的版本——功能相同所以无影响;但若改了逻辑会悄悄影响后面的 cell
    12 mean = X_train.mean(axis=0)重新定义 normalize_features与 C14 相同逻辑,只是变量名 X_train_norm—重复定义覆盖了 C14 的版本——功能相同所以无影响;但若改了逻辑会悄悄影响后面的 cell
    13 std = X_train.std(axis=0)重新定义 normalize_features与 C14 相同逻辑,只是变量名 X_train_norm—重复定义覆盖了 C14 的版本——功能相同所以无影响;但若改了逻辑会悄悄影响后面的 cell
    14 X_train_norm = (X_train - mean) / std重新定义 normalize_features与 C14 相同逻辑,只是变量名 X_train_norm—重复定义覆盖了 C14 的版本——功能相同所以无影响;但若改了逻辑会悄悄影响后面的 cell
    15 X_test_norm = (X_test - mean) / std重新定义 normalize_features与 C14 相同逻辑,只是变量名 X_train_norm—重复定义覆盖了 C14 的版本——功能相同所以无影响;但若改了逻辑会悄悄影响后面的 cell
    16 return X_train_norm, X_test_norm重新定义 normalize_features与 C14 相同逻辑,只是变量名 X_train_norm—重复定义覆盖了 C14 的版本——功能相同所以无影响;但若改了逻辑会悄悄影响后面的 cell
    18X_train, X_test = normalize_features(X_train, X_test)归一化——注释 "(important!)" ✔
    20# Set random seed for reproducibilityseed 42———
    21keras.utils.set_random_seed(42)seed 42———
    23# Create model模型 64-32-1比 Boston 的 16-16 宽(数据 5198 个样本更多);ReLU 隐藏层;linear 输出。参数:64×12=768、32×65=2,080、1×33=33 → 2,881(None,64)→(None,32)→(None,1)漏斗形 64→32 是常见设计
    24model = keras.Sequential([模型 64-32-1比 Boston 的 16-16 宽(数据 5198 个样本更多);ReLU 隐藏层;linear 输出。参数:64×12=768、32×65=2,080、1×33=33 → 2,881(None,64)→(None,32)→(None,1)漏斗形 64→32 是常见设计
    25 layers.Dense(64, activation="relu"), # hidden layer 1模型 64-32-1比 Boston 的 16-16 宽(数据 5198 个样本更多);ReLU 隐藏层;linear 输出。参数:64×12=768、32×65=2,080、1×33=33 → 2,881(None,64)→(None,32)→(None,1)漏斗形 64→32 是常见设计
    26 layers.Dense(32, activation="relu"), # hidden layer 2模型 64-32-1比 Boston 的 16-16 宽(数据 5198 个样本更多);ReLU 隐藏层;linear 输出。参数:64×12=768、32×65=2,080、1×33=33 → 2,881(None,64)→(None,32)→(None,1)漏斗形 64→32 是常见设计
    27 layers.Dense(1, activation="linear") # output layer模型 64-32-1比 Boston 的 16-16 宽(数据 5198 个样本更多);ReLU 隐藏层;linear 输出。参数:64×12=768、32×65=2,080、1×33=33 → 2,881(None,64)→(None,32)→(None,1)漏斗形 64→32 是常见设计
    28])模型 64-32-1比 Boston 的 16-16 宽(数据 5198 个样本更多);ReLU 隐藏层;linear 输出。参数:64×12=768、32×65=2,080、1×33=33 → 2,881(None,64)→(None,32)→(None,1)漏斗形 64→32 是常见设计
    30# Compile with Adam optimizerAdam lr=0.005显式创建优化器对象并设 lr;比默认 0.001 大 5 倍(E1b 的教训:归一化 + ReLU 可以用较大 lr)opt 对象0.005 配 ReLU 稳定;配 sigmoid 可能震荡
    31opt = keras.optimizers.Adam(learning_rate=0.005)Adam lr=0.005显式创建优化器对象并设 lr;比默认 0.001 大 5 倍(E1b 的教训:归一化 + ReLU 可以用较大 lr)opt 对象0.005 配 ReLU 稳定;配 sigmoid 可能震荡
    32model.compile(loss="mean_squared_error", optimizer=opt)compileMSE 回归——
    33# Trainfit 30 轮5198/32 = 163 步/轮(输出 163/163);validation_data 用测试集val_loss 第 3 轮 0.4929 < 0.5 ✔ 达标—
    34history = model.fit(X_train, y_train, epochs=30, verbose=2,fit 30 轮5198/32 = 163 步/轮(输出 163/163);validation_data 用测试集val_loss 第 3 轮 0.4929 < 0.5 ✔ 达标—
    35 validation_data=(X_test, y_test))fit 30 轮5198/32 = 163 步/轮(输出 163/163);validation_data 用测试集val_loss 第 3 轮 0.4929 < 0.5 ✔ 达标—
    运行结果 Epoch 1/30 163/163 - 2s - 10ms/step - loss: 3.1841 - val_loss: 0.9257 Epoch 2/30 163/163 - 0s - 3ms/step - loss: 0.8238 - val_loss: 0.5765 Epoch 3/30 163/163 - 0s - 3ms/step - loss: 0.5828 - val_loss: 0.4929 Epoch 4/30 163/163 - 0s - 3ms/step - loss: 0.5477 - val_loss: 0.4881 Epoch 5/30 163/163 - 0s - 3ms/step - loss: 0.5384 - val_loss: 0.4841 Epoch 6/30 163/163 - 0s - 3ms/step - loss: 0.5313 - val_loss: 0.4775 Epoch 7/30 163/163 - 0s - 3ms/step - loss: 0.5264 - val_loss: 0.4767 Epoch 8/30 163/163 - 0s - 3ms/step - loss: 0.5216 - val_loss: 0.4788 Epoch 9/30 163/163 - 0s - 3ms/step - loss: 0.51
    Cell 54Q2a 画图(带标题、轴标签、show)基础
    plt.plot(history.history["loss"], label="loss")
    plt.plot(history.history["val_loss"], label="val_loss")
    plt.legend()
    plt.xlabel("Epoch")
    plt.ylabel("MSE Loss")
    plt.title("Wine Quality Model Training History")
    plt.show()
    #代码作用机制·语法关联·结果易错点
    1plt.plot(history.history["loss"], label="loss")画 loss / val_loss / legend同 C14——
    2plt.plot(history.history["val_loss"], label="val_loss")画 loss / val_loss / legend同 C14——
    3plt.legend()画 loss / val_loss / legend同 C14——
    4plt.xlabel("Epoch")轴标签 + 标题比 C14 更完整——
    5plt.ylabel("MSE Loss")轴标签 + 标题比 C14 更完整——
    6plt.title("Wine Quality Model Training History")轴标签 + 标题比 C14 更完整——
    7plt.show()show显式显示——
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    &#x2766;

    You may use the following code to do prediction using the trained model.

    Cell 57Q2 预测对比:前 10 个测试样本基础
    N = 10
    y_pred = model.predict(X_test[:N], verbose=0)
    print("Actual:   ", *[f"{x:4.1f}" for x in y_test[:N]])
    print("Predicted:", *[f"{x:4.1f}" for x in y_pred.ravel()])
    #代码作用机制·语法关联·结果易错点
    1N = 10N = 10只看前 10 个——
    2y_pred = model.predict(X_test[:N], verbose=0)predict 前 10 个X_test[:N] (10,11) → 输出 (10,1)y_pred—
    3print("Actual: ", *[f"{x:4.1f}" for x in y_test[:N]])打印实际值*[f"{x:4.1f}" for x in ...]:推导式生成 10 个宽度 4、1 位小数的字符串,* 解包成 print 的多个参数(空格分隔)Actual: 7.0 6.0 …* 解包是 Python 语法;f"{x:4.1f}" 右对齐 4 字符
    4print("Predicted:", *[f"{x:4.1f}" for x in y_pred.ravel()])打印预测值y_pred.ravel() 把 (10,1) 压平成 (10,) 才能逐个格式化Predicted: 6.7 5.1 …不 ravel → 每个元素是长度 1 的数组,f 格式化会得到 "[6.7]"
    运行结果 Actual: 7.0 6.0 6.0 7.0 6.0 7.0 6.0 5.0 5.0 6.0 Predicted: 6.7 5.1 6.2 5.8 6.0 7.1 5.8 5.2 5.1 6.0

    Extras

    More experiments

    E1a (Experimenting with the RMSProp optimizer)

    Modify the baseline model to use the RMSProp optimizer instead of the SGD optimizer. Specifically, copy the two code cells Baseline#1 and Baseline#2 below, and then change "sgd" to "rmsprop" in the compile() method call. Remember to execute the two cells in order.


    State the validation loss in the final training epoch, and compare this loss to that of the baseline model. Comment on the curve of validation loss.

    E1b (Experimenting with a customized Adam optimizer)

    Modify the baseline model to use a customized Adam optimizer instead of the SGD optimizer. Specifically, copy the two code cells Baseline#1 and Baseline#2 below, and then:


  • create an Adam optimizer with a learning rate 0.1, and
  • use that Adam optimizer in the `compile()` method call.

  • The modified code is shown below:


    adam_opt = keras.optimizers.Adam(learning_rate=0.1)
    model.compile(loss="mean_squared_error", optimizer=adam_opt)
    

    Remember to execute the two cells in order.


    State the validation loss in the final training epoch, and compare this loss to that of the baseline model. Comment on the curve of validation loss.

    E1c (Experimenting with no feature normalization)

    In the program of the baseline model, the input features are normalized. Modify the program so that the features are not normalized. Specifically, copy the two code cells Baseline#1 and Baseline#2 below, and then remove or comment out the line that calls the normalize_features() function. Remember to execute the two cells in order.


    State the validation loss in the final training epoch, and compare this loss to that of the baseline model. Comment on the curve of validation curve.

    Solutions to extra exercises

    E1a
    Cell 65E1a 解答:优化器改 RMSprop(默认 lr=0.001)练习·作答
    # Solution
    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()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(1, activation="linear")     # output layer
    ])
    
    model.compile(loss="mean_squared_error", optimizer="rmsprop")
    history = model.fit(X_train, y_train, epochs=20, verbose=2,
              validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1# Solution同 C17———
    2from tensorflow import keras同 C17———
    3from tensorflow.keras import layers同 C17———
    4from tensorflow.keras.datasets import boston_housing同 C17———
    6keras.utils.set_random_seed(42)同 C17———
    7(X_train, y_train), (X_test, y_test) = boston_housing.load_data()同 C17———
    9X_train, X_test = normalize_features(X_train, X_test)同 C17———
    11model = keras.Sequential([同 C17———
    12 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17———
    13 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17———
    14 layers.Dense(1, activation="linear") # output layer同 C17———
    15])同 C17———
    17model.compile(loss="mean_squared_error", optimizer="rmsprop")optimizer="rmsprop"RMSprop 默认 lr=0.001、ρ=0.9;与 Adam 同样受小 lr 影响——
    18history = model.fit(X_train, y_train, epochs=20, verbose=2,fit缩进少了 2 格但仍在函数调用括号内——合法val_loss ≈ 463.3,与 Adam 几乎一样曲线形状同 Adam:线性慢降
    19 validation_data=(X_test, y_test))fit缩进少了 2 格但仍在函数调用括号内——合法val_loss ≈ 463.3,与 Adam 几乎一样曲线形状同 Adam:线性慢降
    运行结果 Epoch 1/20 13/13 - 1s - 79ms/step - loss: 604.3279 - val_loss: 626.2670 Epoch 2/20 13/13 - 0s - 9ms/step - loss: 590.9719 - val_loss: 614.6714 Epoch 3/20 13/13 - 0s - 9ms/step - loss: 580.1841 - val_loss: 603.9874 Epoch 4/20 13/13 - 0s - 9ms/step - loss: 570.0052 - val_loss: 593.7173 Epoch 5/20 13/13 - 0s - 9ms/step - loss: 560.1910 - val_loss: 583.7769 Epoch 6/20 13/13 - 0s - 9ms/step - loss: 550.6938 - val_loss: 574.1365 Epoch 7/20 13/13 - 0s - 9ms/step - loss: 541.4748 - val_loss: 564.7508 Epoch 8/20 13/13 - 0s - 11ms/step - loss: 532.5129 - val_loss: 555.6362 Epoch 9/20 13/13 - 0s - 9ms/st
    Cell 66E1a 画图基础
    # Solution
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution注释———
    2plot_history(history)画图———
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    The final validation loss is about 463.3, which is much higher than 23.9 of the baseline model. In these 20 epochs of training, RMSProp performs very poorly compared to SGD.


    The curve of validation loss is very similar to the case of Adam. The losses are high but decreasing, indicating some slow learning.

    E1b
    Cell 69E1b 解答:Adam lr=0.1重点展开
    # Solution
    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()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(1, activation="linear")     # output layer
    ])
    
    adam_opt = keras.optimizers.Adam(learning_rate=0.1)
    model.compile(loss="mean_squared_error", optimizer=adam_opt)
    history = model.fit(X_train, y_train, epochs=20, verbose=2,
              validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1# Solution同 C17———
    2from tensorflow import keras同 C17———
    3from tensorflow.keras import layers同 C17———
    4from tensorflow.keras.datasets import boston_housing同 C17———
    6keras.utils.set_random_seed(42)同 C17———
    7(X_train, y_train), (X_test, y_test) = boston_housing.load_data()同 C17———
    9X_train, X_test = normalize_features(X_train, X_test)同 C17———
    11model = keras.Sequential([同 C17———
    12 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17———
    13 layers.Dense(16, activation="sigmoid"), # hidden layer同 C17———
    14 layers.Dense(1, activation="linear") # output layer同 C17———
    15])同 C17———
    17adam_opt = keras.optimizers.Adam(learning_rate=0.1)创建 Adam(lr=0.1)显式指定学习率,比默认大 100 倍adam_opt 对象—
    18model.compile(loss="mean_squared_error", optimizer=adam_opt)compile 用对象optimizer 参数可接受字符串或优化器对象——
    19history = model.fit(X_train, y_train, epochs=20, verbose=2,fit—val_loss 170 → 第 2 轮 84 → 第 20 轮 ≈ 21.2,优于 SGD 的 23.9与 C30 对比:同一优化器、不同 lr → 469.9 vs 21.2,证明 lr 是关键
    20 validation_data=(X_test, y_test))fit—val_loss 170 → 第 2 轮 84 → 第 20 轮 ≈ 21.2,优于 SGD 的 23.9与 C30 对比:同一优化器、不同 lr → 469.9 vs 21.2,证明 lr 是关键
    运行结果 Epoch 1/20 13/13 - 1s - 92ms/step - loss: 364.1589 - val_loss: 170.1368 Epoch 2/20 13/13 - 0s - 8ms/step - loss: 102.9480 - val_loss: 84.4871 Epoch 3/20 13/13 - 0s - 8ms/step - loss: 89.6025 - val_loss: 75.8175 Epoch 4/20 13/13 - 0s - 8ms/step - loss: 70.4991 - val_loss: 59.6751 Epoch 5/20 13/13 - 0s - 8ms/step - loss: 56.3263 - val_loss: 49.4119 Epoch 6/20 13/13 - 0s - 8ms/step - loss: 48.4531 - val_loss: 43.5143 Epoch 7/20 13/13 - 0s - 9ms/step - loss: 44.4016 - val_loss: 40.6923 Epoch 8/20 13/13 - 0s - 8ms/step - loss: 38.7069 - val_loss: 36.4770 Epoch 9/20 13/13 - 0s - 8ms/step - loss: 30.
    Cell 70E1b 画图基础
    # Solution
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution注释 / 画图—曲线形状与基线相似—
    2plot_history(history)注释 / 画图—曲线形状与基线相似—
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    The final validation loss is about 21.2, which is lower than 23.9 of the baseline model. Adam with a suitable learning rate works better than SGD for the task.


    The curve of validation loss is similar to that of the baseline model.

    E1c
    Cell 73E1c 解答:不归一化重点展开
    # Solution
    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()
    
    # X_train, X_test = normalize_features(X_train, X_test)
    
    model = keras.Sequential([
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(16, activation="sigmoid"),  # hidden layer
        layers.Dense(1, activation="linear")     # output layer
    ])
    
    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))
    #代码作用机制·语法关联·结果易错点
    1# Solution同 C17———
    2from tensorflow import keras同 C17———
    3from tensorflow.keras import layers同 C17———
    4from tensorflow.keras.datasets import boston_housing同 C17———
    6keras.utils.set_random_seed(42)同 C17———
    7(X_train, y_train), (X_test, y_test) = boston_housing.load_data()同 C17———
    9# X_train, X_test = normalize_features(X_train, X_test)注释掉归一化X 保持原始尺度:特征 2 ≈ 0.0–0.9、特征 12 ≈ 300–700—这就是 E1c 的唯一改动
    11model = keras.Sequential([模型不变———
    12 layers.Dense(16, activation="sigmoid"), # hidden layer模型不变———
    13 layers.Dense(16, activation="sigmoid"), # hidden layer模型不变———
    14 layers.Dense(1, activation="linear") # output layer模型不变———
    15])模型不变———
    17model.compile(loss="mean_squared_error", optimizer="sgd")compile 不变———
    18history = model.fit(X_train, y_train, epochs=20, verbose=2,fit—val_loss 86 → 第 2 轮后卡在 ≈ 79.5 水平线诊断:"水平线不动" = 梯度被大尺度特征淹没 / sigmoid 饱和(输入达几百 → σ 饱和 → 梯度 0)
    19 validation_data=(X_test, y_test))fit—val_loss 86 → 第 2 轮后卡在 ≈ 79.5 水平线诊断:"水平线不动" = 梯度被大尺度特征淹没 / sigmoid 饱和(输入达几百 → σ 饱和 → 梯度 0)
    运行结果 Epoch 1/20 13/13 - 1s - 74ms/step - loss: 240.2499 - val_loss: 85.9966 Epoch 2/20 13/13 - 0s - 35ms/step - loss: 85.0180 - val_loss: 83.2166 Epoch 3/20 13/13 - 0s - 11ms/step - loss: 84.3991 - val_loss: 81.7578 Epoch 4/20 13/13 - 0s - 14ms/step - loss: 83.5500 - val_loss: 83.3779 Epoch 5/20 13/13 - 0s - 15ms/step - loss: 84.8286 - val_loss: 83.0458 Epoch 6/20 13/13 - 0s - 15ms/step - loss: 84.5798 - val_loss: 82.8497 Epoch 7/20 13/13 - 0s - 11ms/step - loss: 84.2870 - val_loss: 82.6245 Epoch 8/20 13/13 - 0s - 8ms/step - loss: 83.9568 - val_loss: 82.3656 Epoch 9/20 13/13 - 0s - 8ms/step - loss:
    Cell 74E1c 画图基础
    # Solution
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution注释 / 画图—两条几乎水平的线与 M75 的文字对照
    2plot_history(history)注释 / 画图—两条几乎水平的线与 M75 的文字对照
    运行结果 <Figure size 640x480 with 1 Axes> [image/png]

    The final validation loss is about 79.5, which is much higher than 23.9 of the baseline model. Without feature normalization, the model cannot be trained or the training is extremely slow.


    The curve of validation loss is mainly horizontal, indicating not much learning is achieved.

    &#x2766;

    📘 Tutorial 5(= Lab 5)· 多分类与二分类(MNIST 手写数字 → 奇偶二分类;Wine Quality 11 分类)

    t05-s13903054.ipynb,61 cells。对应 Unit 5 讲义 p6–p18(分类与反向传播)、p19–p40(softmax、交叉熵、二分类)。核心三件套:softmax 输出 + 交叉熵损失 + argmax 读结果。结果速览:MNIST 64-64-10 → 30 轮 val_acc ≈ 0.96(第 1 轮就 0.8392);Q1 奇偶二分类 Dense(1,sigmoid)+bce → 第 1 轮 val_acc 0.9032、最终 ≈ 0.98;Q2 葡萄酒 11 类 → val_acc ≈ 0.56–0.58(刚好过 0.56 线);E1 sparse 与 categorical 结果逐位相同。
    读法:本 Lab 是第一次做"分类",与 t04 回归的唯一结构差别在输出层与损失函数:回归是 Dense(1) 线性 + MSE;多分类是 Dense(类别数, softmax) + categorical_crossentropy(标签 one-hot)或 sparse_categorical_crossentropy(标签整数);二分类是 Dense(1, sigmoid) + binary_crossentropy(标签 0/1)。C12 四个工具函数(载入子集 / 缩放+展平 / one-hot / 画图)被后面所有 cell 复用,是本 notebook 的"库"。
    四个必会数字:① 15000/256 = 58.6 → 59 步/轮;② 多分类参数 64×785 + 64×65 + 10×65 = 50,240+4,160+650 = 55,050;③ 二分类把 Dense(10) 换成 Dense(1) → 50,240+4,160+65 = 54,465(少 585);④ wine 3918/32 = 122.4 → 123 步/轮,3918/256 = 15.3 → 16 步。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同前IPython 魔术命令;须在 import tensorflow 前env: TF_CPP_MIN_LOG_LEVEL=2每个 notebook 第一个 cell
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • multiclass classification and binary classification tasks, and
  • designing a neural network for classification.
  • Student name: Yin Bang
    Student ID: 13903054

    Multiclass and binary classification

    Two main types of classification tasks are multiclass and binary classification. We first work on a neural network for a multiclass classification task -- classifying hand-written digit images.

    The dataset


    The MNIST dataset consists of hand-written digit images and labels. There are 60,000 training examples and 10,000 test examples. Each example is a 2D 28&times;28 image, and consists of 28&times;28 = 784 grayscale pixels.


    The following code loads the dataset, and prints the dimensions and data type of the dataset.

    MNIST 四个张量:X 是 (N, 28, 28) 的 uint8 灰度图(0–255),y 是 (N,) 的整数标签 0–9。这里 y 还没有 one-hot——one-hot 是在 C15 里手动做的;而 keras.datasets.mnist.load_data() 返回的顺序固定是 (X_train, y_train), (X_test, y_test),所以 L3 的括号解包顺序不能错。
    Cell 8载入 MNIST 并查看形状 / dtype导入·绘图·输出
    from tensorflow.keras.datasets import mnist
    
    (X_train, y_train), (X_test, y_test) = mnist.load_data()
    print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
    print(X_train.dtype, y_train.dtype, X_test.dtype, y_test.dtype)
    #代码作用机制·语法关联·结果易错点
    1from tensorflow.keras.datasets import mnist导入 mnist 数据集模块来自 keras.datasets,首次运行会下载 mnist.npz——
    3(X_train, y_train), (X_test, y_test) = mnist.load_data()载入并解包返回 ((X_train, y_train), (X_test, y_test)) 两个元组的元组X_train (60000,28,28)解包顺序不能反;返回的是 numpy 数组而非 tf.data
    4print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)打印四个张量的形状—(60000, 28, 28) (60000,) (10000, 28, 28) (10000,)—
    5print(X_train.dtype, y_train.dtype, X_test.dtype, y_test.dtype)打印 dtypeuint8 = 0–255 的整数全部 uint8dtype 决定后面为什么要 /255
    运行结果 Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step (60000, 28, 28) (60000,) (10000, 28, 28) (10000,) uint8 uint8 uint8 uint8

    The first 20 labels and images in the test set are displayed below.

    ↳ 题目说"前 20 个"但 C10 的 subplots(4, 5) 正好 4×5 = 20 张;cmap=plt.cm.gray_r 的 _r 是 reverse(黑底白字→白底黑字),数字看起来更自然。
    Cell 10显示测试集前 20 张数字图导入·绘图·输出
    # Display first 20 digits
    import matplotlib.pyplot as plt
    
    print(y_test[:20])
    fig, axs = plt.subplots(4, 5, figsize=(10, 5))
    for i, ax in enumerate(axs.flat):
        im = ax.imshow(X_test[i], cmap=plt.cm.gray_r)
        ax.axis("off")
    fig.colorbar(im, ax=axs.ravel().tolist(), shrink=0.95);
    #代码作用机制·语法关联·结果易错点
    1# Display first 20 digits注释———
    2import matplotlib.pyplot as plt导入 pyplotas plt——
    4print(y_test[:20])打印前 20 个标签与下面 20 张图一一对应[7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4]标签顺序 = 图片顺序
    5fig, axs = plt.subplots(4, 5, figsize=(10, 5))创建 4×5 网格子图figsize=(10,5) 英寸;返回 fig 与 4×5 的 Axes 数组 axs—subplots 返回 (fig, ax);单行/列时 axs 是一维数组,要 .flat 遍历
    6for i, ax in enumerate(axs.flat):遍历 20 个子图轴enumerate(axs.flat) 把二维数组展平,i 是 0–19 的序号—axs.flat 是迭代器,不是数组
    7 im = ax.imshow(X_test[i], cmap=plt.cm.gray_r)在第 i 个轴上画第 i 张图imshow 显示 28×28 灰度阵;cmap=gray_r 反色(白底黑字)im 保存最后的 Image 对象,供 colorbar 用X_test[i] 是 (28,28),不要 reshape
    8 ax.axis("off")关闭坐标轴———
    9fig.colorbar(im, ax=axs.ravel().tolist(), shrink=0.95);添加颜色条并抑制输出fig.colorbar(im, ax=axs.ravel().tolist()) 让色条横跨整个网格;shrink=0.95 缩短 5%;结尾分号抑制 Out[]
    21 = 20 张图 + 1 个色条;分号是 notebook 专有技巧
    运行结果 [7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4] <Figure size 1000x500 with 21 Axes> [image/png]

    The multiclass classification model


    The following functions are utilities to load a subset of the dataset, scale and perform 2D-to-1D conversion on input features, one-hot encode categorical labels, and plot the training history. They are used several times in the programs below.

    为什么只取 25%:C12 的 ratio=0.25 让训练集从 60,000 降到 15,000、测试集 10,000 → 2,500,训练时间降到 1/4,课堂演示够用。代价是精度略降(完整集同样模型可达 0.97–0.98)。归一化为什么除以 255:uint8 的最大值是 255,/255 把像素压到 [0,1],与 t04 的 (x-mean)/std 标准化不同——图像所有像素同尺度,简单缩放就够。
    Cell 12工具函数:载入子集 / 缩放展平 / one-hot / 画历史曲线重点展开
    import matplotlib.pyplot as plt
    from tensorflow import keras
    
    def load_mnist_dataset(ratio=0.25):
        (X_train, y_train), (X_test, y_test) = mnist.load_data()
        if ratio < 1:
            sz_train = int(len(X_train) * ratio)
            sz_test = int(len(X_test) * ratio)
            X_train, y_train = X_train[:sz_train], y_train[:sz_train]
            X_test, y_test = X_test[:sz_test], y_test[:sz_test]
            return X_train, y_train, X_test, y_test
        else:
            return X_train, y_train, X_test, y_test
    
    def prep_mnist_features(X_train, X_test):
        X_train_out = X_train.astype(float) / 255  # scale to range 0 to 1
        X_test_out = X_test.astype(float) / 255
        X_train_out = X_train_out.reshape(-1, 28*28)  # convert 2D to 1D
        X_test_out = X_test_out.reshape(-1, 28*28)
        return X_train_out, X_test_out
    
    def one_hot_encode(y_train, y_test, n_categories):
        y_train_oh = keras.utils.to_categorical(y_train, n_categories)
        y_test_oh = keras.utils.to_categorical(y_test, n_categories)
        return y_train_oh, y_test_oh
    
    def plot_history(history):
        plt.figure(figsize=(8, 4))
        plt.subplot(121)
        plt.plot(history.history["loss"], label="loss")
        plt.plot(history.history["val_loss"], label="val_loss")
        plt.legend()
        plt.subplot(122)
        plt.plot(history.history["acc"], label="acc")
        plt.plot(history.history["val_acc"], label="val_acc")
        plt.legend()
        plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入绘图与 keraskeras 用于 to_categorical;mnist 已在 C8 导入—本 cell 定义 4 个函数,不产生输出
    2from tensorflow import keras导入绘图与 keraskeras 用于 to_categorical;mnist 已在 C8 导入—本 cell 定义 4 个函数,不产生输出
    4def load_mnist_dataset(ratio=0.25):定义 load_mnist_dataset(ratio=0.25)参数默认取 25% 子集;ratio=1 取全集—ratio 是 0–1 的小数,不是个数
    5 (X_train, y_train), (X_test, y_test) = mnist.load_data()载入全集与 C8 相同60000 / 10000—
    6 if ratio < 1:判断是否取子集if ratio < 1—ratio=1 走 else 分支原样返回
    7 sz_train = int(len(X_train) * ratio)计算子集大小int(len(X) * ratio):60000×0.25 = 15000;10000×0.25 = 2500sz_train=15000, sz_test=2500int() 向下取整;若 ratio 使乘积非整数会被截断
    8 sz_test = int(len(X_test) * ratio)计算子集大小int(len(X) * ratio):60000×0.25 = 15000;10000×0.25 = 2500sz_train=15000, sz_test=2500int() 向下取整;若 ratio 使乘积非整数会被截断
    9 X_train, y_train = X_train[:sz_train], y_train[:sz_train]切片取前 N 个X[:sz] 取索引 0..sz-1(不含 sz);同时切 X 和 y,保持一一对应X_train (15000,28,28)必须同时切 y!只切 X 会导致 X/y 长度不匹配
    10 X_test, y_test = X_test[:sz_test], y_test[:sz_test]切片取前 N 个X[:sz] 取索引 0..sz-1(不含 sz);同时切 X 和 y,保持一一对应X_train (15000,28,28)必须同时切 y!只切 X 会导致 X/y 长度不匹配
    11 return X_train, y_train, X_test, y_test返回子集——返回顺序 (X_train, y_train, X_test, y_test)
    12 else:ratio≥1 时原样返回———
    13 return X_train, y_train, X_test, y_testratio≥1 时原样返回———
    15def prep_mnist_features(X_train, X_test):定义 prep_mnist_features输入原始 uint8 图像,输出 float 的 (N,784) 矩阵—注意函数不改 y,只处理 X
    16 X_train_out = X_train.astype(float) / 255 # scale to range 0 to 1转 float 并除 255astype(float) 先复制为 float64 再除;值域 0–255 → [0,1]像素均值 ≈ 0.13–0.97必须先转 float:若写成 X//255 仍是 uint8 → 全 0;astype 产生新数组,原 X_train 不变
    17 X_test_out = X_test.astype(float) / 255转 float 并除 255astype(float) 先复制为 float64 再除;值域 0–255 → [0,1]像素均值 ≈ 0.13–0.97必须先转 float:若写成 X//255 仍是 uint8 → 全 0;astype 产生新数组,原 X_train 不变
    18 X_train_out = X_train_out.reshape(-1, 28*28) # convert 2D to 1D2D → 1D 展平reshape(-1, 28*28):-1 自动推断为 15000,每行 784 个像素;Dense 层只接受 2D (样本, 特征)X_train (15000,784)Dense 不能直接吃 (N,28,28)——会报 "expected shape (None, 784)";-1 只能出现一次
    19 X_test_out = X_test_out.reshape(-1, 28*28)2D → 1D 展平reshape(-1, 28*28):-1 自动推断为 15000,每行 784 个像素;Dense 层只接受 2D (样本, 特征)X_train (15000,784)Dense 不能直接吃 (N,28,28)——会报 "expected shape (None, 784)";-1 只能出现一次
    20 return X_train_out, X_test_out返回———
    22def one_hot_encode(y_train, y_test, n_categories):定义 one_hot_encode参数 n_categories:MNIST 传 10、wine 传 11—类别数决定 one-hot 向量长度
    23 y_train_oh = keras.utils.to_categorical(y_train, n_categories)调用 to_categorical整数标签 (N,) → (N, n_categories) 的 0/1 矩阵,每行只在标签处为 1y_train (15000,10) float32若标签最大值 ≥ n_categories 会报错(wine 的 quality 最大 9 < 11 ✔)
    24 y_test_oh = keras.utils.to_categorical(y_test, n_categories)调用 to_categorical整数标签 (N,) → (N, n_categories) 的 0/1 矩阵,每行只在标签处为 1y_train (15000,10) float32若标签最大值 ≥ n_categories 会报错(wine 的 quality 最大 9 < 11 ✔)
    25 return y_train_oh, y_test_oh返回———
    27def plot_history(history):定义 plot_history接收 model.fit 返回的 History 对象—history 是 Python 对象,.history 属性是字典
    28 plt.figure(figsize=(8, 4))新建画布figsize=(8,4) 英寸——
    29 plt.subplot(121)左侧子图 121subplot(nrows, ncols, index) 三位整数 = 1 行 2 列第 1 个;之后 plot 画在当前子图—121/122 是 1 行 2 列的简写;与 C10 的 subplots(带 s)不同
    30 plt.plot(history.history["loss"], label="loss")画 loss 与 val_losshistory.history 是 dict:键 "loss" / "val_loss" 对应每轮的训练/验证损失—键名必须是 fit 时实际记录的;若无 validation_data 则没有 val_* 键 → KeyError
    31 plt.plot(history.history["val_loss"], label="val_loss")画 loss 与 val_losshistory.history 是 dict:键 "loss" / "val_loss" 对应每轮的训练/验证损失—键名必须是 fit 时实际记录的;若无 validation_data 则没有 val_* 键 → KeyError
    32 plt.legend()显示图例——label 要先设才能 legend 显示
    33 plt.subplot(122)右侧子图 122第 2 个子图画 acc / val_acc——
    34 plt.plot(history.history["acc"], label="acc")画 acc 与 val_acc键 "acc" / "val_acc"—Keras 3 中 metrics=["acc"] 仍记录为 "acc"(compile 的名字),但新版有时记为 "accuracy"——若 KeyError 查 history.history.keys()
    35 plt.plot(history.history["val_acc"], label="val_acc")画 acc 与 val_acc键 "acc" / "val_acc"—Keras 3 中 metrics=["acc"] 仍记录为 "acc"(compile 的名字),但新版有时记为 "accuracy"——若 KeyError 查 history.history.keys()
    36 plt.legend()图例———
    37 plt.tight_layout()自动收紧布局防止两个子图标题/轴标签重叠
    —
    四个函数的"数据流"(记这张图):
    load_mnist_dataset() → (15000,28,28) uint8, y (15000,) int → prep_mnist_features() → (15000,784) float [0,1] → one_hot_encode(…,10) → y (15000,10) float32 → model.fit → History → plot_history()。
    易错点 1:三个预处理函数都不修改原数组(切片赋给新名;astype 是拷贝;to_categorical 是新数组)——所以要写 X_train, X_test = prep_mnist_features(X_train, X_test) 接住返回值,不能只调用不赋值。
    易错点 2:prep_mnist_features 和 one_hot_encode 的参数顺序都是 (train, test),返回也是 (train_out, test_out)。
    易错点 3:history.history["acc"]——这个字符串键依赖 compile 时 metrics=["acc"] 写的是 "acc",若写 metrics=["accuracy"] 则键名变成 "accuracy",plot_history 会 KeyError。
    Cell Multiclass#1

    The code below loads and prepares the dataset; creates, compiles, and trains a Keras model. Note the one-hot encoding operation, softmax neurons of the output layer, and the categorical cross-entropy loss function.

    Multiclass#1 的结构(Unit 5 讲义 p19–p24 的代码版):输入 784 → Dense(64, relu) → Dense(64, relu) → Dense(10, softmax)。softmax 把 10 个 logit 变成和为 1 的概率分布:p_i = e^{z_i} / Σ e^{z_j};categorical_crossentropy = −Σ y_i log p_i,对 one-hot 标签退化为 −log p_正确类(讲义 p28)。梯度简洁式:∂L/∂z_i = p_i − y_i(softmax + CE 的联合导数,讲义 p31),所以第 1 轮结束时正确类概率从 0.1 升到 0.70。
    Cell 15Multiclass#1:载入 → 预处理 → 64-64-10 softmax → compile → fit 30 轮重点展开
    # Cell Multiclass#1
    
    from tensorflow import keras
    from tensorflow.keras import layers
    
    keras.utils.set_random_seed(42)
    X_train, y_train, X_test, y_test = load_mnist_dataset()
    X_train, X_test = prep_mnist_features(X_train, X_test)
    y_train, y_test = one_hot_encode(y_train, y_test, 10)
    
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),
        layers.Dense(64, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    
    model.compile(loss="categorical_crossentropy", optimizer="adam",
                  metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=30, batch_size=256,
                        verbose=2, validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1# Cell Multiclass#1注释 / 空行———
    3from tensorflow import keras导入 keras 与 layersC12 已导入 keras,这里重复导入无害——
    4from tensorflow.keras import layers导入 keras 与 layersC12 已导入 keras,这里重复导入无害——
    6keras.utils.set_random_seed(42)固定随机种子set_random_seed(42) 同时设定 Python random / numpy / tf 的种子—不设种子则每次初始权重不同,结果不可复现
    7X_train, y_train, X_test, y_test = load_mnist_dataset()载入 25% 子集调用 C12 的 load_mnist_dataset(),ratio 用默认 0.25X_train (15000,28,28) y_train (15000,)C12 必须先执行,否则 NameError
    8X_train, X_test = prep_mnist_features(X_train, X_test)缩放 + 展平调用 prep_mnist_featuresX_train (15000,784) float—
    9y_train, y_test = one_hot_encode(y_train, y_test, 10)one-hot 标签调用 one_hot_encode(…, 10)y_train (15000,10)必须 10 类;one-hot 后 y 不能再用于 sparse CE
    11model = keras.Sequential([搭建 64-64-10 模型两个隐藏层 ReLU + 输出层 softmax;Dense 自动推断输入维 784(第一层)—输出层单元数 = 类别数;激活必须是 softmax(不是 sigmoid)
    12 layers.Dense(64, activation="relu"),搭建 64-64-10 模型两个隐藏层 ReLU + 输出层 softmax;Dense 自动推断输入维 784(第一层)—输出层单元数 = 类别数;激活必须是 softmax(不是 sigmoid)
    13 layers.Dense(64, activation="relu"),搭建 64-64-10 模型两个隐藏层 ReLU + 输出层 softmax;Dense 自动推断输入维 784(第一层)—输出层单元数 = 类别数;激活必须是 softmax(不是 sigmoid)
    14 layers.Dense(10, activation="softmax")搭建 64-64-10 模型两个隐藏层 ReLU + 输出层 softmax;Dense 自动推断输入维 784(第一层)—输出层单元数 = 类别数;激活必须是 softmax(不是 sigmoid)
    15])搭建 64-64-10 模型两个隐藏层 ReLU + 输出层 softmax;Dense 自动推断输入维 784(第一层)—输出层单元数 = 类别数;激活必须是 softmax(不是 sigmoid)
    17model.compile(loss="categorical_crossentropy", optimizer="adam",compileloss="categorical_crossentropy" 配 one-hot 标签;optimizer="adam";metrics=["acc"] → history 里键名 "acc"—loss 与标签格式必须配套:one-hot+categorical / 整数+sparse
    18 metrics=["acc"])compileloss="categorical_crossentropy" 配 one-hot 标签;optimizer="adam";metrics=["acc"] → history 里键名 "acc"—loss 与标签格式必须配套:one-hot+categorical / 整数+sparse
    19history = model.fit(X_train, y_train, epochs=30, batch_size=256,fit 30 轮batch_size=256 → 15000/256 = 58.6 → 59 步/轮;verbose=2 每轮一行;validation_data=(X_test, y_test) 每轮末评估第 1 轮 acc .7019 / loss 1.1082 / val_acc .8392 / val_loss .5835validation_data 必须是 (X, y) 元组;y 要与 loss 匹配(one-hot)
    20 verbose=2, validation_data=(X_test, y_test))fit 30 轮batch_size=256 → 15000/256 = 58.6 → 59 步/轮;verbose=2 每轮一行;validation_data=(X_test, y_test) 每轮末评估第 1 轮 acc .7019 / loss 1.1082 / val_acc .8392 / val_loss .5835validation_data 必须是 (X, y) 元组;y 要与 loss 匹配(one-hot)
    运行结果 Epoch 1/30 59/59 - 2s - 31ms/step - acc: 0.7019 - loss: 1.1082 - val_acc: 0.8392 - val_loss: 0.5835 Epoch 2/30 59/59 - 0s - 7ms/step - acc: 0.8975 - loss: 0.3710 - val_acc: 0.8752 - val_loss: 0.4261 Epoch 3/30 59/59 - 0s - 6ms/step - acc: 0.9195 - loss: 0.2855 - val_acc: 0.8948 - val_loss: 0.3638 Epoch 4/30 59/59 - 0s - 6ms/step - acc: 0.9323 - loss: 0.2427 - val_acc: 0.9044 - val_loss: 0.3287 Epoch 5/30 59/59 - 0s - 6ms/step - acc: 0.9413 - loss: 0.2111 - val_acc: 0.9108 - val_loss: 0.3042 Epoch 6/30 59/59 - 0s - 6ms/step - acc: 0.9479 - loss: 0.1854 - val_acc: 0.9184 - val_loss: 0.2868 Epoch
    参数手算(Course Review 必考题型):Dense(64) on 784 → 64×(784+1) = 50,240;Dense(64) on 64 → 64×65 = 4,160;Dense(10) on 64 → 10×65 = 650;总 55,050。
    第 1 轮读数:初始 loss ≈ ln(10) = 2.303(10 类随机猜);第 1 轮结束 loss 1.1082、acc 0.70——softmax+CE 的梯度 p−y 让正确类概率快速上升。val_acc 0.8392 > acc 0.7019 是正常的:acc 是整轮平均(含前半轮的差权重),val_acc 是轮末用最终权重算的。
    Cell Multiclass#2

    A plot of the training history -- including losses and accuracies -- is shown below.

    Cell 18Multiclass#2:画出 loss / acc 曲线基础
    # Cell Multiclass#2
    
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Cell Multiclass#2注释 / 空行———
    3plot_history(history)调用 plot_historyhistory 是 C15 fit 的返回值
    若 C15 未重跑,画的是旧 history
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]

    The model is used to predict three test examples as follows. The predicted probabilities and one-hot encoded labels are shown. The position of the largest probability in the predicted result and the position of the encoded '1' in a label indicate the digit. For instance, for the first test example, the eighth probability (at index 7) is largest, and the encoded '1' in the label is also at the eighth position (at index 7). Both indicate the digit 7, so the prediction is correct.

    怎么读 C20 的输出:第一行 [2.2e-08, …, 9.9974447e-01, …]——index 7 的概率 0.9997,其余接近 0;Actual 第一行 one-hot 的 1 也在 index 7 → 预测 7 ✔。第二行 index 2 ≈ 0.9997 → 2 ✔;第三行 index 1 ≈ 0.997 → 1 ✔。注意 2.3031581e-09 这种写法是科学计数法(e-09 = ×10⁻⁹),不是精确 0——softmax 的输出永远 >0,只是很小。
    Cell 20预测 3 个测试样本:概率 vs one-hot重点展开
    y_pred = model.predict(X_test[:3], verbose=0)
    print("Predicted: ", y_pred)
    print("Actual:    ", y_test[:3])
    #代码作用机制·语法关联·结果易错点
    1y_pred = model.predict(X_test[:3], verbose=0)predict 前 3 个verbose=0 关闭进度条;返回 (3, 10) 概率矩阵,每行和为 1y_pred (3,10)predict 输入是 X_test(已展平归一化),不是原始 28×28
    2print("Predicted: ", y_pred)打印概率科学计数法显示第 1 行 index 7 = 0.9997读法:找每行最大的位置
    3print("Actual: ", y_test[:3])打印真实 one-hoty_test 仍是 one-hot 格式[[0…1…0] [0 0 1…] [0 1 0…]]概率 vs one-hot 对比:位置一致 → 预测对
    运行结果 Predicted: [[2.2084974e-08 4.5356394e-09 1.7843893e-05 2.3697768e-04 3.4798361e-10 2.3031581e-09 7.5619703e-16 9.9974447e-01 2.1202899e-07 4.5222671e-07] [2.6387488e-07 3.3988585e-05 9.9966919e-01 2.8980974e-04 4.1139418e-12 3.2492951e-06 2.1356273e-06 1.3960516e-11 1.4664785e-06 2.1003024e-12] [2.1375976e-07 9.9710000e-01 1.3637679e-03 2.3328114e-04 5.2066749e-05 9.9010631e-06 4.8014581e-06 9.7473012e-04 2.5595838e-04 5.2679670e-06]] Actual: [[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.] [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.] [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]]

    Instead of looking at the probabilities and encoded '1' values, it is easier for us to read their indices, which represent the digits. The code below shows the predicted and actual labels of 20 test examples.

    argmax 读法:y_pred.argmax(axis=1) 对每行取最大概率的下标 = 预测数字;y_test[:30].argmax(axis=1) 对 one-hot 取 1 的位置 = 真实数字。C22 结果里 30 个中错 2 个:第 9 个(index 8)真实 5 → 预测 6;第 19 个(index 18)真实 3 → 预测 8。val_acc ≈ 0.96 意味着每 100 个约错 4 个,与这里 2/30 吻合。
    Cell 22预测 30 个:argmax 对比重点展开
    y_pred = model.predict(X_test[:30], verbose=0)
    print("Predicted: ", y_pred.argmax(axis=1))
    print("Actual:    ", y_test[:30].argmax(axis=1))
    #代码作用机制·语法关联·结果易错点
    1y_pred = model.predict(X_test[:30], verbose=0)predict 前 30 个返回 (30,10)——
    2print("Predicted: ", y_pred.argmax(axis=1))argmax(axis=1)对每行取最大概率的下标 → 预测数字 (30,)[7 2 1 0 4 1 4 9 6 9 … 8 …]axis=1 是按行;axis=0 是按列(错)
    3print("Actual: ", y_test[:30].argmax(axis=1))真实标签 argmaxone-hot 的 1 所在位置 = 真实数字[7 2 1 0 4 1 4 9 5 9 … 3 …]index 8 与 18 两处不同 → 30 个错 2 个
    运行结果 Predicted: [7 2 1 0 4 1 4 9 6 9 0 6 9 0 1 5 9 7 8 4 9 6 6 5 4 0 7 4 0 1] Actual: [7 2 1 0 4 1 4 9 5 9 0 6 9 0 1 5 9 7 3 4 9 6 6 5 4 0 7 4 0 1]

    Practice - Question 1 of 2

    In this question, a neural network is implemented to perform a binary classification task. The MNIST digit dataset is modified for binary classification for our study. The original labels (before one-hot encoding) in the dataset are integers from 0 to 9. We'll modify the labels to be either 0 or 1: 0 if the digit is even, and 1 if the digit is odd.

    Q1a


    Modify the multiclass classification model to do binary classification. Specifically, copy the two code cells Multiclass#1 and Multiclass#2 below, and then do the following:


  • Import the NumPy module: `import numpy as np`.
  • Remove or comment out the line that calls the `one_hot_encode()` function.
  • Instead of one-hot encoding, convert the labels to either 0 (for even digits) or 1 (for odd digits) using this code:

  •     y_train = np.where(y_train % 2 == 0, 0, 1)
        y_test = np.where(y_test % 2 == 0, 0, 1)
    
  • Modify the output layer to use 1 `"sigmoid"` neuron instead of 10 `"softmax"` neurons.
  • Modify the `compile()` method call to use `"binary_crossentropy"` instead of `"categorical_crossentropy"` for the loss function.

  • Remember to execute the two cells in order.

    Q1a 题目拆解:① 导入 numpy;② 去掉 one_hot_encode;③ 用 np.where(y % 2 == 0, 0, 1) 把 0–9 映射为 偶→0 / 奇→1;④ 输出层改 Dense(1, sigmoid);⑤ 损失改 binary_crossentropy;⑥ 其余不变。这五步就是"多分类 → 二分类"的全部改动——记熟这 5 步,考试改代码题就是送分。
    Cell 26Q1a 学生作答:奇偶二分类 Dense(1, sigmoid) + binary_crossentropy练习·作答
    import numpy as np
    from tensorflow import keras
    from tensorflow.keras import layers
    
    keras.utils.set_random_seed(42)
    X_train, y_train, X_test, y_test = load_mnist_dataset()
    X_train, X_test = prep_mnist_features(X_train, X_test)
    
    y_train = np.where(y_train % 2 == 0, 0, 1)
    y_test = np.where(y_test % 2 == 0, 0, 1)
    
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),
        layers.Dense(64, activation="relu"),
        layers.Dense(1, activation="sigmoid")])
    
    model.compile(loss="binary_crossentropy",optimizer="adam", metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=30, batch_size=256,verbose=2, validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入 numpy题目要求 ①—np.where 需要 numpy
    2from tensorflow import keras导入 keras / layers同 C15——
    3from tensorflow.keras import layers导入 keras / layers同 C15——
    5keras.utils.set_random_seed(42)固定种子同 C15——
    6X_train, y_train, X_test, y_test = load_mnist_dataset()载入 + 预处理特征同 C15X (15000,784)—
    7X_train, X_test = prep_mnist_features(X_train, X_test)载入 + 预处理特征同 C15X (15000,784)—
    9y_train = np.where(y_train % 2 == 0, 0, 1)标签改奇偶np.where(条件, 0, 1):y%2==0 为 True 的位置填 0(偶),否则 1(奇)y_train (15000,) 值为 0/1 的 inty 不再 one-hot;顺序 (y%2==0 → 0) 对应 题目 "0 if even"
    10y_test = np.where(y_test % 2 == 0, 0, 1)标签改奇偶np.where(条件, 0, 1):y%2==0 为 True 的位置填 0(偶),否则 1(奇)y_train (15000,) 值为 0/1 的 inty 不再 one-hot;顺序 (y%2==0 → 0) 对应 题目 "0 if even"
    12model = keras.Sequential([输出层改 Dense(1, sigmoid)二分类只需 1 个神经元输出 P(odd);sigmoid 把 logit 压到 (0,1)—不能保留 Dense(10):10 个输出配 bce 会变成 10 个独立二分类
    13 layers.Dense(64, activation="relu"),输出层改 Dense(1, sigmoid)二分类只需 1 个神经元输出 P(odd);sigmoid 把 logit 压到 (0,1)—不能保留 Dense(10):10 个输出配 bce 会变成 10 个独立二分类
    14 layers.Dense(64, activation="relu"),输出层改 Dense(1, sigmoid)二分类只需 1 个神经元输出 P(odd);sigmoid 把 logit 压到 (0,1)—不能保留 Dense(10):10 个输出配 bce 会变成 10 个独立二分类
    15 layers.Dense(1, activation="sigmoid")])输出层改 Dense(1, sigmoid)二分类只需 1 个神经元输出 P(odd);sigmoid 把 logit 压到 (0,1)—不能保留 Dense(10):10 个输出配 bce 会变成 10 个独立二分类
    17model.compile(loss="binary_crossentropy",optimizer="adam", metrics=["acc"])compile 改 bcebinary_crossentropy = −[y log p + (1−y) log(1−p)];optimizer 与 metrics 不变—Dense(1)+sigmoid 必须配 bce,配 categorical 会报错或算错
    18history = model.fit(X_train, y_train, epochs=30, batch_size=256,verbose=2, validation_data=(X_test, y_test))fit参数与 C15 完全相同第 1 轮 acc .8657 / val_acc .9032;第 6 轮 val_acc .9644—
    运行结果 Epoch 1/30 59/59 - 2s - 28ms/step - acc: 0.8657 - loss: 0.3267 - val_acc: 0.9032 - val_loss: 0.2459 Epoch 2/30 59/59 - 0s - 6ms/step - acc: 0.9457 - loss: 0.1521 - val_acc: 0.9404 - val_loss: 0.1679 Epoch 3/30 59/59 - 1s - 10ms/step - acc: 0.9649 - loss: 0.1044 - val_acc: 0.9560 - val_loss: 0.1354 Epoch 4/30 59/59 - 1s - 9ms/step - acc: 0.9731 - loss: 0.0809 - val_acc: 0.9596 - val_loss: 0.1178 Epoch 5/30 59/59 - 0s - 7ms/step - acc: 0.9784 - loss: 0.0653 - val_acc: 0.9636 - val_loss: 0.1079 Epoch 6/30 59/59 - 0s - 6ms/step - acc: 0.9831 - loss: 0.0539 - val_acc: 0.9644 - val_loss: 0.1061 Epoc
    Q1a 你的作答核对:全部正确 ✔——五步改动(import numpy / 去掉 one-hot / np.where 奇偶 / Dense(1,sigmoid) / bce)一个不少。参数手算:Dense(64) on 784 → 50,240;Dense(64) on 64 → 4,160;Dense(1) on 64 → 65;总 54,465(比多分类 55,050 少 585 = 650−65)。
    为什么第 1 轮 val_acc 就 0.90:随机猜 10 个数字的奇偶也有 50% 基线;网络只需学到"形状→奇偶"的粗映射,第 1 轮就远超基线。
    Cell 27Q1a 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)调用 plot_historyhistory 是 C26 的
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]

    Q1b


    The following code uses the model to predict for a few test examples, showing the predicted probabilities (for odd digits) and the actual labels (0 for even digits and 1 for odd digits).

    Cell 29Q1b 题目给的概率读法练习·作答
    y_pred = model.predict(X_test[:10], verbose=0)
    print("Predicted: ", y_pred.ravel().round(2))
    print("Actual:    ", y_test[:10])
    #代码作用机制·语法关联·结果易错点
    1y_pred = model.predict(X_test[:10], verbose=0)predict 前 10 个返回 (10, 1) 的 P(odd)—形状是 (10,1) 不是 (10,)
    2print("Predicted: ", y_pred.ravel().round(2))ravel + roundravel() 把 (10,1) 展平成 (10,);round(2) 保留两位[1. 0.02 1. 0. 0. 1. 0. 1. 0.91 1.]不 ravel 会打印 [[1.] [0.02] …] 很难看
    3print("Actual: ", y_test[:10])打印真实 0/1 标签y_test 此时是 0/1 整数[1 0 1 0 0 1 0 1 1 1]index 8 的 0.91 最接近 0.5 → 最不自信
    运行结果 Predicted: [1. 0.02 1. 0. 0. 1. 0. 1. 0.91 1. ] Actual: [1 0 1 0 0 1 0 1 1 1]

    Write code below to do the same prediction, but display the outputs in a different way. Instead of showing the probabilities and 0/1 label values, print "odd" for a probability above 0.5 and for a "1" label, and print "even" for a probability below or equal to 0.5 and for a "0" label. Show the predicted and actual values in a clear and easy-to-compare way, and not necessarily in two lines.

    Cell 31Q1b 学生作答:输出 "odd"/"even" 字符串练习·作答
    y_pred = model.predict(X_test[:10], verbose=0)
    
    pred_labels = np.where(y_pred.ravel() > 0.5, "odd", "even")
    actual_labels = np.where(y_test[:10] == 1, "odd", "even")
    
    print("Predicted: ", pred_labels)
    print("Actual:    ", actual_labels)
    
    for i in range(10):
        print(f"Example {i}: predicted = {pred_labels[i]:4s}, actual = {actual_labels[i]}")
    #代码作用机制·语法关联·结果易错点
    1y_pred = model.predict(X_test[:10], verbose=0)predict 前 10 个同 C29——
    3pred_labels = np.where(y_pred.ravel() > 0.5, "odd", "even")概率 → 字符串np.where(y_pred.ravel() > 0.5, "odd", "even"):大于 0.5 判奇;ravel 不可省pred_labels = ['odd' 'even' …]阈值用 > 0.5;题目说 "below or equal to 0.5 → even" ✔ 与 > 一致
    4actual_labels = np.where(y_test[:10] == 1, "odd", "even")标签 → 字符串np.where(y_test[:10] == 1, "odd", "even"):1 是奇、0 是偶['odd' 'even' …]这里是 == 1 判断,不是 %2
    6print("Predicted: ", pred_labels)打印两个数组—两行完全相同—
    7print("Actual: ", actual_labels)打印两个数组—两行完全相同—
    9for i in range(10):逐例打印range(10);f-string {x:4s} 左对齐占 4 字符(odd 后补空格)Example 0: predicted = odd , actual = odd:4s 对 "odd"(3 字符)右补 1 空格,对 "even" 恰好 4 字符——对齐用
    10 print(f"Example {i}: predicted = {pred_labels[i]:4s}, actual = {actual_labels[i]}")逐例打印range(10);f-string {x:4s} 左对齐占 4 字符(odd 后补空格)Example 0: predicted = odd , actual = odd:4s 对 "odd"(3 字符)右补 1 空格,对 "even" 恰好 4 字符——对齐用
    运行结果 Predicted: ['odd' 'even' 'odd' 'even' 'even' 'odd' 'even' 'odd' 'odd' 'odd'] Actual: ['odd' 'even' 'odd' 'even' 'even' 'odd' 'even' 'odd' 'odd' 'odd'] Example 0: predicted = odd , actual = odd Example 1: predicted = even, actual = even Example 2: predicted = odd , actual = odd Example 3: predicted = even, actual = even Example 4: predicted = even, actual = even Example 5: predicted = odd , actual = odd Example 6: predicted = even, actual = even Example 7: predicted = odd , actual = odd Example 8: predicted = odd , actual = odd Example 9: predicted = odd , actual = odd
    Q1b 你的作答核对:正确 ✔——既输出了数组形式又逐例打印,满足 "not necessarily in two lines" 与 "easy-to-compare"。两种阈值写法等价:np.where(p > 0.5, "odd", "even") ≡ np.where(p <= 0.5, "even", "odd")。可改进的小点:L3/L4 的 .ravel() 也可以用 .flatten()(返回拷贝);若想一行输出对比可用 zip:for p, a in zip(pred_labels, actual_labels): print(p, a)。

    Q1c


    In the above, two neural networks were implemented for two tasks: classifying 10 digits and classifying old and even digits. Discuss which of the tasks is more difficult for the neural network; refer to the performance results of the networks in your discussion. Write your answer in a text cell below.

    Solution:



    <div class='alert alert-warning' role='alert'><b>Distinguishing between odd and even (a binary classification task) is more difficult. Parity is an abstract attribute with poor separability. The differences in numerical shapes are significant, while the differences in parity are minor.</b></div>

    Q1c 你的作答核对——结论对,但"refer to the performance results"这半句没答到:你写 "Parity is an abstract attribute with poor separability. The differences in numerical shapes are significant, while the differences in parity are minor."——形状分析 ✔。但题目明确要求 "refer to the performance results",要引用数字:多分类 val_acc 从第 1 轮 0.8392 → 30 轮 ≈ 0.96;二分类第 1 轮 0.9032 → ≈ 0.98。二分类准确率反而更高(任务更粗:只分两堆),但"更难"要从损失下降速度与残差看:二分类第 6 轮 loss 已到 0.054,而多分类第 6 轮 0.185——二分类 loss 更早趋平,错误集中在 3/5/8 这类形近数字上(奇偶性不可线性分,网络要靠像素组合间接判断)。
    更稳妥的答法:"The binary task reaches a higher accuracy (≈0.98 vs ≈0.96) but is conceptually harder: parity is not determined by any single stroke, so the residual errors are structural (confusions among 3/5/8) rather than noise."

    &#x2766;

    Designing a neural network model

    In the preceding lesson, you used the wine_quality dataset of TensorFlow Datasets (tfds) for a regression task. The same dataset can also be used for a classification task. As the label is an evaluation score between 0 and 10 (an integer), it may be considered as either a number or 1 out of 11 categories. Of course, a regression model and a classification model would have different performance in predicting the labels. The performance, however, depends on many factors as you have learned in the preceding lesson. Let's try a classification model next.


    The following load_wine_quality() function loads the wine_quality dataset.

    与 t04 的衔接:t04 的 load_wine_quality 合并红+白葡萄酒(6,497 行);本 Lab 只用白葡萄酒(L10 把 red 注释掉了)→ 4,898 行 × 0.8 = 3,918.4 → 3,918 / 980。标签 quality 是 3–9 的整数,作为 11 类(0–10)one-hot,其中 0/1/2/10 四类没有样本——这就是 11 类里"有用的只有 7 类"。
    Cell 37load_wine_quality:只读白葡萄酒 → 3918/980重点展开
    import numpy as np
    import tensorflow_datasets as tfds
    import pandas as pd
    
    def load_wine_quality(train_ratio=0.8):
        red_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"
        white_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"
    
        df = pd.concat([
            # pd.read_csv(red_url, sep=';'),
            pd.read_csv(white_url, sep=';')
        ], ignore_index=True)
    
        LABEL_COL = "quality"
    
        # split
        n_train = int(len(df) * train_ratio)
        train_df = df.iloc[:n_train]
        test_df  = df.iloc[n_train:]
    
        X_train = train_df.drop(columns=[LABEL_COL]).values
        y_train = train_df[LABEL_COL].values
        X_test  = test_df.drop(columns=[LABEL_COL]).values
        y_test  = test_df[LABEL_COL].values
    
        return X_train, y_train, X_test, y_test
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入 numpy / tfds / pandastfds 本 cell 未用到但保留——
    2import tensorflow_datasets as tfds导入 numpy / tfds / pandastfds 本 cell 未用到但保留——
    3import pandas as pd导入 numpy / tfds / pandastfds 本 cell 未用到但保留——
    5def load_wine_quality(train_ratio=0.8):定义 load_wine_qualitytrain_ratio=0.8 默认——
    6 red_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv"两个 CSV 的 URLUCI 酒度数据集;红 / 白—URL 不要打错
    7 white_url = "https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv"两个 CSV 的 URLUCI 酒度数据集;红 / 白—URL 不要打错
    9 df = pd.concat([只 concat 白葡萄酒L10 的 red 被 # 注释掉;pd.read_csv(sep=";") 因为该 CSV 用分号分隔;ignore_index=True 重排索引df (4898, 12)sep=";" 必须写,否则整行读成一列;t04 是红+白 6497 行,这里只有 4898
    10 # pd.read_csv(red_url, sep=';'),只 concat 白葡萄酒L10 的 red 被 # 注释掉;pd.read_csv(sep=";") 因为该 CSV 用分号分隔;ignore_index=True 重排索引df (4898, 12)sep=";" 必须写,否则整行读成一列;t04 是红+白 6497 行,这里只有 4898
    11 pd.read_csv(white_url, sep=';')只 concat 白葡萄酒L10 的 red 被 # 注释掉;pd.read_csv(sep=";") 因为该 CSV 用分号分隔;ignore_index=True 重排索引df (4898, 12)sep=";" 必须写,否则整行读成一列;t04 是红+白 6497 行,这里只有 4898
    12 ], ignore_index=True)只 concat 白葡萄酒L10 的 red 被 # 注释掉;pd.read_csv(sep=";") 因为该 CSV 用分号分隔;ignore_index=True 重排索引df (4898, 12)sep=";" 必须写,否则整行读成一列;t04 是红+白 6497 行,这里只有 4898
    14 LABEL_COL = "quality"标签列名"quality" 列是评分 3–9——
    16 # split注释 # split———
    17 n_train = int(len(df) * train_ratio)计算切分点int(4898 × 0.8) = 3918n_train = 3918int 向下取整
    18 train_df = df.iloc[:n_train]iloc 切分df.iloc[:3918] 前 3918 行 → 训练;iloc[3918:] 剩余 980 → 测试train 3918 / test 980没有 shuffle!按文件原始行序切——若数据按类别排序会有分布偏差(本数据集是随机序,问题不大)
    19 test_df = df.iloc[n_train:]iloc 切分df.iloc[:3918] 前 3918 行 → 训练;iloc[3918:] 剩余 980 → 测试train 3918 / test 980没有 shuffle!按文件原始行序切——若数据按类别排序会有分布偏差(本数据集是随机序,问题不大)
    21 X_train = train_df.drop(columns=[LABEL_COL]).values分离特征与标签drop(columns=["quality"]) 去掉标签列得 11 维特征;[LABEL_COL] 取标签列;.values 转 numpyX (3918,11) y (3918,)drop 要指定 columns=,否则按行标签删
    22 y_train = train_df[LABEL_COL].values分离特征与标签drop(columns=["quality"]) 去掉标签列得 11 维特征;[LABEL_COL] 取标签列;.values 转 numpyX (3918,11) y (3918,)drop 要指定 columns=,否则按行标签删
    23 X_test = test_df.drop(columns=[LABEL_COL]).values分离特征与标签drop(columns=["quality"]) 去掉标签列得 11 维特征;[LABEL_COL] 取标签列;.values 转 numpyX (3918,11) y (3918,)drop 要指定 columns=,否则按行标签删
    24 y_test = test_df[LABEL_COL].values分离特征与标签drop(columns=["quality"]) 去掉标签列得 11 维特征;[LABEL_COL] 取标签列;.values 转 numpyX (3918,11) y (3918,)drop 要指定 columns=,否则按行标签删
    26 return X_train, y_train, X_test, y_test返回顺序 (X_train, y_train, X_test, y_test)—与 mnist 的返回顺序一致

    This code loads the dataset and displays the dimensions of the dataset. The training set contains 3918 examples, and the test set contains 980 examples. An example has 11 features and a label.

    Cell 39调用 load_wine_quality 并打印形状导入·绘图·输出
    X_train, y_train, X_test, y_test = load_wine_quality()
    print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
    #代码作用机制·语法关联·结果易错点
    1X_train, y_train, X_test, y_test = load_wine_quality()载入使用默认 train_ratio=0.8——
    2print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)打印形状—(3918, 11) (3918,) (980, 11) (980,)与 M38 的文字一致:3918 / 980,11 特征
    运行结果 (3918, 11) (3918,) (980, 11) (980,)

    The following utility function normalizes input features.

    Cell 41normalize_features:按训练集均值/标准差标准化重点展开
    # Normalize input features
    def normalize_features(X_train, X_test):
        mean = X_train.mean(axis=0)  # mean values of features
        std = X_train.std(axis=0)  # SD values of features
        X_train_normalized = (X_train - mean) / std
        X_test_normalized = (X_test - mean) / std
        return X_train_normalized, X_test_normalized
    #代码作用机制·语法关联·结果易错点
    1# Normalize input features注释———
    2def normalize_features(X_train, X_test):定义 normalize_features输入 (X_train, X_test),输出标准化后的两份—注意顺序 train 在前
    3 mean = X_train.mean(axis=0) # mean values of features训练集按列求均值axis=0 沿样本方向 → 每个特征一个均值 (11,)mean (11,)axis=0 消掉行维;不能用 axis=1
    4 std = X_train.std(axis=0) # SD values of features训练集按列求标准差同上std (11,)std 默认 ddof=0(总体标准差)
    5 X_train_normalized = (X_train - mean) / std训练集标准化(X − mean) / std,广播 (3918,11) − (11,) → 每列减自己的均值均值 0 方差 1—
    6 X_test_normalized = (X_test - mean) / std测试集用训练集的统计量同一 mean/std 应用到 X_test—不能对测试集单独算均值!那是数据泄漏——测试集在真实场景中是未见过的
    7 return X_train_normalized, X_test_normalized返回———

    Practice - Question 2 of 2

    Q2a


    Write code to train a multiclass classification model for the wine_quality dataset. Specifically:


  • load the wine_quality dataset,
  • normalize the features (use `normalize_features()`)
  • one-hot encode the labels (to 11 categories),
  • create a Keras model,
  • compile the model,
  • train the model, and
  • plot the training history.

  • Try different components in the model design in order to improve the model performance. A validation accuracy above 0.56 is acceptable; you are not required to search extensively for the highest accuracy. Submit the best model of your choice, and keep its execution output.


    These are some suggestions, but not requirements, of possible components that you may try:


  • 1 to 3 hidden layers,
  • 8 to 64 neurons in a hidden layer,
  • ReLU, sigmoid, or tanh neurons in the hidden layer,
  • SGD, Adam, or RMSProp optimizer, and
  • 10 to 50 training epochs.
  • Q2a 题目拆解:与 Multiclass#1 完全同构,只换数据源与类别数:load_wine_quality → normalize → one-hot(11) → 64-64-11 softmax → categorical CE → fit(50, batch 32) → plot。val_acc ≥ 0.56 达标。能尝试的改动:宽度(64→128)、深度(+1 层)、优化器、lr、epochs、batch_size。
    Cell 44Q2a 学生作答:wine 11 分类 64-64-11 → 50 轮 batch 32练习·作答
    import numpy as np
    from tensorflow import keras
    from tensorflow.keras import layers
    
    keras.utils.set_random_seed(42)
    
    X_train, y_train, X_test, y_test = load_wine_quality()
    
    X_train, X_test = normalize_features(X_train, X_test)
    
    y_train, y_test = one_hot_encode(y_train, y_test, 11)
    
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),
        layers.Dense(64, activation="relu"),
        layers.Dense(11, activation="softmax")
    ])
    
    model.compile(loss="categorical_crossentropy", optimizer="adam",
                  metrics=["acc"])
    
    history = model.fit(X_train, y_train, epochs=50, batch_size=32,
                        verbose=2, validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入同前——
    2from tensorflow import keras导入同前——
    3from tensorflow.keras import layers导入同前——
    5keras.utils.set_random_seed(42)种子———
    7X_train, y_train, X_test, y_test = load_wine_quality()载入 wineload_wine_quality()X (3918,11)—
    9X_train, X_test = normalize_features(X_train, X_test)标准化调用 C41 的 normalize_features—t04 E1c 证明了不归一化会学不动
    11y_train, y_test = one_hot_encode(y_train, y_test, 11)one-hot 11 类标签 3–9 → one-hot 长度 11(0–10)y (3918,11)n_categories=11 而不是 7:类别编号就是 quality 值本身
    13model = keras.Sequential([64-64-11 softmax与 MNIST 同构,只换输出单元数——
    14 layers.Dense(64, activation="relu"),64-64-11 softmax与 MNIST 同构,只换输出单元数——
    15 layers.Dense(64, activation="relu"),64-64-11 softmax与 MNIST 同构,只换输出单元数——
    16 layers.Dense(11, activation="softmax")64-64-11 softmax与 MNIST 同构,只换输出单元数——
    17])64-64-11 softmax与 MNIST 同构,只换输出单元数——
    19model.compile(loss="categorical_crossentropy", optimizer="adam",compilecategorical_crossentropy + adam——
    20 metrics=["acc"])compilecategorical_crossentropy + adam——
    22history = model.fit(X_train, y_train, epochs=50, batch_size=32,fit 50 轮 batch 323918/32 = 122.4 → 123 步/轮第 1 轮 acc .4206 / val_acc .5245;第 5 轮 val_acc .5653 > 0.56 ✔batch_size 变小 → 每轮步数变多、更新更频繁
    23 verbose=2, validation_data=(X_test, y_test))fit 50 轮 batch 323918/32 = 122.4 → 123 步/轮第 1 轮 acc .4206 / val_acc .5245;第 5 轮 val_acc .5653 > 0.56 ✔batch_size 变小 → 每轮步数变多、更新更频繁
    运行结果 Epoch 1/50 123/123 - 2s - 16ms/step - acc: 0.4206 - loss: 1.6026 - val_acc: 0.5245 - val_loss: 1.1381 Epoch 2/50 123/123 - 1s - 5ms/step - acc: 0.5260 - loss: 1.1565 - val_acc: 0.5367 - val_loss: 1.0766 Epoch 3/50 123/123 - 1s - 5ms/step - acc: 0.5378 - loss: 1.1094 - val_acc: 0.5500 - val_loss: 1.0503 Epoch 4/50 123/123 - 1s - 5ms/step - acc: 0.5431 - loss: 1.0879 - val_acc: 0.5582 - val_loss: 1.0341 Epoch 5/50 123/123 - 0s - 4ms/step - acc: 0.5495 - loss: 1.0724 - val_acc: 0.5653 - val_loss: 1.0265 Epoch 6/50 123/123 - 0s - 3ms/step - acc: 0.5556 - loss: 1.0599 - val_acc: 0.5684 - val_loss:
    Q2a 你的作答核对:达标 ✔——第 5 轮 val_acc 0.5653 已超过 0.56 线。参数手算:Dense(64) on 11 → 64×12 = 768;Dense(64) on 64 → 4,160;Dense(11) on 64 → 11×65 = 715;总 5,643。
    为什么只有 0.56:quality 是主观评分,相邻分数(5 vs 6)边界模糊,人类一致性也仅约 60%;且 4 个空类别稀释 softmax 概率。能提分的方向:+BN / dropout / 更多轮数 / 把 11 类合并成 3 类(差/中/好)。
    Cell 45Q2a 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)调用 plot_historyhistory 是 C44 的
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]

    &#x2766;

    You may use the following code to do prediction using the trained model.

    Cell 48Q2 预测 30 个:argmax 对比基础
    y_pred = model.predict(X_test[:30], verbose=0)
    print("Predicted: ", y_pred.argmax(axis=1))
    print("Actual:    ", y_test[:30].argmax(axis=1))
    #代码作用机制·语法关联·结果易错点
    1y_pred = model.predict(X_test[:30], verbose=0)predict 前 30 个返回 (30,11)——
    2print("Predicted: ", y_pred.argmax(axis=1))预测 argmax—[7 7 6 5 7 5 5 6 …]—
    3print("Actual: ", y_test[:30].argmax(axis=1))真实 argmaxy_test 仍是 one-hot[7 6 6 5 7 5 5 5 …]30 个中约 1/3 不同——与 val_acc ≈ 0.57 吻合;错多为相邻分数 ±1
    运行结果 Predicted: [7 7 6 5 7 5 5 6 6 7 6 6 6 7 7 6 6 5 6 5 6 6 5 6 6 6 6 6 7 7] Actual: [7 6 6 5 7 5 5 5 6 5 5 5 6 6 8 4 6 5 6 5 6 6 5 5 6 6 6 6 6 7]

    Extras

    Sparse categorical cross-entropy


    For multiclass classification, a general recommendation is one-hot encoding the labels and using categorical cross-entropy as the loss function. Another option is integer encoding the labels and using sparse categorical cross-entropy as the loss function. Integer encoding means representing the label categories as integer values, such as 0 for the first category, 1 for the second category, and so on. Such an encoding scheme may be more natural to programmers and commonly used in datasets.

    sparse categorical CE vs categorical CE(E1 的理论依据):数学上完全相同:L = −log p_正确类。区别只在标签格式与实现方式——categorical 接收 one-hot 矩阵 (N, 10),内部做 −Σ y_i log p_i;sparse 接收整数 (N,),内部先 gather 出 p_正确类再取 −log。为什么结果逐位相同(C55 vs C15):同样的 seed 42、同样的初始权重、同样的数据顺序 → 前向/反向数值完全一致 → loss 1.1082 / acc 0.7019 / val_acc 0.8392 每一位都相同。sparse 的优点:省内存(一个 int vs 10 个 float)、标签天然是整数时不用转换;缺点:model.predict 仍输出 (N,10) 概率,但 y_test 不能 argmax(它已是整数),要直接 print(y_test[:30])。
    E1a

    Modify the multiclass classification model for the MNIST dataset to use sparse categorical cross-entropy. Specifically, copy the two code cells Multiclass#1 and Multiclass#2 below, and then do the following:


  • Remove or comment out the line that calls the `one_hot_encode()` function.
  • Modify the `compile()` method call to use `"sparse_categorical_crossentropy"` instead of `"categorical_crossentropy"` for the loss function.

  • Remember to execute the two cells in order.


    Compare the validation loss and the training history to those of the original multiclass classification model that uses categorical cross-entropy.

    E1b

    Re-implement the neural network for the wine_quality dataset in question 2 to use sparse categorical cross-entropy instead of categorical cross-entropy. Remember not to one-hot encode the labels.

    Solutions to extra exercises

    E1a
    Cell 55E1a 解答:sparse_categorical_crossentropy(标签保持整数)重点展开
    # Solution
    
    from tensorflow import keras
    from tensorflow.keras import layers
    
    keras.utils.set_random_seed(42)
    X_train, y_train, X_test, y_test = load_mnist_dataset()
    X_train, X_test = prep_mnist_features(X_train, X_test)
    # y_train, y_test = one_hot_encode(y_train, y_test, 10)
    
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),
        layers.Dense(64, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    
    model.compile(loss="sparse_categorical_crossentropy", optimizer="adam",
                  metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=30, batch_size=256,
                        verbose=2, validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1# Solution注释 / 空行———
    3from tensorflow import keras导入同 C15——
    4from tensorflow.keras import layers导入同 C15——
    6keras.utils.set_random_seed(42)种子同 C15——
    7X_train, y_train, X_test, y_test = load_mnist_dataset()载入 + 预处理同 C15——
    8X_train, X_test = prep_mnist_features(X_train, X_test)载入 + 预处理同 C15——
    9# y_train, y_test = one_hot_encode(y_train, y_test, 10)注释掉 one-hoty_train/y_test 保持整数 (15000,)y (15000,) int这是 E1a 的关键改动 #1
    11model = keras.Sequential([模型不变仍是 64-64-10 softmax—sparse 不影响模型结构,只影响损失的计算方式
    12 layers.Dense(64, activation="relu"),模型不变仍是 64-64-10 softmax—sparse 不影响模型结构,只影响损失的计算方式
    13 layers.Dense(64, activation="relu"),模型不变仍是 64-64-10 softmax—sparse 不影响模型结构,只影响损失的计算方式
    14 layers.Dense(10, activation="softmax")模型不变仍是 64-64-10 softmax—sparse 不影响模型结构,只影响损失的计算方式
    15])模型不变仍是 64-64-10 softmax—sparse 不影响模型结构,只影响损失的计算方式
    17model.compile(loss="sparse_categorical_crossentropy", optimizer="adam",compile 改 sparseloss="sparse_categorical_crossentropy" 接收整数标签,内部 gather 正确类概率再 −log—关键改动 #2;若标签已 one-hot 又用 sparse → 报错 "expected shape (None,)」
    18 metrics=["acc"])compile 改 sparseloss="sparse_categorical_crossentropy" 接收整数标签,内部 gather 正确类概率再 −log—关键改动 #2;若标签已 one-hot 又用 sparse → 报错 "expected shape (None,)」
    19history = model.fit(X_train, y_train, epochs=30, batch_size=256,fit同 C15acc .7019 / loss 1.1082 / val_acc .8392 — 与 C15 逐位相同证明两种损失数学等价
    20 verbose=2, validation_data=(X_test, y_test))fit同 C15acc .7019 / loss 1.1082 / val_acc .8392 — 与 C15 逐位相同证明两种损失数学等价
    运行结果 Epoch 1/30 59/59 - 2s - 26ms/step - acc: 0.7019 - loss: 1.1082 - val_acc: 0.8392 - val_loss: 0.5835 Epoch 2/30 59/59 - 0s - 6ms/step - acc: 0.8975 - loss: 0.3710 - val_acc: 0.8752 - val_loss: 0.4261 Epoch 3/30 59/59 - 0s - 6ms/step - acc: 0.9195 - loss: 0.2855 - val_acc: 0.8948 - val_loss: 0.3638 Epoch 4/30 59/59 - 0s - 6ms/step - acc: 0.9323 - loss: 0.2427 - val_acc: 0.9044 - val_loss: 0.3287 Epoch 5/30 59/59 - 0s - 6ms/step - acc: 0.9413 - loss: 0.2111 - val_acc: 0.9108 - val_loss: 0.3042 Epoch 6/30 59/59 - 0s - 6ms/step - acc: 0.9479 - loss: 0.1854 - val_acc: 0.9184 - val_loss: 0.2868 Epoch
    Cell 56E1a 画图基础
    # Solution
    
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution注释 / 空行———
    3plot_history(history)调用 plot_historyhistory 是 C55 的曲线与 C18 完全一致与 C15 的逐位相同呼应
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]

    The final validation loss and the training history are identical to those of the original model that uses categorical cross-entropy.

    E1b
    Cell 59E1b 解答:wine 用 sparse(batch 256 → 16 步)重点展开
    # Solution
    
    from tensorflow import keras
    from tensorflow.keras import layers
    
    keras.utils.set_random_seed(42)
    X_train, y_train, X_test, y_test = load_wine_quality()
    X_train, X_test = normalize_features(X_train, X_test)
    # y_train, y_test = one_hot_encode(y_train, y_test, 11)
    
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),
        layers.Dense(64, activation="relu"),
        layers.Dense(11, activation="softmax")
    ])
    
    model.compile(loss="sparse_categorical_crossentropy", optimizer="adam",
                  metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=2, validation_data=(X_test, y_test))
    #代码作用机制·语法关联·结果易错点
    1# Solution注释 / 空行———
    3from tensorflow import keras导入———
    4from tensorflow.keras import layers导入———
    6keras.utils.set_random_seed(42)种子———
    7X_train, y_train, X_test, y_test = load_wine_quality()载入 + 标准化同 C44——
    8X_train, X_test = normalize_features(X_train, X_test)载入 + 标准化同 C44——
    9# y_train, y_test = one_hot_encode(y_train, y_test, 11)注释掉 one-hoty 保持整数 3–9y (3918,) intsparse 要求整数
    11model = keras.Sequential([模型 64-64-11同 C44——
    12 layers.Dense(64, activation="relu"),模型 64-64-11同 C44——
    13 layers.Dense(64, activation="relu"),模型 64-64-11同 C44——
    14 layers.Dense(11, activation="softmax")模型 64-64-11同 C44——
    15])模型 64-64-11同 C44——
    17model.compile(loss="sparse_categorical_crossentropy", optimizer="adam",compile 改 sparse———
    18 metrics=["acc"])compile 改 sparse———
    19history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 50 轮 batch 2563918/256 = 15.3 → 16 步/轮(与 C44 的 123 步不同)第 1 轮 acc .2215 / val_acc .2714;第 3 轮 val_acc .5633与 C44 不可直接比:这里 batch 变了(32→256),不是纯粹的 sparse vs categorical 对比
    20 verbose=2, validation_data=(X_test, y_test))fit 50 轮 batch 2563918/256 = 15.3 → 16 步/轮(与 C44 的 123 步不同)第 1 轮 acc .2215 / val_acc .2714;第 3 轮 val_acc .5633与 C44 不可直接比:这里 batch 变了(32→256),不是纯粹的 sparse vs categorical 对比
    运行结果 Epoch 1/50 16/16 - 1s - 80ms/step - acc: 0.2215 - loss: 2.4535 - val_acc: 0.2714 - val_loss: 2.1841 Epoch 2/50 16/16 - 0s - 7ms/step - acc: 0.3073 - loss: 1.9513 - val_acc: 0.2816 - val_loss: 1.6903 Epoch 3/50 16/16 - 0s - 7ms/step - acc: 0.4137 - loss: 1.5577 - val_acc: 0.5633 - val_loss: 1.3019 Epoch 4/50 16/16 - 0s - 7ms/step - acc: 0.5048 - loss: 1.3268 - val_acc: 0.5592 - val_loss: 1.1655 Epoch 5/50 16/16 - 0s - 7ms/step - acc: 0.5258 - loss: 1.2375 - val_acc: 0.5531 - val_loss: 1.1130 Epoch 6/50 16/16 - 0s - 7ms/step - acc: 0.5268 - loss: 1.1887 - val_acc: 0.5776 - val_loss: 1.0871 Epoch
    E1b 读输出时要注意:题目只要求把损失改成 sparse,但解答 cell 同时把 batch_size 从 32 改成了 256——所以第 1 轮 acc 0.2215 比 C44 的 0.4206 低很多,是 batch 变大(每轮更新次数 123→16)导致的,不是 sparse 的问题。E1a 的 MNIST 才是干净对照(其余全同 → 逐位相同)。考试若问 "compare sparse vs categorical",答:结果相同,区别只是标签编码格式与内存/便利性。
    Cell 60E1b 画图基础
    # Solution
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution注释 # Solution———
    2plot_history(history)调用 plot_historyhistory 是 C59 的
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]

    &#x2766;

    📘 Tutorial 6(= Lab 6)· 模型开发流程(1 层 / 2 层宽度扫描 → 重训评估)+ L1 / L2 正则化

    t06-s13903054.ipynb,90 cells。对应 Unit 6 讲义 p6–p15(开发流程:训练 / 验证 / 测试三集)、p16–p32(宽度扫描与过拟合)、p33–p46(L1 正则化)。方法是字典 + 循环式扫描:每个模型一个 cell,结果存进 final_values[model.name],最后 pd.DataFrame.from_dict(…, orient="index") 汇总成表。结果速览(val_loss 越小越好):1 层 32→512:.2587 → .2012;2 层 32→512:.2690 → .2129;L1 最佳 1x512_1e-6 .1657;L2 最佳 2x512_1e-7 .1615;重训后测试集:1x512 [.2197, .9430] / 2x512 [.2270, .9490] / L1 1e-6 [.1700, .9460] / L2 1e-7 [.1839, .9480]。
    读法:本 notebook 有 4 组"同构 cell"(1 层 5 个 / 2 层 5 个 / L1 8 个 / L2 8 个),每组只有 单元数、层数、正则强度三个变量在变。每组的第一个 cell 逐行精讲,后续 cell 每行仍列出,但只讲"变了什么 + 结果怎么读"。
    本 Lab 的三个必会机制:① validation_split=0.2 是从 X_train 的末尾切 20%(不打乱),不碰 X_test——X_test 只在最终 evaluate 时用一次(Unit 6 讲义 p9 "test set is for evaluating the final accepted model");② 选模型看 val_loss 而不是 val_acc(讲义 p27:loss 是连续量、对置信度敏感,acc 是离散量);③ 选好后用全部 X_train(训练+验证)重训、不带 validation_split,再在 X_test 上评估——这就是"部署前重训"的标准流程。
    必会数字:ratio=0.1 → 6000/1000;split 后 4800 训练 / 1200 验证 → 4800/256 = 18.75 → 19 步/轮;重训 6000/256 → 24 步;参数 1x32 25,450、1x512 407,050、2x512 669,706。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同前IPython 魔术命令;须在 import tensorflow 前env: TF_CPP_MIN_LOG_LEVEL=2每个 notebook 第一个 cell
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • the process of developing a suitable model for a task, and
  • application of weight regularization.
  • Student name: Yin Bang
    Student ID: 13903054

    The process of developing neural network models

    Developing a suitable model for a task is an iterative process. Multiple models are created, trained, evaluated, until a suitable model is accepted. The models are mainly created or tuned based on results of preceding models.


    The available data, or examples, are divided into 3 subsets:


  • the training set for training each model,
  • the validation set for evaluating each model, and
  • the test set for evaluating the final accepted model.

  • There are different ways of selecting and tuning the models. One possible way is described below and adopted in this lesson.


    1. Start with one or a few simple and potentially proper models.

    1. Increase model complexity, observing the resulting performance and overfitting.

    1. Select a few promising models, and regularize them to reduce overfitting.

    1. Repeat step 2 and/or step 3 until a acceptable model is found.


    In each stage, it is ideal to examine a lot of models with different settings, but this is simply infeasible in practice due to time and resource constraints. We typically design or select a small number of models to examine based on model variety, previous experience, and validation results of preceding models.

    三集分工(Unit 6 讲义 p7–p10):训练集——算梯度、更新权重;验证集——每轮末评估、用来选模型/超参数(可以反复用,因为它参与了"决策");测试集——只在最终接受模型后评估一次,估计泛化性能(用多了就变成验证集,估计会偏乐观)。本 Lab 用 validation_split 从 X_train 里切验证集,X_test 全程只在 C31/C45/C66/C89 出现。

    Utility code

    Below are utility functions for use in developing the models.


    This function loads the MNIST dataset, prepares the data, and returns portion of the data in a 4-tuple: X_train, y_train, X_test, y_test.

    Cell 9load_and_prep_mnist(ratio=0.1):种子 + 子集 + 缩放展平 + one-hot 一站式重点展开
    from tensorflow import keras
    from tensorflow.keras import layers, regularizers
    from tensorflow.keras.datasets import mnist
    
    def load_and_prep_mnist(ratio=0.1):
        keras.utils.set_random_seed(42)
        (X_train, y_train), (X_test, y_test) = mnist.load_data()
        if ratio < 1:
            sz_train = int(len(X_train) * ratio)
            sz_test = int(len(X_test) * ratio)
            X_train, y_train = X_train[:sz_train], y_train[:sz_train]
            X_test, y_test = X_test[:sz_test], y_test[:sz_test]
        X_train_out = X_train.astype(float) / 255  # scale to range 0 to 1
        X_test_out = X_test.astype(float) / 255
        X_train_out = X_train_out.reshape(-1, 28*28)  # convert 2D to 1D
        X_test_out = X_test_out.reshape(-1, 28*28)
        y_train_oh = keras.utils.to_categorical(y_train, 10)  # one-hot encode
        y_test_oh = keras.utils.to_categorical(y_test, 10)
        return X_train_out, y_train_oh, X_test_out, y_test_oh
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入 keras / layers / regularizers / mnistregularizers 在 L1/L2 实验(C53 起)才用到,这里先导入—regularizers 是 keras 的子模块,与 layers 平级
    2from tensorflow.keras import layers, regularizers导入 keras / layers / regularizers / mnistregularizers 在 L1/L2 实验(C53 起)才用到,这里先导入—regularizers 是 keras 的子模块,与 layers 平级
    3from tensorflow.keras.datasets import mnist导入 keras / layers / regularizers / mnistregularizers 在 L1/L2 实验(C53 起)才用到,这里先导入—regularizers 是 keras 的子模块,与 layers 平级
    5def load_and_prep_mnist(ratio=0.1):定义 load_and_prep_mnist(ratio=0.1)默认取 10%:6000 训练 / 1000 测试(t05 是 25%)—函数内把 t05 的 3 个工具合成 1 个
    6 keras.utils.set_random_seed(42)set_random_seed(42) 写在函数内每次调用都重置种子 → 每个模型的初始权重相同、数据切分相同 → 可控变量—t05 是在 cell 里设一次;放函数内保证重复调用也复现
    7 (X_train, y_train), (X_test, y_test) = mnist.load_data()载入全集—60000 / 10000—
    8 if ratio < 1:if ratio < 1———
    9 sz_train = int(len(X_train) * ratio)计算子集大小int(60000×0.1)=6000;int(10000×0.1)=1000——
    10 sz_test = int(len(X_test) * ratio)计算子集大小int(60000×0.1)=6000;int(10000×0.1)=1000——
    11 X_train, y_train = X_train[:sz_train], y_train[:sz_train]切片X[:6000] / X_test[:1000]—X 与 y 必须同时切
    12 X_test, y_test = X_test[:sz_test], y_test[:sz_test]切片X[:6000] / X_test[:1000]—X 与 y 必须同时切
    13 X_train_out = X_train.astype(float) / 255 # scale to range 0 to 1astype(float)/255uint8 → float64,值域 [0,1]—先 astype 再除,防 uint8 溢出
    14 X_test_out = X_test.astype(float) / 255astype(float)/255uint8 → float64,值域 [0,1]—先 astype 再除,防 uint8 溢出
    15 X_train_out = X_train_out.reshape(-1, 28*28) # convert 2D to 1Dreshape(-1, 784)(6000,28,28) → (6000,784)—Dense 需要 2D
    16 X_test_out = X_test_out.reshape(-1, 28*28)reshape(-1, 784)(6000,28,28) → (6000,784)—Dense 需要 2D
    17 y_train_oh = keras.utils.to_categorical(y_train, 10) # one-hot encodeto_categorical(…, 10)整数 → one-hot (6000,10)—这里 one-hot 写死了 10 类,wine 不能复用此函数
    18 y_test_oh = keras.utils.to_categorical(y_test, 10)to_categorical(…, 10)整数 → one-hot (6000,10)—这里 one-hot 写死了 10 类,wine 不能复用此函数
    19 return X_train_out, y_train_oh, X_test_out, y_test_oh返回四元组顺序 (X_train, y_train, X_test, y_test),y 已 one-hot—返回名 _out/_oh 强调"已处理"
    与 t05 C12 的三点区别:① 种子放进函数内(每次调用重置);② ratio 0.25 → 0.1(6000 样本训练更快,且更容易过拟合以便演示正则化);③ 不分三个函数而是一个一站式函数。调用一次的代价:每次 load_and_prep_mnist() 都重新下载检查/读 npz、重新 astype(拷贝 6000×784 float64 ≈ 37 MB)——所以每个实验 cell 都调一次,保证每个模型拿到完全相同的数据与初始权重。

    This function retrieves the final results in a training history, i.e. values of "loss", "val_loss", "acc", and "val_acc" in the final epoch.

    Cell 11history_final_values:取每条曲线最后一轮的值重点展开
    def history_final_values(history):
        return {k: round(v[-1], 4) for k, v in history.history.items()}
    #代码作用机制·语法关联·结果易错点
    1def history_final_values(history):定义 history_final_values输入 fit 返回的 History 对象—History.history 是 dict:{键: 每轮值的列表}
    2 return {k: round(v[-1], 4) for k, v in history.history.items()}字典推导式对 history.history 的每个 (k, v):k 是 "loss"/"val_loss"/"acc"/"val_acc",v 是 50 轮的列表;v[-1] 取最后一轮;round(…, 4) 保留 4 位{'acc': 0.9862, 'loss': 0.0708, 'val_acc': 0.9225, 'val_loss': 0.2587}v[-1] 是最后一轮不是最好一轮——若曲线末尾反弹,这个数不是最优;要看最优应 v.min()(loss)或 max()(acc)
    ↳ 一行代码的三个语法点:{k: expr for k, v in d.items()} 是字典推导式;v[-1] 负索引取末元素;round(x, 4) 返回 float(不是字符串格式化)。这个 dict 直接成为 final_values 的值,pandas 能把它转成一行。

    This function plots a training history, including both training and validation results.

    Cell 13plot_history:pandas DataFrame 版画图导入·绘图·输出
    import matplotlib.pyplot as plt
    import pandas as pd
    
    def plot_history(history):
        df = pd.DataFrame(history.history)
        df.index = df.index + 1
        fig, axs = plt.subplots(1, 2, figsize=(8, 4))
        df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])
        df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])
        plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入 pyplot 与 pandaspandas 画图是 DataFrame.plot 的封装——
    2import pandas as pd导入 pyplot 与 pandaspandas 画图是 DataFrame.plot 的封装——
    4def plot_history(history):定义 plot_history(history)与 t05 同名但实现不同(这里用 pandas)——
    5 df = pd.DataFrame(history.history)把 history dict 转成 DataFramepd.DataFrame(dict of lists) → 每键一列、每轮一行(50 行 × 4 列)df 列:loss val_loss acc val_acc若 history 只有 acc/loss(重训时),L8/L9 会 KeyError
    6 df.index = df.index + 1索引从 1 开始df.index 默认 0..49;+1 变成 1..50,图的横轴"轮数"更自然x 轴 1–50—
    7 fig, axs = plt.subplots(1, 2, figsize=(8, 4))创建 1×2 子图subplots(1, 2) → axs 是长度 2 的一维数组—与 t05 的 subplot(121) 等价
    8 df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])左图画 loss / val_lossdf.plot(y=[列名列表], grid=True, ax=axs[0]):pandas 直接画多条线并自动图例—y 必须是 df 里存在的列名
    9 df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])右图画 acc / val_acc同上 ax=axs[1]
    —
    10 plt.tight_layout()收紧布局———

    This function compiles and fits a model, and returns the training history. In the fit() method, the argument validation_split=0.2 specifies 20% of X_train/y_train are used for validation and 80% are used for training. Note that the number of epochs, batch size, ratio of validation split are fixed in this function for convenience in this lesson; in reality; these are hyperparameters to be tuned in the process of model development.

    validation_split vs validation_data(Unit 6 讲义 p11):validation_data=(X_val, y_val) 自己指定验证集(t05 用的就是这个,直接把 X_test 当验证集——严格说不规范);validation_split=0.2 让 Keras 在 fit 前自动切 X_train 的最后 20%(切之前不 shuffle,所以是末尾连续的 1200 个样本)。共同点:都不会用这 20% 算梯度。易错:split 发生在 load_and_prep_mnist(ratio=0.1) 之后,所以是 6000 的 20% = 1200,不是 60000 的 20%。
    Cell 15compile_and_fit_model:固定 50 轮 / batch 256 / validation_split 0.2重点展开
    def compile_and_fit_model(model, X_train, y_train):
        model.compile(loss="categorical_crossentropy",
                      optimizer="adam", metrics=["acc"])
        history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                            verbose=0, validation_split=0.2)
        return history
    #代码作用机制·语法关联·结果易错点
    1def compile_and_fit_model(model, X_train, y_train):定义 compile_and_fit_model(model, X_train, y_train)把 compile + fit 封装,保证所有模型训练条件一致—这就是"控制变量"的代码体现
    2 model.compile(loss="categorical_crossentropy",compilecategorical_crossentropy(配 one-hot y)+ adam + acc—写死在函数里,所有模型共用
    3 optimizer="adam", metrics=["acc"])compilecategorical_crossentropy(配 one-hot y)+ adam + acc—写死在函数里,所有模型共用
    4 history = model.fit(X_train, y_train, epochs=50, batch_size=256,fitepochs=50 固定;batch_size=256;verbose=0 完全不输出(每个 cell 只打印 final_values);validation_split=0.2:X_train 末尾 20% 做验证4800 训练 / 1200 验证 → 19 步/轮split 在 fit 内部切,不 shuffle;若 X_train 已 shuffle 过则切出来的是随机子集
    5 verbose=0, validation_split=0.2)fitepochs=50 固定;batch_size=256;verbose=0 完全不输出(每个 cell 只打印 final_values);validation_split=0.2:X_train 末尾 20% 做验证4800 训练 / 1200 验证 → 19 步/轮split 在 fit 内部切,不 shuffle;若 X_train 已 shuffle 过则切出来的是随机子集
    6 return history返回 history——函数不返回 model——model 是传入的同一对象,权重已被原地更新
    为什么把超参数写死在函数里(M14 的解释):本课只研究"宽度 / 深度 / 正则强度"三个变量,其余(epochs、batch、split、优化器)必须固定,否则结果不可比。真实项目里这些也都是要调的超参数。
    verbose 三档:0 = 静默;1 = 进度条;2 = 每轮一行。本 Lab 用 0 是因为 50 轮 × 20 多个模型会刷屏。

    Models with one hidden layer

    Let's get started with simple models that contain one hidden layer. Models with a hidden layer of various numbers of neurons are explored below.


  • Model 1x32: 1 hidden layer of 32 neurons
  • Model 1x64: 1 hidden layer of 64 neurons
  • Model 1x128: 1 hidden layer of 128 neurons
  • Model 1x256: 1 hidden layer of 256 neurons
  • Model 1x512: 1 hidden layer of 512 neurons

  • Training and validation results of the models are stored in a dictionary called final_values, which facilitates the display of results and is first created.

    Cell 18创建结果字典 final_values基础
    final_values = {}
    #代码作用机制·语法关联·结果易错点
    1final_values = {}final_values = {}空字典;键 = model.name,值 = history_final_values 的结果 dict—只需运行一次;重复运行会清空之前所有结果(C42 的表会少行)

    The models are built and trained, their training and validation results are saved, and training histories are plotted below. Note that a name is specified for each Keras model for convenience; the names are optional and must not contain special characters of spaces or = etc.

    ↳ name="1x32":Keras 模型名会显示在 summary / plot_model / 日志里;名字里的 x 与 - 是合法的,但 =、空格、/ 不行(M19 的提醒)。model.name 就是字典的键,所以名字必须唯一,否则后训的会覆盖前面的结果。
    Cell 20Model 1x32:单隐藏层 32 神经元(模板 cell,逐行精讲)重点展开
    # Model 1x32
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x32")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x32注释:模型名———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载数据每次重新调用 → 种子重置 + 相同数据X_train (6000,784)保证每个模型起点一致
    3model = keras.Sequential([搭建模型Sequential([...], name="1x32"):Dense(32, relu) 自动推断输入 784;Dense(10, softmax) 输出参数 32×785 + 10×33 = 25,120+330 = 25,450name 必须唯一且无特殊字符
    4 layers.Dense(32, activation="relu"),搭建模型Sequential([...], name="1x32"):Dense(32, relu) 自动推断输入 784;Dense(10, softmax) 输出参数 32×785 + 10×33 = 25,120+330 = 25,450name 必须唯一且无特殊字符
    5 layers.Dense(10, activation="softmax")搭建模型Sequential([...], name="1x32"):Dense(32, relu) 自动推断输入 784;Dense(10, softmax) 输出参数 32×785 + 10×33 = 25,120+330 = 25,450name 必须唯一且无特殊字符
    6], name="1x32")搭建模型Sequential([...], name="1x32"):Dense(32, relu) 自动推断输入 784;Dense(10, softmax) 输出参数 32×785 + 10×33 = 25,120+330 = 25,450name 必须唯一且无特殊字符
    7history = compile_and_fit_model(model, X_train, y_train)compile + fit调用 C15 的封装函数history 含 acc/loss/val_acc/val_loss 各 50 个值—
    8final_values[model.name] = history_final_values(history)存结果final_values[model.name] = history_final_values(history):键 "1x32" → 4 个末值—model.name 取自 L6,所以改模型不用改这行
    9print(final_values[model.name])打印本模型结果{'acc': 0.9862, 'loss': 0.0708, 'val_acc': 0.9225, 'val_loss': 0.2587}val_loss .2587 是 5 个 1 层模型里最高—
    10plot_history(history)画历史曲线C13 的 pandas 版
    —
    运行结果 Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step {'acc': 0.9862, 'loss': 0.0708, 'val_acc': 0.9225, 'val_loss': 0.2587} <Figure size 800x400 with 2 Axes> [image/png]
    这个 10 行模板后面会重复 25 次(5 个 1 层 + 5 个 2 层 + 8 个 L1 + 8 个 L2 - 1 个示例),只改 3 个地方:L1 注释、L4/L5 的 Dense 行(单元数 / 层数 / activity_regularizer)、L6 的 name。其余 7 行完全一样——所以请把这个 cell 的每一行都吃透。
    读 1x32 的曲线:训练 loss 从 ≈0.5 一路降到 0.07、acc 到 0.986;val_loss 在 ≈15 轮后趋平并略回升到 .2587(过拟合开始),val_acc .9225。这是容量不足 + 轻度过拟合并存:模型太小学不全,但 4800 样本也够它记住。
    Cell 21Model 1x64基础
    # Model 1x64
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x64")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x64注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载同 C20——
    3model = keras.Sequential([Dense(64) + name="1x64"唯一改动:32 → 64参数 64×785+650 = 50,890—
    4 layers.Dense(64, activation="relu"),Dense(64) + name="1x64"唯一改动:32 → 64参数 64×785+650 = 50,890—
    5 layers.Dense(10, activation="softmax")Dense(64) + name="1x64"唯一改动:32 → 64参数 64×785+650 = 50,890—
    6], name="1x64")Dense(64) + name="1x64"唯一改动:32 → 64参数 64×785+650 = 50,890—
    7history = compile_and_fit_model(model, X_train, y_train)compile+fit同 C20——
    8final_values[model.name] = history_final_values(history)存结果键 "1x64"——
    9print(final_values[model.name])打印{'acc': 0.9973, 'loss': 0.0328, 'val_acc': 0.9325, 'val_loss': 0.2513}val_loss .2587 → .2513—
    10plot_history(history)画图———
    运行结果 {'acc': 0.9973, 'loss': 0.0328, 'val_acc': 0.9325, 'val_loss': 0.2513} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 22Model 1x128基础
    # Model 1x128
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(128, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x128")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x128注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(128) + name="1x128"64 → 128参数 128×785+1,290 = 101,770—
    4 layers.Dense(128, activation="relu"),Dense(128) + name="1x128"64 → 128参数 128×785+1,290 = 101,770—
    5 layers.Dense(10, activation="softmax")Dense(128) + name="1x128"64 → 128参数 128×785+1,290 = 101,770—
    6], name="1x128")Dense(128) + name="1x128"64 → 128参数 128×785+1,290 = 101,770—
    7history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    8final_values[model.name] = history_final_values(history)存结果———
    9print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0126, 'val_acc': 0.9383, 'val_loss': 0.223}训练 acc 首次到 1.0;val_loss .223训练 acc 1.0 = 完全记住训练集,开始过拟合的信号
    10plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0126, 'val_acc': 0.9383, 'val_loss': 0.223} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 23Model 1x256基础
    # Model 1x256
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(256, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x256")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x256注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(256) + name="1x256"128 → 256参数 256×785+2,570 = 203,530—
    4 layers.Dense(256, activation="relu"),Dense(256) + name="1x256"128 → 256参数 256×785+2,570 = 203,530—
    5 layers.Dense(10, activation="softmax")Dense(256) + name="1x256"128 → 256参数 256×785+2,570 = 203,530—
    6], name="1x256")Dense(256) + name="1x256"128 → 256参数 256×785+2,570 = 203,530—
    7history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    8final_values[model.name] = history_final_values(history)存结果———
    9print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.005, 'val_acc': 0.9483, 'val_loss': 0.212}val_loss .212—
    10plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.005, 'val_acc': 0.9483, 'val_loss': 0.212} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 24Model 1x512基础
    # Model 1x512
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x512")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x512注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(512) + name="1x512"256 → 512参数 512×785+5,130 = 407,050(16 倍于 1x32)—
    4 layers.Dense(512, activation="relu"),Dense(512) + name="1x512"256 → 512参数 512×785+5,130 = 407,050(16 倍于 1x32)—
    5 layers.Dense(10, activation="softmax")Dense(512) + name="1x512"256 → 512参数 512×785+5,130 = 407,050(16 倍于 1x32)—
    6], name="1x512")Dense(512) + name="1x512"256 → 512参数 512×785+5,130 = 407,050(16 倍于 1x32)—
    7history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    8final_values[model.name] = history_final_values(history)存结果———
    9print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0022, 'val_acc': 0.9508, 'val_loss': 0.2012}1 层最佳 .2012 → 被 C30 选为"接受模型"—
    10plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0022, 'val_acc': 0.9508, 'val_loss': 0.2012} <Figure size 800x400 with 2 Axes> [image/png]

    The training and validation results of the models are shown in a table below. This is done by creating a pandas dataframe from the final_values dictionary of results.

    Cell 26把 final_values 字典转成表格重点展开
    pd.DataFrame.from_dict(final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(final_values, orient="index")pd.DataFrame.from_dict(final_values, orient="index")字典 {模型名: {指标: 值}} → 行=模型、列=指标;orient="index" 说明外层键是行标签5 行 × 4 列表默认 orient="columns" 会把模型名当列名,表会转置;最后一行表达式自动显示(notebook 特性)
    运行结果 acc loss val_acc val_loss 1x32 0.9862 0.0708 0.9225 0.2587 1x64 0.9973 0.0328 0.9325 0.2513 1x128 1.0000 0.0126 0.9383 0.2230 1x256 1.0000 0.0050 0.9483 0.2120 1x512 1.0000 0.0022 0.9508 0.2012

    According to the validation losses (and validation accuracies), the results show that more neurons achieve better performance. In general, more complex neural networks are more capable and have more potential to learn more from data. However, more complex models are more likely to encounter overfitting, which will be considered later.

    怎么读 C26 的表(考试 "comment on the results" 题模板):① 宽度 ↑ → 训练 acc 0.9862 → 1.0、loss 0.0708 → 0.0022(更多参数 = 更强拟合能力);② val_loss .2587 → .2012 单调下降——在这 5 个模型里没看到过拟合拐点,因为 50 轮、4800 样本、没有正则时,宽模型的 val_loss 仍在其最低点附近(Unit 6 讲义 p21–p24 的 U 形曲线在这里只看到左半段);③ 但 acc 和 val_acc 的差距在扩大(1x32 差 0.064,1x512 差 0.049)——不是单调的,说明 acc 太粗,要看 loss。正确写法:"More neurons give lower training loss monotonically; validation loss also decreases but with diminishing returns (.2587→.2012 over 16× more parameters). The gap between training and validation loss widens (0.19→0.20), hinting at the onset of overfitting."

    Model evaluation

    For demonstration, let's pretend for now that we accept the best model above, model 1x512, and are going to deploy it for production. The following code retrains the model using the training set and validation set combined (X_train/y_train), and evaluates the retrained model using the test set (X_test/y_test). In particular, the fit() method does not have a validation_split argument, so it would use the whole X_train and y_train for training and would not perform validation.

    为什么重训要"训练+验证合并":选模型时验证集被"用过了",不能再当测试集;但它是真实数据,扔掉可惜——所以最终模型用 全部 X_train(6000)重训,然后只在 X_test(1000)上评估一次。重训后 history.history 只有 acc/loss 两个键(没有 val_*),所以 history_final_values 返回 {'acc': 1.0, 'loss': 0.0018};model.evaluate(X_test, y_test) 返回 [test_loss, test_acc]。对比:验证时 val_loss .2012 → 测试 .2197(略升,正常:测试集是真正未见过的)。
    Cell 30重训 1x512(训练+验证合并,无 validation_split)重点展开
    # Retrain model 1x512 using training set and validation set combined
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x512_retrain")
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=0) # no validation_split
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# Retrain model 1x512 using training set and validation set combined注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()重新加载数据拿回完整 X_train(6000)——注意之前 fit 的 validation_split 没有真正修改 X_train,这里只是保证干净起点X_train (6000,784)—
    3model = keras.Sequential([同样的结构,新名字与 C24 完全相同的 1x512;name 加 _retrain 后缀避免覆盖—名字必须不同,否则 final_values 会混淆(虽然这里没存)
    4 layers.Dense(512, activation="relu"),同样的结构,新名字与 C24 完全相同的 1x512;name 加 _retrain 后缀避免覆盖—名字必须不同,否则 final_values 会混淆(虽然这里没存)
    5 layers.Dense(10, activation="softmax")同样的结构,新名字与 C24 完全相同的 1x512;name 加 _retrain 后缀避免覆盖—名字必须不同,否则 final_values 会混淆(虽然这里没存)
    6], name="1x512_retrain")同样的结构,新名字与 C24 完全相同的 1x512;name 加 _retrain 后缀避免覆盖—名字必须不同,否则 final_values 会混淆(虽然这里没存)
    7model.compile(loss="categorical_crossentropy",compile(自己写,不用封装函数)因为封装函数的 fit 写死了 validation_split=0.2,重训不要 split,所以手写 compile+fit—若偷懒调 compile_and_fit_model,就只用了 4800 样本,不是"合并重训"
    8 optimizer="adam", metrics=["acc"])compile(自己写,不用封装函数)因为封装函数的 fit 写死了 validation_split=0.2,重训不要 split,所以手写 compile+fit—若偷懒调 compile_and_fit_model,就只用了 4800 样本,不是"合并重训"
    9history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 不带 validation_split全部 6000 样本训练;6000/256 = 23.4 → 24 步/轮history 只有 acc / loss没有 val_* 键——所以 plot_history 会 KeyError,C30 没有画图
    10 verbose=0) # no validation_splitfit 不带 validation_split全部 6000 样本训练;6000/256 = 23.4 → 24 步/轮history 只有 acc / loss没有 val_* 键——所以 plot_history 会 KeyError,C30 没有画图
    11print(history_final_values(history))打印末值{'acc': 1.0, 'loss': 0.0018}比 C24 的 .0022 更低(多了 1200 个样本)—
    运行结果 {'acc': 1.0, 'loss': 0.0018}
    Cell 31在测试集上评估重训模型重点展开
    print("Evaluation of model " + model.name,
          model.evaluate(X_test, y_test, verbose=0))
    #代码作用机制·语法关联·结果易错点
    1print("Evaluation of model " + model.name,model.evaluate(X_test, y_test, verbose=0)返回 [loss, acc] 列表(顺序 = compile 里的 loss 然后 metrics);print 用逗号拼接字符串与列表[0.2197, 0.9430]整个 notebook 里 X_test 只在这里和 C45/C66/C89 用到——这就是"测试集只用一次"的实践;evaluate 不改权重
    2 model.evaluate(X_test, y_test, verbose=0))model.evaluate(X_test, y_test, verbose=0)返回 [loss, acc] 列表(顺序 = compile 里的 loss 然后 metrics);print 用逗号拼接字符串与列表[0.2197, 0.9430]整个 notebook 里 X_test 只在这里和 C45/C66/C89 用到——这就是"测试集只用一次"的实践;evaluate 不改权重
    运行结果 Evaluation of model 1x512_retrain [0.21973389387130737, 0.9430000185966492]
    三个数放一起看:验证 val_loss .2012 / val_acc .9508(4800 样本训、1200 验)→ 测试 test_loss .2197 / test_acc .9430(6000 样本训、1000 测)。测试略差是正常的:① 测试集真正未见;② 没有早停,重训 50 轮可能过拟合更深(loss .0018 vs .0022)。考试若问 "why retrain on train+val":选模型时验证集参与了决策,最终模型应利用所有带标签数据;测试集保持独立以给出无偏估计。

    Models with two hidden layers

    In this section, we explore some models with two hidden layers.


  • Model 2x32: 2 hidden layers each of 32 neurons
  • Model 2x64: 2 hidden layers each of 64 neurons
  • Model 2x128: 2 hidden layers each of 128 neurons
  • Model 2x256: 2 hidden layers each of 256 neurons
  • Model 2x512: 2 hidden layers each of 512 neurons
  • Practice - Question 1 of 2

    Q1a


    Write code to build and train the models, save their training and validation results in the final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 36Model 2x32:两层各 32(Q1a 学生作答,模板 cell)练习·作答
    # Model 2x32
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(32, activation="relu"),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x32")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x32注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载数据与 C20 相同——
    3model = keras.Sequential([两层 Dense(32)比 1x32 多一行 Dense(32, relu):第二层输入自动 = 第一层输出 32参数 32×785 + 32×33 + 10×33 = 25,120+1,056+330 = 26,506第二层不用写 input_dim,Sequential 自动推断
    4 layers.Dense(32, activation="relu"),两层 Dense(32)比 1x32 多一行 Dense(32, relu):第二层输入自动 = 第一层输出 32参数 32×785 + 32×33 + 10×33 = 25,120+1,056+330 = 26,506第二层不用写 input_dim,Sequential 自动推断
    5 layers.Dense(32, activation="relu"),两层 Dense(32)比 1x32 多一行 Dense(32, relu):第二层输入自动 = 第一层输出 32参数 32×785 + 32×33 + 10×33 = 25,120+1,056+330 = 26,506第二层不用写 input_dim,Sequential 自动推断
    6 layers.Dense(10, activation="softmax")两层 Dense(32)比 1x32 多一行 Dense(32, relu):第二层输入自动 = 第一层输出 32参数 32×785 + 32×33 + 10×33 = 25,120+1,056+330 = 26,506第二层不用写 input_dim,Sequential 自动推断
    7], name="2x32")name="2x32"命名规则:<层数>x<每层单元数>——
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit同 C2019 步/轮—
    9final_values[model.name] = history_final_values(history)存结果键 "2x32" 追加进 final_values——
    10print(final_values[model.name])打印{'acc': 0.9967, 'loss': 0.0344, 'val_acc': 0.9342, 'val_loss': 0.269}val_loss .269 > 1x32 的 .2587两层 32 参数只多 1,056,但更深 → 更难训;val_loss 反而更高
    11plot_history(history)画图—
    —
    运行结果 {'acc': 0.9967, 'loss': 0.0344, 'val_acc': 0.9342, 'val_loss': 0.269} <Figure size 800x400 with 2 Axes> [image/png]
    Q1a 你的作答核对:正确 ✔——五个 2 层模型全部按模板写,名字规范(2x32…2x512),结果都进了 final_values(C42 表里有 10 行)。观察 2x32 vs 1x32:深度加倍但 val_loss .2690 > .2587——说明"更深"不等于"更好";小容量下加深度只增加了优化难度。但到 2x256/2x512 时,两层 .2180/.2129 反超一层的 .2120/.2012?不——仍是 1 层略优(见 C42 全表)。
    Cell 37Model 2x64基础
    # Model 2x64
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(64, activation="relu"),
        layers.Dense(64, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([两层 Dense(64) + name="2x64"32 → 64参数 64×785+64×65+650 = 55,050(与 t05 的 64-64-10 同构)—
    4 layers.Dense(64, activation="relu"),两层 Dense(64) + name="2x64"32 → 64参数 64×785+64×65+650 = 55,050(与 t05 的 64-64-10 同构)—
    5 layers.Dense(64, activation="relu"),两层 Dense(64) + name="2x64"32 → 64参数 64×785+64×65+650 = 55,050(与 t05 的 64-64-10 同构)—
    6 layers.Dense(10, activation="softmax")两层 Dense(64) + name="2x64"32 → 64参数 64×785+64×65+650 = 55,050(与 t05 的 64-64-10 同构)—
    7], name="2x64")两层 Dense(64) + name="2x64"32 → 64参数 64×785+64×65+650 = 55,050(与 t05 的 64-64-10 同构)—
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9final_values[model.name] = history_final_values(history)存结果———
    10print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.007, 'val_acc': 0.9375, 'val_loss': 0.2633}val_loss .2633—
    11plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.007, 'val_acc': 0.9375, 'val_loss': 0.2633} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 38Model 2x128基础
    # Model 2x128
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(128, activation="relu"),
        layers.Dense(128, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x128")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x128注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([两层 Dense(128) + name="2x128"64 → 128参数 128×785+128×129+1,290 = 118,282—
    4 layers.Dense(128, activation="relu"),两层 Dense(128) + name="2x128"64 → 128参数 128×785+128×129+1,290 = 118,282—
    5 layers.Dense(128, activation="relu"),两层 Dense(128) + name="2x128"64 → 128参数 128×785+128×129+1,290 = 118,282—
    6 layers.Dense(10, activation="softmax")两层 Dense(128) + name="2x128"64 → 128参数 128×785+128×129+1,290 = 118,282—
    7], name="2x128")两层 Dense(128) + name="2x128"64 → 128参数 128×785+128×129+1,290 = 118,282—
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9final_values[model.name] = history_final_values(history)存结果———
    10print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0012, 'val_acc': 0.9375, 'val_loss': 0.2503}val_loss .2503—
    11plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0012, 'val_acc': 0.9375, 'val_loss': 0.2503} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 39Model 2x256基础
    # Model 2x256
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(256, activation="relu"),
        layers.Dense(256, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x256")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x256注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([两层 Dense(256) + name="2x256"128 → 256参数 256×785+256×257+2,570 = 269,322—
    4 layers.Dense(256, activation="relu"),两层 Dense(256) + name="2x256"128 → 256参数 256×785+256×257+2,570 = 269,322—
    5 layers.Dense(256, activation="relu"),两层 Dense(256) + name="2x256"128 → 256参数 256×785+256×257+2,570 = 269,322—
    6 layers.Dense(10, activation="softmax")两层 Dense(256) + name="2x256"128 → 256参数 256×785+256×257+2,570 = 269,322—
    7], name="2x256")两层 Dense(256) + name="2x256"128 → 256参数 256×785+256×257+2,570 = 269,322—
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9final_values[model.name] = history_final_values(history)存结果———
    10print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0004, 'val_acc': 0.9492, 'val_loss': 0.218}val_loss .218—
    11plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0004, 'val_acc': 0.9492, 'val_loss': 0.218} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 40Model 2x512基础
    # Model 2x512
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dense(512, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x512")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([两层 Dense(512) + name="2x512"256 → 512参数 512×785+512×513+5,130 = 401,920+262,656+5,130 = 669,706(t05 模型的 12 倍)—
    4 layers.Dense(512, activation="relu"),两层 Dense(512) + name="2x512"256 → 512参数 512×785+512×513+5,130 = 401,920+262,656+5,130 = 669,706(t05 模型的 12 倍)—
    5 layers.Dense(512, activation="relu"),两层 Dense(512) + name="2x512"256 → 512参数 512×785+512×513+5,130 = 401,920+262,656+5,130 = 669,706(t05 模型的 12 倍)—
    6 layers.Dense(10, activation="softmax")两层 Dense(512) + name="2x512"256 → 512参数 512×785+512×513+5,130 = 401,920+262,656+5,130 = 669,706(t05 模型的 12 倍)—
    7], name="2x512")两层 Dense(512) + name="2x512"256 → 512参数 512×785+512×513+5,130 = 401,920+262,656+5,130 = 669,706(t05 模型的 12 倍)—
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9final_values[model.name] = history_final_values(history)存结果———
    10print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9533, 'val_loss': 0.2129}训练 loss 1e-4;val_loss .2129 > 1x512 的 .2012→ 被 Q1c 选为"接受模型"(练习用)
    11plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9533, 'val_loss': 0.2129} <Figure size 800x400 with 2 Axes> [image/png]

    Q1b


    Write code to display the training and validation results in the final_values dictionary, which contains the results of the models with 1 hidden layer and those with 2 hidden layers for now.

    Cell 42Q1b:显示 10 个模型的汇总表练习·作答
    pd.DataFrame.from_dict(final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(final_values, orient="index")pd.DataFrame.from_dict(final_values, orient="index")同 C26;此时字典已有 10 个键10 行 × 4 列表(5 个 1x + 5 个 2x)若 C18 被重复运行,1x 的 5 行会丢失——字典在 C18 被清空
    运行结果 acc loss val_acc val_loss 1x32 0.9862 0.0708 0.9225 0.2587 1x64 0.9973 0.0328 0.9325 0.2513 1x128 1.0000 0.0126 0.9383 0.2230 1x256 1.0000 0.0050 0.9483 0.2120 1x512 1.0000 0.0022 0.9508 0.2012 2x32 0.9967 0.0344 0.9342 0.2690 2x64 1.0000 0.0070 0.9375 0.2633 2x128 1.0000 0.0012 0.9375 0.2503 2x256 1.0000 0.0004 0.9492 0.2180 2x512 1.0000 0.0001 0.9533 0.2129
    Q1b 你的作答核对:正确 ✔。读表:① 同宽度比较——2 层 val_loss 普遍略高于 1 层(2x32 .2690 vs 1x32 .2587;2x512 .2129 vs 1x512 .2012),本实验里深度没带来收益;② 1x512 val_loss .2012 最低、val_acc .9508;2x512 val_acc .9533 最高但 val_loss 不是最低——再次印证按 val_loss 选(讲义 p27)。

    Q1c


    For practice, let's pretend that model 2x512 is accepted and will be deployed to production. Write code to retrain that model 2x512 using the training set and validation set combined (X_train/y_train), and evaluate the retrained model using the test set (X_test/y_test).

    Cell 44Q1c:重训 2x512(训练+验证合并)练习·作答
    # Retrain model 2x512 using training set and validation set combined
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dense(512, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x512_retrain")
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=0)  # no validation_split
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# Retrain model 2x512 using training set and validation set combined注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()重新加载同 C30X_train (6000,784)—
    3model = keras.Sequential([两层 512,name="2x512_retrain"与 C40 相同结构;名字加 _retrain——
    4 layers.Dense(512, activation="relu"),两层 512,name="2x512_retrain"与 C40 相同结构;名字加 _retrain——
    5 layers.Dense(512, activation="relu"),两层 512,name="2x512_retrain"与 C40 相同结构;名字加 _retrain——
    6 layers.Dense(10, activation="softmax")两层 512,name="2x512_retrain"与 C40 相同结构;名字加 _retrain——
    7], name="2x512_retrain")两层 512,name="2x512_retrain"与 C40 相同结构;名字加 _retrain——
    8model.compile(loss="categorical_crossentropy",手写 compile与 C30 相同——
    9 optimizer="adam", metrics=["acc"])手写 compile与 C30 相同——
    10history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 无 validation_split6000 样本全部用于训练;24 步/轮history 只有 {'acc', 'loss'}这是 Q1c 的核心要求:去掉 validation_split
    11 verbose=0) # no validation_splitfit 无 validation_split6000 样本全部用于训练;24 步/轮history 只有 {'acc', 'loss'}这是 Q1c 的核心要求:去掉 validation_split
    12print(history_final_values(history))打印末值{'acc': 1.0, 'loss': 0.0002}与 C40 的 .0001 同量级(.0002 略高,随机波动);两者都已把训练集记到接近 100%—
    运行结果 {'acc': 1.0, 'loss': 0.0002}
    Q1c 你的作答核对:正确 ✔——照搬 C30 的模式:重新加载 → 同结构 + _retrain 名 → 手写 compile → fit 不带 validation_split → 打印末值 → C45 evaluate。
    Cell 45Q1c:测试集评估练习·作答
    print("Evaluation of model " + model.name,
          model.evaluate(X_test, y_test, verbose=0))
    #代码作用机制·语法关联·结果易错点
    1print("Evaluation of model " + model.name,evaluate同 C31[0.2270, 0.9490]test_acc .9490 > 1x512 的 .9430,但 test_loss .2270 > .2197——两个指标结论不一致时,以 loss 为准(讲义 p27)
    2 model.evaluate(X_test, y_test, verbose=0))evaluate同 C31[0.2270, 0.9490]test_acc .9490 > 1x512 的 .9430,但 test_loss .2270 > .2197——两个指标结论不一致时,以 loss 为准(讲义 p27)
    运行结果 Evaluation of model 2x512_retrain [0.22696872055530548, 0.9490000009536743]

    &#x2766;

    L1 regularization

    In this section, L1 regularization is applied for mitigating (i.e. reducing) overfitting. Two selected models, 1x512 and 2x512, with different strengths of regularization are examined.


  • Model 1x512_L1_1e-5: 1 hidden layer of 512 neurons with L1 of strength 1e-5
  • Model 1x512_L1_1e-6: 1 hidden layer of 512 neurons with L1 of strength 1e-6
  • Model 1x512_L1_1e-7: 1 hidden layer of 512 neurons with L1 of strength 1e-7
  • Model 1x512_L1_1e-8: 1 hidden layer of 512 neurons with L1 of strength 1e-8
  • Model 2x512_L1_1e-5: 2 hidden layers each of 512 neurons with L1 of strength 1e-5
  • Model 2x512_L1_1e-6: 2 hidden layers each of 512 neurons with L1 of strength 1e-6
  • Model 2x512_L1_1e-7: 2 hidden layers each of 512 neurons with L1 of strength 1e-7
  • Model 2x512_L1_1e-8: 2 hidden layers each of 512 neurons with L1 of strength 1e-8
  • L1 正则化(Unit 6 讲义 p33–p40):在损失上加 λ·Σ|w|(权重正则)或 λ·Σ|a|(活动正则)。本 Lab 用的是 activity_regularizer——惩罚的是该层输出激活值的 L1 范数:loss_total = CE + λ · mean_over_batch(Σ_neurons |a|)。效果:把激活推向稀疏(很多神经元的输出变成 0),等效减少有效容量。强度 1e-5 → 1e-8 跨 3 个数量级:1e-5 太强(val_loss .2014 反而比不正则的 .1657…不对——是比 1e-6 差,见 C63 表),1e-6 刚好(.1657,整张表最低),1e-7/1e-8 太弱(.1871/.1993,接近不正则的 .2012)。这就是讲义 p38 的 U 形:λ 太大 → 欠拟合,太小 → 没效果。
    训练 loss 为什么从 .0022 涨到 .0519:显示的 loss 包含正则项,1e-5 × Σ|a| 贡献了约 0.05——这不是 CE 变差,而是惩罚项在"账面"上。所以 正则化模型之间不能比训练 loss,要比 val_loss(val_loss 不含正则项)。

    Practice - Question 2 of 2

    The training and validation results of these regularized models will be saved in a dictionary called l1_final_values, which is created below.

    Cell 51创建 L1 结果字典 l1_final_values基础
    l1_final_values = {}
    #代码作用机制·语法关联·结果易错点
    1l1_final_values = {}l1_final_values = {}与 final_values 分开存,便于 L1/L2 对照—只能运行一次

    Q2a


    The code for the first regularized model, 1x512_L1_1e-5, is shown below. L1 regularization with strength 1e-5 (i.e. 0.000_01) is implemented as an object of the l1 class in the regularizers module and specified in the activity_regularizer argument of the Dense layer.

    Cell 53Model 1x512_L1_1e-5:第一个 L1 正则模型(模板 cell)重点展开
    # Model 1x512_L1_1e-5
    from tensorflow.keras import regularizers
    l1 = regularizers.l1(1e-5)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L1_1e-5")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x512_L1_1e-5注释———
    2from tensorflow.keras import regularizers导入 regularizersC9 已导入过,这里再导一次无害——
    3l1 = regularizers.l1(1e-5)l1 = regularizers.l1(1e-5)创建 L1 正则化器对象,强度 λ = 1e-5;对象可复用给多个层—1e-5 = 0.00001;强度越大惩罚越重
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载数据———
    5model = keras.Sequential([模型:activity_regularizer=l1只在隐藏层加;输出层 softmax 不加(惩罚概率输出没有意义)参数不变 407,050(正则不增加参数)activity_regularizer 惩罚输出 a;kernel_regularizer 惩罚权重 w——本 Lab 用的是前者(讲义 p36)
    6 layers.Dense(512, activation="relu", activity_regularizer=l1),模型:activity_regularizer=l1只在隐藏层加;输出层 softmax 不加(惩罚概率输出没有意义)参数不变 407,050(正则不增加参数)activity_regularizer 惩罚输出 a;kernel_regularizer 惩罚权重 w——本 Lab 用的是前者(讲义 p36)
    7 layers.Dense(10, activation="softmax")模型:activity_regularizer=l1只在隐藏层加;输出层 softmax 不加(惩罚概率输出没有意义)参数不变 407,050(正则不增加参数)activity_regularizer 惩罚输出 a;kernel_regularizer 惩罚权重 w——本 Lab 用的是前者(讲义 p36)
    8], name="1x512_L1_1e-5")name="1x512_L1_1e-5"命名含正则类型与强度—名字里的 - 合法
    9history = compile_and_fit_model(model, X_train, y_train)compile+fit同 C15——
    10l1_final_values[model.name] = history_final_values(history)存进 l1_final_values注意字典名换了—别写回 final_values
    11print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0519, 'val_acc': 0.9508, 'val_loss': 0.2014}训练 loss .0519 ≫ 不正则的 .0022——显示值含正则项;val_loss .2014 与不正则 .2012 几乎相同正则化模型的训练 loss 之间不可比
    12plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0519, 'val_acc': 0.9508, 'val_loss': 0.2014} <Figure size 800x400 with 2 Axes> [image/png]
    activity_regularizer 的数学(Unit 6 讲义 p36):总损失 = CE + λ · (1/B) Σ_samples Σ_neurons |a|。对 1x512,每样本 512 个激活值,ReLU 后多数为 0、非零的均值约 0.x → Σ|a| 约 5,000 × λ。λ=1e-5 → 正则项 ≈ 0.05,正好解释训练 loss 从 .0022 跳到 .0519。梯度:∂(λ|a|)/∂a = λ·sign(a),每个激活被持续推向 0,绝对值小的先归零 → 稀疏激活。
    读结果:λ=1e-5 时 val_loss .2014 ≈ 无正则 .2012——太强了反而没收益(欠拟合抵消了正则化的好处);C55 的 1e-6 才是最优点 .1657。

    Write code to build and train the other regularized models, save their training and validation results in the l1_final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 55Model 1x512_L1_1e-6(L1 最佳)重点展开
    # Model 1x512_L1_1e-6
    l1 = regularizers.l1(1e-6)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L1_1e-6")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x512_L1_1e-6注释———
    2l1 = regularizers.l1(1e-6)l1 = regularizers.l1(1e-6)λ 缩小 10 倍—这是与 C53 的唯一改动
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([模型 + name="1x512_L1_1e-6"———
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),模型 + name="1x512_L1_1e-6"———
    6 layers.Dense(10, activation="softmax")模型 + name="1x512_L1_1e-6"———
    7], name="1x512_L1_1e-6")模型 + name="1x512_L1_1e-6"———
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9l1_final_values[model.name] = history_final_values(history)存结果———
    10print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0226, 'val_acc': 0.9542, 'val_loss': 0.1657}val_loss .1657 是 L1 组最低,也是全 notebook 最低之一;比无正则 .2012 低 18%训练 loss .0226 含 ≈0.02 正则项
    11plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0226, 'val_acc': 0.9542, 'val_loss': 0.1657} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 56Model 1x512_L1_1e-7基础
    # Model 1x512_L1_1e-7
    l1 = regularizers.l1(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L1_1e-7")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x512_L1_1e-7注释———
    2l1 = regularizers.l1(1e-7)l1(1e-7)λ 再小 10 倍——
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([模型 + name———
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),模型 + name———
    6 layers.Dense(10, activation="softmax")模型 + name———
    7], name="1x512_L1_1e-7")模型 + name———
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9l1_final_values[model.name] = history_final_values(history)存结果———
    10print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.008, 'val_acc': 0.95, 'val_loss': 0.1871}val_loss .1871——比 1e-6 差,比无正刚好λ 太小 → 正则化效果不足
    11plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.008, 'val_acc': 0.95, 'val_loss': 0.1871} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 57Model 1x512_L1_1e-8基础
    # Model 1x512_L1_1e-8
    l1 = regularizers.l1(1e-8)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L1_1e-8")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x512_L1_1e-8注释———
    2l1 = regularizers.l1(1e-8)l1(1e-8)λ 最小——
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([模型 + name———
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),模型 + name———
    6 layers.Dense(10, activation="softmax")模型 + name———
    7], name="1x512_L1_1e-8")模型 + name———
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9l1_final_values[model.name] = history_final_values(history)存结果———
    10print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.003, 'val_acc': 0.9508, 'val_loss': 0.1993}val_loss .1993 ≈ 无正则 .2012λ=1e-8 基本没效果
    11plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.003, 'val_acc': 0.9508, 'val_loss': 0.1993} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 58Model 2x512_L1_1e-5(两层版模板)重点展开
    # Model 2x512_L1_1e-5
    l1 = regularizers.l1(1e-5)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L1_1e-5")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_L1_1e-5注释———
    2l1 = regularizers.l1(1e-5)l1(1e-5)———
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([两层都加 activity_regularizer两个 Dense(512) 都写 activity_regularizer=l1,复用同一个 l1 对象正则项 = 两层 Σ|a| 之和只给一层加会让另一层无约束;两层都加才对称
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),两层都加 activity_regularizer两个 Dense(512) 都写 activity_regularizer=l1,复用同一个 l1 对象正则项 = 两层 Σ|a| 之和只给一层加会让另一层无约束;两层都加才对称
    6 layers.Dense(512, activation="relu", activity_regularizer=l1),两层都加 activity_regularizer两个 Dense(512) 都写 activity_regularizer=l1,复用同一个 l1 对象正则项 = 两层 Σ|a| 之和只给一层加会让另一层无约束;两层都加才对称
    7 layers.Dense(10, activation="softmax")两层都加 activity_regularizer两个 Dense(512) 都写 activity_regularizer=l1,复用同一个 l1 对象正则项 = 两层 Σ|a| 之和只给一层加会让另一层无约束;两层都加才对称
    8], name="2x512_L1_1e-5")name="2x512_L1_1e-5"———
    9history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    10l1_final_values[model.name] = history_final_values(history)存结果———
    11print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0301, 'val_acc': 0.9333, 'val_loss': 0.2577}val_loss .2577 明显变差——两层 × 1e-5 惩罚太重欠拟合:val_acc 也掉到 .9333
    12plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0301, 'val_acc': 0.9333, 'val_loss': 0.2577} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 59Model 2x512_L1_1e-6基础
    # Model 2x512_L1_1e-6
    l1 = regularizers.l1(1e-6)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L1_1e-6")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_L1_1e-6注释———
    2l1 = regularizers.l1(1e-6)l1(1e-6)———
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([两层 + name———
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),两层 + name———
    6 layers.Dense(512, activation="relu", activity_regularizer=l1),两层 + name———
    7 layers.Dense(10, activation="softmax")两层 + name———
    8], name="2x512_L1_1e-6")两层 + name———
    9history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    10l1_final_values[model.name] = history_final_values(history)存结果———
    11print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0089, 'val_acc': 0.95, 'val_loss': 0.1954}val_loss .1954—
    12plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0089, 'val_acc': 0.95, 'val_loss': 0.1954} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 60Model 2x512_L1_1e-7(L1 组 val_acc 最高)基础
    # Model 2x512_L1_1e-7
    l1 = regularizers.l1(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L1_1e-7")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_L1_1e-7注释———
    2l1 = regularizers.l1(1e-7)l1(1e-7)———
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([两层 + name———
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),两层 + name———
    6 layers.Dense(512, activation="relu", activity_regularizer=l1),两层 + name———
    7 layers.Dense(10, activation="softmax")两层 + name———
    8], name="2x512_L1_1e-7")两层 + name———
    9history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    10l1_final_values[model.name] = history_final_values(history)存结果———
    11print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0058, 'val_acc': 0.9575, 'val_loss': 0.171}val_acc .9575 是 L1 组最高,但 val_loss .171 > 1x512_1e-6 的 .1657若按 val_acc 选会选它——题目说按 val_loss
    12plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0058, 'val_acc': 0.9575, 'val_loss': 0.171} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 61Model 2x512_L1_1e-8基础
    # Model 2x512_L1_1e-8
    l1 = regularizers.l1(1e-8)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L1_1e-8")
    history = compile_and_fit_model(model, X_train, y_train)
    l1_final_values[model.name] = history_final_values(history)
    print(l1_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_L1_1e-8注释———
    2l1 = regularizers.l1(1e-8)l1(1e-8)———
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([两层 + name———
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),两层 + name———
    6 layers.Dense(512, activation="relu", activity_regularizer=l1),两层 + name———
    7 layers.Dense(10, activation="softmax")两层 + name———
    8], name="2x512_L1_1e-8")两层 + name———
    9history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    10l1_final_values[model.name] = history_final_values(history)存结果———
    11print(l1_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0013, 'val_acc': 0.9533, 'val_loss': 0.1963}val_loss .1963 ≈ 无正则 .2129 略好—
    12plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0013, 'val_acc': 0.9533, 'val_loss': 0.1963} <Figure size 800x400 with 2 Axes> [image/png]

    Q2b


    Write code to display the training and validation results in the l1_final_values dictionary, which contains the results of the L1 regularized models.

    Cell 63Q2b:显示 8 个 L1 模型的汇总表练习·作答
    pd.DataFrame.from_dict(l1_final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(l1_final_values, orient="index")pd.DataFrame.from_dict(l1_final_values, orient="index")8 行 × 4 列最低 val_loss:1x512_L1_1e-6 .1657按 val_loss 排序而非 acc
    运行结果 acc loss val_acc val_loss 1x512_L1_1e-5 1.0 0.0519 0.9508 0.2014 1x512_L1_1e-6 1.0 0.0226 0.9542 0.1657 1x512_L1_1e-7 1.0 0.0080 0.9500 0.1871 1x512_L1_1e-8 1.0 0.0030 0.9508 0.1993 2x512_L1_1e-5 1.0 0.0301 0.9333 0.2577 2x512_L1_1e-6 1.0 0.0089 0.9500 0.1954 2x512_L1_1e-7 1.0 0.0058 0.9575 0.1710 2x512_L1_1e-8 1.0 0.0013 0.9533 0.1963
    Q2b 你的作答核对:正确 ✔。读表三条:① λ 的 U 形——1 层 .2014 → .1657 → .1871 → .1993,1e-6 是谷底;② 两层更敏感——同样 1e-5,1 层 .2014 还行、两层 .2577 明显欠拟合(惩罚项翻倍);③ 最优 λ 与模型容量有关:容量越大,合适 λ 越小(1 层 1e-6、2 层 1e-7)。

    Q2c


    Referring to the above results of regularized models, select the best model that has the smallest validation loss (val_loss). Write code to retrain that model using the training set and validation set combined (X_train/y_train), and evaluate the retrained model using the test set (X_test/y_test).

    Cell 65Q2c:重训 L1 最佳模型 1x512_L1_1e-6练习·作答
    # Retrain best model using training set and validation set combined
    l1 = regularizers.l1(1e-6)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L1_1e-6_retrain")
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=0)  # no validation_split
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# Retrain best model using training set and validation set combined注释———
    2l1 = regularizers.l1(1e-6)l1 = regularizers.l1(1e-6)保持与 C55 相同的正则强度—重训必须保留正则化,否则结构变了
    3X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([模型带 activity_regularizer与 C55 相同;name 加 _retrain——
    5 layers.Dense(512, activation="relu", activity_regularizer=l1),模型带 activity_regularizer与 C55 相同;name 加 _retrain——
    6 layers.Dense(10, activation="softmax")模型带 activity_regularizer与 C55 相同;name 加 _retrain——
    7], name="1x512_L1_1e-6_retrain")模型带 activity_regularizer与 C55 相同;name 加 _retrain——
    8model.compile(loss="categorical_crossentropy",手写 compile———
    9 optimizer="adam", metrics=["acc"])手写 compile———
    10history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 无 validation_split6000 样本;24 步/轮{'acc': 1.0, 'loss': 0.0201}训练 loss 含正则项 ≈0.02
    11 verbose=0) # no validation_splitfit 无 validation_split6000 样本;24 步/轮{'acc': 1.0, 'loss': 0.0201}训练 loss 含正则项 ≈0.02
    12print(history_final_values(history))打印{'acc': 1.0, 'loss': 0.0201}——
    运行结果 {'acc': 1.0, 'loss': 0.0201}
    Q2c 你的作答核对:正确 ✔——按 val_loss 选了 1x512_L1_1e-6(.1657 最低),重训时保留 regularizer、去掉 validation_split、改名字。
    Cell 66Q2c:测试集评估练习·作答
    print("Evaluation of model " + model.name,
          model.evaluate(X_test, y_test, verbose=0))
    #代码作用机制·语法关联·结果易错点
    1print("Evaluation of model " + model.name,evaluate同 C31[0.1700, 0.9460]test_loss .1700 明显优于无正则的 .2197——正则化在真正未见数据上生效;test_acc .9460 与 .9430 相近
    2 model.evaluate(X_test, y_test, verbose=0))evaluate同 C31[0.1700, 0.9460]test_loss .1700 明显优于无正则的 .2197——正则化在真正未见数据上生效;test_acc .9460 与 .9430 相近
    运行结果 Evaluation of model 1x512_L1_1e-6_retrain [0.1700492948293686, 0.9459999799728394]

    &#x2766;

    Extras


    In the following, L2 regularization is applied to mitigate overfitting.

    L2 regularization

    These models with L2 regularization are examined.


  • Model 1x512_L2_1e-5: 1 hidden layer of 512 neurons with L2 of strength 1e-5
  • Model 1x512_L2_1e-6: 1 hidden layer of 512 neurons with L2 of strength 1e-6
  • Model 1x512_L2_1e-7: 1 hidden layer of 512 neurons with L2 of strength 1e-7
  • Model 1x512_L2_1e-8: 1 hidden layer of 512 neurons with L2 of strength 1e-8
  • Model 2x512_L2_1e-5: 2 hidden layers each of 512 neurons with L2 of strength 1e-5
  • Model 2x512_L2_1e-6: 2 hidden layers each of 512 neurons with L2 of strength 1e-6
  • Model 2x512_L2_1e-7: 2 hidden layers each of 512 neurons with L2 of strength 1e-7
  • Model 2x512_L2_1e-8: 2 hidden layers each of 512 neurons with L2 of strength 1e-8
  • L2 vs L1(Unit 6 讲义 p41–p46):L2 惩罚 Σw²(或 Σa²),梯度与 w 成正比 → 把权重均匀压小但不为 0;L1 梯度是常数 sign(w) → 把小权重直接推到 0,产生稀疏。经验:L2 更平滑、对强度不那么敏感,是默认选择;L1 适合需要特征选择的场景。本 Lab 结果 L2 最佳 .1615(2x512_1e-7)略优于 L1 最佳 .1657(1x512_1e-6),但差异在噪声范围内——结论写 "comparable" 即可。
    E1a

    Write code to build and train these regularized models, save their training and validation results in the l2_final_values dictionary (created below) for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 72创建 L2 结果字典基础
    l2_final_values = {}
    #代码作用机制·语法关联·结果易错点
    1l2_final_values = {}l2_final_values = {}——只运行一次
    E1b

    Write code to display the training and validation results in the l2_final_values dictionary, which contains the results of the L2 regularized models.

    E1c

    Referring to the above results of regularized models, select the best model that has the smallest validation loss (val_loss). Write code to retrain that model using the training set and validation set combined (X_train/y_train), and evaluate the retrained model using the test set (X_test/y_test).

    Solutions to extra exercises

    ↳ E1 解答的 cell 比 L1 版本多了 # Solution 注释行和空行(L1–L2),所以 2 层模型每行行号比 L1 版大 1。读的时候对照 C58–C61。
    E1a
    Cell 77E1a 解答:Model 1x512_L2_1e-5(L2 模板 cell)重点展开
    # Solution
    
    # Model 1x512_L2_1e-5
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-5)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L2_1e-5")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution# Solution / 空行———
    3# Model 1x512_L2_1e-5注释———
    4from tensorflow.keras import regularizers导入 regularizers———
    5l2 = regularizers.l2(1e-5)l2 = regularizers.l2(1e-5)L2 正则化器:惩罚 Σa²,梯度 ∂(λa²)/∂a = 2λa—与 L1 的区别:梯度与 a 成正比,小 a 受力小、不会被推到 0
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([模型 activity_regularizer=l2只在隐藏层参数不变—
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),模型 activity_regularizer=l2只在隐藏层参数不变—
    9 layers.Dense(10, activation="softmax")模型 activity_regularizer=l2只在隐藏层参数不变—
    10], name="1x512_L2_1e-5")name="1x512_L2_1e-5"———
    11history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    12l2_final_values[model.name] = history_final_values(history)存进 l2_final_values字典名换了—别写进 l1_final_values
    13print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0401, 'val_acc': 0.9525, 'val_loss': 0.2105}训练 loss 含 Σa² 项—
    14plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0401, 'val_acc': 0.9525, 'val_loss': 0.2105} <Figure size 800x400 with 2 Axes> [image/png]
    L2 activity 正则的数学(Unit 6 讲义 p41–p44):总损失 = CE + λ · (1/B) Σ Σ a²。ReLU 激活 a 多在 0–2 之间,a² 比 |a| 大 → 同样 λ 下 L2 的"账面"惩罚更重(.0401 vs L1 的 .0519 相当)。但效果更温和:L2 把大激活压小、小的保留(连续收缩),L1 把小的直接归零(稀疏)。结果对比:同为 1e-5,L2 val_loss .2105 < L1 .2014?不——.2105 > .2014,这个 λ 下 L1 反而略好;但到 2 层 1e-7 时 L2 .1615 < L1 .1710。结论写 "comparable, L2 slightly better at 2x512"。
    Cell 78Model 1x512_L2_1e-6基础
    # Solution
    
    # Model 1x512_L2_1e-6
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-6)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L2_1e-6")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 1x512_L2_1e-6注释———
    4from tensorflow.keras import regularizers导入———
    5l2 = regularizers.l2(1e-6)l2(1e-6)———
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([模型 + name———
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),模型 + name———
    9 layers.Dense(10, activation="softmax")模型 + name———
    10], name="1x512_L2_1e-6")模型 + name———
    11history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    12l2_final_values[model.name] = history_final_values(history)存结果———
    13print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.018, 'val_acc': 0.9483, 'val_loss': 0.1692}1 层 L2 最佳 .1692—
    14plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.018, 'val_acc': 0.9483, 'val_loss': 0.1692} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 79Model 1x512_L2_1e-7基础
    # Solution
    
    # Model 1x512_L2_1e-7
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L2_1e-7")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 1x512_L2_1e-7注释———
    4from tensorflow.keras import regularizers导入———
    5l2 = regularizers.l2(1e-7)l2(1e-7)———
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([模型 + name———
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),模型 + name———
    9 layers.Dense(10, activation="softmax")模型 + name———
    10], name="1x512_L2_1e-7")模型 + name———
    11history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    12l2_final_values[model.name] = history_final_values(history)存结果———
    13print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0077, 'val_acc': 0.9492, 'val_loss': 0.1791}val_loss .1791—
    14plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0077, 'val_acc': 0.9492, 'val_loss': 0.1791} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 80Model 1x512_L2_1e-8基础
    # Solution
    
    # Model 1x512_L2_1e-8
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-8)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="1x512_L2_1e-8")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 1x512_L2_1e-8注释———
    4from tensorflow.keras import regularizers导入———
    5l2 = regularizers.l2(1e-8)l2(1e-8)———
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([模型 + name———
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),模型 + name———
    9 layers.Dense(10, activation="softmax")模型 + name———
    10], name="1x512_L2_1e-8")模型 + name———
    11history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    12l2_final_values[model.name] = history_final_values(history)存结果———
    13print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0032, 'val_acc': 0.95, 'val_loss': 0.1977}val_loss .1977 ≈ 无正则—
    14plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0032, 'val_acc': 0.95, 'val_loss': 0.1977} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 81Model 2x512_L2_1e-5基础
    # Solution
    
    # Model 2x512_L2_1e-5
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-5)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L2_1e-5")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 2x512_L2_1e-5注释———
    4from tensorflow.keras import regularizers导入———
    5l2 = regularizers.l2(1e-5)l2(1e-5)———
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([两层都加 l2 + name———
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),两层都加 l2 + name———
    9 layers.Dense(512, activation="relu", activity_regularizer=l2),两层都加 l2 + name———
    10 layers.Dense(10, activation="softmax")两层都加 l2 + name———
    11], name="2x512_L2_1e-5")两层都加 l2 + name———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13l2_final_values[model.name] = history_final_values(history)存结果———
    14print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0195, 'val_acc': 0.9325, 'val_loss': 0.2366}val_loss .2366——两层 1e-5 太强比 L1 两层 1e-5 的 .2577 好一点:L2 更温和
    15plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0195, 'val_acc': 0.9325, 'val_loss': 0.2366} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 82Model 2x512_L2_1e-6基础
    # Solution
    
    # Model 2x512_L2_1e-6
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-6)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L2_1e-6")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 2x512_L2_1e-6注释———
    4from tensorflow.keras import regularizers导入———
    5l2 = regularizers.l2(1e-6)l2(1e-6)———
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([两层 + name———
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),两层 + name———
    9 layers.Dense(512, activation="relu", activity_regularizer=l2),两层 + name———
    10 layers.Dense(10, activation="softmax")两层 + name———
    11], name="2x512_L2_1e-6")两层 + name———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13l2_final_values[model.name] = history_final_values(history)存结果———
    14print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0056, 'val_acc': 0.9458, 'val_loss': 0.1939}val_loss .1939—
    15plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0056, 'val_acc': 0.9458, 'val_loss': 0.1939} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 83Model 2x512_L2_1e-7(L2 组最佳 .1615)重点展开
    # Solution
    
    # Model 2x512_L2_1e-7
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L2_1e-7")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 2x512_L2_1e-7注释———
    4from tensorflow.keras import regularizers导入———
    5l2 = regularizers.l2(1e-7)l2(1e-7)两层 512 的最优点——
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([两层 + name———
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),两层 + name———
    9 layers.Dense(512, activation="relu", activity_regularizer=l2),两层 + name———
    10 layers.Dense(10, activation="softmax")两层 + name———
    11], name="2x512_L2_1e-7")两层 + name———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13l2_final_values[model.name] = history_final_values(history)存结果———
    14print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0033, 'val_acc': 0.9567, 'val_loss': 0.1615}全 notebook 最低 val_loss(L1 最低 .1657)→ E1c 选它重训
    15plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0033, 'val_acc': 0.9567, 'val_loss': 0.1615} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 84Model 2x512_L2_1e-8基础
    # Solution
    
    # Model 2x512_L2_1e-8
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-8)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L2_1e-8")
    history = compile_and_fit_model(model, X_train, y_train)
    l2_final_values[model.name] = history_final_values(history)
    print(l2_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 2x512_L2_1e-8注释———
    4from tensorflow.keras import regularizers导入———
    5l2 = regularizers.l2(1e-8)l2(1e-8)———
    6X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    7model = keras.Sequential([两层 + name———
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),两层 + name———
    9 layers.Dense(512, activation="relu", activity_regularizer=l2),两层 + name———
    10 layers.Dense(10, activation="softmax")两层 + name———
    11], name="2x512_L2_1e-8")两层 + name———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13l2_final_values[model.name] = history_final_values(history)存结果———
    14print(l2_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0014, 'val_acc': 0.955, 'val_loss': 0.1881}val_loss .1881—
    15plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0014, 'val_acc': 0.955, 'val_loss': 0.1881} <Figure size 800x400 with 2 Axes> [image/png]
    E1b
    Cell 86E1b:显示 8 个 L2 模型表基础
    # Solution
    
    pd.DataFrame.from_dict(l2_final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3pd.DataFrame.from_dict(l2_final_values, orient="index")pd.DataFrame.from_dict(l2_final_values, orient="index")8 行 × 4 列最低:2x512_L2_1e-7 .1615—
    运行结果 acc loss val_acc val_loss 1x512_L2_1e-5 1.0 0.0401 0.9525 0.2105 1x512_L2_1e-6 1.0 0.0180 0.9483 0.1692 1x512_L2_1e-7 1.0 0.0077 0.9492 0.1791 1x512_L2_1e-8 1.0 0.0032 0.9500 0.1977 2x512_L2_1e-5 1.0 0.0195 0.9325 0.2366 2x512_L2_1e-6 1.0 0.0056 0.9458 0.1939 2x512_L2_1e-7 1.0 0.0033 0.9567 0.1615 2x512_L2_1e-8 1.0 0.0014 0.9550 0.1881
    E1c
    Cell 88E1c:重训 L2 最佳 2x512_L2_1e-7重点展开
    # Solution
    
    # Retrain model 2x512_L2_1e-7 using training set and validation set combined
    l2 = regularizers.l2(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L2_1e-7_retrain")
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=0) # no validation_split
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Retrain model 2x512_L2_1e-7 using training set and validation set combined注释———
    4l2 = regularizers.l2(1e-7)l2 = regularizers.l2(1e-7)保留正则强度——
    5X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    6model = keras.Sequential([两层带 l2 + name _retrain与 C83 相同——
    7 layers.Dense(512, activation="relu", activity_regularizer=l2),两层带 l2 + name _retrain与 C83 相同——
    8 layers.Dense(512, activation="relu", activity_regularizer=l2),两层带 l2 + name _retrain与 C83 相同——
    9 layers.Dense(10, activation="softmax")两层带 l2 + name _retrain与 C83 相同——
    10], name="2x512_L2_1e-7_retrain")两层带 l2 + name _retrain与 C83 相同——
    11model.compile(loss="categorical_crossentropy",手写 compile———
    12 optimizer="adam", metrics=["acc"])手写 compile———
    13history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 无 validation_split6000 样本{'acc': 1.0, 'loss': 0.0025}训练 loss 仍含正则项
    14 verbose=0) # no validation_splitfit 无 validation_split6000 样本{'acc': 1.0, 'loss': 0.0025}训练 loss 仍含正则项
    15print(history_final_values(history))打印{'acc': 1.0, 'loss': 0.0025}——
    运行结果 {'acc': 1.0, 'loss': 0.0025}
    Cell 89E1c:测试集评估重点展开
    # Solution
    
    print("Evaluation of model " + model.name,
          model.evaluate(X_test, y_test, verbose=0))
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3print("Evaluation of model " + model.name,evaluate同 C31[0.1839, 0.9480]test_loss .1839 < 无正则 2x512 的 .2270,但 > L1 1x512 的 .1700——验证时的 .1615 没有完全兑现到测试集(噪声 + 过拟合验证集)
    4 model.evaluate(X_test, y_test, verbose=0))evaluate同 C31[0.1839, 0.9480]test_loss .1839 < 无正则 2x512 的 .2270,但 > L1 1x512 的 .1700——验证时的 .1615 没有完全兑现到测试集(噪声 + 过拟合验证集)
    运行结果 Evaluation of model 2x512_L2_1e-7_retrain [0.18385010957717896, 0.9480000138282776]

    &#x2766;

    📘 Tutorial 7(= Lab 7)· Dropout 与 Batch Normalization(+ He 初始化)

    t07-s13903054.ipynb,78 cells。对应 Unit 7 讲义 p6–p12(复习 L1/L2)、p13–p28(Dropout: rate 扫描、输入层 dropout)、p29–p44(BatchNorm:after/before activation、宽度扫描)、p45–p50(He 初始化)。工具函数与 t06 完全相同。结果速览(val_loss):无正则 2x512 .2129 → L1_1e-7 .1710 → L2_1e-7 .1615;Dropout 2xD25 .2325 / 2xD50 .2014 / 2xD75 .1955(只加隐藏层 反而更差);加输入层 3xD25 .1614 / 3xD50 .1392(最佳) / 3xD75 .3762(不收敛);BN_AA 512/1024/2048 .1924/.1902/.2281,BN_BA .1659/.1665/.1919;He 版 2x512 .2117 / 3xD50 .1434 / BN_AA .1930 / BN_BA .1711。测试集:3xD50 [.1357, .9580]、BN_BA [.2229, .9410]。
    读法:本 Lab 延续 t06 的"字典 + 模板 cell"模式,三组对照实验:① Dropout——rate 0.25/0.50/0.75 × {只在隐藏层, 输入层+隐藏层};② BatchNorm——宽度 512/1024/2048 × {激活后 AA, 激活前 BA};③ He 初始化——把前两组最佳结构换个初始化。C19/C30/C51 三个模板逐行精讲,其余讲"变了什么 + 结果怎么读"。
    必会机制:Dropout 训练时按 rate 随机置零并 ×1/(1−rate) 放大(inverted dropout),推理时不丢弃;BatchNorm 训练时用当前 batch的均值/方差归一化并学习 γ、β,同时用滑动平均(momentum=0.99)记录统计量供推理用——所以 BN 层每层 4×units 个参数, trainable 只有 2×units(Unit 7 讲义 p34)。
    三条结论:① Dropout 对输入层也要加才有效(只加隐藏层 .2325 > 无正则 .2129);② BN 放在激活前(BA)优于激活后(AA);③ He 初始化对 ReLU + Dropout 的组合略有帮助(.1392 → .1434,其实在噪声范围内——别过度解读)。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同前IPython 魔术命令;须在 import tensorflow 前env: TF_CPP_MIN_LOG_LEVEL=2每个 notebook 第一个 cell
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • application of dropout to neural networks, and
  • application of batch normalization to neural networks.
  • Student name: Yin Bang
    Student ID: 13903054

    Backgrounds and utilities


    In the preceding lesson, we used weight regularization to mitigate overfitting. This lesson continues the preceding lesson, and attempts to deal with overfitting using some other techniques -- dropout and batch normalization.


    This section contains some utility functions for use and some previously examined models for reference in the rest of the lesson.

    三种抗过拟合手段的定位(Unit 7 讲义 p4–p5):权重正则(t06)——给损失加惩罚项,约束权重/激活的大小;Dropout——训练时随机屏蔽神经元,阻止共适应(co-adaptation);BatchNorm——本意是稳定分布、加速训练,顺带有轻微正则效果(因为 batch 统计量有噪声)。三者可以叠加使用。

    Utility code

    This function loads the MNIST dataset, prepares the data, and returns portion of the data in a 4-tuple: X_train, y_train, X_test, y_test.

    Cell 8load_and_prep_mnist(ratio=0.1)——与 t06 C9 完全相同基础
    from tensorflow import keras
    from tensorflow.keras import layers, regularizers
    from tensorflow.keras.datasets import mnist
    
    def load_and_prep_mnist(ratio=0.1):
        keras.utils.set_random_seed(42)
        (X_train, y_train), (X_test, y_test) = mnist.load_data()
        if ratio < 1:
            sz_train = int(len(X_train) * ratio)
            sz_test = int(len(X_test) * ratio)
            X_train, y_train = X_train[:sz_train], y_train[:sz_train]
            X_test, y_test = X_test[:sz_test], y_test[:sz_test]
        X_train_out = X_train.astype(float) / 255  # scale to range 0 to 1
        X_test_out = X_test.astype(float) / 255
        X_train_out = X_train_out.reshape(-1, 28*28)  # convert 2D to 1D
        X_test_out = X_test_out.reshape(-1, 28*28)
        y_train_oh = keras.utils.to_categorical(y_train, 10)  # one-hot encode
        y_test_oh = keras.utils.to_categorical(y_test, 10)
        return X_train_out, y_train_oh, X_test_out, y_test_oh
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入 keras / layers / regularizers / mnistregularizers 在 C20/C21 用——
    2from tensorflow.keras import layers, regularizers导入 keras / layers / regularizers / mnistregularizers 在 C20/C21 用——
    3from tensorflow.keras.datasets import mnist导入 keras / layers / regularizers / mnistregularizers 在 C20/C21 用——
    5def load_and_prep_mnist(ratio=0.1):定义 + 种子ratio=0.1 → 6000/1000;种子在函数内—同 t06 C9
    6 keras.utils.set_random_seed(42)定义 + 种子ratio=0.1 → 6000/1000;种子在函数内—同 t06 C9
    7 (X_train, y_train), (X_test, y_test) = mnist.load_data()载入 + 切子集—X_train (6000,28,28)—
    8 if ratio < 1:载入 + 切子集—X_train (6000,28,28)—
    9 sz_train = int(len(X_train) * ratio)载入 + 切子集—X_train (6000,28,28)—
    10 sz_test = int(len(X_test) * ratio)载入 + 切子集—X_train (6000,28,28)—
    11 X_train, y_train = X_train[:sz_train], y_train[:sz_train]载入 + 切子集—X_train (6000,28,28)—
    12 X_test, y_test = X_test[:sz_test], y_test[:sz_test]载入 + 切子集—X_train (6000,28,28)—
    13 X_train_out = X_train.astype(float) / 255 # scale to range 0 to 1缩放 + 展平—(6000,784)—
    14 X_test_out = X_test.astype(float) / 255缩放 + 展平—(6000,784)—
    15 X_train_out = X_train_out.reshape(-1, 28*28) # convert 2D to 1D缩放 + 展平—(6000,784)—
    16 X_test_out = X_test_out.reshape(-1, 28*28)缩放 + 展平—(6000,784)—
    17 y_train_oh = keras.utils.to_categorical(y_train, 10) # one-hot encodeone-hot + 返回—y (6000,10)逐行精讲见 t06 C9
    18 y_test_oh = keras.utils.to_categorical(y_test, 10)one-hot + 返回—y (6000,10)逐行精讲见 t06 C9
    19 return X_train_out, y_train_oh, X_test_out, y_test_ohone-hot + 返回—y (6000,10)逐行精讲见 t06 C9

    This function retrieves the final results in a training history, i.e. values of "loss", "val_loss", "acc", and "val_acc" in the final epoch.

    Cell 10history_final_values基础
    def history_final_values(history):
        return {k: round(v[-1], 4) for k, v in history.history.items()}
    #代码作用机制·语法关联·结果易错点
    1def history_final_values(history):同 t06 C11字典推导式取 v[-1] round 4—逐行精讲见 t06
    2 return {k: round(v[-1], 4) for k, v in history.history.items()}同 t06 C11字典推导式取 v[-1] round 4—逐行精讲见 t06

    This function plots a training history, including both training and validation results.

    Cell 12plot_history(pandas 版)基础
    import matplotlib.pyplot as plt
    import pandas as pd
    
    def plot_history(history):
        df = pd.DataFrame(history.history)
        df.index = df.index + 1
        fig, axs = plt.subplots(1, 2, figsize=(8, 4))
        df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])
        df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])
        plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    2import pandas as pd同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    4def plot_history(history):同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    5 df = pd.DataFrame(history.history)同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    6 df.index = df.index + 1同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    7 fig, axs = plt.subplots(1, 2, figsize=(8, 4))同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    8 df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    9 df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06
    10 plt.tight_layout()同 t06 C13DataFrame + df.plot 两子图—逐行精讲见 t06

    This function compiles and fits a model, and returns the training history. Note that the number of epochs, batch size, ratio of validation split are fixed in this function, and thus in this lesson; in reality; these are hyperparameters to be tuned in the process of model development.

    Cell 14compile_and_fit_model(50 轮 / 256 / split 0.2)基础
    def compile_and_fit_model(model, X_train, y_train):
        model.compile(loss="categorical_crossentropy",
                      optimizer="adam", metrics=["acc"])
        history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                            verbose=0, validation_split=0.2)
        return history
    #代码作用机制·语法关联·结果易错点
    1def compile_and_fit_model(model, X_train, y_train):同 t06 C15—19 步/轮逐行精讲见 t06
    2 model.compile(loss="categorical_crossentropy",同 t06 C15—19 步/轮逐行精讲见 t06
    3 optimizer="adam", metrics=["acc"])同 t06 C15—19 步/轮逐行精讲见 t06
    4 history = model.fit(X_train, y_train, epochs=50, batch_size=256,同 t06 C15—19 步/轮逐行精讲见 t06
    5 verbose=0, validation_split=0.2)同 t06 C15—19 步/轮逐行精讲见 t06
    6 return history同 t06 C15—19 步/轮逐行精讲见 t06

    Previous models

    In this section, selected models from the preceding lab are reviewed for comparison. Training and validation results of the models are stored in a dictionary called final_values, which facilitates the display of results and is first created.

    Cell 17创建 final_values基础
    final_values = {}
    #代码作用机制·语法关联·结果易错点
    1final_values = {}空字典——只运行一次

    These selected models are implemented below.


  • Model 2x512: 2 hidden layers each of 512 neurons
  • Model 2x512_L1_1e-7: 2 hidden layers each of 512 neurons with L1 of strength 1e-7
  • Model 2x512_L2_1e-7: 2 hidden layers each of 512 neurons with L2 of strength 1e-7
  • Cell 19复习模型 2x512(t06 的无正则基线)基础
    # Model 2x512
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dense(512, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x512")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([两层 Dense(512) + softmax与 t06 C40 相同参数 669,706—
    4 layers.Dense(512, activation="relu"),两层 Dense(512) + softmax与 t06 C40 相同参数 669,706—
    5 layers.Dense(512, activation="relu"),两层 Dense(512) + softmax与 t06 C40 相同参数 669,706—
    6 layers.Dense(10, activation="softmax")两层 Dense(512) + softmax与 t06 C40 相同参数 669,706—
    7], name="2x512")两层 Dense(512) + softmax与 t06 C40 相同参数 669,706—
    8history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    9final_values[model.name] = history_final_values(history)存结果键 "2x512"——
    10print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9533, 'val_loss': 0.2129}与 t06 C40 结果完全一致(种子相同)复现性验证
    11plot_history(history)画图———
    运行结果 Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz 11490434/11490434 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step {'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9533, 'val_loss': 0.2129} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 20复习模型 2x512_L1_1e-7基础
    # Model 2x512_L1_1e-7
    from tensorflow.keras import regularizers
    l1 = regularizers.l1(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(512, activation="relu", activity_regularizer=l1),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L1_1e-7")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_L1_1e-7注释———
    2from tensorflow.keras import regularizers导入 regularizers———
    3l1 = regularizers.l1(1e-7)l1(1e-7)———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([两层带 activity_regularizer=l1同 t06 C60——
    6 layers.Dense(512, activation="relu", activity_regularizer=l1),两层带 activity_regularizer=l1同 t06 C60——
    7 layers.Dense(512, activation="relu", activity_regularizer=l1),两层带 activity_regularizer=l1同 t06 C60——
    8 layers.Dense(10, activation="softmax")两层带 activity_regularizer=l1同 t06 C60——
    9], name="2x512_L1_1e-7")两层带 activity_regularizer=l1同 t06 C60——
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11final_values[model.name] = history_final_values(history)存结果———
    12print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0058, 'val_acc': 0.9575, 'val_loss': 0.171}与 t06 C60 一致—
    13plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0058, 'val_acc': 0.9575, 'val_loss': 0.171} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 21复习模型 2x512_L2_1e-7(t06 最佳)基础
    # Model 2x512_L2_1e-7
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L2_1e-7")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_L2_1e-7注释———
    2from tensorflow.keras import regularizers导入 regularizers———
    3l2 = regularizers.l2(1e-7)l2(1e-7)———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([两层带 activity_regularizer=l2同 t06 C83——
    6 layers.Dense(512, activation="relu", activity_regularizer=l2),两层带 activity_regularizer=l2同 t06 C83——
    7 layers.Dense(512, activation="relu", activity_regularizer=l2),两层带 activity_regularizer=l2同 t06 C83——
    8 layers.Dense(10, activation="softmax")两层带 activity_regularizer=l2同 t06 C83——
    9], name="2x512_L2_1e-7")两层带 activity_regularizer=l2同 t06 C83——
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11final_values[model.name] = history_final_values(history)存结果———
    12print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0033, 'val_acc': 0.9567, 'val_loss': 0.1615}与 t06 C83 一致—
    13plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0033, 'val_acc': 0.9567, 'val_loss': 0.1615} <Figure size 800x400 with 2 Axes> [image/png]

    The training and validation results in the final_values dictionary are shown below.

    Cell 23三个复习模型的汇总表基础
    pd.DataFrame.from_dict(final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(final_values, orient="index")from_dict 表3 行L2_1e-7 .1615 最佳—
    运行结果 acc loss val_acc val_loss 2x512 1.0 0.0001 0.9533 0.2129 2x512_L1_1e-7 1.0 0.0058 0.9575 0.1710 2x512_L2_1e-7 1.0 0.0033 0.9567 0.1615

    For demonstration, let's pretend model 2x512_L2_1e-7 will be deployed to production. The following code retrains the model and evaluates it using the test set.

    Cell 25重训 2x512_L2_1e-7(示范)基础
    # Model 2x512_L2_1e-7_retrain
    from tensorflow.keras import regularizers
    l2 = regularizers.l2(1e-7)
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(512, activation="relu", activity_regularizer=l2),
        layers.Dense(10, activation="softmax")
    ], name="2x512_L2_1e-7_retrain")
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=0) # no validation_split
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_L2_1e-7_retrain注释———
    2from tensorflow.keras import regularizers导入 + l2(1e-7)保留正则——
    3l2 = regularizers.l2(1e-7)导入 + l2(1e-7)保留正则——
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([模型 + _retrain———
    6 layers.Dense(512, activation="relu", activity_regularizer=l2),模型 + _retrain———
    7 layers.Dense(512, activation="relu", activity_regularizer=l2),模型 + _retrain———
    8 layers.Dense(10, activation="softmax")模型 + _retrain———
    9], name="2x512_L2_1e-7_retrain")模型 + _retrain———
    10model.compile(loss="categorical_crossentropy",手写 compile———
    11 optimizer="adam", metrics=["acc"])手写 compile———
    12history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 无 split6000 样本{'acc': 1.0, 'loss': 0.0025}同 t06 C88
    13 verbose=0) # no validation_splitfit 无 split6000 样本{'acc': 1.0, 'loss': 0.0025}同 t06 C88
    14print(history_final_values(history))打印———
    运行结果 {'acc': 1.0, 'loss': 0.0025}
    Cell 26测试集评估基础
    print("Evaluation of model " + model.name,
          model.evaluate(X_test, y_test, verbose=0))
    #代码作用机制·语法关联·结果易错点
    1print("Evaluation of model " + model.name,evaluate—[.1837, .9480]与 t06 C89 的 .1839 几乎一致(随机性)
    2 model.evaluate(X_test, y_test, verbose=0))evaluate—[.1837, .9480]与 t06 C89 的 .1839 几乎一致(随机性)
    运行结果 Evaluation of model 2x512_L2_1e-7_retrain [0.18372704088687897, 0.9480000138282776]

    Dropout


    Dropout is a technique that temporarily drops a random subset of neurons in each iteration of training. Models with various settings of dropout are examined below.

    Dropout 的数学(Unit 7 讲义 p14–p18):训练时对某层每个激活值以概率 p 置零,其余乘 1/(1−p)——这叫 inverted dropout,保证期望不变:E[ã] = (1−p)·a·1/(1−p) + p·0 = a。推理时不做 dropout(Keras 自动切换 training=False)。效果:每个 batch 训练的是不同 的"子网络",等价于指数多个网络的集成;且每个神经元不能依赖特定其他神经元的存在 → 学到更鲁棒的特征。代价:训练 loss 变高(C33 3xD75 的 .6531)、收敛变慢——这是正常的,不是模型变差。

    Practice - Question 1 of 2

    Q1a


    Different dropout rates are applied to the hidden layers of model 2x512 as follows.


  • Model 2x512_2xD25: 2 hidden layers each of 512 neurons, with 0.25 dropout in each hidden layer
  • Model 2x512_2xD50: 2 hidden layers each of 512 neurons, with 0.50 dropout in each hidden layer
  • Model 2x512_2xD75: 2 hidden layers each of 512 neurons, with 0.75 dropout in each hidden layer

  • The first model, 2x512_2xD25, is implemented in this code.

    Cell 30Model 2x512_2xD25:隐藏层 Dropout 0.25(Dropout 模板 cell)重点展开
    # Model 2x512_2xD25
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.25),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.25),
        layers.Dense(10, activation="softmax")
    ], name="2x512_2xD25")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_2xD25注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载数据同 C19——
    3model = keras.Sequential([第一层 Dense(512, relu)———
    4 layers.Dense(512, activation="relu"),第一层 Dense(512, relu)———
    5 layers.Dropout(0.25),layers.Dropout(0.25)rate=0.25:训练时每个激活值以 25% 概率置零,其余 ×1/0.75;推理时不作用Dropout 层无参数Dropout 放在激活之后(Dense 已含 relu);rate 是丢弃比例不是保留比例
    6 layers.Dense(512, activation="relu"),第二层 Dense + Dropout(0.25)两层隐藏层各跟一个 Dropout——
    7 layers.Dropout(0.25),第二层 Dense + Dropout(0.25)两层隐藏层各跟一个 Dropout——
    8 layers.Dense(10, activation="softmax")输出层softmax 不加 Dropout(输出概率不能被置零)——
    9], name="2x512_2xD25")name="2x512_2xD25"2 个 Dropout × rate .25——
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit同 C14——
    11final_values[model.name] = history_final_values(history)存结果键 "2x512_2xD25"——
    12print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0019, 'val_acc': 0.9475, 'val_loss': 0.2325}val_loss .2325 > 无 dropout 的 .2129——更差!训练 acc 仍 1.0:0.25 的 dropout 没能阻止记住训练集
    13plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0019, 'val_acc': 0.9475, 'val_loss': 0.2325} <Figure size 800x400 with 2 Axes> [image/png]
    为什么隐藏层 dropout 反而更差(Unit 7 讲义 p20–p24 的解释):① 2x512 容量很大(67 万参数),丢 25% 神经元后仍足以记住 6000 样本;② 丢隐藏层只影响"特征组合",输入仍是完整的 784 像素,网络照样能靠像素级线索记忆;③ 50 轮对 dropout 模型可能不够(收敛慢)。正解见 C36–C38:把 Dropout 加到输入层,强迫网络从残缺像素里学特征 → 3xD50 的 .1392。
    Dropout 层的位置约定:Keras 里 Dense(activation="relu") 后接 Dropout = 对激活值做 dropout(最常见);若要 对线性输出做 dropout 需拆成 Dense() → Dropout → Activation。

    Write code to build and train the other two models, 2x512_2xD50 and 2x512_2xD75, save their training and validation results in the final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 32Model 2x512_2xD50基础
    # Model 2x512_2xD50
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.50),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.50),
        layers.Dense(10, activation="softmax")
    ], name="2x512_2xD50")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_2xD50注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(512)———
    4 layers.Dense(512, activation="relu"),Dense(512)———
    5 layers.Dropout(0.50),Dropout(0.50)rate 翻倍——
    6 layers.Dense(512, activation="relu"),Dense + Dropout(0.50)———
    7 layers.Dropout(0.50),Dense + Dropout(0.50)———
    8 layers.Dense(10, activation="softmax")输出层———
    9], name="2x512_2xD50")name="2x512_2xD50"———
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11final_values[model.name] = history_final_values(history)存结果———
    12print(final_values[model.name])打印{'acc': 0.996, 'loss': 0.0138, 'val_acc': 0.9575, 'val_loss': 0.2014}val_loss .2014——开始比无 dropout 好训练 acc .996 < 1.0:dropout 终于让模型记不全了
    13plot_history(history)画图———
    运行结果 {'acc': 0.996, 'loss': 0.0138, 'val_acc': 0.9575, 'val_loss': 0.2014} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 33Model 2x512_2xD75基础
    # Model 2x512_2xD75
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.75),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.75),
        layers.Dense(10, activation="softmax")
    ], name="2x512_2xD75")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_2xD75注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(512)———
    4 layers.Dense(512, activation="relu"),Dense(512)———
    5 layers.Dropout(0.75),Dropout(0.75)75% 置零,剩 25% ×4 放大——
    6 layers.Dense(512, activation="relu"),Dense + Dropout(0.75)———
    7 layers.Dropout(0.75),Dense + Dropout(0.75)———
    8 layers.Dense(10, activation="softmax")输出层———
    9], name="2x512_2xD75")name="2x512_2xD75"———
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11final_values[model.name] = history_final_values(history)存结果———
    12print(final_values[model.name])打印{'acc': 0.9742, 'loss': 0.0869, 'val_acc': 0.955, 'val_loss': 0.1955}val_loss .1955;训练 acc .9742—
    13plot_history(history)画图———
    运行结果 {'acc': 0.9742, 'loss': 0.0869, 'val_acc': 0.955, 'val_loss': 0.1955} <Figure size 800x400 with 2 Axes> [image/png]

    Q1b


    Dropout can be applied to the input layer in addition to the hidden layers, as in the following models.


  • Model 2x512_3xD25: 2 hidden layers each of 512 neurons, with 0.25 dropout in the input layer and in each hidden layer
  • Model 2x512_3xD50: 2 hidden layers each of 512 neurons, with 0.50 dropout in the input layer and in each hidden layer
  • Model 2x512_3xD75: 2 hidden layers each of 512 neurons, with 0.75 dropout in the input layer and in each hidden layer

  • Note that the InputLayer can be omitted in Keras Sequential models (as we often do). To apply dropout to the input layer, simply add a Dropout layer as the first layer to the model.


    model = keras.Sequential([
        layers.Dropout(0.25),  # dropout in input layer
        layers.Dense(512, activation="relu"),
        ...
    ])
    
    输入层 Dropout 的意思:MNIST 像素 ~80% 本来就是 0,再随机丢 25–50% 的输入像素,强迫网络不依赖任何单个像素 → 更鲁棒。Keras 机制:Dropout 作为 Sequential 第一层时,输入形状在 fit 时才推断(Keras 3 允许无 InputLayer 的第一层是 Dropout)。命名规则:2xD = 2 个 Dropout(隐藏层),3xD = 3 个 Dropout(输入 + 2 隐藏),D50 = rate 0.50。

    Write code to build and train the above 3 models, save their training and validation results in the final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models. (Some of the models may not converge within the designated training epochs. Such models should be further investigated in practice, e.g. by more training. In this lab however, for the sake of simplicity, consider their training/validation results so far for their performance.)

    Cell 36Model 2x512_3xD25:输入层 + 隐藏层 Dropout 0.25(3xD 模板 cell)重点展开
    # Model 2x512_3xD25
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dropout(0.25),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.25),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.25),
        layers.Dense(10, activation="softmax")
    ], name="2x512_3xD25")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_3xD25注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([第一层就是 Dropout(0.25)对输入像素做 dropout:训练时随机 25% 像素置零;Sequential 允许无 InputLayer 时第一层为 Dropout,输入形状在 fit 时推断—这是与 C30 的关键区别;M34 给的示例代码就是这么写
    4 layers.Dropout(0.25),第一层就是 Dropout(0.25)对输入像素做 dropout:训练时随机 25% 像素置零;Sequential 允许无 InputLayer 时第一层为 Dropout,输入形状在 fit 时推断—这是与 C30 的关键区别;M34 给的示例代码就是这么写
    5 layers.Dense(512, activation="relu"),Dense(512, relu)输入仍自动推断为 784(Dropout 不改变形状)——
    6 layers.Dropout(0.25),Dropout(0.25)隐藏层 dropout——
    7 layers.Dense(512, activation="relu"),Dense(512, relu)———
    8 layers.Dropout(0.25),Dropout(0.25)———
    9 layers.Dense(10, activation="softmax")输出层———
    10], name="2x512_3xD25")name="2x512_3xD25"3 个 Dropout——
    11history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    12final_values[model.name] = history_final_values(history)存结果———
    13print(final_values[model.name])打印{'acc': 0.9956, 'loss': 0.0146, 'val_acc': 0.9542, 'val_loss': 0.1614}val_loss .1614 ≈ L2_1e-7 的 .1615——同样 rate 下加输入层从 .2325 → .1614输入 dropout 才是 MNIST 上的有效正则
    14plot_history(history)画图—
    —
    运行结果 {'acc': 0.9956, 'loss': 0.0146, 'val_acc': 0.9542, 'val_loss': 0.1614} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 37Model 2x512_3xD50(Dropout 组最佳 .1392)重点展开
    # Model 2x512_3xD50
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dropout(0.50),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.50),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.50),
        layers.Dense(10, activation="softmax")
    ], name="2x512_3xD50")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_3xD50注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dropout(0.50) 在输入一半像素置零——
    4 layers.Dropout(0.50),Dropout(0.50) 在输入一半像素置零——
    5 layers.Dense(512, activation="relu"),Dense(512)———
    6 layers.Dropout(0.50),Dropout(0.50)———
    7 layers.Dense(512, activation="relu"),Dense(512)———
    8 layers.Dropout(0.50),Dropout(0.50)———
    9 layers.Dense(10, activation="softmax")输出层———
    10], name="2x512_3xD50")name="2x512_3xD50"———
    11history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    12final_values[model.name] = history_final_values(history)存结果———
    13print(final_values[model.name])打印{'acc': 0.9585, 'loss': 0.1242, 'val_acc': 0.955, 'val_loss': 0.1392}val_loss .1392 是全部 dropout 模型最低;训练 acc .9585(不再 1.0)val_loss < train loss!——因为 train loss 是 dropout 开启时算的,val 是关闭时算的;这是 dropout 模型的正常现象
    14plot_history(history)画图—
    —
    运行结果 {'acc': 0.9585, 'loss': 0.1242, 'val_acc': 0.955, 'val_loss': 0.1392} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 38Model 2x512_3xD75(不收敛)基础
    # Model 2x512_3xD75
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dropout(0.75),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.75),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.75),
        layers.Dense(10, activation="softmax")
    ], name="2x512_3xD75")
    history = compile_and_fit_model(model, X_train, y_train)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_3xD75注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dropout(0.75) 在输入75% 像素置零 + 75% 隐藏置零:有效信息太少——
    4 layers.Dropout(0.75),Dropout(0.75) 在输入75% 像素置零 + 75% 隐藏置零:有效信息太少——
    5 layers.Dense(512, activation="relu"),Dense(512)———
    6 layers.Dropout(0.75),Dropout(0.75)———
    7 layers.Dense(512, activation="relu"),Dense(512)———
    8 layers.Dropout(0.75),Dropout(0.75)———
    9 layers.Dense(10, activation="softmax")输出层———
    10], name="2x512_3xD75")name="2x512_3xD75"———
    11history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    12final_values[model.name] = history_final_values(history)存结果———
    13print(final_values[model.name])打印{'acc': 0.7915, 'loss': 0.6531, 'val_acc': 0.92, 'val_loss': 0.3762}训练 acc .7915、loss .65——50 轮远未收敛M35 提醒:"some models may not converge";实践中应加轮数(t08 会看到 3xD75 收敛后的表现)
    14plot_history(history)画图—
    —
    运行结果 {'acc': 0.7915, 'loss': 0.6531, 'val_acc': 0.92, 'val_loss': 0.3762} <Figure size 800x400 with 2 Axes> [image/png]

    Q1c


    Write code to display the training and validation results in the final_values dictionary.

    Cell 40Q1c:9 个模型汇总表练习·作答
    pd.DataFrame.from_dict(final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(final_values, orient="index")from_dict(final_values)3 复习 + 6 dropout = 9 行——
    运行结果 acc loss val_acc val_loss 2x512 1.0000 0.0001 0.9533 0.2129 2x512_L1_1e-7 1.0000 0.0058 0.9575 0.1710 2x512_L2_1e-7 1.0000 0.0033 0.9567 0.1615 2x512_2xD25 1.0000 0.0019 0.9475 0.2325 2x512_2xD50 0.9960 0.0138 0.9575 0.2014 2x512_2xD75 0.9742 0.0869 0.9550 0.1955 2x512_3xD25 0.9956 0.0146 0.9542 0.1614 2x512_3xD50 0.9585 0.1242 0.9550 0.1392 2x512_3xD75 0.7915 0.6531 0.9200 0.3762
    Q1c 你的作答核对:正确 ✔。读表:① 2xD 系列(只隐藏层):.2325 → .2014 → .1955,rate 越大越好但都 ≥ 无正则 .2129?——D50/D75 略好于 .2129,D25 更差;② 3xD 系列(加输入层):.1614 → .1392 → .3762,U 形,0.5 是谷底;③ 同 rate 对比 3xD vs 2xD:.1614 vs .2325、.1392 vs .2014——输入 dropout 是 MNIST 的关键。最佳 2x512_3xD50 .1392 → Q1d 选它。

    Q1d


    Referring to the above results of models with dropout, select the best model that has the smallest validation loss (val_loss). Write code to retrain that model using the training set and validation set combined (X_train/y_train), and evaluate the retrained model using the test set (X_test/y_test).

    Cell 42Q1d:重训 2x512_3xD50练习·作答
    # Retrain best model (2x512_3xD50) using training set + validation set combined
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    
    model = keras.Sequential([
        layers.Dropout(0.50),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.50),
        layers.Dense(512, activation="relu"),
        layers.Dropout(0.50),
        layers.Dense(10, activation="softmax")
    ], name="2x512_3xD50_retrain")
    
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=0)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# Retrain best model (2x512_3xD50) using training set + validation set combined注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    5 layers.Dropout(0.50),与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    6 layers.Dense(512, activation="relu"),与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    7 layers.Dropout(0.50),与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    8 layers.Dense(512, activation="relu"),与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    9 layers.Dropout(0.50),与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    10 layers.Dense(10, activation="softmax")与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    11], name="2x512_3xD50_retrain")与 C37 相同结构 + _retrainDropout 层必须保留(它是模型的一部分)—重训时 Dropout 仍生效——fit 时 training=True
    13model.compile(loss="categorical_crossentropy",手写 compile———
    14 optimizer="adam", metrics=["acc"])手写 compile———
    16history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 无 validation_split6000 样本;24 步/轮{'acc': 0.9595, 'loss': 0.1294}训练 acc .9595 与 C37 的 .9585 一致——dropout 下不会到 1.0
    17 verbose=0)fit 无 validation_split6000 样本;24 步/轮{'acc': 0.9595, 'loss': 0.1294}训练 acc .9595 与 C37 的 .9585 一致——dropout 下不会到 1.0
    18print(history_final_values(history))打印{'acc': 0.9595, 'loss': 0.1294}——
    运行结果 {'acc': 0.9595, 'loss': 0.1294}
    Q1d 你的作答核对:正确 ✔——按 val_loss 选了 3xD50(.1392),重训保留 3 个 Dropout 层、去掉 split。代码风格比 t06 更松(有空行),可读性好。
    Cell 43Q1d:测试集评估练习·作答
    print("Evaluation of model " + model.name,
          model.evaluate(X_test, y_test, verbose=0))
    #代码作用机制·语法关联·结果易错点
    1print("Evaluation of model " + model.name,evaluate推理时 Dropout 自动关闭[0.1357, 0.9580]test_loss .1357 全 Lab 最低;test_acc .9580 > 验证 .9550——dropout 模型测试反超验证是常见现象(验证时 dropout 已关,但训练集更大后泛化更好)
    2 model.evaluate(X_test, y_test, verbose=0))evaluate推理时 Dropout 自动关闭[0.1357, 0.9580]test_loss .1357 全 Lab 最低;test_acc .9580 > 验证 .9550——dropout 模型测试反超验证是常见现象(验证时 dropout 已关,但训练集更大后泛化更好)
    运行结果 Evaluation of model 2x512_3xD50_retrain [0.13573238253593445, 0.9580000042915344]

    &#x2766;

    Batch normalization


    Batch normalization, or batch norm, normalizes batches of data in a layer of neurons to achieve regularization and other desirable effects.

    BatchNorm 的数学(Unit 7 讲义 p30–p34):对一个 batch 内每个特征维度:μ_B、σ_B² 是当前 batch 的均值/方差(沿样本轴算);x̂ = (x−μ_B)/√(σ_B²+ε);输出 y = γ·x̂ + β。γ、β 可学习(每层 2×units 个 trainable 参数)。推理时用训练期累积的滑动平均 μ_m、σ_m(momentum 0.99)——所以每层还有 2×units 个 non-trainable 参数。为什么 BA 优于 AA:ReLU 后一半激活是 0,对这种稀疏分布做 BN 统计量失真;先 BN 再 ReLU 让输入分布对称、ReLU 的零点更合理(讲义 p41–p44 的实验结论,与本 Lab C60 一致:.1659 vs .1924)。

    Practice - Question 2 of 2

    Q2a


    The following models have different numbers of neurons, with batch norm applied after activation in the hidden layers.


  • Model 2x512_BN_AA: 2 hidden layers each of 512 neurons, with batch norm applied after activation
  • Model 2x1024_BN_AA: 2 hidden layers each of 1024 neurons, with batch norm applied after activation
  • Model 2x2048_BN_AA: 2 hidden layers each of 2048 neurons, with batch norm applied after activation
  • Training and validation results of the models are stored in a dictionary called bn_final_values, which facilitates the display of results and is first created.

    Cell 49创建 bn_final_values基础
    bn_final_values = {}
    #代码作用机制·语法关联·结果易错点
    1bn_final_values = {}空字典BN 组单独存—只运行一次

    The first model, 2x512_BN_AA, is implemented in this code.

    Cell 51Model 2x512_BN_AA:BN 放在激活之后(BN 模板 cell)重点展开
    # Model 2x512_BN_AA
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu"),
        layers.BatchNormalization(),
        layers.Dense(512, activation="relu"),
        layers.BatchNormalization(),
        layers.Dense(10, activation="softmax")
    ], name="2x512_BN_AA")
    history = compile_and_fit_model(model, X_train, y_train)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_BN_AA注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(512, relu)线性 + ReLU 一起——
    4 layers.Dense(512, activation="relu"),Dense(512, relu)线性 + ReLU 一起——
    5 layers.BatchNormalization(),layers.BatchNormalization()对 ReLU 输出按特征维归一化:训练时用 batch 的 μ/σ,推理时用滑动平均;γ、β 可学每层 4×512 = 2,048 参数(trainable 1,024 + non-trainable 1,024)AA = After Activation;BN 放在 Dense 之后 = 对激活值归一化
    6 layers.Dense(512, activation="relu"),Dense(512, relu) + BN———
    7 layers.BatchNormalization(),Dense(512, relu) + BN———
    8 layers.Dense(10, activation="softmax")输出层softmax 前不加 BN—输出层后加 BN 会破坏 softmax 的概率语义
    9], name="2x512_BN_AA")name="2x512_BN_AA"———
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11bn_final_values[model.name] = history_final_values(history)存进 bn_final_values字典名换了——
    12print(bn_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9492, 'val_loss': 0.1924}val_loss .1924——比无 BN 的 .2129 好,但不如 L2 .1615训练 acc 1.0:BN 的正则效果弱
    13plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9492, 'val_loss': 0.1924} <Figure size 800x400 with 2 Axes> [image/png]
    BatchNormalization() 的默认参数(Unit 7 讲义 p33):axis=-1(沿最后一维=特征维归一化)、momentum=0.99(滑动平均:m ← 0.99·m + 0.01·batch 值)、epsilon=1e-3(防止除 0)、center=True, scale=True(启用 β 和 γ)。
    参数账:2x512_BN 的 trainable = 669,706 + 2×1,024 = 671,754;total = 671,754 + 2×1,024(moving_mean/var)= 673,802。summary() 里会看到两行数字不一样——这就是 Unit 8 讲义 "Optimizer=2×Trainable+2" 里 Trainable 只算 γ/β 的原因。
    BN 的两个作用:① 加速训练(每层输入分布稳定 → 可用更大 lr);② 轻微正则(batch 统计量的噪声相当于数据增强)。但正则力度不如 dropout——所以 BN 模型训练 acc 仍 1.0。

    Write code to build and train the other two models, 2x1024_BN_AA and 2x2048_BN_AA, save their training and validation results in the bn_final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 53Model 2x1024_BN_AA基础
    # Model 2x1024_BN_AA
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(1024, activation="relu"),
        layers.BatchNormalization(),
        layers.Dense(1024, activation="relu"),
        layers.BatchNormalization(),
        layers.Dense(10, activation="softmax")
    ], name="2x1024_BN_AA")
    history = compile_and_fit_model(model, X_train, y_train)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x1024_BN_AA注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(1024)512 → 1024dense 参数 1,854,090—
    4 layers.Dense(1024, activation="relu"),Dense(1024)512 → 1024dense 参数 1,854,090—
    5 layers.BatchNormalization(),BatchNormalization()每层 4×1024 = 4,096 参数trainable 1,856,138—
    6 layers.Dense(1024, activation="relu"),Dense(1024) + BN———
    7 layers.BatchNormalization(),Dense(1024) + BN———
    8 layers.Dense(10, activation="softmax")输出层———
    9], name="2x1024_BN_AA")name———
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11bn_final_values[model.name] = history_final_values(history)存结果———
    12print(bn_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9558, 'val_loss': 0.1902}val_loss .1902—
    13plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9558, 'val_loss': 0.1902} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 54Model 2x2048_BN_AA基础
    # Model 2x2048_BN_AA
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(2048, activation="relu"),
        layers.BatchNormalization(),
        layers.Dense(2048, activation="relu"),
        layers.BatchNormalization(),
        layers.Dense(10, activation="softmax")
    ], name="2x2048_BN_AA")
    history = compile_and_fit_model(model, X_train, y_train)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x2048_BN_AA注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(2048)1024 → 2048dense 参数 5,804,682参数爆炸:2048×2049 = 4.2M 只在第二层
    4 layers.Dense(2048, activation="relu"),Dense(2048)1024 → 2048dense 参数 5,804,682参数爆炸:2048×2049 = 4.2M 只在第二层
    5 layers.BatchNormalization(),BatchNormalization()4×2048 = 8,192trainable 5,808,778—
    6 layers.Dense(2048, activation="relu"),Dense(2048) + BN———
    7 layers.BatchNormalization(),Dense(2048) + BN———
    8 layers.Dense(10, activation="softmax")输出层———
    9], name="2x2048_BN_AA")name———
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11bn_final_values[model.name] = history_final_values(history)存结果———
    12print(bn_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0, 'val_acc': 0.9558, 'val_loss': 0.2281}val_loss .2281——变宽反而更差过拟合:训练 loss 0.0(完全记住)
    13plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0, 'val_acc': 0.9558, 'val_loss': 0.2281} <Figure size 800x400 with 2 Axes> [image/png]

    Q2b


    Batch norm can also be applied before activation of a layer. For example, it can be implemented in Keras using a Dense(512) layer without activation argument, followed by BatchNormalization() layer, and then followed by a Activation(activation="relu") layer.


    The following models have different numbers of neurons, with batch norm applied before activation in the hidden layers.


  • Model 2x512_BN_BA: 2 hidden layers each of 512 neurons, with batch norm applied before activation
  • Model 2x1024_BN_BA: 2 hidden layers each of 1024 neurons, with batch norm applied before activation
  • Model 2x2048_BN_BA: 2 hidden layers each of 2048 neurons, with batch norm applied before activation

  • Write code to build and train these models, save their training and validation results in the bn_final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 56Model 2x512_BN_BA:BN 放在激活之前(BA 模板 cell,Q2b 学生作答)重点展开
    # Model 2x512_BN_BA
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(512),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x512_BN_BA")
    history = compile_and_fit_model(model, X_train, y_train)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x512_BN_BA注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(512) → BN → Activation("relu")Dense 不写 activation(线性输出)→ 对 z 做归一化 → 再 ReLU—BA = Before Activation;M55 给的三行写法;Dense() 无 activation 默认 linear
    4 layers.Dense(512),Dense(512) → BN → Activation("relu")Dense 不写 activation(线性输出)→ 对 z 做归一化 → 再 ReLU—BA = Before Activation;M55 给的三行写法;Dense() 无 activation 默认 linear
    5 layers.BatchNormalization(),Dense(512) → BN → Activation("relu")Dense 不写 activation(线性输出)→ 对 z 做归一化 → 再 ReLU—BA = Before Activation;M55 给的三行写法;Dense() 无 activation 默认 linear
    6 layers.Activation("relu"),第二层同样三行———
    7 layers.Dense(512),第二层同样三行———
    8 layers.BatchNormalization(),第二层同样三行———
    9 layers.Activation("relu"),第二层同样三行———
    10 layers.Dense(10, activation="softmax")输出层———
    11], name="2x512_BN_BA")name="2x512_BN_BA"———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13bn_final_values[model.name] = history_final_values(history)存结果———
    14print(bn_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0002, 'val_acc': 0.9492, 'val_loss': 0.1659}val_loss .1659 ≪ AA 的 .1924→ Q2d 选它重训
    15plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0002, 'val_acc': 0.9492, 'val_loss': 0.1659} <Figure size 800x400 with 2 Axes> [image/png]
    Q2b 你的作答核对:正确 ✔——严格按 M55 的写法拆成 Dense → BatchNormalization → Activation 三层。参数与 AA 版完全相同(BN 参数不随位置变),但 val_loss 从 .1924 → .1659。
    为什么 BA 更好(Unit 7 讲义 p41–p44):AA 是对 ReLU 后的稀疏分布(一半为 0)做 BN,均值/方差被 0 拉偏,归一化后再被 softmax 前的层处理时信息有损;BA 是对对称的 z 做归一化,再 ReLU 截断——这是原始 BatchNorm 论文(Ioffe & Szegedy 2015)推荐的顺序,"BN before nonlinearity"。
    Cell 57Model 2x1024_BN_BA基础
    # Model 2x1024_BN_BA
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(1024),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(1024),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x1024_BN_BA")
    history = compile_and_fit_model(model, X_train, y_train)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x1024_BN_BA注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(1024) → BN → relu———
    4 layers.Dense(1024),Dense(1024) → BN → relu———
    5 layers.BatchNormalization(),Dense(1024) → BN → relu———
    6 layers.Activation("relu"),第二层———
    7 layers.Dense(1024),第二层———
    8 layers.BatchNormalization(),第二层———
    9 layers.Activation("relu"),第二层———
    10 layers.Dense(10, activation="softmax")输出层———
    11], name="2x1024_BN_BA")name———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13bn_final_values[model.name] = history_final_values(history)存结果———
    14print(bn_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9592, 'val_loss': 0.1665}val_loss .1665;val_acc .9592 是 BN 组最高按 val_loss 仍选 512 版(.1659 < .1665)
    15plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9592, 'val_loss': 0.1665} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 58Model 2x2048_BN_BA基础
    # Model 2x2048_BN_BA
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(2048),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(2048),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x2048_BN_BA")
    history = compile_and_fit_model(model, X_train, y_train)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x2048_BN_BA注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Dense(2048) → BN → relu———
    4 layers.Dense(2048),Dense(2048) → BN → relu———
    5 layers.BatchNormalization(),Dense(2048) → BN → relu———
    6 layers.Activation("relu"),第二层———
    7 layers.Dense(2048),第二层———
    8 layers.BatchNormalization(),第二层———
    9 layers.Activation("relu"),第二层———
    10 layers.Dense(10, activation="softmax")输出层———
    11], name="2x2048_BN_BA")name———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13bn_final_values[model.name] = history_final_values(history)存结果———
    14print(bn_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9558, 'val_loss': 0.1919}val_loss .1919——2048 又变差同 AA:宽度 512 最佳
    15plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.9558, 'val_loss': 0.1919} <Figure size 800x400 with 2 Axes> [image/png]

    Q2c


    Write code to display the training and validation results in the bn_final_values dictionary.

    Cell 60Q2c:6 个 BN 模型汇总表练习·作答
    pd.DataFrame.from_dict(bn_final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(bn_final_values, orient="index")from_dict(bn_final_values)6 行最低 2x512_BN_BA .1659—
    运行结果 acc loss val_acc val_loss 2x512_BN_AA 1.0 0.0001 0.9492 0.1924 2x1024_BN_AA 1.0 0.0001 0.9558 0.1902 2x2048_BN_AA 1.0 0.0000 0.9558 0.2281 2x512_BN_BA 1.0 0.0002 0.9492 0.1659 2x1024_BN_BA 1.0 0.0001 0.9592 0.1665 2x2048_BN_BA 1.0 0.0001 0.9558 0.1919
    Q2c 你的作答核对:正确 ✔。读表两条规律:① BA < AA 同宽度下都成立(.1659 vs .1924、.1665 vs .1902、.1919 vs .2281);② 宽度 512 最佳,1024 持平、2048 变差——BN 不能阻止极宽模型的过拟合,它只是让训练更稳定。

    Q2d


    Referring to the above results of models with batch norm, select the best model that has the smallest validation loss (val_loss). Write code to retrain that model using the training set and validation set combined (X_train/y_train), and evaluate the retrained model using the test set (X_test/y_test).

    Cell 62Q2d:重训 2x512_BN_BA练习·作答
    # Retrain best BN model (2x512_BN_BA) using training set + validation set combined
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    
    model = keras.Sequential([
        layers.Dense(512),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(512),
        layers.BatchNormalization(),
        layers.Activation("relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x512_BN_BA_retrain")
    
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    
    history = model.fit(X_train, y_train, epochs=50, batch_size=256,
                        verbose=0)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# Retrain best BN model (2x512_BN_BA) using training set + validation set combined注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    4model = keras.Sequential([与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    5 layers.Dense(512),与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    6 layers.BatchNormalization(),与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    7 layers.Activation("relu"),与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    8 layers.Dense(512),与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    9 layers.BatchNormalization(),与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    10 layers.Activation("relu"),与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    11 layers.Dense(10, activation="softmax")与 C56 相同 + _retrainBN 层必须保留—重训时 BN 的滑动平均从零重新累积
    12], name="2x512_BN_BA_retrain")空行———
    14model.compile(loss="categorical_crossentropy",手写 compile———
    15 optimizer="adam", metrics=["acc"])空行———
    17history = model.fit(X_train, y_train, epochs=50, batch_size=256,fit 无 validation_split6000 样本;24 步/轮history 只有 acc/loss—
    18 verbose=0)空行———
    19print(history_final_values(history))打印末值{'acc': 1.0, 'loss': 0.0001}——
    运行结果 {'acc': 1.0, 'loss': 0.0001}
    Q2d 你的作答核对:正确 ✔——按 val_loss 选 BA 版 512(.1659 < .1665),重训保留 BN 层。
    Cell 63Q2d:测试集评估练习·作答
    print("Evaluation of model " + model.name,
          model.evaluate(X_test, y_test, verbose=0))
    #代码作用机制·语法关联·结果易错点
    1print("Evaluation of model " + model.name,evaluateBN 推理用滑动平均[0.2229, 0.9410]test_loss .2229 远差于验证 .1659——BN 模型重训后泛化没兑现;对比 dropout 3xD50 的 .1357:本任务上 dropout > BN
    2 model.evaluate(X_test, y_test, verbose=0))evaluateBN 推理用滑动平均[0.2229, 0.9410]test_loss .2229 远差于验证 .1659——BN 模型重训后泛化没兑现;对比 dropout 3xD50 的 .1357:本任务上 dropout > BN
    运行结果 Evaluation of model 2x512_BN_BA_retrain [0.22287023067474365, 0.9409999847412109]

    &#x2766;

    Extras

    He initialization of weights


    In a Keras Dense layer, Glorot initialization is applied to weights by default; i.e. the Dense class has the default argument kernel_initializer="glorot_uniform". With ReLU activation, however, He initialization is preferred in general; this can be specified using the argument kernel_initializer="he_normal".

    He vs Glorot 初始化(Unit 7 讲义 p46–p50):Glorot(默认 glorot_uniform):限制 = √(6/(fan_in+fan_out)),设计目标是让 tanh/sigmoid 的前向/反向方差都稳定;He(he_normal):std = √(2/fan_in),因子 2 补偿 ReLU 砍掉一半(负半轴)的方差。对 784→512:Glorot std ≈ 0.039,He std ≈ 0.051——大 30%。什么时候 He 有用:深网络 + ReLU + 无 BN;有 BN 时初始化影响被归一化抵消(C74 .1930 ≈ C51 .1924)。
    E1a

    Write code to build and train the following models with He initialization for weights (kernel_initializer="he_normal"), save their training and validation results in the he_final_values dictionary (created below) for later display, and plot their training histories. Make sure to specify proper names for the Keras models.


  • Model 2x512_he: 2 hidden layers each of 512 neurons, with He initialization
  • Model 2x512_3xD50_he: 2 hidden layers each of 512 neurons, with 0.50 dropout in the input layer and in each hidden layer, with He initialization
  • Model 2x512_BN_AA_he: 2 hidden layers each of 512 neurons, with batch norm applied after activation, with He initialization
  • Model 2x512_BN_BA_he: 2 hidden layers each of 512 neurons, with batch norm applied before activation, with He initialization
  • Cell 68创建 he_final_values基础
    he_final_values = {}
    #代码作用机制·语法关联·结果易错点
    1he_final_values = {}空字典He 组—只运行一次
    E1b

    Write code to display the training and validation results in the he_final_values dictionary.

    Solutions to extra exercises

    ↳ E1 解答 cell 比 t06 的解答少一个 from tensorflow.keras import regularizers 行(不需要正则化器),结构更紧凑。
    E1a
    Cell 72E1a 解答:2x512_he(He 模板 cell)重点展开
    # Solution
    
    # Model 2x512_he
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", kernel_initializer="he_normal"),
        layers.Dense(512, activation="relu", kernel_initializer="he_normal"),
        layers.Dense(10, activation="softmax")
    ], name="2x512_he")
    history = compile_and_fit_model(model, X_train, y_train)
    he_final_values[model.name] = history_final_values(history)
    print(he_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution# Solution / 空行———
    3# Model 2x512_he注释———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([kernel_initializer="he_normal"每层 Dense 加参数:权重从 N(0, √(2/fan_in)) 采样;偏置仍为 0;输出层 softmax 保持 Glorot(He 是为 ReLU 设计的)权重 std:第一层 √(2/784)=.0505 vs Glorot .039只给 relu 层用 He;kernel 指权重矩阵,bias_initializer 另有参数
    6 layers.Dense(512, activation="relu", kernel_initializer="he_normal"),kernel_initializer="he_normal"每层 Dense 加参数:权重从 N(0, √(2/fan_in)) 采样;偏置仍为 0;输出层 softmax 保持 Glorot(He 是为 ReLU 设计的)权重 std:第一层 √(2/784)=.0505 vs Glorot .039只给 relu 层用 He;kernel 指权重矩阵,bias_initializer 另有参数
    7 layers.Dense(512, activation="relu", kernel_initializer="he_normal"),kernel_initializer="he_normal"每层 Dense 加参数:权重从 N(0, √(2/fan_in)) 采样;偏置仍为 0;输出层 softmax 保持 Glorot(He 是为 ReLU 设计的)权重 std:第一层 √(2/784)=.0505 vs Glorot .039只给 relu 层用 He;kernel 指权重矩阵,bias_initializer 另有参数
    8 layers.Dense(10, activation="softmax")输出层———
    9], name="2x512_he")name="2x512_he"———
    10history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    11he_final_values[model.name] = history_final_values(history)存进 he_final_values———
    12print(he_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0002, 'val_acc': 0.955, 'val_loss': 0.2117}val_loss .2117 ≈ Glorot 版 .2129——几乎没差浅网络 + 无 BN 时初始化影响小
    13plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0002, 'val_acc': 0.955, 'val_loss': 0.2117} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 73E1a 解答:2x512_3xD50_he重点展开
    # Solution
    
    # Model 2x512_3xD50_he
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dropout(0.5),
        layers.Dense(512, activation="relu", kernel_initializer="he_normal"),
        layers.Dropout(0.5),
        layers.Dense(512, activation="relu", kernel_initializer="he_normal"),
        layers.Dropout(0.5),
        layers.Dense(10, activation="softmax")
    ], name="2x512_3xD50_he")
    history = compile_and_fit_model(model, X_train, y_train)
    he_final_values[model.name] = history_final_values(history)
    print(he_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solution# Solution / 空行———
    3# Model 2x512_3xD50_he注释———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([开始 Sequential———
    6 layers.Dropout(0.5),Dropout(0.5) 输入层同 C37——
    7 layers.Dense(512, activation="relu", kernel_initializer="he_normal"),Dense(512, relu, he_normal)C37 + He——
    8 layers.Dropout(0.5),Dropout(0.5)———
    9 layers.Dense(512, activation="relu", kernel_initializer="he_normal"),Dense(512, relu, he_normal)———
    10 layers.Dropout(0.5),Dropout(0.5)———
    11 layers.Dense(10, activation="softmax")输出层———
    12], name="2x512_3xD50_he")name="2x512_3xD50_he"———
    13history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    14he_final_values[model.name] = history_final_values(history)存结果———
    15print(he_final_values[model.name])打印{'acc': 0.9479, 'loss': 0.155, 'val_acc': 0.9575, 'val_loss': 0.1434}val_loss .1434 vs Glorot .1392——略差,噪声范围He 理论上配 ReLU 更好,但 dropout 主导了结果
    16plot_history(history)画图—
    —
    运行结果 {'acc': 0.9479, 'loss': 0.155, 'val_acc': 0.9575, 'val_loss': 0.1434} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 74E1a 解答:2x512_BN_AA_he基础
    # Solution
    
    # Model 2x512_BN_AA_he
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, activation="relu", kernel_initializer="he_normal"),
        layers.BatchNormalization(),
        layers.Dense(512, activation="relu", kernel_initializer="he_normal"),
        layers.BatchNormalization(),
        layers.Dense(10, activation="softmax")
    ], name="2x512_BN_AA_he")
    history = compile_and_fit_model(model, X_train, y_train)
    he_final_values[model.name] = history_final_values(history)
    print(he_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 2x512_BN_AA_he注释———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([开始 Sequential———
    6 layers.Dense(512, activation="relu", kernel_initializer="he_normal"),Dense(512, relu, he_normal)C51 + He——
    7 layers.BatchNormalization(),BN———
    8 layers.Dense(512, activation="relu", kernel_initializer="he_normal"),Dense(512, relu, he_normal)———
    9 layers.BatchNormalization(),BN———
    10 layers.Dense(10, activation="softmax")输出层———
    11], name="2x512_BN_AA_he")name———
    12history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    13he_final_values[model.name] = history_final_values(history)存结果———
    14print(he_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0002, 'val_acc': 0.9467, 'val_loss': 0.193}val_loss .1930 ≈ C51 .1924BN 抹平了初始化差异——BN 一归一化,权重尺度就不重要了
    15plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0002, 'val_acc': 0.9467, 'val_loss': 0.193} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 75E1a 解答:2x512_BN_BA_he基础
    # Solution
    
    # Model 2x512_BN_BA_he
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Dense(512, kernel_initializer="he_normal"),
        layers.BatchNormalization(),
        layers.Activation(activation="relu"),
        layers.Dense(512, kernel_initializer="he_normal"),
        layers.BatchNormalization(),
        layers.Activation(activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x512_BN_BA_he")
    history = compile_and_fit_model(model, X_train, y_train)
    he_final_values[model.name] = history_final_values(history)
    print(he_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 2x512_BN_BA_he注释———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([开始 Sequential———
    6 layers.Dense(512, kernel_initializer="he_normal"),Dense(512, kernel_initializer="he_normal")无 activation → BA 结构——
    7 layers.BatchNormalization(),BN———
    8 layers.Activation(activation="relu"),Activation(activation="relu")关键字参数写法,与 C56 的 Activation("relu") 等价—两种写法都对
    9 layers.Dense(512, kernel_initializer="he_normal"),第二层三行———
    10 layers.BatchNormalization(),第二层三行———
    11 layers.Activation(activation="relu"),第二层三行———
    12 layers.Dense(10, activation="softmax")输出层———
    13], name="2x512_BN_BA_he")name———
    14history = compile_and_fit_model(model, X_train, y_train)compile+fit———
    15he_final_values[model.name] = history_final_values(history)存结果———
    16print(he_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0003, 'val_acc': 0.955, 'val_loss': 0.1711}val_loss .1711 vs C56 .1659——略差—
    17plot_history(history)画图—
    —
    运行结果 {'acc': 1.0, 'loss': 0.0003, 'val_acc': 0.955, 'val_loss': 0.1711} <Figure size 800x400 with 2 Axes> [image/png]
    E1b
    Cell 77E1b:He 组汇总表基础
    # Solution
    
    pd.DataFrame.from_dict(he_final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3pd.DataFrame.from_dict(he_final_values, orient="index")from_dict(he_final_values)4 行3xD50_he .1434 最低与 Glorot 版对照:.2117/.2118、.1434/.1392、.1930/.1924、.1711/.1659——全部在噪声范围
    运行结果 acc loss val_acc val_loss 2x512_he 1.0000 0.0002 0.9550 0.2117 2x512_3xD50_he 0.9479 0.1550 0.9575 0.1434 2x512_BN_AA_he 1.0000 0.0002 0.9467 0.1930 2x512_BN_BA_he 1.0000 0.0003 0.9550 0.1711

    &#x2766;

    📘 Tutorial 8(= Lab 8)· CNN 结构与组件:卷积层数 / 核数 / BN / Dropout(MNIST)

    t08-s13903054.ipynb,74 cells。对应 Unit 8 讲义 p5–p16(卷积运算、输出尺寸 ⌊(I+2P−K)/S⌋+1、参数 (K·K·d_in+1)·n)、p17–p26(Flatten + Dense、summary 读法、Optimizer=2×Trainable+2)、p27–p40(BN/Dropout 在 CNN 中的位置)。与 t06/t07 的两点关键差别:① 数据 reshape 成 (N,28,28,1) 4D 而不是展平;② 用 validation_data=(X_test, y_test) 而不是 validation_split(且 20 轮而非 50 轮)。结果速览(val_loss):1 层 16/32/64 核 .1949/.2072/.1709;2 层 .1944/.1732/.1473;BN 双 .2093 / BN1 .6767(异常)/ BN2 .1701;Dropout D25 .2044 / D50 .1376 / D75 .1225;3 层 .1792 / BN3 .1053 / 3xD75 .0952(全 Lab 最佳)。
    读法:本 Lab 的模板 cell 是 C17(Conv2D → Flatten → Dense(32) → Dense(10)),后面 13 个模型只改三处:Conv2D 的核数 / 层数、是否插入 BatchNormalization / Dropout、fit 的 epochs。C17 与 C28(summary)逐行精讲,其余讲差异与读数。
    必会公式(Unit 8 讲义 p34):① 输出边长 = ⌊(I + 2P − K)/S⌋ + 1,valid padding、stride 1 时就是 I − K + 1 → 28→26→24→22;② Conv2D 参数 = (K·K·d_in + 1) × n_kernels → 第一层 64×(9×1+1) = 640,第二层 64×(9×64+1) = 36,928;③ Flatten 后 Dense(32) 占了 97% 参数(24×24×64 = 36,864 → 1,179,680);④ Optimizer params = 2×Trainable + 2(Adam 的 m、v 两个矩 + iterations + seed)。
    三条结论:① 更深比更宽有效(2x64 .1473 < 1x64 .1709;3x64 加 BN3 .1053);② BN 放在一组卷积之后(BN2 > BN1_BN2 >> BN1 .6767 训崩);③ CNN 的 dropout 可以用得比 MLP 猛(D75 .1225 最佳,t07 MLP 的 D75 不收敛)——因为 CNN 参数少、特征图冗余高。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同前IPython 魔术命令;须在 import tensorflow 前env: TF_CPP_MIN_LOG_LEVEL=2每个 notebook 第一个 cell
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • exploring structures and components of CNNs, and
  • application of batch normalization and dropout to CNNs.
  • Student name: Yin Bang
    Student ID: 13903054

    Utility code


    This section contains some utility functions for use in the lesson.

    This function loads the MNIST dataset, prepares the data, and returns portion of the data in a 4-tuple: X_train, y_train, X_test, y_test. Note that the input feature arrays X_train and X_test are reshaped to 4D, i.e. each input feature example reshaped to 3D.

    为什么是 4D:Conv2D 期望输入 (batch, height, width, channels)——channels_last 格式(Keras 默认)。MNIST 是灰度图,所以 channels=1:reshape(-1, 28, 28, 1)。若忘了加最后一维会报 "expected min_ndim=4, found ndim=3"。
    Cell 7load_and_prep_mnist(ratio=0.1):reshape 成 4D (N,28,28,1)重点展开
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.datasets import mnist
    
    def load_and_prep_mnist(ratio=0.1):
        keras.utils.set_random_seed(42)
        (X_train, y_train), (X_test, y_test) = mnist.load_data()
        if ratio < 1:
            sz_train = int(len(X_train) * ratio)
            sz_test = int(len(X_test) * ratio)
            X_train, y_train = X_train[:sz_train], y_train[:sz_train]
            X_test, y_test = X_test[:sz_test], y_test[:sz_test]
        X_train_out = X_train.astype(float) / 255  # scale to range 0 to 1
        X_test_out = X_test.astype(float) / 255
        X_train_out = X_train_out.reshape(-1, 28, 28, 1)  # convert 2D to 3D
        X_test_out = X_test_out.reshape(-1, 28, 28, 1)
        y_train_oh = keras.utils.to_categorical(y_train, 10)  # one-hot encode
        y_test_oh = keras.utils.to_categorical(y_test, 10)
        return X_train_out, y_train_oh, X_test_out, y_test_oh
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入本 Lab 不需要 regularizers——
    2from tensorflow.keras import layers导入本 Lab 不需要 regularizers——
    3from tensorflow.keras.datasets import mnist导入本 Lab 不需要 regularizers——
    5def load_and_prep_mnist(ratio=0.1):定义 + 种子同 t06——
    6 keras.utils.set_random_seed(42)定义 + 种子同 t06——
    7 (X_train, y_train), (X_test, y_test) = mnist.load_data()载入 + 子集ratio=0.1 → 6000/1000——
    8 if ratio < 1:载入 + 子集ratio=0.1 → 6000/1000——
    9 sz_train = int(len(X_train) * ratio)载入 + 子集ratio=0.1 → 6000/1000——
    10 sz_test = int(len(X_test) * ratio)载入 + 子集ratio=0.1 → 6000/1000——
    11 X_train, y_train = X_train[:sz_train], y_train[:sz_train]载入 + 子集ratio=0.1 → 6000/1000——
    12 X_test, y_test = X_test[:sz_test], y_test[:sz_test]载入 + 子集ratio=0.1 → 6000/1000——
    13 X_train_out = X_train.astype(float) / 255 # scale to range 0 to 1缩放—[0,1]—
    14 X_test_out = X_test.astype(float) / 255缩放—[0,1]—
    15 X_train_out = X_train_out.reshape(-1, 28, 28, 1) # convert 2D to 3Dreshape(-1, 28, 28, 1)与 t06 的唯一区别:不是展平成 784,而是加一个通道维 → (6000, 28, 28, 1)Conv2D 需要 4D channels_last少写最后的 1 会报错;-1 自动推断 batch 维
    16 X_test_out = X_test_out.reshape(-1, 28, 28, 1)reshape(-1, 28, 28, 1)与 t06 的唯一区别:不是展平成 784,而是加一个通道维 → (6000, 28, 28, 1)Conv2D 需要 4D channels_last少写最后的 1 会报错;-1 自动推断 batch 维
    17 y_train_oh = keras.utils.to_categorical(y_train, 10) # one-hot encodeone-hot + 返回—y (6000,10)—
    18 y_test_oh = keras.utils.to_categorical(y_test, 10)one-hot + 返回—y (6000,10)—
    19 return X_train_out, y_train_oh, X_test_out, y_test_ohone-hot + 返回—y (6000,10)—

    This function retrieves the final results in a training history, i.e. values of "loss", "val_loss", "acc", and "val_acc" in the final epoch.

    Cell 9history_final_values基础
    def history_final_values(history):
        return {k: round(v[-1], 4) for k, v in history.history.items()}
    #代码作用机制·语法关联·结果易错点
    1def history_final_values(history):同 t06——见 t06 C11
    2 return {k: round(v[-1], 4) for k, v in history.history.items()}同 t06——见 t06 C11

    This function plots a training history, including both training and validation results.

    Cell 11plot_history基础
    import matplotlib.pyplot as plt
    import pandas as pd
    
    def plot_history(history):
        df = pd.DataFrame(history.history)
        df.index = df.index + 1
        fig, axs = plt.subplots(1, 2, figsize=(8, 4))
        df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])
        df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])
        plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt同 t06——见 t06 C13
    2import pandas as pd同 t06——见 t06 C13
    4def plot_history(history):同 t06——见 t06 C13
    5 df = pd.DataFrame(history.history)同 t06——见 t06 C13
    6 df.index = df.index + 1同 t06——见 t06 C13
    7 fig, axs = plt.subplots(1, 2, figsize=(8, 4))同 t06——见 t06 C13
    8 df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])同 t06——见 t06 C13
    9 df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])同 t06——见 t06 C13
    10 plt.tight_layout()同 t06——见 t06 C13

    This function compiles and fits a model, and returns the training history.

    compile_and_fit_model 的新签名(与 t06/t07 对比):多了 X_test, y_test 两个必填参数 + epochs=20, batch_size=256, verbose=0 三个带默认值的关键字参数。内部用 validation_data=(X_test, y_test)——直接拿测试集当验证集(这在教学演示里常见,严格来说不规范,因为测试集参与了模型选择;t06 用 validation_split 更严谨)。epochs 从 50 降到 20:CNN 收敛快。BN 实验传 epochs=30。
    Cell 13compile_and_fit_model:validation_data + 20 轮(新签名)重点展开
    def compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                              epochs=20, batch_size=256, verbose=0):
        model.compile(loss="categorical_crossentropy",
                      optimizer="adam", metrics=["acc"])
        history = model.fit(X_train, y_train, epochs=epochs,
                            batch_size=batch_size, verbose=verbose,
                            validation_data=(X_test, y_test))
        return history
    #代码作用机制·语法关联·结果易错点
    1def compile_and_fit_model(model, X_train, y_train, X_test, y_test,签名:model, X_train, y_train, X_test, y_test, epochs=20, batch_size=256, verbose=0前 5 个必填,后 3 个有默认值;调用时可只传 epochs=30 改轮数—必填参数没有默认值,调用时顺序不能错;关键字参数可省略
    2 epochs=20, batch_size=256, verbose=0):签名:model, X_train, y_train, X_test, y_test, epochs=20, batch_size=256, verbose=0前 5 个必填,后 3 个有默认值;调用时可只传 epochs=30 改轮数—必填参数没有默认值,调用时顺序不能错;关键字参数可省略
    3 model.compile(loss="categorical_crossentropy",compile同前——
    4 optimizer="adam", metrics=["acc"])compile同前——
    5 history = model.fit(X_train, y_train, epochs=epochs,fit 用 validation_data=(X_test, y_test)每轮末在 X_test 上评估;不用 validation_split6000/256 = 23.4 → 24 步/轮;val_* 来自 1000 个测试样本测试集被当验证集用——教学演示可接受; epochs/batch_size 透传自参数
    6 batch_size=batch_size, verbose=verbose,fit 用 validation_data=(X_test, y_test)每轮末在 X_test 上评估;不用 validation_split6000/256 = 23.4 → 24 步/轮;val_* 来自 1000 个测试样本测试集被当验证集用——教学演示可接受; epochs/batch_size 透传自参数
    7 validation_data=(X_test, y_test))fit 用 validation_data=(X_test, y_test)每轮末在 X_test 上评估;不用 validation_split6000/256 = 23.4 → 24 步/轮;val_* 来自 1000 个测试样本测试集被当验证集用——教学演示可接受; epochs/batch_size 透传自参数
    8 return history返回 history———

    Convolutional layers and kernels


    In CNNs, patterns in images are identified by convolutional layers of kernels. The number of convolutional layers and the number of kernels in a convolutional layer are two key factors of a CNN's capability and complexity.


    A number of CNN models for classifying the MNIST digit dataset are examined below. Training and validation results of the models are stored in a dictionary called final_values, which facilitates the display of results and is first created.

    Conv2D(16, kernel_size=(3,3), activation="relu") 做了什么(Unit 8 讲义 p5–p12):16 个 3×3×1 的可学习核,每个核在 28×28 输入上滑动(stride 1、valid padding),每个位置做 9 个乘加 + 偏置 → 一个标量 → 拼成 26×26 的特征图;16 个核 → 16 张特征图 → 输出 (26, 26, 16)。关键性质:参数只与核大小和深度有关,与图像大小无关——28×28 和 224×224 用同一个 Conv2D 参数量一样;且平移等变:数字平移,特征图跟着平移。这就是 CNN 比 MLP(t05 的 50,240 个第一层参数)更省参数、更适合图像的原因。
    Cell 15创建 final_values基础
    final_values = {}
    #代码作用机制·语法关联·结果易错点
    1final_values = {}空字典——只运行一次

    The following 3 models have 1 convolutional layer, but they have different numbers of kernels in a layer -- 16, 32, and 64 3&times;3 kernels, respectively.


  • Model 1x16_K3x3: 1 convolutional layer of 16 3&times;3 kernels
  • Model 1x32_K3x3: 1 convolutional layer of 32 3&times;3 kernels
  • Model 1x64_K3x3: 1 convolutional layer of 64 3&times;3 kernels
  • Cell 17Model 1x16_K3x3:单卷积层 16 核(CNN 模板 cell)重点展开
    # Model 1x16_K3x3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(16, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x16_K3x3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x16_K3x3注释:1 层 × 16 核 × 3×3命名规则:<层数>x<核数>_K<核尺寸>——
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载 4D 数据—X (6000,28,28,1)—
    3model = keras.Sequential([开始 Sequential———
    4 layers.Conv2D(16, kernel_size=(3, 3), activation="relu"),Conv2D(16, kernel_size=(3,3), activation="relu")16 个 3×3 核;stride 默认 1、padding 默认 valid;输入通道自动推断为 1输出 (26,26,16);参数 16×(9×1+1) = 160第一个参数是核数不是核尺寸;kernel_size 可写 3 或 (3,3);不要写 input_shape(Keras 3 自动推断)
    5 layers.Flatten(),Flatten()把 (26,26,16) 展平成 10,816 维向量,供 Dense 使用;无参数(None, 10816)Flatten 不改变 batch 维;与 GlobalAveragePooling 的区别:后者把每张特征图求均值 → 16 维
    6 layers.Dense(32, activation="relu"),Dense(32, relu)全连接 32 个单元参数 32×(10816+1) = 346,144(占 99.9%)CNN 的大头参数在 Dense 层——这是后来用 GAP 替代 Flatten 的动机
    7 layers.Dense(10, activation="softmax")Dense(10, softmax)输出330—
    8], name="1x16_K3x3")name="1x16_K3x3"———
    9history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)compile_and_fit_model(model, X, y, X_test, y_test)5 个位置参数;epochs 用默认 20—这里必须传 X_test/y_test(与 t06 的 3 参数版本不同)
    10final_values[model.name] = history_final_values(history)存结果键 "1x16_K3x3"——
    11print(final_values[model.name])打印{'acc': 0.9987, 'loss': 0.0154, 'val_acc': 0.94, 'val_loss': 0.1949}val_loss .1949—
    12plot_history(history)画图—
    —
    运行结果 {'acc': 0.9987, 'loss': 0.0154, 'val_acc': 0.94, 'val_loss': 0.1949} <Figure size 800x400 with 2 Axes> [image/png]
    参数总账(1x16):160 + 346,144 + 330 = 346,634。对比 t05 的 MLP 64-64-10(55,050)——这个最小 CNN 参数反而是它的 6 倍,但 val_acc .94 vs .96?不对,t05 用 15000 样本训 30 轮,这里 6000 样本 20 轮,不可直接比。
    Conv2D 的三个默认值要记:strides=(1,1)、padding="valid"(不补零,尺寸缩水)、activation=None(要显式写 relu)。若要保尺寸用 padding="same"(Unit 8 讲义 p34 公式里的 P)。
    Cell 18Model 1x32_K3x3基础
    # Model 1x32_K3x3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x32_K3x3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x32_K3x3注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),Conv2D(32)16 → 32 核输出 (26,26,32);参数 320—
    5 layers.Flatten(),Flatten(None, 21632)——
    6 layers.Dense(32, activation="relu"),Dense(32)692,576——
    7 layers.Dense(10, activation="softmax")Dense(10)330——
    8], name="1x32_K3x3")name———
    9history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    10final_values[model.name] = history_final_values(history)存———
    11print(final_values[model.name])打印{'acc': 0.9988, 'loss': 0.0116, 'val_acc': 0.943, 'val_loss': 0.2072}val_loss .2072——比 16 核还差!核数翻倍参数翻倍,但 val_loss 没降——6000 样本喂不饱
    12plot_history(history)画图———
    运行结果 {'acc': 0.9988, 'loss': 0.0116, 'val_acc': 0.943, 'val_loss': 0.2072} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 19Model 1x64_K3x3基础
    # Model 1x64_K3x3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="1x64_K3x3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 1x64_K3x3注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64)32 → 64 核输出 (26,26,64);参数 640—
    5 layers.Flatten(),Flatten(None, 43264)——
    6 layers.Dense(32, activation="relu"),Dense(32)1,384,480——
    7 layers.Dense(10, activation="softmax")Dense(10)330——
    8], name="1x64_K3x3")name———
    9history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    10final_values[model.name] = history_final_values(history)存———
    11print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0036, 'val_acc': 0.955, 'val_loss': 0.1709}val_loss .1709——1 层最佳—
    12plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0036, 'val_acc': 0.955, 'val_loss': 0.1709} <Figure size 800x400 with 2 Axes> [image/png]

    Practice - Question 1 of 3


    In this section, we examine CNNs with 2 convolutional layers.

    Q1a


    Write code to build and train the following models with 2 convolutional layers. Save their training and validation results in the final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.


  • Model 2x16_K3x3: 2 convolutional layers each of 16 3&times;3 kernels
  • Model 2x32_K3x3: 2 convolutional layers each of 32 3&times;3 kernels
  • Model 2x64_K3x3: 2 convolutional layers each of 64 3&times;3 kernels
  • Cell 22Q1a 学生作答:Model 2x16_K3x3(两层模板)练习·作答
    # Model 2x16_K3x3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(16, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(16, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x16_K3x3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x16_K3x3注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(16, kernel_size=(3, 3), activation="relu"),Conv2D(16) 第一层输入通道 1(26,26,16);160—
    5 layers.Conv2D(16, kernel_size=(3, 3), activation="relu"),Conv2D(16) 第二层输入通道自动 = 16(上一层核数);尺寸 26−3+1 = 24(24,24,16);参数 16×(9×16+1) = 2,320第二层不用指定 input_shape,Sequential 自动衔接
    6 layers.Flatten(),Flatten24×24×16 = 9,216(None, 9216)—
    7 layers.Dense(32, activation="relu"),Dense(32)294,944——
    8 layers.Dense(10, activation="softmax")Dense(10)330——
    9], name="2x16_K3x3")name="2x16_K3x3"———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 0.999, 'loss': 0.0078, 'val_acc': 0.936, 'val_loss': 0.1944}val_loss .1944——与 1x16 持平总参数 297,754
    13plot_history(history)画图———
    运行结果 {'acc': 0.999, 'loss': 0.0078, 'val_acc': 0.936, 'val_loss': 0.1944} <Figure size 800x400 with 2 Axes> [image/png]
    Q1a 你的作答核对:正确 ✔——三个两层模型结构、命名、存储都对。注意 2x16 的 val_loss .1944 ≈ 1x16 的 .1949:小核数时加深度没用。
    Cell 23Model 2x32_K3x3基础
    # Model 2x32_K3x3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x32_K3x3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x32_K3x3注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),Conv2D(32) 第一层—(26,26,32);320—
    5 layers.Conv2D(32, kernel_size=(3, 3), activation="relu"),Conv2D(32) 第二层32×(9×32+1) = 9,248(24,24,32)—
    6 layers.Flatten(),Flatten18,432——
    7 layers.Dense(32, activation="relu"),Dense(32)589,856——
    8 layers.Dense(10, activation="softmax")Dense(10)330——
    9], name="2x32_K3x3")name———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 0.9997, 'loss': 0.0029, 'val_acc': 0.955, 'val_loss': 0.1732}val_loss .1732总参数 599,754
    13plot_history(history)画图———
    运行结果 {'acc': 0.9997, 'loss': 0.0029, 'val_acc': 0.955, 'val_loss': 0.1732} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 24Model 2x64_K3x3(Q1 最佳 .1473)基础
    # Model 2x64_K3x3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64_K3x3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64_K3x3注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) 第一层—(26,26,64);640—
    5 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) 第二层64×(9×64+1) = 36,928(24,24,64)—
    6 layers.Flatten(),Flatten36,864(None, 36864)—
    7 layers.Dense(32, activation="relu"),Dense(32)1,179,680——
    8 layers.Dense(10, activation="softmax")Dense(10)330——
    9], name="2x64_K3x3")name———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0003, 'val_acc': 0.964, 'val_loss': 0.1473}val_loss .1473;val_acc .964总 trainable 1,217,578(见 C28)
    13plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0003, 'val_acc': 0.964, 'val_loss': 0.1473} <Figure size 800x400 with 2 Axes> [image/png]

    Q1b


    Write code to display the training and validation results in the final_values dictionary.

    Cell 26Q1b:6 个模型汇总表练习·作答
    pd.DataFrame.from_dict(final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(final_values, orient="index")from_dict6 行最佳 2x64_K3x3 .1473—
    运行结果 acc loss val_acc val_loss 1x16_K3x3 0.9987 0.0154 0.940 0.1949 1x32_K3x3 0.9988 0.0116 0.943 0.2072 1x64_K3x3 1.0000 0.0036 0.955 0.1709 2x16_K3x3 0.9990 0.0078 0.936 0.1944 2x32_K3x3 0.9997 0.0029 0.955 0.1732 2x64_K3x3 1.0000 0.0003 0.964 0.1473
    Q1b 你的作答核对:正确 ✔。读表规律:① 核数:16→32 几乎无变化甚至变差(.1949→.2072),32→64 才明显下降(→.1709)——需要足够的核才能覆盖笔画多样性;② 层数:同核数下 2 层 ≤ 1 层(.1944 vs .1949、.1732 vs .2072、.1473 vs .1709)——第二层能组合第一层的边缘特征成更复杂的图案(Unit 8 讲义 p14–p16)。

    Q1c


    The following summary of model 2x64_K3x3 shows the output shapes and numbers of trainable parameters of the model's layers. The input layer, which contains placeholders for input data and performs no operations, is not shown in the summary; it has an input shape of (None, 28, 28, 1), which means a batch of 28&times;28 1-channel (i.e. grayscale) images.

    summary() 的读法(Unit 8 讲义 p17–p22):每行 = 层名(类型) / Output Shape / Param #。Output Shape 的 None 是 batch 维(不固定);conv2d_7 的 7 是 Keras 全局层计数器(本 notebook 第 7 个 Conv2D,因为前面 C17–C24 已经建了 6 个)。InputLayer 不显示——Sequential 没写 Input 时,summary 只在 build 后(即 fit 或调用一次后)才有输入形状信息。
    Cell 28model.summary():逐层读 2x64_K3x3重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()model.summary()打印层表:Layer / Output Shape / Param #;末尾 Trainable / Non-trainable / Optimizer 三行conv2d_7 (None,26,26,64) 640;conv2d_8 (None,24,24,64) 36,928;flatten (None,36864) 0;dense_? (None,32) 1,179,680;(None,10) 330model 是 C24 的 2x64_K3x3(最后一个建的);summary 只对已 build 的模型有效
    运行结果 Model: "2x64_K3x3" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ conv2d_7 (Conv2D) │ (None, 26, 26, 64) │ 640 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ conv2d_8 (Conv2D) │ ([38;5;4  Total params: 3,652,736 (13.93 MB)  Trainable params: 1,217,578 (4.64 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 2,435,158 (9.29 MB)
    summary() 四个数逐个复算(考试 "determine # of trainable parameters" 必考):
    ① conv2d_7:(3×3×1+1)×64 = 10×64 = 640(输入深度 1)
    ② conv2d_8:(3×3×64+1)×64 = 577×64 = 36,928(输入深度 = 上一核数)
    ③ flatten:0 参数;输出 24×24×64 = 36,864
    ④ Dense(32):32×(36,864+1) = 1,179,680(97%)
    ⑤ Dense(10):10×(32+1) = 330
    Trainable = 640+36,928+1,179,680+330 = 1,217,578 ✔
    Optimizer params = 2,435,158 = 2×1,217,578 + 2 ✔——Adam 为每个参数存 m 和 v 两个矩(×2),加 iterations 和 一个 seed(+2)。Total = Trainable + Non-trainable(0) + Optimizer = 3,652,736 ✔。这个 "2T+2" 公式全课程通用(Unit 8 讲义 p22)。

    Consider the first convolutional layer of 64 3&times;3 kernels. In the output shape, the width/height can be calculated as: input size 28 - kernel size 3 + 1 = 26; the depth is 64 (i.e. number of kernels). The number of trainable parameters can be calculated as: 64 kernels &times; (kernel size 3&times;3 &times; input depth 1 + 1 bias) = 640.


    The number of trainable parameters of the second convolutional layer is 36,928. Explain this number by writing an expression for calculating it, and describing the key terms in the expression. Write your answer in a text cell below.

    C30 你的作答核对:完全正确 ✔——"64×(3×3×64+1)=64×577=36,928",三项都解释到了:64 = 核数(输出深度)、3×3×64 = 每个核的 3×3 空间 × 输入深度 64(第一层输出)、+1 = 每核一个偏置。这就是 Unit 8 讲义 p34 的 (K·K·d_in+1)·n 公式。
    补充一个常考变式:若题目问"第二层的 计算量",那是另一个数——24×24 个位置 × 64 核 × 577 次乘加 ≈ 2,127 万 MACs,是第一层(43 万)的 49 倍;参数量 36,928 却只有 Dense(32) 的 3%。参数少 ≠ 计算少——这是 CNN 的特点。

    Solution:



    <div class='alert alert-warning' role='alert'><b>The second convolutional layer has 64 kernels of size 3×3. Its input is the 26×26×64 feature map produced by the first convolutional layer (depth 64). The number of trainable parameters is:

    64×(3×3×64+1)=64×577=36,928</b></div>

    &#x2766;

    Model 2x64_K3x3, which has 2 convolutional layers and 64 3&times;3 kernels in each convolutional layer, is a capable model but has overfitting. Let's try to overcome its overfitting using some regularization techniques.

    ↳ 2x64 的过拟合证据:C24 训练 acc 1.0 / loss .0003,val_acc .964 / val_loss .1473——train loss 是 val 的 1/500。接下来用 BN 和 Dropout 两种手段压它。

    Batch normalization


    Batch normalization improves training of neural networks in several ways, such as reducing overfitting. Based on model 2x64_K3x3, the following models apply batch norm after the convolutional layers.


  • Model 2x64_K3x3_BN1_BN2: 2 convolutional layers each of 64 3&times;3 kernels, with batch norm after both convolutional layers
  • Model 2x64_K3x3_BN1: 2 convolutional layers each of 64 3&times;3 kernels, with batch norm after the first convolutional layer
  • Model 2x64_K3x3_BN2: 2 convolutional layers each of 64 3&times;3 kernels, with batch norm after the second convolutional layer
  • Training and validation results of the models are stored in a dictionary called bn_final_values, which facilitates the display of results and is first created.

    Cell 35创建 bn_final_values基础
    bn_final_values = {}
    #代码作用机制·语法关联·结果易错点
    1bn_final_values = {}空字典——只运行一次

    The first model, 2x64_K3x3_BN1_BN2, is implemented as follows. Note that the model is trained in 30 epochs (instead of 20 epochs).

    Cell 37Model 2x64_K3x3_BN1_BN2:两个卷积层后各加 BN(30 轮)重点展开
    # Model 2x64_K3x3_BN1_BN2
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.BatchNormalization(),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.BatchNormalization(),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64_K3x3_BN1_BN2")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=30)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64_K3x3_BN1_BN2注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64)—(26,26,64)—
    5 layers.BatchNormalization(),BatchNormalization()对 64 张特征图各自归一化(按通道,axis=-1 默认即 channels_last 的通道维);BN 放在 Conv2D(含 relu)之后 = after activation每层 +256 trainable(γ,β)+ 256 non-trainableConv2D 后的 BN 与 Dense 后的 BN 参数算法相同:4×通道数
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) + BN———
    7 layers.BatchNormalization(),Conv2D(64) + BN———
    8 layers.Flatten(),Flatten / Dense(32) / Dense(10)———
    9 layers.Dense(32, activation="relu"),Flatten / Dense(32) / Dense(10)———
    10 layers.Dense(10, activation="softmax")Flatten / Dense(32) / Dense(10)———
    11], name="2x64_K3x3_BN1_BN2")name———
    12history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,compile_and_fit_model(..., epochs=30)位置参数 5 个 + 关键字 epochs=30 覆盖默认 2030 轮:BN 模型收敛慢,多给 10 轮关键字参数写在最后
    13 epochs=30)compile_and_fit_model(..., epochs=30)位置参数 5 个 + 关键字 epochs=30 覆盖默认 2030 轮:BN 模型收敛慢,多给 10 轮关键字参数写在最后
    14bn_final_values[model.name] = history_final_values(history)存进 bn_final_values———
    15print(bn_final_values[model.name])打印{'acc': 0.9998, 'loss': 0.0003, 'val_acc': 0.949, 'val_loss': 0.2093}val_loss .2093——比无 BN 的 .1473 差—
    16plot_history(history)画图———
    运行结果 {'acc': 0.9998, 'loss': 0.0003, 'val_acc': 0.949, 'val_loss': 0.2093} <Figure size 800x400 with 2 Axes> [image/png]

    Practice - Question 2 of 3

    Q2a


    Write code to build and train (in 30 epochs) the other 2 models, i.e. 2x64_K3x3_BN1 and 2x64_K3x3_BN2. Save their training and validation results in the bn_final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 40Q2a 学生作答:Model 2x64_K3x3_BN1(训练崩溃 .6767)练习·作答
    # Model 2x64_K3x3_BN1
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.BatchNormalization(),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64_K3x3_BN1")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test, epochs=30)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64_K3x3_BN1注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64)———
    5 layers.BatchNormalization(),BN 在第一层后BN 夹在两组卷积之间—这就是 BN1 的定义
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64)输入被归一化——
    7 layers.Flatten(),Flatten / Dense———
    8 layers.Dense(32, activation="relu"),Flatten / Dense———
    9 layers.Dense(10, activation="softmax")Flatten / Dense———
    10], name="2x64_K3x3_BN1")name="..._BN1"———
    11history = compile_and_fit_model(model, X_train, y_train, X_test, y_test, epochs=30)fit epochs=30———
    12bn_final_values[model.name] = history_final_values(history)存———
    13print(bn_final_values[model.name])打印{'acc': 0.9933, 'loss': 0.1912, 'val_acc': 0.912, 'val_loss': 0.6767}val_loss .6767——训练崩溃;acc 却还有 .912acc 高但 loss 高 = 多数对但错的那些错得离谱(置信度反向极值)
    14plot_history(history)画图—
    曲线上应能看到某轮 val_loss 突然跳升
    运行结果 {'acc': 0.9933, 'loss': 0.1912, 'val_acc': 0.912, 'val_loss': 0.6767} <Figure size 800x400 with 2 Axes> [image/png]
    Q2a 你的作答核对:代码正确 ✔,结果是真实的实验现象。BN1 的 .6767 不是 bug——见 M45 的说明。你的 C41 BN2 .1701 正常。考试若问 "explain why BN1 performs badly":BN inserted between convolutional layers disrupts the feature magnitude distribution that the second conv layer relies on; placing BN at the output of the conv block (BN2) preserves within-block feature learning.
    Cell 41Q2a 学生作答:Model 2x64_K3x3_BN2(.1701)练习·作答
    # Model 2x64_K3x3_BN2
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.BatchNormalization(),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64_K3x3_BN2")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test, epochs=30)
    bn_final_values[model.name] = history_final_values(history)
    print(bn_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64_K3x3_BN2注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),两个 Conv2D 连着中间不插 BN——
    5 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),两个 Conv2D 连着中间不插 BN——
    6 layers.BatchNormalization(),BN 在第二层后、Flatten 前放在整组卷积的出口—BN2 的定义
    7 layers.Flatten(),Flatten / Dense———
    8 layers.Dense(32, activation="relu"),Flatten / Dense———
    9 layers.Dense(10, activation="softmax")Flatten / Dense———
    10], name="2x64_K3x3_BN2")name———
    11history = compile_and_fit_model(model, X_train, y_train, X_test, y_test, epochs=30)fit epochs=30———
    12bn_final_values[model.name] = history_final_values(history)存———
    13print(bn_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0, 'val_acc': 0.959, 'val_loss': 0.1701}val_loss .1701;BN 组最佳—
    14plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0, 'val_acc': 0.959, 'val_loss': 0.1701} <Figure size 800x400 with 2 Axes> [image/png]

    Q2b


    Write code to display the training and validation results in the bn_final_values dictionary.

    Cell 43Q2b:BN 组汇总表练习·作答
    pd.DataFrame.from_dict(bn_final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(bn_final_values, orient="index")from_dict(bn_final_values)3 行BN2 .1701 < BN1_BN2 .2093 << BN1 .6767—
    运行结果 acc loss val_acc val_loss 2x64_K3x3_BN1_BN2 0.9998 0.0003 0.949 0.2093 2x64_K3x3_BN1 0.9933 0.1912 0.912 0.6767 2x64_K3x3_BN2 1.0000 0.0000 0.959 0.1701
    Q2b 你的作答核对:正确 ✔。结论(M45):"batch norm works well after, rather than within, a bunch of convolutional layers"——注意 BN 组没有一个超过无 BN 的 .1473:在 6000 样本 + 20/30 轮的设定下,BN 的正则效果不如 dropout。

    &#x2766;

    We should find that model 2x64_K3x3_BN2 performs the best. In general, batch norm works well after, rather than within, a bunch of convolutional layers.

    BN1 为什么崩(val_loss .6767)——这是本 Lab 最值得理解的异常:BN 只放在第一层卷积之后、第二层卷积之前("within" 一组卷积)。第二层卷积的输入被强行归一化成均值 0 方差 1,破坏了第一层学到的特征幅值信息;同时 BN 在训练/推理模式间用不同统计量,第二层对这种切换很敏感 → 训练后期 loss 突然发散(acc .9933 但 loss .1912,说明少数样本的置信度严重错)。对比:BN2(放在两组卷积之后、Flatten 之前).1701 正常;BN1_BN2 .2093 介于中间。M45 的结论:"batch norm works well after, rather than within, a bunch of convolutional layers"——放在一组卷积的出口,不要夹在中间。这与 t07 的 BA(BN 放激活前)不矛盾:t07 是单个 Dense 层内部的顺序,这里是跨层的放置位置。

    Dropout


    Dropout is another regularization technique to mitigate overfitting. Based on model 2x64_K3x3, the following models apply dropout in the convolutional layers.


  • Model 2x64_K3x3_2xD25: 2 convolutional layers each of 64 3&times;3 kernels, with 0.25 dropout in each convolutional layer
  • Model 2x64_K3x3_2xD50: 2 convolutional layers each of 64 3&times;3 kernels, with 0.5 dropout in each convolutional layer
  • Model 2x64_K3x3_2xD75: 2 convolutional layers each of 64 3&times;3 kernels, with 0.75 dropout in each convolutional layer
  • Training and validation results of these models are stored in a dictionary called drop_final_values, which facilitates the display of results and is first created.

    Cell 48创建 drop_final_values基础
    drop_final_values = {}
    #代码作用机制·语法关联·结果易错点
    1drop_final_values = {}空字典——只运行一次

    The first model, 2x64_K3x3_2xD25, is implemented as follows. The model is trained in 20 epochs (the default).

    Cell 50Model 2x64_K3x3_2xD25:卷积层后 Dropout 0.25(模板)重点展开
    # Model 2x64_K3x3_2xD25
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.25),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.25),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64_K3x3_2xD25")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    drop_final_values[model.name] = history_final_values(history)
    print(drop_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64_K3x3_2xD25注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64)—(26,26,64)—
    5 layers.Dropout(0.25),Dropout(0.25)对 26×26×64 的特征图逐元素随机置零 25%(Keras 3 默认);推理时关闭无参数普通 Dropout 是逐元素的;SpatialDropout2D 是整张特征图置零——CNN 里后者往往更好,但本课用前者
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) + Dropout(0.25)———
    7 layers.Dropout(0.25),Conv2D(64) + Dropout(0.25)———
    8 layers.Flatten(),Flatten / Dense———
    9 layers.Dense(32, activation="relu"),Flatten / Dense———
    10 layers.Dense(10, activation="softmax")Flatten / Dense———
    11], name="2x64_K3x3_2xD25")name———
    12history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit 默认 20 轮不传 epochs—与 BN 组的 30 轮不同——两组之间不可直接比
    13drop_final_values[model.name] = history_final_values(history)存进 drop_final_values———
    14print(drop_final_values[model.name])打印{'acc': 0.9995, 'loss': 0.0037, 'val_acc': 0.953, 'val_loss': 0.2044}val_loss .2044——D25 没什么用—
    15plot_history(history)画图———
    运行结果 {'acc': 0.9995, 'loss': 0.0037, 'val_acc': 0.953, 'val_loss': 0.2044} <Figure size 800x400 with 2 Axes> [image/png]

    Practice - Question 3 of 3

    Q3a


    Write code to build and train the other 2 models, i.e. 2x64_K3x3_2xD50 and 2x64_K3x3_2xD75. Save their training and validation results in the drop_final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    Cell 53Q3a 学生作答:Model 2x64_K3x3_2xD50练习·作答
    # Model 2x64_K3x3_2xD50
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.5),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.5),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64_K3x3_2xD50")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    drop_final_values[model.name] = history_final_values(history)
    print(drop_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64_K3x3_2xD50注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64)———
    5 layers.Dropout(0.5),Dropout(0.5)rate 翻倍——
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) + Dropout(0.5)———
    7 layers.Dropout(0.5),Conv2D(64) + Dropout(0.5)———
    8 layers.Flatten(),Flatten / Dense———
    9 layers.Dense(32, activation="relu"),Flatten / Dense———
    10 layers.Dense(10, activation="softmax")Flatten / Dense———
    11], name="2x64_K3x3_2xD50")name———
    12history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit 20 轮———
    13drop_final_values[model.name] = history_final_values(history)存———
    14print(drop_final_values[model.name])打印{'acc': 0.9973, 'loss': 0.0094, 'val_acc': 0.968, 'val_loss': 0.1376}val_loss .1376;val_acc .968—
    15plot_history(history)画图———
    运行结果 {'acc': 0.9973, 'loss': 0.0094, 'val_acc': 0.968, 'val_loss': 0.1376} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 54Q3a 学生作答:Model 2x64_K3x3_2xD75(.1225)练习·作答
    # Model 2x64_K3x3_2xD75
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.75),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.75),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="2x64_K3x3_2xD75")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    drop_final_values[model.name] = history_final_values(history)
    print(drop_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 2x64_K3x3_2xD75注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64)———
    5 layers.Dropout(0.75),Dropout(0.75)75% 特征图元素置零——
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) + Dropout(0.75)———
    7 layers.Dropout(0.75),Conv2D(64) + Dropout(0.75)———
    8 layers.Flatten(),Flatten / Dense———
    9 layers.Dense(32, activation="relu"),Flatten / Dense———
    10 layers.Dense(10, activation="softmax")Flatten / Dense———
    11], name="2x64_K3x3_2xD75")name———
    12history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit 20 轮———
    13drop_final_values[model.name] = history_final_values(history)存———
    14print(drop_final_values[model.name])打印{'acc': 0.9887, 'loss': 0.0351, 'val_acc': 0.964, 'val_loss': 0.1225}val_loss .1225——2 层组最佳训练 acc .9887 终于不到 1.0
    15plot_history(history)画图———
    运行结果 {'acc': 0.9887, 'loss': 0.0351, 'val_acc': 0.964, 'val_loss': 0.1225} <Figure size 800x400 with 2 Axes> [image/png]

    Q3b


    Write code to display the training and validation results in the drop_final_values dictionary.

    Cell 56Q3b:Dropout 组汇总表(注意少了 2xD25)练习·作答
    pd.DataFrame.from_dict(drop_final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1pd.DataFrame.from_dict(drop_final_values, orient="index")from_dict(drop_final_values)只有 2 行——D25 不在D75 .1225 < D50 .1376C50 的 D25 结果没进字典:很可能是重启 kernel 后先跑了 Q3a 的两个 cell、没重跑 C50;完整对比需加上 C50 的 .2044
    运行结果 acc loss val_acc val_loss 2x64_K3x3_2xD50 0.9973 0.0094 0.968 0.1376 2x64_K3x3_2xD75 0.9887 0.0351 0.964 0.1225
    Q3b 你的作答核对:代码正确,但表缺一行。M58 的结论 "higher dropout rates (0.5 and 0.75) have slightly better results" 是对比 D25 .2044 得出的——你提交的表里没有 D25,读者无法验证这句话。建议:交作业前 "Restart & Run All" 确保所有 cell 按序执行。

    &#x2766;

    Using higher dropout rates (0.5 and 0.75) has slightly better results according to the validation loss. More dropout leads to stronger regularization and thus less overfitting for this task.

    为什么 CNN 能承受 D75:① 每个卷积层只有 36,928 参数,Dense 层占 97% 但 dropout 没加在它上面;② 特征图高度冗余——相邻位置的激活相似,丢掉 75% 仍能恢复;③ 卷积的权重共享让每个核看到全图所有位置,等于自带数据增强。t07 的 MLP 3xD75 不收敛是因为输入层 75% 像素丢掉后信息真的没了。注意 C56 的表少了 2xD25 那一行——学生跑 Q3b 时 drop_final_values 只含 D50/D75(C50 的 D25 可能在重启 kernel 后没重跑);完整对比见 C50 .2044。

    Extras

    The previous models contain either 1 or 2 convolutional layers. In this section, we examine models containing 3 convolutional layers and see if they have better results.


  • Model 3x64_K3x3: 3 convolutional layers each of 64 3&times;3 kernels
  • Model 3x64_K3x3_BN3: 3 convolutional layers each of 64 3&times;3 kernels, with batch norm after the third convolutional layer
  • Model 3x64_K3x3_3xD75: 3 convolutional layers each of 64 3&times;3 kernels, with 0.75 dropout in each convolutional layer
  • 3 层的尺寸链:28 → 26 → 24 → 22,Flatten 后 22×22×64 = 30,976(比 2 层的 36,864 还少);第三层参数 64×(9×64+1) = 36,928(与第二层同);总 trainable 1,066,090。感受野:3 层 3×3 堆叠 = 一个 7×7 的感受野,但参数只有 3×577 vs 49×d_in——这是 VGG 的核心思想(Unit 9 讲义)。

    Training and validation results of these models are stored in a dictionary called extra_final_values, which facilitates the display of results and is first created.

    Cell 62创建 extra_final_values基础
    extra_final_values = {}
    #代码作用机制·语法关联·结果易错点
    1extra_final_values = {}空字典——只运行一次

    The first model, 3x64_K3x3, is implemented as follows.

    Cell 64Model 3x64_K3x3:三层卷积(尺寸 28→26→24→22)重点展开
    # Model 3x64_K3x3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="3x64_K3x3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    extra_final_values[model.name] = history_final_values(history)
    print(extra_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Model 3x64_K3x3注释———
    2X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) #1输入通道 1(26,26,64);640—
    5 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) #2输入通道 64(24,24,64);36,928—
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) #3输入通道 64;24−3+1 = 22(22,22,64);36,928三层 3×3 堆叠 → 感受野 7×7
    7 layers.Flatten(),Flatten22×22×64 = 30,976(None, 30976)比 2 层的 36,864 少
    8 layers.Dense(32, activation="relu"),Dense(32)991,264——
    9 layers.Dense(10, activation="softmax")Dense(10)330——
    10], name="3x64_K3x3")name———
    11history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit 20 轮———
    12extra_final_values[model.name] = history_final_values(history)存进 extra_final_values———
    13print(extra_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.968, 'val_loss': 0.1792}val_loss .1792——比 2x64 的 .1473 差!更深但没正则 → 过拟合更重(train loss 1e-4)
    14plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0001, 'val_acc': 0.968, 'val_loss': 0.1792} <Figure size 800x400 with 2 Axes> [image/png]
    E1a

    Write code to build and train the other 2 models, i.e. 3x64_K3x3_BN3 and 3x64_K3x3_3xD75. Save their training and validation results in the extra_final_values dictionary for later display, and plot their training histories. Make sure to specify proper names for the Keras models.

    E1b

    Write code to display the training and validation results in the extra_final_values dictionary.

    Solutions to extra exercises

    E1a
    Cell 69E1a 解答:Model 3x64_K3x3_BN3(.1053)重点展开
    # Solution
    
    # Model 3x64_K3x3_BN3
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.BatchNormalization(),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="3x64_K3x3_BN3")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    extra_final_values[model.name] = history_final_values(history)
    print(extra_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 3x64_K3x3_BN3注释———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([Sequential———
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),三个 Conv2D(64) 连着中间不插任何层22×22×64—
    7 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),三个 Conv2D(64) 连着中间不插任何层22×22×64—
    8 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),三个 Conv2D(64) 连着中间不插任何层22×22×64—
    9 layers.BatchNormalization(),BatchNormalization() 在第三层后放在整组卷积出口(M45 的原则)+256 trainableBN3 的定义
    10 layers.Flatten(),Flatten / Dense———
    11 layers.Dense(32, activation="relu"),Flatten / Dense———
    12 layers.Dense(10, activation="softmax")Flatten / Dense———
    13], name="3x64_K3x3_BN3")name———
    14history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit 20 轮———
    15extra_final_values[model.name] = history_final_values(history)存———
    16print(extra_final_values[model.name])打印{'acc': 1.0, 'loss': 0.0, 'val_acc': 0.968, 'val_loss': 0.1053}val_loss .1053——比 2x64_BN2 .1701 好得多三层 + 出口 BN 的组合生效
    17plot_history(history)画图———
    运行结果 {'acc': 1.0, 'loss': 0.0, 'val_acc': 0.968, 'val_loss': 0.1053} <Figure size 800x400 with 2 Axes> [image/png]
    Cell 70E1a 解答:Model 3x64_K3x3_3xD75(.0952 全 Lab 最佳)重点展开
    # Solution
    
    # Model 3x64_K3x3_3xD75
    X_train, y_train, X_test, y_test = load_and_prep_mnist()
    model = keras.Sequential([
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.75),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.75),
        layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),
        layers.Dropout(0.75),
        layers.Flatten(),
        layers.Dense(32, activation="relu"),
        layers.Dense(10, activation="softmax")
    ], name="3x64_K3x3_3xD75")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    extra_final_values[model.name] = history_final_values(history)
    print(extra_final_values[model.name])
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3# Model 3x64_K3x3_3xD75注释———
    4X_train, y_train, X_test, y_test = load_and_prep_mnist()加载———
    5model = keras.Sequential([Sequential———
    6 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) #1———
    7 layers.Dropout(0.75),Dropout(0.75)———
    8 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) #2———
    9 layers.Dropout(0.75),Dropout(0.75)———
    10 layers.Conv2D(64, kernel_size=(3, 3), activation="relu"),Conv2D(64) #3———
    11 layers.Dropout(0.75),Dropout(0.75)三个 dropout——
    12 layers.Flatten(),Flatten / Dense———
    13 layers.Dense(32, activation="relu"),Flatten / Dense———
    14 layers.Dense(10, activation="softmax")Flatten / Dense———
    15], name="3x64_K3x3_3xD75")name———
    16history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit 20 轮———
    17extra_final_values[model.name] = history_final_values(history)存———
    18print(extra_final_values[model.name])打印{'acc': 0.975, 'loss': 0.0792, 'val_acc': 0.964, 'val_loss': 0.0952}val_loss .0952——全 Lab 最低;val_acc .964训练 acc .975——强正则下仍能学
    19plot_history(history)画图———
    运行结果 {'acc': 0.975, 'loss': 0.0792, 'val_acc': 0.964, 'val_loss': 0.0952} <Figure size 800x400 with 2 Axes> [image/png]
    E1b
    Cell 72E1b:3 层组汇总表基础
    # Solution
    
    pd.DataFrame.from_dict(extra_final_values, orient="index")
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3pd.DataFrame.from_dict(extra_final_values, orient="index")from_dict(extra_final_values)3 行3xD75 .0952 < BN3 .1053 < 无正则 .1792M73:3 层 + 正则 > 对应的 2 层版本(.1225 / .1701)
    运行结果 acc loss val_acc val_loss 3x64_K3x3 1.000 0.0001 0.968 0.1792 3x64_K3x3_BN3 1.000 0.0000 0.968 0.1053 3x64_K3x3_3xD75 0.975 0.0792 0.964 0.0952

    Being more capable with 3 convolutional layers and using batch norm and dropout for mitigating overfitting, models 3x64_K3x3_BN3 and 3x64_K3x3_3xD75 perform better than their respective counterparts with 2 convolutional layers.

    &#x2766;

    📘 Tutorial 9(= Lab 9)· 迁移学习(MobileNet / VGG-16)+ 上采样·缩放 + Google Drive + 数据增强

    t09-s13903054.ipynb,94 cells。对应 Unit 9 讲义 p6–p14(迁移学习概念:冻结卷积基 + 新分类头)、p15–p24(MobileNet、输入尺寸限制 128/160/192/224、上采样 vs 缩放)、p25–p34(image_dataset_from_directory、Google Drive)、p35–p42(数据增强 RandomFlip/RandomRotation)、p43–p56(VGG-16 结构、裁剪 VGG 块)。三个任务:① CIFAR-10(25,000/5,000)→ MobileNet:32 输入 val_acc .21(无效)→ 上采样 128 .87 / 224 .83 → Resizing 128 .87 / 224 .86;② 猫狗 40 张图(28/12)→ MobileNet 224:val_acc .42 → 加数据增强 .83;③ VGG-16 on CIFAR-10 @32:25 轮 val_acc ≈ .63(过拟合)→ 裁 1 块([:-4])更好 → 裁 2 块([:-8])欠拟合 .13。
    读法:本 Lab 跳出 MNIST,第一次用预训练模型。C15(MobileNet 迁移学习母版)、C35(Drive 挂载)、C41(目录数据集)、C48(猫狗模型)逐行精讲;C20/C22/C26/C28 四个变体只讲差异。
    迁移学习四步曲(Unit 9 讲义 p9):① preprocess_input——用预训练模型自己的预处理(MobileNet/VGG16 是 "caffe 风格":RGB→BGR + 减 ImageNet 均值,不是 /255,所以 scale_x=False);② base_model.trainable = False——冻结卷积基,只训新加的层;③ 加分类头(Flatten → Dense);④ 训练。为什么冻结:卷积基学的是通用特征(边缘→纹理→部件),ImageNet 上学到的对 CIFAR/猫狗也有用;数据少时若不冻结会破坏这些特征且过拟合。
    必会数字:CIFAR-10 ratio 0.5 → 25,000/5,000 → 98 步/轮;MobileNet 卷积基 3,228,864 参数(冻结);猫狗模型 Dense(1024) on 7×7×1024 = 50,176 → 51,381,248(占 99.99%);VGG-16 卷积基 14,714,688;VGG 18 层 = 13 conv + 5 maxpool(不含 input),块结构 2-2-3-3-3。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同前—env: TF_CPP_MIN_LOG_LEVEL=2每个 notebook 第一个 cell
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • transfer learning,
  • the VGG-16 and MobileNet pre-trained models,
  • using Google drive in Colab, and
  • data augmentation.
  • Student name: Yin Bang
    Student ID: 13903054

    Utility code


    This section contains some utility functions for use in the rest of the lesson.

    This function loads the CIFAR-10 dataset, prepares the data, and returns portion of the data in a 4-tuple: X_train, y_train, X_test, y_test. Note that this function does not scale the features (X_train and X_test), which will be preprocessed using the preprocess_input() function of Keras applications.

    与 MNIST 版本的三点区别:① 数据集 cifar10:50,000/10,000 张 32×32×3 彩色(已有通道维,不用 reshape);② scale_x=True 默认会 /255,但 MobileNet/VGG16 用 preprocess_input 时不该先 /255,所以 C15 传 scale_x=False;③ y 是 (N,1) 形状(cifar10 的标签是二维的),to_categorical 自动处理成 (N,10)。
    Cell 7load_and_prep_cifar10(ratio=0.5, scale_x=True):不 reshape、可选缩放重点展开
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.datasets import cifar10
    
    def load_and_prep_cifar10(ratio=0.5, scale_x=True):
        keras.utils.set_random_seed(42)
        (X_train, y_train), (X_test, y_test) = cifar10.load_data()
        if ratio < 1:
            sz_train = int(len(X_train) * ratio)
            sz_test = int(len(X_test) * ratio)
            X_train, y_train = X_train[:sz_train], y_train[:sz_train]
            X_test, y_test = X_test[:sz_test], y_test[:sz_test]
        if scale_x:
            X_train = X_train.astype(float) / 255  # scale to range 0-1
            X_test = X_test.astype(float) / 255
        y_train_oh = keras.utils.to_categorical(y_train, 10)  # one-hot
        y_test_oh = keras.utils.to_categorical(y_test, 10)
        return X_train, y_train_oh, X_test, y_test_oh
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入cifar10 代替 mnist;不需要 regularizers——
    2from tensorflow.keras import layers导入cifar10 代替 mnist;不需要 regularizers——
    3from tensorflow.keras.datasets import cifar10导入cifar10 代替 mnist;不需要 regularizers——
    5def load_and_prep_cifar10(ratio=0.5, scale_x=True):定义 load_and_prep_cifar10(ratio=0.5, scale_x=True)两个参数:ratio 取一半(25,000/5,000,CNN 训练慢);scale_x 控制是否 /255—scale_x 是新增开关:用 preprocess_input 时传 False
    6 keras.utils.set_random_seed(42)种子———
    7 (X_train, y_train), (X_test, y_test) = cifar10.load_data()cifar10.load_data()返回 ((50000,32,32,3), (50000,1)), ((10000,32,32,3), (10000,1))——y 是二维首次下载 170 MBy 形状 (N,1) 不是 (N,);to_categorical 能处理
    8 if ratio < 1:ratio 切片int(50000×0.5) = 25000;int(10000×0.5) = 5000——
    9 sz_train = int(len(X_train) * ratio)ratio 切片int(50000×0.5) = 25000;int(10000×0.5) = 5000——
    10 sz_test = int(len(X_test) * ratio)ratio 切片int(50000×0.5) = 25000;int(10000×0.5) = 5000——
    11 X_train, y_train = X_train[:sz_train], y_train[:sz_train]ratio 切片int(50000×0.5) = 25000;int(10000×0.5) = 5000——
    12 X_test, y_test = X_test[:sz_test], y_test[:sz_test]ratio 切片int(50000×0.5) = 25000;int(10000×0.5) = 5000——
    13 if scale_x:if scale_x: /255只在 scale_x=True 时执行;本 Lab 用 MobileNet/VGG16 时传 False—传 False 时 X 保持 0–255 的 uint8 → float?不——不 astype 就还是 uint8;preprocess_input 内部会转
    14 X_train = X_train.astype(float) / 255 # scale to range 0-1if scale_x: /255只在 scale_x=True 时执行;本 Lab 用 MobileNet/VGG16 时传 False—传 False 时 X 保持 0–255 的 uint8 → float?不——不 astype 就还是 uint8;preprocess_input 内部会转
    15 X_test = X_test.astype(float) / 255if scale_x: /255只在 scale_x=True 时执行;本 Lab 用 MobileNet/VGG16 时传 False—传 False 时 X 保持 0–255 的 uint8 → float?不——不 astype 就还是 uint8;preprocess_input 内部会转
    16 y_train_oh = keras.utils.to_categorical(y_train, 10) # one-hotone-hotto_categorical(y (N,1), 10) → (N,10)——
    17 y_test_oh = keras.utils.to_categorical(y_test, 10)one-hotto_categorical(y (N,1), 10) → (N,10)——
    18 return X_train, y_train_oh, X_test, y_test_oh返回———

    This function retrieves the final results in a training history, i.e. values of "loss", "val_loss", "acc", and "val_acc" in the final epoch.

    Cell 9history_final_values基础
    def history_final_values(history):
        return {k: round(v[-1], 4) for k, v in history.history.items()}
    #代码作用机制·语法关联·结果易错点
    1def history_final_values(history):同 t06——见 t06 C11
    2 return {k: round(v[-1], 4) for k, v in history.history.items()}同 t06——见 t06 C11

    This function plots a training history, including both training and validation results.

    Cell 11plot_history(C11 里重复定义了一次 history_final_values)基础
    import matplotlib.pyplot as plt
    import pandas as pd
    
    def history_final_values(history):
        return {k: round(v[-1], 4) for k, v in history.history.items()}
    
    def plot_history(history):
        df = pd.DataFrame(history.history)
        df.index = df.index + 1
        fig, axs = plt.subplots(1, 2, figsize=(8, 4))
        df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])
        df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])
        plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入———
    2import pandas as pd导入———
    4def history_final_values(history):history_final_values 重复定义与 C9 完全相同——无害,覆盖同一个名字— redundant:可以删
    5 return {k: round(v[-1], 4) for k, v in history.history.items()}history_final_values 重复定义与 C9 完全相同——无害,覆盖同一个名字— redundant:可以删
    7def plot_history(history):plot_history同 t06 C13—见 t06
    8 df = pd.DataFrame(history.history)plot_history同 t06 C13—见 t06
    9 df.index = df.index + 1plot_history同 t06 C13—见 t06
    10 fig, axs = plt.subplots(1, 2, figsize=(8, 4))plot_history同 t06 C13—见 t06
    11 df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])plot_history同 t06 C13—见 t06
    12 df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])plot_history同 t06 C13—见 t06
    13 plt.tight_layout()plot_history同 t06 C13—见 t06

    This function compiles and fits a model, and returns the training history.

    Cell 13compile_and_fit_model:默认 verbose=2(本 Lab 要看每轮)重点展开
    def compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                              epochs=20, batch_size=256, verbose=2):
        model.compile(loss="categorical_crossentropy",
                      optimizer="adam", metrics=["acc"])
        history = model.fit(X_train, y_train, epochs=epochs,
                            batch_size=batch_size, verbose=verbose,
                            validation_data=(X_test, y_test))
        return history
    #代码作用机制·语法关联·结果易错点
    1def compile_and_fit_model(model, X_train, y_train, X_test, y_test,签名同 t08,但 verbose 默认 2—verbose=2 每轮一行——本 Lab 只训 3–25 轮,看得过来
    2 epochs=20, batch_size=256, verbose=2):签名同 t08,但 verbose 默认 2—verbose=2 每轮一行——本 Lab 只训 3–25 轮,看得过来
    3 model.compile(loss="categorical_crossentropy",compile———
    4 optimizer="adam", metrics=["acc"])compile———
    5 history = model.fit(X_train, y_train, epochs=epochs,fit validation_data—CIFAR 25000/256 = 97.7 → 98 步/轮—
    6 batch_size=batch_size, verbose=verbose,fit validation_data—CIFAR 25000/256 = 97.7 → 98 步/轮—
    7 validation_data=(X_test, y_test))fit validation_data—CIFAR 25000/256 = 97.7 → 98 步/轮—
    8 return history返回———

    Transfer learning with MobileNet


    Transfer learning refers to reusing pre-trained models for new different applications. It often involves incorporating a pre-trained model into your new model and training the new model for the application in question.


    MobileNet is a capable CNN yet very small in size. The following model reuses the MobileNet CNN. Note the input shape of 32&times;32&times;3 specified in the MobileNet model creation.

    MobileNet 是什么(Unit 9 讲义 p15–p18):为移动设备设计的轻量 CNN:用深度可分离卷积(depthwise + pointwise)替代标准卷积,参数量约为 VGG-16 的 1/9(330 万 vs 1,470 万),精度略低。合法输入尺寸只有 128/160/192/224 四种(因为权重按这些尺寸训练,且网络里下采样 32 倍后要求整除)。C15 传 32 会有 UserWarning:仍能跑(卷积核与尺寸无关),但下采样 32 倍后 32×32 → 1×1 特征图,空间信息全丢,所以 val_acc 只有 .21(接近随机 .1 的两倍)。
    Cell 15MobileNet 迁移学习母版:preprocess_input → 冻结 → 分类头(输入 32,无效)重点展开
    from tensorflow.keras.applications import mobilenet
    
    X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)
    X_train = mobilenet.preprocess_input(X_train)
    X_test = mobilenet.preprocess_input(X_test)
    base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,
                                     input_shape=(32, 32, 3))
    base_model.trainable = False
    model = keras.Sequential([
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=10)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1from tensorflow.keras.applications import mobilenet导入 mobilenet 应用模块含 MobileNet 类 + preprocess_input 函数——
    3X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)load_and_prep_cifar10(scale_x=False)不做 /255——MobileNet 的 preprocess_input 会自己做X (25000,32,32,3) uint8若 scale_x=True 再 preprocess 会双重预处理,val_acc 掉 5–10 个点
    4X_train = mobilenet.preprocess_input(X_train)mobilenet.preprocess_input把 0–255 图转成模型期望的输入:RGB→BGR、减 ImageNet 均值(不除 255)X 变 float32,值域约 [−127, +127]这是 caffe 风格;不同模型不同:ResNet/VGG/MobileNet 是 caffe 式,Inception/EfficientNet 是 [−1,1] 或 [0,1]——查文档
    5X_test = mobilenet.preprocess_input(X_test)mobilenet.preprocess_input把 0–255 图转成模型期望的输入:RGB→BGR、减 ImageNet 均值(不除 255)X 变 float32,值域约 [−127, +127]这是 caffe 风格;不同模型不同:ResNet/VGG/MobileNet 是 caffe 式,Inception/EfficientNet 是 [−1,1] 或 [0,1]——查文档
    6base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,MobileNet(weights="imagenet", include_top=False, input_shape=(32,32,3))weights 下载 ImageNet 预训练权重;include_top=False 去掉全局池化 + Dense(1000);input_shape 必须 3 通道下载 mobilenet_1_0_224_tf_no_top.h5(17 MB);UserWarning:32 不在 [128,160,192,224]卷积基参数 3,228,864;输出 (None,1,1,1024)——32/32 = 1
    7 input_shape=(32, 32, 3))MobileNet(weights="imagenet", include_top=False, input_shape=(32,32,3))weights 下载 ImageNet 预训练权重;include_top=False 去掉全局池化 + Dense(1000);input_shape 必须 3 通道下载 mobilenet_1_0_224_tf_no_top.h5(17 MB);UserWarning:32 不在 [128,160,192,224]卷积基参数 3,228,864;输出 (None,1,1,1024)——32/32 = 1
    8base_model.trainable = Falsebase_model.trainable = False冻结:fit 时不更新卷积基权重,也不算它的梯度summary 里 Non-trainable 3,228,864必须在 fit 前设置;compile 后再改要重新 compile
    9model = keras.Sequential([新模型 = base + Flatten + Dense(1024) + Dense(10)Sequential 可以嵌套整个 model 作为一层;Flatten 把 1×1×1024 → 1024Dense(1024) on 1024:1,049,600;Dense(10):10,250—
    10 base_model,新模型 = base + Flatten + Dense(1024) + Dense(10)Sequential 可以嵌套整个 model 作为一层;Flatten 把 1×1×1024 → 1024Dense(1024) on 1024:1,049,600;Dense(10):10,250—
    11 layers.Flatten(),新模型 = base + Flatten + Dense(1024) + Dense(10)Sequential 可以嵌套整个 model 作为一层;Flatten 把 1×1×1024 → 1024Dense(1024) on 1024:1,049,600;Dense(10):10,250—
    12 layers.Dense(1024, activation="relu"),新模型 = base + Flatten + Dense(1024) + Dense(10)Sequential 可以嵌套整个 model 作为一层;Flatten 把 1×1×1024 → 1024Dense(1024) on 1024:1,049,600;Dense(10):10,250—
    13 layers.Dense(10, activation="softmax")新模型 = base + Flatten + Dense(1024) + Dense(10)Sequential 可以嵌套整个 model 作为一层;Flatten 把 1×1×1024 → 1024Dense(1024) on 1024:1,049,600;Dense(10):10,250—
    14])新模型 = base + Flatten + Dense(1024) + Dense(10)Sequential 可以嵌套整个 model 作为一层;Flatten 把 1×1×1024 → 1024Dense(1024) on 1024:1,049,600;Dense(10):10,250—
    15history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 10 轮—第 1 轮 acc .1931 / val_acc .2086;第 4 轮 .2252val_acc ≈ .21 = 比 10 类随机 .1 好一点但没用
    16 epochs=10)fit 10 轮—第 1 轮 acc .1931 / val_acc .2086;第 4 轮 .2252val_acc ≈ .21 = 比 10 类随机 .1 好一点但没用
    17print(history_final_values(history))打印末值———
    运行结果 Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 170498071/170498071 ━━━━━━━━━━━━━━━━━━━━ 637s 4us/step /tmp/ipykernel_1451/4027265818.py:6: UserWarning: `input_shape` is undefined or non-square, or `rows` is not in [128, 160, 192, 224]. Weights for input shape (224, 224) will be loaded as the default. base_model = mobilenet.MobileNet(weights="imagenet", include_top=False, Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet/mobilenet_1_0_224_tf_no_top.h5 17225924/17225924 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step Epoch 1/10 98/98 - 27s - 278ms/step - acc: 0.1931 - loss: 2.1879 - val_acc: 0.2086 - val_loss: 2.1459 Epoch 2/10 98/98 - 40s - 410ms/step - acc: 0.2146 - loss: 2.1359 - val_acc: 0.2146 - val_loss: 2.1320 Epoch 3/10 98/98 - 24s - 243ms/step - acc: 0.2204 - loss: 2.1211 - val_acc: 0.2144 - val_loss: 2.1257 Epoch 4/10 98/98 - 24s - 246ms/step - acc: 0.2252 - loss: 2.1113 - val_acc: 0.2158 -
    迁移学习四步曲在本 cell 的对应:① L4–L5 preprocess_input;② L8 冻结;③ L9–L14 加头;④ L15 训练。为什么 @32 失败:MobileNet 内部有 5 次 stride-2 下采样(224 → 112 → 56 → 28 → 14 → 7),输入 32 → 1×1×1024;每张特征图只剩 1 个数,Flatten 后是 1024 维"全局平均池化向量"——没有任何空间位置信息,Dense 头只能靠"有没有某种纹理"分类,CIFAR 类别间的纹理差异不够 → .21。解法:放大输入(Q1)。

    The performance of this model is poor. Note the warning message in the execution output: the number of "rows", which is 32 in the model, is not one of 128, 160, 192, 224. In other words, MobileNet expects the input size to be one of these four values.

    读 warning:"rows is not in [128, 160, 192, 224]. Weights for input shape (224, 224) will be loaded as the default"——权重照常加载(卷积核尺寸固定),但 MobileNet 的每一层 stride-2 下采样是按 224 设计的;输入 32 经过 5 次 /2 只剩 1×1,最后的 1024 张特征图各只有 1 个值 → Flatten 后 1024 维 → 几乎没有可分类的空间结构。解法:把输入放大到 ≥128(Q1a/Q1b)。

    Up-sampling and resizing images


    In this section, we modify the input images to sizes that MobileNet expects to work with.

    Practice - Question 1 of 2

    Q1a


    Modify the above provided MobileNet transfer learning model to up-sample the input images to 128&times;128. Specifically, make these changes:


  • in the `MobileNet` creation, set the `input_shape` argument to `(128, 128, 3)` instead of `(32, 32, 3)`;
  • in the `model` creation, add an up-sampling layer `layers.UpSampling2D(size=(4, 4))` as the very first layer, i.e. before `base_model`; and
  • (optional) change the call to `compile_and_fit_model()` to add the argument `epochs=3` to reduce execution time.
  • Cell 20Q1a 学生作答:UpSampling2D(4,4) → 128 → val_acc .87练习·作答
    from tensorflow.keras.applications import mobilenet
    
    X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)
    X_train = mobilenet.preprocess_input(X_train)
    X_test  = mobilenet.preprocess_input(X_test)
    
    base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,
                                     input_shape=(128, 128, 3))
    base_model.trainable = False
    
    model = keras.Sequential([
        layers.UpSampling2D(size=(4, 4)),   # 32 -> 128
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=3)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1from tensorflow.keras.applications import mobilenet导入同 C15——
    3X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)载入 + preprocess同 C15X (25000,32,32,3)—
    4X_train = mobilenet.preprocess_input(X_train)载入 + preprocess同 C15X (25000,32,32,3)—
    5X_test = mobilenet.preprocess_input(X_test)载入 + preprocess同 C15X (25000,32,32,3)—
    7base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,MobileNet input_shape=(128,128,3)题目改动 ①:告知模型输入是 128下载 mobilenet_1_0_128_tf_no_top.h5;输出 (4,4,1024)权重文件按尺寸不同——因为 MobileNet 的权重含 reshape 层参数
    8 input_shape=(128, 128, 3))MobileNet input_shape=(128,128,3)题目改动 ①:告知模型输入是 128下载 mobilenet_1_0_128_tf_no_top.h5;输出 (4,4,1024)权重文件按尺寸不同——因为 MobileNet 的权重含 reshape 层参数
    9base_model.trainable = False冻结———
    11model = keras.Sequential([开始 Sequential———
    12 layers.UpSampling2D(size=(4, 4)), # 32 -> 128layers.UpSampling2D(size=(4,4))题目改动 ②:放在最前;每个像素复制成 4×4 → 32→128;最近邻、无参数(None,128,128,3)必须在 base_model 之前;size 是 (行,列) 倍数
    13 base_model,base / Flatten / DenseFlatten 4×4×1024 = 16,384Dense(1024) 16,779,264—
    14 layers.Flatten(),base / Flatten / DenseFlatten 4×4×1024 = 16,384Dense(1024) 16,779,264—
    15 layers.Dense(1024, activation="relu"),base / Flatten / DenseFlatten 4×4×1024 = 16,384Dense(1024) 16,779,264—
    16 layers.Dense(10, activation="softmax")base / Flatten / DenseFlatten 4×4×1024 = 16,384Dense(1024) 16,779,264—
    17])结束———
    19history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 3 轮题目改动 ③(可选):缩短时间第 1 轮 acc .7266 / val_acc .8520;第 3 轮 ≈ .87第 1 轮 loss 5.28 偏大——初始权重随机、头很大
    20 epochs=3)fit 3 轮题目改动 ③(可选):缩短时间第 1 轮 acc .7266 / val_acc .8520;第 3 轮 ≈ .87第 1 轮 loss 5.28 偏大——初始权重随机、头很大
    21print(history_final_values(history))打印———
    运行结果 Downloading data from https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz 170498071/170498071 ━━━━━━━━━━━━━━━━━━━━ 761s 4us/step Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet/mobilenet_1_0_128_tf_no_top.h5 17225924/17225924 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step Epoch 1/3 98/98 - 63s - 645ms/step - acc: 0.7266 - loss: 5.2795 - val_acc: 0.8520 - val_loss: 0.4404 Epoch 2/3 98/98 - 6s - 66ms/step - acc: 0.8986 - loss: 0.2967 - val_acc: 0.8662 - val_loss: 0.3928 Epoch 3/3 98/98 - 6s - 6
    Q1a 你的作答核对:三处改动全部正确 ✔。val_acc 从 .21 → .87——证明 @32 的问题就是空间信息丢失。

    Q1b


    Modify the above provided MobileNet transfer learning model to up-sample the input images to 224&times;224. Specifically, make these changes:


  • in the `MobileNet` creation, set the `input_shape` argument to `(224, 224, 3)` instead of `(32, 32, 3)`;
  • in the `model` creation, add an up-sampling layer `layers.UpSampling2D(size=(7, 7))` as the very first layer, i.e. before `base_model`; and
  • (optional) change the call to `compile_and_fit_model()` to add the argument `epochs=3` to reduce execution time.
  • Cell 22Q1b 学生作答:UpSampling2D(7,7) → 224 → val_acc .83练习·作答
    base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,
                                     input_shape=(224, 224, 3))
    base_model.trainable = False
    
    model = keras.Sequential([
        layers.UpSampling2D(size=(7, 7)),   # 32 -> 224
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=3)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,MobileNet input_shape=(224,224,3)224 是 MobileNet 原生尺寸,无 warning下载 mobilenet_1_0_224_tf_no_top.h5;输出 (7,7,1024)—
    2 input_shape=(224, 224, 3))MobileNet input_shape=(224,224,3)224 是 MobileNet 原生尺寸,无 warning下载 mobilenet_1_0_224_tf_no_top.h5;输出 (7,7,1024)—
    3base_model.trainable = False冻结———
    5model = keras.Sequential([Sequential———
    6 layers.UpSampling2D(size=(7, 7)), # 32 -> 224UpSampling2D(size=(7,7))32×7 = 224(None,224,224,3)—
    7 base_model,base / Flatten / DenseFlatten 7×7×1024 = 50,176Dense(1024) 51,381,248——参数爆炸—
    8 layers.Flatten(),base / Flatten / DenseFlatten 7×7×1024 = 50,176Dense(1024) 51,381,248——参数爆炸—
    9 layers.Dense(1024, activation="relu"),base / Flatten / DenseFlatten 7×7×1024 = 50,176Dense(1024) 51,381,248——参数爆炸—
    10 layers.Dense(10, activation="softmax")base / Flatten / DenseFlatten 7×7×1024 = 50,176Dense(1024) 51,381,248——参数爆炸—
    11])结束———
    13history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 3 轮每轮 20s(128 版 6s)第 1 轮 loss 16.01(梯度爆炸迹象);val_acc .8176 → .8282 → .8252比 128 版差且慢
    14 epochs=3)fit 3 轮每轮 20s(128 版 6s)第 1 轮 loss 16.01(梯度爆炸迹象);val_acc .8176 → .8282 → .8252比 128 版差且慢
    15print(history_final_values(history))打印{'acc': 0.949, 'loss': 0.1874, 'val_acc': 0.8252, 'val_loss': 0.5338}——
    运行结果 Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/mobilenet/mobilenet_1_0_224_tf_no_top.h5 17225924/17225924 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step Epoch 1/3 98/98 - 120s - 1s/step - acc: 0.6436 - loss: 16.0115 - val_acc: 0.8176 - val_loss: 0.5506 Epoch 2/3 98/98 - 20s - 207ms/step - acc: 0.8877 - loss: 0.3405 - val_acc: 0.8282 - val_loss: 0.4945 Epoch 3/3 98/98 - 20s - 207ms/step - acc: 0.9490 - loss: 0.1874 - val_acc: 0.8252 - val_loss: 0.5338 {'acc': 0.949, 'loss': 0.1874, 'val_acc': 0.8252, 'val_loss': 0.5338}
    读数:训练 acc .949 < 128 版?——C20 输出被截断看不到末值,但 val_acc .8252 < .87。M23 的结论 "128 works better than 224" 成立。注意本 cell 没有重新载入数据——复用 C20 的 X_train/X_test(已在内存里,preprocess 过),这是合法的。

    Both models with up-sampling have good performance. Among the two, the model that up-samples input to 128&times;128 works better than the one that up-samples input to 224&times;224.

    Q1a/Q1b 结果对比(128 vs 224):128:val_acc .852 → .866 → .87,val_loss .44 → .39 → .40;224:.818 → .828 → .825,val_loss .55 → .49 → .53。128 更好且快 3 倍(6s/轮 vs 20s/轮)。原因:① CIFAR 本身是 32×32 低分辨率图,放大到 224 只是重复像素 7 次,没有新信息,反而让 MobileNet 的高层(期望看到精细纹理)收到模糊输入;② 224 的 Flatten 维度 7×7×1024 = 50,176 是 128 的 3 倍,Dense(1024) 参数 5,138 万 → 更容易过拟合(第 1 轮 loss 16.0 vs 5.3 就是初始梯度爆炸的迹象)。

    Q1c


    Up-sampling is one way to adapt the example size to the expected input size of a pre-trained model. For images, up-sampling works by repeating each pixel multiple times. Therefore, the target size must be a multiple of the original image size.


    Another way to adapt the data size is resizing the images. Resizing applies interpolation and does not enforce a relation between the target size and the original size. However, interpolation demands more processing, and resizing is generally slower.

    UpSampling2D vs Resizing(Unit 9 讲义 p22–p24):UpSampling2D(size=(4,4))——最近邻重复:每个像素复制成 4×4 块,纯内存操作、无参数、极快;要求目标尺寸是原尺寸的整数倍(32→128)。Resizing(128,128)——双线性插值:新生成的像素是相邻像素的加权平均,图像更平滑;任意目标尺寸都行,但计算量大一点。Q1c/Q1d 结果:Resizing 128 val_acc .853 / 224 .852——与上采样相当(128)或略好(224:.852 vs .825)。M31 说 "Both models with resizing perform better"——按 val_loss 看 128:.4604 vs .3928(上采样反而好);224:.5618 vs .5338(上采样好)。结论应写 "comparable",不要写死。

    Modify the model in Q1a to use layers.Resizing(128, 128) as the first layer (instead of the UpSampling2D layer).

    Cell 26Q1c 学生作答:Resizing(128,128) → val_acc .853练习·作答
    base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,
                                     input_shape=(128, 128, 3))
    base_model.trainable = False
    
    model = keras.Sequential([
        layers.Resizing(128, 128),   #  32 -> 128
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=3)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,MobileNet 128同 C20——
    2 input_shape=(128, 128, 3))MobileNet 128同 C20——
    3base_model.trainable = False冻结———
    5model = keras.Sequential([Sequential———
    6 layers.Resizing(128, 128), # 32 -> 128layers.Resizing(128,128)双线性插值到任意尺寸;无参数;对 tf.data 或 numpy 输入都可(None,128,128,3)Resizing 参数是 (height, width);插值方法默认 bilinear,可 interpolation="nearest"/"bicubic"
    7 base_model,base / Flatten / Dense同 C20——
    8 layers.Flatten(),base / Flatten / Dense同 C20——
    9 layers.Dense(1024, activation="relu"),base / Flatten / Dense同 C20——
    10 layers.Dense(10, activation="softmax")base / Flatten / Dense同 C20——
    11])结束———
    13history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 3 轮每轮 7s(比上采样 6s 略慢)val_acc .8552 → .8664 → .8530—
    14 epochs=3)fit 3 轮每轮 7s(比上采样 6s 略慢)val_acc .8552 → .8664 → .8530—
    15print(history_final_values(history))打印{'acc': 0.9514, 'loss': 0.153, 'val_acc': 0.853, 'val_loss': 0.4604}与上采样 128 的 .87 相当—
    运行结果 Epoch 1/3 98/98 - 19s - 189ms/step - acc: 0.7410 - loss: 3.3742 - val_acc: 0.8552 - val_loss: 0.4324 Epoch 2/3 98/98 - 7s - 70ms/step - acc: 0.9151 - loss: 0.2556 - val_acc: 0.8664 - val_loss: 0.3973 Epoch 3/3 98/98 - 7s - 70ms/step - acc: 0.9514 - loss: 0.1530 - val_acc: 0.8530 - val_loss: 0.4604 {'acc': 0.9514, 'loss': 0.153, 'val_acc': 0.853, 'val_loss': 0.4604}

    Q1d


    Modify the model in Q1b to use layers.Resizing(224, 224) as the first layer (instead of the UpSampling2D layer).

    Cell 28Q1d 学生作答:Resizing(224,224) → val_acc .852练习·作答
    base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,
                                     input_shape=(224, 224, 3))
    base_model.trainable = False
    
    model = keras.Sequential([
        layers.Resizing(224, 224),
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=3)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1base_model = mobilenet.MobileNet(weights="imagenet", include_top=False,MobileNet 224———
    2 input_shape=(224, 224, 3))MobileNet 224———
    3base_model.trainable = False冻结———
    5model = keras.Sequential([Sequential———
    6 layers.Resizing(224, 224),Resizing(224,224)插值到 224(None,224,224,3)—
    7 base_model,base / Flatten / Dense50,176 → Dense(1024) 51.4M——
    8 layers.Flatten(),base / Flatten / Dense50,176 → Dense(1024) 51.4M——
    9 layers.Dense(1024, activation="relu"),base / Flatten / Dense50,176 → Dense(1024) 51.4M——
    10 layers.Dense(10, activation="softmax")base / Flatten / Dense50,176 → Dense(1024) 51.4M——
    11])结束———
    13history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 3 轮每轮 21sval_acc .8508 → .8448 → .8516——比上采样 224 的 .825 好插值后的 224 图比重复像素的 224 图更"像"ImageNet
    14 epochs=3)fit 3 轮每轮 21sval_acc .8508 → .8448 → .8516——比上采样 224 的 .825 好插值后的 224 图比重复像素的 224 图更"像"ImageNet
    15print(history_final_values(history))打印{'acc': 0.9214, 'loss': 0.2308, 'val_acc': 0.8516, 'val_loss': 0.5618}——
    运行结果 Epoch 1/3 98/98 - 34s - 344ms/step - acc: 0.7135 - loss: 11.2236 - val_acc: 0.8508 - val_loss: 0.4616 Epoch 2/3 98/98 - 21s - 211ms/step - acc: 0.9191 - loss: 0.2378 - val_acc: 0.8448 - val_loss: 0.5282 Epoch 3/3 98/98 - 21s - 210ms/step - acc: 0.9214 - loss: 0.2308 - val_acc: 0.8516 - val_loss: 0.5618 {'acc': 0.9214, 'loss': 0.2308, 'val_acc': 0.8516, 'val_loss': 0.5618}
    Cell 29挂载 Google Drive(首次,示范)导入·绘图·输出
    from google.colab import drive
    drive.mount('/content/drive')
    #代码作用机制·语法关联·结果易错点
    1from google.colab import drivefrom google.colab import driveColab 专有模块;本地 Jupyter 会 ImportError—只在 Colab 能跑——C35 用 try/except 包起来
    2drive.mount('/content/drive')drive.mount("/content/drive")把 Drive 挂载到 VM 的 /content/drive;首次会弹授权窗口Mounted at /content/drive授权后 Drive 文件在 /content/drive/MyDrive/...
    运行结果 Mounted at /content/drive

    &#x2766;

    Both models with resizing perform better than the models with up-sampling.

    Using Google drive and data augmentation

    In this section, we connect to Google drive in a Colab notebook and try data augmentation.


    Two zip files are required: cats20.zip and dogs20.zip. They contain some images from the Kaggle Cats and Dogs Dataset, <https://www.microsoft.com/en-us/download/details.aspx?id=54765>. The task is binary classification.


    For execution in Colab, put the two zip files in the root directory of your Google drive. For execution in a (local) Jupyter server, put the two zip files in the same directory as the notebook file.

    为什么只有 40 张图:cats20.zip / dogs20.zip 各 20 张——故意用极小数据集演示"数据少 → 迁移学习 + 数据增强"的场景。真实 Kaggle 猫狗有 25,000 张。C43 发现 42 个 ._ 文件:macOS 在 zip 里附带资源分叉文件,Colab 解压后 image_dataset_from_directory 把它们当图片读 → 报错或被算进 "80 files"。C44 删掉后正常 "40 files"。

    The following code connects to the Google drive and mounts it to the directory "/content/drive" of the Colab VM. The try-catch construct handles the error when the notebook is executed in a non-Colab environment. In either case, proper constants are defined for the paths of the zip files and the dataset directory that the images will be extracted into.

    Cell 35挂载 Drive(try/except 版)+ 定义三个路径常量重点展开
    try:
        from google.colab import drive
        drive.mount("/content/drive")
        CATS_ZIP = "/content/drive/MyDrive/cats_dogs_dataset/cats20.zip"
        DOGS_ZIP = "/content/drive/MyDrive/cats_dogs_dataset/dogs20.zip"
        DATASET_DIR = "/content/cats_and_dogs_20"
    except:
        CATS_ZIP = "./cats20.zip"
        DOGS_ZIP = "./dogs20.zip"
        DATASET_DIR = "./cats_and_dogs_20"
    #代码作用机制·语法关联·结果易错点
    1try:try:尝试 Colab 路径;失败则进 except—裸 except: 会吞掉所有异常(含 KeyboardInterrupt 之外的)——生产代码应写 except ImportError
    2 from google.colab import drive导入 + 挂载Colab 下成功"Drive already mounted"(C29 已挂过)—
    3 drive.mount("/content/drive")导入 + 挂载Colab 下成功"Drive already mounted"(C29 已挂过)—
    4 CATS_ZIP = "/content/drive/MyDrive/cats_dogs_dataset/cats20.zip"CATS_ZIP / DOGS_ZIPDrive 上两个 zip 的绝对路径;MyDrive 是用户根目录—路径大小写敏感
    5 DOGS_ZIP = "/content/drive/MyDrive/cats_dogs_dataset/dogs20.zip"CATS_ZIP / DOGS_ZIPDrive 上两个 zip 的绝对路径;MyDrive 是用户根目录—路径大小写敏感
    6 DATASET_DIR = "/content/cats_and_dogs_20"DATASET_DIRColab VM 本地目录(不在 Drive 上——解压到本地更快)/content/cats_and_dogs_20—
    7except:except: 本地路径非 Colab 环境走这里:zip 与 notebook 同目录./cats20.zip 等本地运行前提:两个 zip 在 notebook 旁边
    8 CATS_ZIP = "./cats20.zip"except: 本地路径非 Colab 环境走这里:zip 与 notebook 同目录./cats20.zip 等本地运行前提:两个 zip 在 notebook 旁边
    9 DOGS_ZIP = "./dogs20.zip"except: 本地路径非 Colab 环境走这里:zip 与 notebook 同目录./cats20.zip 等本地运行前提:两个 zip 在 notebook 旁边
    10 DATASET_DIR = "./cats_and_dogs_20"except: 本地路径非 Colab 环境走这里:zip 与 notebook 同目录./cats20.zip 等本地运行前提:两个 zip 在 notebook 旁边
    运行结果 Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).

    Next, the images in the two zip files are extracted to the dataset directory. The sub-directory names, "cat" and "dog", will be the class names of the labels when the dataset is loaded.

    Cell 37Shell 命令:建目录、解压、列出重点展开
    !mkdir -p "$DATASET_DIR/cat"
    !mkdir -p "$DATASET_DIR/dog"
    !unzip -j -q -o "$CATS_ZIP" -d "$DATASET_DIR/cat"
    !unzip -j -q -o "$DOGS_ZIP" -d "$DATASET_DIR/dog"
    !ls -R "$DATASET_DIR"
    #代码作用机制·语法关联·结果易错点
    1!mkdir -p "$DATASET_DIR/cat"!mkdir -p "$DATASET_DIR/cat"! 前缀 = Jupyter 执行 shell;-p 自动建父目录且已存在不报错;"$VAR" 引用 Python 变量(Jupyter 会注入)两个空目录子目录名 = 类名(image_dataset_from_directory 的约定)
    2!mkdir -p "$DATASET_DIR/dog"!mkdir -p "$DATASET_DIR/cat"! 前缀 = Jupyter 执行 shell;-p 自动建父目录且已存在不报错;"$VAR" 引用 Python 变量(Jupyter 会注入)两个空目录子目录名 = 类名(image_dataset_from_directory 的约定)
    3!unzip -j -q -o "$CATS_ZIP" -d "$DATASET_DIR/cat"!unzip -j -q -o "$CATS_ZIP" -d "$DATASET_DIR/cat"-j 丢弃 zip 内的目录结构(只留文件);-q 安静;-o 覆盖已存在;-d 目标目录20 张猫图 → cat/没有 -j 会出现 cat/cats20/xxx.jpg 的嵌套,类名就变成 cats20
    4!unzip -j -q -o "$DOGS_ZIP" -d "$DATASET_DIR/dog"同样解压狗图—20 张 → dog/—
    5!ls -R "$DATASET_DIR"!ls -R "$DATASET_DIR"递归列出看到 cat/ 和 dog/ 各 20 个 jpg输出里若有 ._xxx.jpg 就是 macOS 垃圾文件(C43 的伏笔)
    运行结果 /content/cats_and_dogs_20: cat dog /content/cats_and_dogs_20/cat: 10000.jpg 10003.jpg 10006.jpg 10009.jpg 10012.jpg 10015.jpg 10018.jpg 10001.jpg 10004.jpg 10007.jpg 10010.jpg 10013.jpg 10016.jpg 10019.jpg 10002.jpg 10005.jpg 10008.jpg 10011.jpg 10014.jpg 10017.jpg /content/cats_and_dogs_20/dog: 10000.jpg 10003.jpg 10006.jpg 10009.jpg 10012.jpg 10015.jpg 10018.jpg 10001.jpg 10004.jpg 10007.jpg 10010.jpg 10013.jpg 10016.jpg 10019.jpg 10002.jpg 10005.jpg 10008.jpg 10011.jpg 10014.jpg 10017.jpg

    The Google drive is disconnected, as it is no longer needed.

    Cell 39卸载 Drive基础
    try:
        drive.flush_and_unmount()
    except:
        pass
    #代码作用机制·语法关联·结果易错点
    1try:try + drive.flush_and_unmount()把缓存写回 Drive 并卸载无输出已解压完,不再需要 Drive
    2 drive.flush_and_unmount()try + drive.flush_and_unmount()把缓存写回 Drive 并卸载无输出已解压完,不再需要 Drive
    3except:except: pass非 Colab 环境 drive 未定义 → NameError → 忽略—pass = 什么都不做
    4 passexcept: pass非 Colab 环境 drive 未定义 → NameError → 忽略—pass = 什么都不做

    The following code loads the images from the dataset directory, and splits them into a training set and a validation set as two TensorFlow Dataset objects. The argument labels="inferred" specifies to use the sub-directory names as the label names. By default, the image_dataset_from_directory() function automatically resizes the images to 256x256.

    image_dataset_from_directory 的约定(Unit 9 讲义 p27):目录结构 = 标签:DATASET_DIR/cat/*.jpg → 类 "cat",DATASET_DIR/dog/*.jpg → 类 "dog"(labels="inferred" 按子目录名推断,按字母序编码:cat=0, dog=1)。validation_split=0.3, subset="both" 一次返回 (train_ds, val_ds) 两个 tf.data.Dataset;seed=42 固定打乱。默认 image_size=(256,256)(C45 没传,所以是 256,这就是 C48 要加 Resizing(224) 的原因)、batch_size=32——28 张 → 1 个 batch;像素值 0–255 的 float(所以 C48 要 Rescaling)。与 numpy 的区别:Dataset 是惰性的迭代器,.take(1) 取一个 batch,len(train_ds) 是 batch 数(C45 显示 1)。
    Cell 41image_dataset_from_directory:从目录建 tf.data.Dataset(首次,读到 80 个文件)重点展开
    import tensorflow as tf
    
    train_ds, val_ds = tf.keras.utils.image_dataset_from_directory(
        DATASET_DIR, labels="inferred", seed=42,
        validation_split=0.3, subset="both",image_size=(224,224))
    #代码作用机制·语法关联·结果易错点
    1import tensorflow as tfimport tensorflow as tfC7 只导了 keras;这里要 tf.data 相关功能——
    3train_ds, val_ds = tf.keras.utils.image_dataset_from_directory(tf.keras.utils.image_dataset_from_directory(...)参数:DATASET_DIR;labels="inferred" 子目录名=类名;seed=42;validation_split=0.3;subset="both" 返回 (train, val);image_size=(224,224) 指定尺寸"Found 80 files belonging to 2 classes. Using 56 for training. Using 24 for validation."80 = 40 张图 + 40 个 ._ 垃圾文件(42 个 ._ 中有 2 个可能是目录级)——学生为此排查(C43)
    4 DATASET_DIR, labels="inferred", seed=42,tf.keras.utils.image_dataset_from_directory(...)参数:DATASET_DIR;labels="inferred" 子目录名=类名;seed=42;validation_split=0.3;subset="both" 返回 (train, val);image_size=(224,224) 指定尺寸"Found 80 files belonging to 2 classes. Using 56 for training. Using 24 for validation."80 = 40 张图 + 40 个 ._ 垃圾文件(42 个 ._ 中有 2 个可能是目录级)——学生为此排查(C43)
    5 validation_split=0.3, subset="both",image_size=(224,224))tf.keras.utils.image_dataset_from_directory(...)参数:DATASET_DIR;labels="inferred" 子目录名=类名;seed=42;validation_split=0.3;subset="both" 返回 (train, val);image_size=(224,224) 指定尺寸"Found 80 files belonging to 2 classes. Using 56 for training. Using 24 for validation."80 = 40 张图 + 40 个 ._ 垃圾文件(42 个 ._ 中有 2 个可能是目录级)——学生为此排查(C43)
    运行结果 Found 80 files belonging to 2 classes. Using 56 files for training. Using 24 files for validation.
    80 ≠ 40:M33 说每个 zip 20 张,总共 40。但 Colab 输出 "Found 80 files"——说明目录里有 40 个额外文件。C43 的排查找到了 42 个 ._*.jpg(macOS 资源分叉:__MACOSX 或 Finder 复制产生的元数据文件,unzip -j 把它们当普通文件解出来)。这些文件不是图片,image_dataset_from_directory 在真正读取时会报 "cannot identify image file"。根因:zip 是在 macOS 上打的,没加 XZIP/-x "._*" 排除。

    Let's look at some images and labels in the training set.

    Cell 43学生自加:扫描坏图片(PIL verify)练习·作答
    import os
    from PIL import Image
    
    bad_files = []
    for root, dirs, files in os.walk(DATASET_DIR):
        for f in files:
            path = os.path.join(root, f)
            try:
                img = Image.open(path)
                img.verify()
            except Exception as e:
                bad_files.append((path, str(e)))
    
    print("坏文件数量:", len(bad_files))
    for p, err in bad_files:
        print(p, "->", err)
    #代码作用机制·语法关联·结果易错点
    1import os导入 os / PIL.ImagePillow 读图库—PIL 是 Colab 预装的;本地 pip install Pillow
    2from PIL import Image导入 os / PIL.ImagePillow 读图库—PIL 是 Colab 预装的;本地 pip install Pillow
    4bad_files = []bad_files = []收集 (路径, 错误信息)——
    5for root, dirs, files in os.walk(DATASET_DIR):os.walk(DATASET_DIR)递归遍历:每层返回 (root, dirs, files)——
    6 for f in files:遍历文件、拼路径os.path.join 跨平台——
    7 path = os.path.join(root, f)遍历文件、拼路径os.path.join 跨平台——
    8 try:try: Image.open + verify()open 懒加载;verify() 检查文件头完整性但不解码像素正常 jpg 通过;._ 文件抛 UnidentifiedImageErrorverify() 之后 img 不能再用——需要重新 open
    9 img = Image.open(path)try: Image.open + verify()open 懒加载;verify() 检查文件头完整性但不解码像素正常 jpg 通过;._ 文件抛 UnidentifiedImageErrorverify() 之后 img 不能再用——需要重新 open
    10 img.verify()try: Image.open + verify()open 懒加载;verify() 检查文件头完整性但不解码像素正常 jpg 通过;._ 文件抛 UnidentifiedImageErrorverify() 之后 img 不能再用——需要重新 open
    11 except Exception as e:except: 记录Exception as e 捕获所有bad_files.append((path, str(e)))—
    12 bad_files.append((path, str(e)))except: 记录Exception as e 捕获所有bad_files.append((path, str(e)))—
    14print("坏文件数量:", len(bad_files))打印坏文件数—坏文件数量: 4242 个 ._ 文件
    15for p, err in bad_files:逐个打印—都是 ._xxxxx.jpg → "cannot identify image file"—
    16 print(p, "->", err)逐个打印—都是 ._xxxxx.jpg → "cannot identify image file"—
    运行结果 坏文件数量: 42 /content/cats_and_dogs_20/dog/._10006.jpg -> cannot identify image file '/content/cats_and_dogs_20/dog/._10006.jpg' /content/cats_and_dogs_20/dog/._10017.jpg -> cannot identify image file '/content/cats_and_dogs_20/dog/._10017.jpg' /content/cats_and_dogs_20/dog/._10005.jpg -> cannot identify image file '/content/cats_and_dogs_20/dog/._10005.jpg' /content/cats_and_dogs_20/dog/._10010.jpg -> cannot identify image file '/content/cats_and_dogs_20/dog/._10010.jpg' /content/cats_and_dogs_20/dog/._10008.jpg -> cannot identify image file '/content/cats_and_dogs_20/dog/._10008.jpg' /content/c
    这是你自己加的排查 cell——做得好:面对 "Found 80 files" 的异常没有放过,而是写了扫描脚本定位根因。改进建议:① 直接用 !find ... -name "._*" -type f -delete(C44 就是这么做的)更直接;② 更根本的解法是在 macOS 打 zip 时用 zip -r -X 或 ZIPINFO 排除,或者解压时 unzip -x "._*" "__MACOSX/*";③ 这个 cell 的 import Image 在 Colab 里是 from PIL import Image ✔。
    Cell 44学生自加:删除 ._ 垃圾文件练习·作答
    !find /content/cats_and_dogs_20 -name "._*" -type f -delete
    #代码作用机制·语法关联·结果易错点
    1!find /content/cats_and_dogs_20 -name "._*" -type f -delete!find /content/cats_and_dogs_20 -name "._*" -type f -deletefind:-name 匹配 "._" 开头;-type f 只删普通文件;-delete 直接删除无输出硬编码路径而不是 $DATASET_DIR——换环境要改;-delete 不可恢复,先 -print 预览更安全
    Cell 45重建 Dataset(清理后:40 个文件)重点展开
    import tensorflow as tf
    
    train_ds, val_ds = tf.keras.utils.image_dataset_from_directory(
        DATASET_DIR, labels="inferred", class_names=["cat", "dog"], seed=42,
        validation_split=0.3, subset="both")
    
    print(train_ds.class_names)
    print("train batches:", len(train_ds))
    print("val batches:", len(val_ds))
    #代码作用机制·语法关联·结果易错点
    1import tensorflow as tfimport tensorflow as tf重复导入无害——
    3train_ds, val_ds = tf.keras.utils.image_dataset_from_directory(image_dataset_from_directory(...)与 C41 的区别:加了 class_names=["cat","dog"] 显式指定类顺序;没传 image_size → 默认 (256,256)"Found 40 files... Using 28 for training. Using 12 for validation."40×0.7 = 28 ✔;class_names 显式写确保 cat=0 dog=1 不受字母序影响
    4 DATASET_DIR, labels="inferred", class_names=["cat", "dog"], seed=42,image_dataset_from_directory(...)与 C41 的区别:加了 class_names=["cat","dog"] 显式指定类顺序;没传 image_size → 默认 (256,256)"Found 40 files... Using 28 for training. Using 12 for validation."40×0.7 = 28 ✔;class_names 显式写确保 cat=0 dog=1 不受字母序影响
    5 validation_split=0.3, subset="both")image_dataset_from_directory(...)与 C41 的区别:加了 class_names=["cat","dog"] 显式指定类顺序;没传 image_size → 默认 (256,256)"Found 40 files... Using 28 for training. Using 12 for validation."40×0.7 = 28 ✔;class_names 显式写确保 cat=0 dog=1 不受字母序影响
    7print(train_ds.class_names)print(train_ds.class_names)Dataset 对象的属性:类名列表['cat', 'dog']—
    8print("train batches:", len(train_ds))print len(train_ds) / len(val_ds)len(Dataset) = batch 数,不是样本数train batches: 1 / val batches: 128 张 / batch_size 32 = 1 个 batch;每轮只有 1 步——"1/1" 的来源
    9print("val batches:", len(val_ds))print len(train_ds) / len(val_ds)len(Dataset) = batch 数,不是样本数train batches: 1 / val batches: 128 张 / batch_size 32 = 1 个 batch;每轮只有 1 步——"1/1" 的来源
    运行结果 Found 40 files belonging to 2 classes. Using 28 files for training. Using 12 files for validation. ['cat', 'dog'] train batches: 1 val batches: 1
    Cell 46看 9 张训练图 + 标签导入·绘图·输出
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(10, 10))
    for images, labels in train_ds.take(1):
        for i in range(min(9,len(images))):
            ax = plt.subplot(3, 3, i + 1)
            plt.imshow(images[i].numpy().astype("uint8"))
            plt.title(train_ds.class_names[labels[i]])
            plt.axis("off")
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as pltimport pyplot———
    3plt.figure(figsize=(10, 10))10×10 画布———
    4for images, labels in train_ds.take(1):for images, labels in train_ds.take(1)take(1) 取第 1 个 batch;images (28,256,256,3) labels (28,)—Dataset 迭代得到的是 batch 不是单张
    5 for i in range(min(9,len(images))):前 9 张min 防越界——
    6 ax = plt.subplot(3, 3, i + 1)3×3 子图———
    7 plt.imshow(images[i].numpy().astype("uint8"))plt.imshow(images[i].numpy().astype("uint8"))EagerTensor → numpy → uint8(0–255)才能显示—不转 uint8 会显示全白(float 0–255 被当 0–1 clip)
    8 plt.title(train_ds.class_names[labels[i]])标题 = class_names[labels[i]]labels[i] 是 0/1 的 tensor → 索引类名—labels[i] 是 tensor,索引 list 时会自动转 int
    9 plt.axis("off")关闭坐标轴—
    —
    运行结果 <Figure size 1000x1000 with 9 Axes> [image/png]

    The following model applies transfer learning with MobileNet, with input size 224x224. Note that input pixel value normalization and image resizing are performed in the second and third layers of the Keras model.

    Cell 48猫狗模型母版:Input → Rescaling → Resizing → MobileNet → Flatten → Dense(1,sigmoid)重点展开
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.applications import mobilenet
    
    keras.utils.set_random_seed(42)
    IMG_WIDTH, IMG_HEIGHT = 224, 224  # Mobilenet input size
    
    base_model = mobilenet.MobileNet(
        weights="imagenet", include_top=False,
        input_shape=(IMG_HEIGHT, IMG_WIDTH, 3))
    base_model.trainable = False
    model = keras.Sequential([
        layers.Input(shape=(256, 256, 3)),
        layers.Rescaling(1./255),  # rescale image pixel values
        layers.Resizing(IMG_HEIGHT, IMG_WIDTH),  # resize image width and height
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(1, activation="sigmoid")
    ])
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入———
    2from tensorflow.keras import layers导入———
    3from tensorflow.keras.applications import mobilenet导入———
    5keras.utils.set_random_seed(42)种子———
    6IMG_WIDTH, IMG_HEIGHT = 224, 224 # Mobilenet input sizeIMG_WIDTH, IMG_HEIGHT = 224, 224常量便于改—元组赋值
    8base_model = mobilenet.MobileNet(MobileNet(input_shape=(224,224,3))原生尺寸;Dataset 给 256,所以要先 Resizing 到 224输出 (7,7,1024)—
    9 weights="imagenet", include_top=False,MobileNet(input_shape=(224,224,3))原生尺寸;Dataset 给 256,所以要先 Resizing 到 224输出 (7,7,1024)—
    10 input_shape=(IMG_HEIGHT, IMG_WIDTH, 3))MobileNet(input_shape=(224,224,3))原生尺寸;Dataset 给 256,所以要先 Resizing 到 224输出 (7,7,1024)—
    11base_model.trainable = False冻结———
    12model = keras.Sequential([Sequential———
    13 layers.Input(shape=(256, 256, 3)),layers.Input(shape=(256,256,3))显式声明输入:Dataset 的 image_size 默认 256;这里不能省——因为后面 Resizing 需要知道输入尺寸—与 C15 的区别:C15 的第一层是 base_model(能推断输入);这里第一层是 Rescaling(不能),所以要 Input
    14 layers.Rescaling(1./255), # rescale image pixel valueslayers.Rescaling(1./255)像素 0–255 → [0,1];Dataset 给的是未缩放的 float—这里用 1/255 而不是 preprocess_input:Dataset 已经是 RGB float,且 MobileNet 在 Keras 里的权重是 tf 版(文件名 _tf_),官方示例用 Rescaling(1/127.5, offset=-1) 或 1/255;本课用 1/255 简化
    15 layers.Resizing(IMG_HEIGHT, IMG_WIDTH), # resize image width and heightlayers.Resizing(224, 224)256 → 224(None,224,224,3)—
    16 base_model,base_model(None,7,7,1024)冻结—
    17 layers.Flatten(),Flatten50,176——
    18 layers.Dense(1024, activation="relu"),Dense(1024, relu)分类头——51,381,248 参数,占 99.99%—40 张图配 5,000 万参数 = 必然过拟合
    19 layers.Dense(1, activation="sigmoid")Dense(1, sigmoid)二分类:1 个输出 + sigmoid;不是 Dense(2,softmax)1,025配 binary_crossentropy(C50)
    20])结束——本 cell 只建模型不训练(题目让分两步)
    这个模型的三层"预处理"对比 t05–t08 的手动预处理:t05 在 load 函数里 astype/255 + reshape;这里把预处理做进模型(Rescaling、Resizing 是 Keras 层)。好处:① 部署时模型自带预处理,不用在外部重复;② 与数据增强层一样,推理时也能用;③ 能进 plot_model/summary。代价:每步都在 GPU 上做、稍慢;且 Dataset 不能提前 cache 预处理结果。

    The model is compiled and trained next.

    Cell 50compile:binary_crossentropy基础
    model.compile(loss="binary_crossentropy",
                  optimizer="adam", metrics=["acc"])
    #代码作用机制·语法关联·结果易错点
    1model.compile(loss="binary_crossentropy",compile(loss="binary_crossentropy")配 Dense(1,sigmoid) + 0/1 标签—不能用 categorical_crossentropy——那需要 Dense(2) + one-hot
    2 optimizer="adam", metrics=["acc"])compile(loss="binary_crossentropy")配 Dense(1,sigmoid) + 0/1 标签—不能用 categorical_crossentropy——那需要 Dense(2) + one-hot
    Cell 51fit(train_ds, validation_data=val_ds):每轮 1 步重点展开
    history = model.fit(train_ds, validation_data=val_ds,
                        epochs=10, verbose=2)
    #代码作用机制·语法关联·结果易错点
    1history = model.fit(train_ds, validation_data=val_ds,model.fit(train_ds, ...)直接传 Dataset 对象(不是 X/y 数组)——Keras 会迭代它;不传 batch_size(Dataset 已分批)1/1 = 1 个 batch/轮传了 batch_size 会报错:"batch_size must be None when passing a Dataset"
    2 epochs=10, verbose=2)10 轮 verbose=2—val_acc 在 .42–.92 间剧烈跳动;val_loss 87每轮只有 28 个样本 1 步更新——权重震荡
    运行结果 Epoch 1/10 1/1 - 25s - 25s/step - acc: 0.5714 - loss: 1.2874 - val_acc: 0.5833 - val_loss: 89.3322 Epoch 2/10 1/1 - 0s - 161ms/step - acc: 0.4643 - loss: 76.4137 - val_acc: 0.9167 - val_loss: 2.7867 Epoch 3/10 1/1 - 0s - 158ms/step - acc: 1.0000 - loss: 4.6758e-21 - val_acc: 0.8333 - val_loss: 6.9220 Epoch 4/10 1/1 - 0s - 176ms/step - acc: 1.0000 - loss: 7.8298e-34 - val_acc: 0.5000 - val_loss: 31.3274 Epoch 5/10 1/1 - 0s - 173ms/step - acc: 0.9643 - loss: 0.7304 - val_acc: 0.4167 - val_loss: 45.9657 Epoch 6/10 1/1 - 0s - 173ms/step - acc: 1.0000 - loss: 2.4589e-20 - val_acc: 0.4167 - val_loss

    The training history is shown below. The validation accuracy is very poor, about 0.4. The graphs indicate severe overfitting of the model.

    val_loss 87 怎么读:12 张验证图、模型极度自信地错了几张——−log(p) 当 p→0 时趋于无穷,一张图 p=1e-38 就贡献 87。acc .4167 = 12 张对 5 张(比随机 50% 还差)。原因:① 28 张训练图 × 5,138 万参数的 Dense 头 → 瞬间 memorize(训练 loss 第 3 轮就是 4.7e-21);② 没有任何正则;③ 冻结的 MobileNet 特征是为 224 自然图像设计的,256→224 的猫狗照片本应合适,但头太大会把任何特征都能拟合。C55 全预测 0 = "cat":模型坍缩到多数类/常数输出。
    Cell 53打印末值 + 画图基础
    print(history_final_values(history))
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1print(history_final_values(history))打印{'acc': 1.0, 'loss': 0.0235, 'val_acc': 0.4167, 'val_loss': 87.3821}训练 acc 1.0 / 验证 .42——严重过拟合—
    2plot_history(history)画图loss 图的 val 线会飞出天际
    —
    运行结果 {'acc': 1.0, 'loss': 0.0235, 'val_acc': 0.4167, 'val_loss': 87.3821} <Figure size 800x400 with 2 Axes> [image/png]

    Let's use the model to do perform predictions anyway. The predicted results are probability values, and we use the threshold 0.5 to turn them into either 0 or 1.

    Cell 55预测:概率 → 0/1重点展开
    import numpy as np
    y_probs = model.predict(val_ds)
    print(y_probs.ravel().round(4))
    y_pred = np.where(y_probs.ravel() < 0.5, 0, 1)
    print(y_pred)
    #代码作用机制·语法关联·结果易错点
    1import numpy as npimport numpy———
    2y_probs = model.predict(val_ds)model.predict(val_ds)Dataset 直接喂;返回 (12,1)12 个概率—
    3print(y_probs.ravel().round(4))ravel + round(4)展平显示[0. 0. 0. …]——全 0!模型坍缩:全部预测 cat
    4y_pred = np.where(y_probs.ravel() < 0.5, 0, 1)np.where(probs < 0.5, 0, 1)阈值 0.5[0 0 0 …]全预测 0 → val_acc = 实际猫的比例 5/12 = .4167 ✔ 对上
    5print(y_pred)打印———
    运行结果 1/1 ━━━━━━━━━━━━━━━━━━━━ 2s 2s/step [0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [0 0 0 0 0 0 0 0 0 0 0 0]

    The predicted labels, actual labels, and corresponding images are shown below.

    Cell 57可视化预测 vs 真实(红字 = 错)导入·绘图·输出
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(10, 10))
    for images, labels in val_ds.take(1):
        for i in range(9):
            ax = plt.subplot(3, 3, i + 1)
            plt.imshow(images[i].numpy().astype("uint8"))
            title = "Actual: " + val_ds.class_names[labels[i]] + \
                " Predicted: " + val_ds.class_names[y_pred[i]]
            plt.title(title, color="k" if labels[i] == y_pred[i] else "r")
            plt.axis("off")
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt画布———
    3plt.figure(figsize=(10, 10))画布———
    4for images, labels in val_ds.take(1):take(1)val_ds 12 张——
    5 for i in range(9):前 9 张 3×3———
    6 ax = plt.subplot(3, 3, i + 1)前 9 张 3×3———
    7 plt.imshow(images[i].numpy().astype("uint8"))imshow uint8———
    8 title = "Actual: " + val_ds.class_names[labels[i]] + \标题拼接:Actual + Predicted\ 续行;class_names[y_pred[i]] 把 0/1 转回 cat/dog—y_pred 是 numpy int,可直接索引
    9 " Predicted: " + val_ds.class_names[y_pred[i]]标题拼接:Actual + Predicted\ 续行;class_names[y_pred[i]] 把 0/1 转回 cat/dog—y_pred 是 numpy int,可直接索引
    10 plt.title(title, color="k" if labels[i] == y_pred[i] else "r")颜色:对黑错红labels[i] == y_pred[i] → "k" 否则 "r"全黑/全红—
    11 plt.axis("off")axis off—
    —
    运行结果 <Figure size 1000x1000 with 9 Axes> [image/png]

    The main reason for the poor results and overfitting is the very small size of the dataset -- 40 images in total. There are different ways of avoiding overfitting. One way is data augmentation, which we do below.

    过拟合的五种对策(Unit 9 讲义 p35):① 更多数据(本 Lab 做不到);② 数据增强(本节做);③ 正则化/dropout(t07);④ 减小模型(裁剪 VGG 块,E1);⑤ 迁移学习本身(冻结的卷积基已是强先验)。数据增强为什么对小数据集特别有效:每轮每张图随机翻转/旋转后都"不一样",28 张图 ≈ 无限多张,模型无法死记。

    Practice - Question 2 of 2

    Data augmentation modifies the training examples slightly to obtain more examples with limited variations. It works particularly well when very few training examples are available.


    Keras supplies layers that perform data augmentation, e.g. RandomFlip for flipping images and RandomRotation for rotating images.

    Keras 数据增强层的关键机制(Unit 9 讲义 p38):RandomFlip("horizontal")、RandomRotation(0.1) 是层而不是预处理步骤——它们在 fit 时(training=True)才随机变换,predict/evaluate 时(training=False)自动变成恒等映射。所以验证集不会被增强,训练/验证的不对称是设计使然。0.1 = 最大旋转 ±10% × 360° = ±36°。放在哪:Q2a 要求放在 Resizing 之后、base_model 之前(对 224 图做增强,与预训练模型的输入分布一致)。

    Q2a


    Modify the above Keras model for classifying cats and dogs as follows:


  • Create a "model" called `data_augmentation` that contains two layers of data augmentation (use code below), and
  • Insert `data_augmentation` into the Keras model between the resizing layer and the `base_model`.

  • data_augmentation = keras.Sequential([
        layers.RandomFlip("horizontal"),
        layers.RandomRotation(0.1),
    ])
    
    Cell 62Q2a 学生作答:加 data_augmentation(RandomFlip + RandomRotation)练习·作答
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.applications import mobilenet
    
    keras.utils.set_random_seed(42)
    IMG_WIDTH, IMG_HEIGHT = 224, 224  # MobileNet input size
    
    data_augmentation = keras.Sequential([
        layers.RandomFlip("horizontal"),
        layers.RandomRotation(0.1),
    ])
    
    base_model = mobilenet.MobileNet(
        weights="imagenet", include_top=False,
        input_shape=(IMG_HEIGHT, IMG_WIDTH, 3))
    base_model.trainable = False
    
    model = keras.Sequential([
        layers.Input(shape=(256, 256, 3)),
        layers.Rescaling(1./255),
        layers.Resizing(IMG_HEIGHT, IMG_WIDTH),
        data_augmentation,
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(1, activation="sigmoid")
    ])
    
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入———
    2from tensorflow.keras import layers导入———
    3from tensorflow.keras.applications import mobilenet导入———
    5keras.utils.set_random_seed(42)种子———
    6IMG_WIDTH, IMG_HEIGHT = 224, 224 # MobileNet input sizeIMG 尺寸———
    8data_augmentation = keras.Sequential([data_augmentation = Sequential([RandomFlip("horizontal"), RandomRotation(0.1)])一个独立的 Sequential 作为子模型;flip 水平翻转(猫狗左右对称,垂直翻转不合理);rotate ±36°无参数只在 training=True 时生效——fit 随机变换、predict 恒等
    9 layers.RandomFlip("horizontal"),data_augmentation = Sequential([RandomFlip("horizontal"), RandomRotation(0.1)])一个独立的 Sequential 作为子模型;flip 水平翻转(猫狗左右对称,垂直翻转不合理);rotate ±36°无参数只在 training=True 时生效——fit 随机变换、predict 恒等
    10 layers.RandomRotation(0.1),data_augmentation = Sequential([RandomFlip("horizontal"), RandomRotation(0.1)])一个独立的 Sequential 作为子模型;flip 水平翻转(猫狗左右对称,垂直翻转不合理);rotate ±36°无参数只在 training=True 时生效——fit 随机变换、predict 恒等
    11])data_augmentation = Sequential([RandomFlip("horizontal"), RandomRotation(0.1)])一个独立的 Sequential 作为子模型;flip 水平翻转(猫狗左右对称,垂直翻转不合理);rotate ±36°无参数只在 training=True 时生效——fit 随机变换、predict 恒等
    13base_model = mobilenet.MobileNet(MobileNet 224同 C48——
    14 weights="imagenet", include_top=False,MobileNet 224同 C48——
    15 input_shape=(IMG_HEIGHT, IMG_WIDTH, 3))MobileNet 224同 C48——
    16base_model.trainable = False冻结———
    18model = keras.Sequential([Sequential———
    19 layers.Input(shape=(256, 256, 3)),Input / Rescaling / Resizing同 C48——
    20 layers.Rescaling(1./255),Input / Rescaling / Resizing同 C48——
    21 layers.Resizing(IMG_HEIGHT, IMG_WIDTH),Input / Rescaling / Resizing同 C48——
    22 data_augmentation,data_augmentation题目要求:插在 Resizing 之后、base_model 之前(None,224,224,3)位置很重要:在 Resizing 前对 256 图增强也行,但在 base 后增强就错了
    23 base_model,base / Flatten / Dense(1024) / Dense(1)同 C48——
    24 layers.Flatten(),base / Flatten / Dense(1024) / Dense(1)同 C48——
    25 layers.Dense(1024, activation="relu"),base / Flatten / Dense(1024) / Dense(1)同 C48——
    26 layers.Dense(1, activation="sigmoid")base / Flatten / Dense(1024) / Dense(1)同 C48——
    27])结束———
    29model.summary()model.summary()验证结构Total 54,611,137 = 51,382,273 + 3,228,864Non-trainable 3,228,864 = MobileNet;Trainable 51,382,273 全在 Dense
    运行结果 Model: "sequential_6" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ rescaling_1 (Rescaling) │ (None, 256, 256, 3) │ 0 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ resizing_3 (Resizing) │ ([38;5;4  Total params: 54,611,137 (208.32 MB)  Trainable params: 51,382,273 (196.01 MB)  Non-trainable params: 3,228,864 (12.32 MB)
    Q2a 你的作答核对:正确 ✔——data_augmentation 两层、位置在 Resizing 后 base 前、其余与 C48 一致。

    Q2b


    Compile and train the model. Plot the training history.

    Cell 64Q2b 学生作答:compile + fit 10 轮练习·作答
    model.compile(loss="binary_crossentropy",
                  optimizer="adam", metrics=["acc"])
    
    history = model.fit(train_ds, validation_data=val_ds,
                        epochs=10, verbose=2)
    #代码作用机制·语法关联·结果易错点
    1model.compile(loss="binary_crossentropy",compile bce同 C50——
    2 optimizer="adam", metrics=["acc"])compile bce同 C50——
    4history = model.fit(train_ds, validation_data=val_ds,fit同 C51val_acc .58 → .67 → .58 → .83 → .83 → .83 …不再坍缩到全 0;训练 acc .68/.46/.82/.64/.96/1.0——增强让每轮数据都不同
    5 epochs=10, verbose=2)fit同 C51val_acc .58 → .67 → .58 → .83 → .83 → .83 …不再坍缩到全 0;训练 acc .68/.46/.82/.64/.96/1.0——增强让每轮数据都不同
    运行结果 Epoch 1/10 1/1 - 9s - 9s/step - acc: 0.6786 - loss: 0.7725 - val_acc: 0.5833 - val_loss: 54.7573 Epoch 2/10 1/1 - 0s - 177ms/step - acc: 0.4643 - loss: 45.1480 - val_acc: 0.6667 - val_loss: 14.2137 Epoch 3/10 1/1 - 0s - 176ms/step - acc: 0.8214 - loss: 9.9329 - val_acc: 0.5833 - val_loss: 26.5262 Epoch 4/10 1/1 - 0s - 187ms/step - acc: 0.6429 - loss: 13.4864 - val_acc: 0.8333 - val_loss: 3.4064 Epoch 5/10 1/1 - 0s - 178ms/step - acc: 0.9643 - loss: 1.8949 - val_acc: 0.8333 - val_loss: 4.7361 Epoch 6/10 1/1 - 0s - 173ms/step - acc: 1.0000 - loss: 1.3188e-20 - val_acc: 0.8333 - val_loss: 16.7789
    Cell 65Q2b:打印 + 画图基础
    print(history_final_values(history))
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1print(history_final_values(history))打印{'acc': 0.9643, 'loss': 2.524, 'val_acc': 0.8333, 'val_loss': 9.3132}val_acc .42 → .83—
    2plot_history(history)画图—
    —
    运行结果 {'acc': 0.9643, 'loss': 2.524, 'val_acc': 0.8333, 'val_loss': 9.3132} <Figure size 800x400 with 2 Axes> [image/png]

    With data augmentation, the validation results are improved.

    数据增强的效果:val_acc .4167 → .8333(12 张对 10 张);val_loss 87 → 9.3(仍高——剩下的 2 张错得很自信)。训练 acc .9643(不再 1.0)——增强让训练集"记不住"。还能怎么改:epoch 加到 30+、Dense(1024) 改小(256)或加 Dropout、加 base_model.trainable=True 微调最后几层(Unit 9 讲义 p49–p52 的 fine-tuning)。

    &#x2766;

    The improved model can be used to perform predictions as shown below.

    Cell 69增强后预测基础
    import numpy as np
    y_probs = model.predict(val_ds)
    print(y_probs.ravel().round(4))
    y_pred = np.where(y_probs.ravel() < 0.5, 0, 1)
    print(y_pred)
    #代码作用机制·语法关联·结果易错点
    1import numpy as np同 C55—[0 1 1 1 1 1 0 1 0 1 1 1]10/12 对 = .8333 ✔
    2y_probs = model.predict(val_ds)同 C55—[0 1 1 1 1 1 0 1 0 1 1 1]10/12 对 = .8333 ✔
    3print(y_probs.ravel().round(4))同 C55—[0 1 1 1 1 1 0 1 0 1 1 1]10/12 对 = .8333 ✔
    4y_pred = np.where(y_probs.ravel() < 0.5, 0, 1)同 C55—[0 1 1 1 1 1 0 1 0 1 1 1]10/12 对 = .8333 ✔
    5print(y_pred)同 C55—[0 1 1 1 1 1 0 1 0 1 1 1]10/12 对 = .8333 ✔
    运行结果 1/1 ━━━━━━━━━━━━━━━━━━━━ 1s 674ms/step [0. 1. 1. 1. 1. 1. 0. 1. 0. 1. 1. 1.] [0 1 1 1 1 1 0 1 0 1 1 1]

    These are some predicted labels, actual labels, and corresponding images.

    Cell 71增强后可视化导入·绘图·输出
    import matplotlib.pyplot as plt
    
    plt.figure(figsize=(10, 10))
    for images, labels in val_ds.take(1):
        for i in range(9):
            ax = plt.subplot(3, 3, i + 1)
            plt.imshow(images[i].numpy().astype("uint8"))
            title = "Actual: " + val_ds.class_names[labels[i]] + \
                " Predicted: " + val_ds.class_names[y_pred[i]]
            plt.title(title, color="k" if labels[i] == y_pred[i] else "r")
            plt.axis("off")
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt同 C57—
    2 张红字
    3plt.figure(figsize=(10, 10))同 C57—
    2 张红字
    4for images, labels in val_ds.take(1):同 C57—
    2 张红字
    5 for i in range(9):同 C57—
    2 张红字
    6 ax = plt.subplot(3, 3, i + 1)同 C57—
    2 张红字
    7 plt.imshow(images[i].numpy().astype("uint8"))同 C57—
    2 张红字
    8 title = "Actual: " + val_ds.class_names[labels[i]] + \同 C57—
    2 张红字
    9 " Predicted: " + val_ds.class_names[y_pred[i]]同 C57—
    2 张红字
    10 plt.title(title, color="k" if labels[i] == y_pred[i] else "r")同 C57—
    2 张红字
    11 plt.axis("off")同 C57—
    2 张红字
    运行结果 <Figure size 1000x1000 with 9 Axes> [image/png]

    Extras

    Transfer learning with VGG-16


    The following model reuses the VGG-16 pre-trained model for classifying the CIFAR-10 dataset. Note the calls to the vgg16.preprocess_input() function, the input shape of 32&times;32&times;3 specified in the VGG16 model creation, and the setting of the VGG16 model to be not trainable.

    Cell 74E:VGG-16 迁移学习母版(输入 32)重点展开
    from tensorflow.keras.applications import vgg16
    
    X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)
    X_train = vgg16.preprocess_input(X_train)
    X_test = vgg16.preprocess_input(X_test)
    base_model = vgg16.VGG16(weights="imagenet", include_top=False,
                             input_shape=(32, 32, 3))
    base_model.trainable = False
    model = keras.Sequential([
        base_model,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=25)
    #代码作用机制·语法关联·结果易错点
    1from tensorflow.keras.applications import vgg16导入 vgg16含 VGG16 类 + preprocess_input——
    3X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)load scale_x=False———
    4X_train = vgg16.preprocess_input(X_train)vgg16.preprocess_input与 MobileNet 相同风格:BGR + 减均值—每个应用的 preprocess 不同,不能混用
    5X_test = vgg16.preprocess_input(X_test)vgg16.preprocess_input与 MobileNet 相同风格:BGR + 减均值—每个应用的 preprocess 不同,不能混用
    6base_model = vgg16.VGG16(weights="imagenet", include_top=False,VGG16(weights="imagenet", include_top=False, input_shape=(32,32,3))VGG 不限制输入尺寸(全卷积 + 全局池化可省);卷积基 14,714,688 参数下载 vgg16_notop.h5(56 MB);输出 (None,1,1,512)Keras VGG16 没有 BN(Unit 9 讲义 p21)
    7 input_shape=(32, 32, 3))VGG16(weights="imagenet", include_top=False, input_shape=(32,32,3))VGG 不限制输入尺寸(全卷积 + 全局池化可省);卷积基 14,714,688 参数下载 vgg16_notop.h5(56 MB);输出 (None,1,1,512)Keras VGG16 没有 BN(Unit 9 讲义 p21)
    8base_model.trainable = False冻结—Non-trainable 14,714,688—
    9model = keras.Sequential([base + Flatten + Dense(1024) + Dense(10)Flatten 1×1×512 = 512Dense(1024) 525,312;Dense(10) 10,250—
    10 base_model,base + Flatten + Dense(1024) + Dense(10)Flatten 1×1×512 = 512Dense(1024) 525,312;Dense(10) 10,250—
    11 layers.Flatten(),base + Flatten + Dense(1024) + Dense(10)Flatten 1×1×512 = 512Dense(1024) 525,312;Dense(10) 10,250—
    12 layers.Dense(1024, activation="relu"),base + Flatten + Dense(1024) + Dense(10)Flatten 1×1×512 = 512Dense(1024) 525,312;Dense(10) 10,250—
    13 layers.Dense(10, activation="softmax")base + Flatten + Dense(1024) + Dense(10)Flatten 1×1×512 = 512Dense(1024) 525,312;Dense(10) 10,250—
    14])base + Flatten + Dense(1024) + Dense(10)Flatten 1×1×512 = 512Dense(1024) 525,312;Dense(10) 10,250—
    15history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 25 轮VGG 比 MobileNet 快(@32 小图)第 1 轮 .5422/.5922 → 第 6 轮 .9161/.6268val_loss 第 1 轮 2.0 后不降反升 → 过拟合
    16 epochs=25)fit 25 轮VGG 比 MobileNet 快(@32 小图)第 1 轮 .5422/.5922 → 第 6 轮 .9161/.6268val_loss 第 1 轮 2.0 后不降反升 → 过拟合
    运行结果 Epoch 1/25 98/98 - 17s - 176ms/step - acc: 0.5422 - loss: 3.4411 - val_acc: 0.5922 - val_loss: 2.0026 Epoch 2/25 98/98 - 4s - 43ms/step - acc: 0.6861 - loss: 1.1580 - val_acc: 0.6062 - val_loss: 1.6918 Epoch 3/25 98/98 - 5s - 47ms/step - acc: 0.7851 - loss: 0.6809 - val_acc: 0.6098 - val_loss: 1.7320 Epoch 4/25 98/98 - 4s - 41ms/step - acc: 0.8390 - loss: 0.4741 - val_acc: 0.5968 - val_loss: 1.8132 Epoch 5/25 98/98 - 6s - 59ms/step - acc: 0.8815 - loss: 0.3476 - val_acc: 0.6192 - val_loss: 1.7811 Epoch 6/25 98/98 - 5s - 52ms/step - acc: 0.9161 - loss: 0.2476 - val_acc: 0.6268 - val_loss: 1.770
    Cell 75VGG 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot_historyval_loss 曲线从第 2 轮起上扬
    M76 的结论
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]

    The training is relatively fast, and the validation results are good. However, the curve of the validation loss indicates overfitting.

    VGG-16 @32 为什么 .63:VGG-16 是为 224 设计的深网络(16 层),输入 32 经过 5 次 maxpool → 1×1,与 C15 的 MobileNet 问题一样,但 VGG 的卷积核更通用(3×3 堆叠),前几块的低层特征仍有用 → 比 MobileNet@32 的 .21 好很多。但 Flatten 后只有 512 维 + Dense(1024) → 过拟合(val_loss 从第 2 轮 1.69 一路涨)。M76:"validation loss curve indicates overfitting"——val_acc 还在涨但 val_loss 在涨 = 预测越来越自信地错。

    Simplifying pre-trained models


    In this section, we attempt to mitigate overfitting by simplifying the VGG-16 pre-trained model. Customizing the structure of a pre-trained model is not a frequently-used technique, and may not be applicable to some pre-trained models. Anyway, we adopt this technique to learn about the structure of the VGG-16 model and how model simplicity reduces overfitting.


    The summary of the VGG-16 model is shown below. The model contains 5 VGG blocks, where each VGG block contains 2 or 3 convolutional layers followed by 1 max-pooling layer.

    VGG-16 结构(Unit 9 讲义 p43–p48):输入 224×224×3 → 块 1:Conv64 ×2 → MaxPool(→112)→ 块 2:Conv128 ×2 → MaxPool(→56)→ 块 3:Conv256 ×3 → MaxPool(→28)→ 块 4:Conv512 ×3 → MaxPool(→14)→ 块 5:Conv512 ×3 → MaxPool(→7)→ 原版还有 Flatten + Dense(4096)×2 + Dense(1000)(include_top=False 去掉)。层数账:13 conv + 5 pool = 18 层(不含 InputLayer),加 3 个 Dense = 16 个加权层("16" 的由来)。参数 14,714,688(其中 FC 三层占 123M——所以去掉 top 只剩 14.7M)。Keras 版本没有 BN(原论文也没有)——Unit 9 讲义 p21 特别强调,考试常考。
    Cell 78base_model.summary():VGG-16 结构重点展开
    base_model.summary()
    #代码作用机制·语法关联·结果易错点
    1base_model.summary()base_model.summary()看冻结的 VGG 卷积基input (None,32,32,3) → 5 块 → (None,1,1,512);Total 14,714,688 / Trainable 0 / Non-trainable 14,714,688Trainable 0 = 冻结成功;对比 C62 的 Trainable 51M
    运行结果 Model: "vgg16" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━┩ │ input_layer_15 (InputLayer) │ (None, 32, 32, 3) │ 0 │ ├──────────────────────────────────────┼─────────────────────────────┼─────────────────┤  Total params: 14,714,688 (56.13 MB)  Trainable params: 0 (0.00 B)  Non-trainable params: 14,714,688 (56.13 MB)
    数层数(E1a/E1c 要裁层):InputLayer 后:块 1 = conv1_1, conv1_2, pool1(3);块 2 = conv2_1, conv2_2, pool2(3);块 3 = conv3_1, conv3_2, conv3_3, pool3(4);块 4 = 4 层;块 5 = 4 层。总 18 层(不含 input)。base_model.layers[:-4] 去掉最后 4 层 = 块 5(conv5_1, conv5_2, conv5_3, pool5)→ 剩 14 层,输出变成块 4 的 pool4:(None,2,2,512)。[:-8] 去掉块 5 + 块 4 → 剩 10 层,输出 pool3:(None,4,4,256)。

    One way to simplify the structure of the VGG-16 model is discarding one or two final VGG blocks (i.e. near the output layer, or near the "top").

    E1a


    Modify the above provided VGG-16 transfer learning model to discard the final 4 layers (i.e. 1 VGG block) in the VGG-16 pre-trained model. Specifically, modify the model creation to set the first layer to


    keras.Sequential(base_model.layers[:-4])
    

    instead of base_model.

    E1b


    You should find the model in E1a (i.e. with the final 4 layers discarded) having better validation results. Discuss some possible reasons for the improved performance.


    (Hint: Consider the relation between model complexity and overfitting, and the kind of patterns/knowledge learned in different convolutional layers in a model.)

    E1b 的标准答案思路(Unit 9 讲义 p53–p56):① 复杂度 ↓ → 过拟合 ↓:裁掉块 5(3 conv + 1 pool)少 ~7M 参数,特征图从 1×1×512 变成 2×2×512(@32 输入)——Flatten 后 2,048 维而不是 512,有空间信息可用;② 特征的层级性:浅层 = 通用(边缘、颜色、纹理),深层 = ImageNet 特定(物体部件、整体形状)。ImageNet 的"狗品种级"特征对 CIFAR-10 的"飞机/汽车/鸟"无用甚至有害;③ 小输入的几何问题:32×32 经过 5 次 pool 太小,裁一块后 pool 少一次,特征图 2×2 保留更多结构。

    E1c


    Modify the above provided VGG-16 transfer learning model to discard the final 8 layers (i.e. 2 VGG blocks) in the VGG-16 pre-trained model. Specifically, modify the model creation to set the first layer to


    keras.Sequential(base_model.layers[:-8])
    

    instead of base_model.

    E1d


    You should find the model in E1c (i.e. with the final 8 layers discarded) having poor validation results. Discuss one or more possible reasons for the poor performance.

    E1d 的标准答案思路:裁 2 块 = 只剩块 1–3(边缘、纹理、简单形状),没有能组合出"物体"的层;而且只剩 3 次 pool → @32 特征图 4×4×256 = 4,096 维直接接 Dense(1024)——Dense 要独自完成从"纹理"到"10 类物体"的全部抽象,4M 参数在 25,000 样本上学不会。训练 acc 也只有 .13 ≈ 随机 → 欠拟合(不是过拟合)。正确写法:"Training and validation accuracy are both ≈0.13, indicating underfitting: the remaining shallow layers cannot capture the object-level patterns needed for CIFAR-10."

    Solutions to extra exercises

    E1a
    Cell 86E1a 解答:裁掉最后 4 层(块 5)重点展开
    # Solution
    
    from tensorflow.keras.applications import vgg16
    
    X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)
    X_train = vgg16.preprocess_input(X_train)
    X_test = vgg16.preprocess_input(X_test)
    base_model = vgg16.VGG16(weights="imagenet", include_top=False,
                             input_shape=(32, 32, 3))
    base_model.trainable = False
    base_model_trimmed = keras.Sequential(base_model.layers[:-4])
    model = keras.Sequential([
        base_model_trimmed,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=25)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3from tensorflow.keras.applications import vgg16导入 / 载入 / preprocess / VGG16同 C74——
    5X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)导入 / 载入 / preprocess / VGG16同 C74——
    6X_train = vgg16.preprocess_input(X_train)导入 / 载入 / preprocess / VGG16同 C74——
    7X_test = vgg16.preprocess_input(X_test)导入 / 载入 / preprocess / VGG16同 C74——
    8base_model = vgg16.VGG16(weights="imagenet", include_top=False,导入 / 载入 / preprocess / VGG16同 C74——
    9 input_shape=(32, 32, 3))导入 / 载入 / preprocess / VGG16同 C74——
    10base_model.trainable = Falsebase_model.trainable = False冻结原始 base_model—裁剪后的子层继承 trainable=False
    11base_model_trimmed = keras.Sequential(base_model.layers[:-4])base_model_trimmed = keras.Sequential(base_model.layers[:-4])layers 是 Model 的层列表;[:-4] 切片去掉末 4 层;包成新 Sequential输出 (None,2,2,512)冻结仍在:层的 trainable 属性跟着层走;新 Sequential 的 trainable 默认 True 但子层各自 False
    12model = keras.Sequential([model = trimmed + Flatten + DenseFlatten 2×2×512 = 2,048Dense(1024) 2,098,176—
    13 base_model_trimmed,model = trimmed + Flatten + DenseFlatten 2×2×512 = 2,048Dense(1024) 2,098,176—
    14 layers.Flatten(),model = trimmed + Flatten + DenseFlatten 2×2×512 = 2,048Dense(1024) 2,098,176—
    15 layers.Dense(1024, activation="relu"),model = trimmed + Flatten + DenseFlatten 2×2×512 = 2,048Dense(1024) 2,098,176—
    16 layers.Dense(10, activation="softmax")model = trimmed + Flatten + DenseFlatten 2×2×512 = 2,048Dense(1024) 2,098,176—
    17])model = trimmed + Flatten + DenseFlatten 2×2×512 = 2,048Dense(1024) 2,098,176—
    18history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 25 轮—第 1 轮 loss 116(头初始化 + 大特征图)→ 第 6 轮 .6211/.5840—
    19 epochs=25)fit 25 轮—第 1 轮 loss 116(头初始化 + 大特征图)→ 第 6 轮 .6211/.5840—
    运行结果 Epoch 1/25 98/98 - 8s - 86ms/step - acc: 0.4503 - loss: 116.2840 - val_acc: 0.3282 - val_loss: 2.4714 Epoch 2/25 98/98 - 7s - 74ms/step - acc: 0.3810 - loss: 2.0278 - val_acc: 0.4054 - val_loss: 2.0103 Epoch 3/25 98/98 - 5s - 49ms/step - acc: 0.4792 - loss: 1.6179 - val_acc: 0.4892 - val_loss: 1.7796 Epoch 4/25 98/98 - 5s - 52ms/step - acc: 0.5442 - loss: 1.3552 - val_acc: 0.5384 - val_loss: 1.6581 Epoch 5/25 98/98 - 5s - 52ms/step - acc: 0.5867 - loss: 1.2053 - val_acc: 0.5582 - val_loss: 1.6217 Epoch 6/25 98/98 - 4s - 40ms/step - acc: 0.6211 - loss: 1.0775 - val_acc: 0.5840 - val_loss: 1.567
    Cell 87E1a 画图基础
    # Solution
    
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行 / plotval_loss 比 C75 平缓
    —
    3plot_history(history)Solution / 空行 / plotval_loss 比 C75 平缓
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    E1b

    Solution:


    Discarding some layers reduces the complexity of a model, which in turns reduces the overfitting problem that occurs when the whole VGG-16 pre-trained model is incorporated.


    In a CNN, initial convolutional layers detect low-level generic features such as lines and simple shapes, while final convolutional layers detect high-level task-specific features. Discarding some final layers reduces the knowledge specific to the original task of the pre-trained model; such knowledge is not useful for, and may even worsen, our new model for the current task. Reducing such knowledge helps improving our new model.

    E1c
    Cell 90E1c 解答:裁掉最后 8 层(块 5 + 块 4)→ 欠拟合重点展开
    # Solution
    
    from tensorflow.keras.applications import vgg16
    
    X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)
    X_train = vgg16.preprocess_input(X_train)
    X_test = vgg16.preprocess_input(X_test)
    base_model = vgg16.VGG16(weights="imagenet", include_top=False,
                             input_shape=(32, 32, 3))
    base_model.trainable = False
    base_model_trimmed = keras.Sequential(base_model.layers[:-8])
    model = keras.Sequential([
        base_model_trimmed,
        layers.Flatten(),
        layers.Dense(1024, activation="relu"),
        layers.Dense(10, activation="softmax")
    ])
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                                    epochs=25)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 导入 / 载入 / VGG16 / 冻结同 C86——
    3from tensorflow.keras.applications import vgg16Solution / 导入 / 载入 / VGG16 / 冻结同 C86——
    5X_train, y_train, X_test, y_test = load_and_prep_cifar10(scale_x=False)Solution / 导入 / 载入 / VGG16 / 冻结同 C86——
    6X_train = vgg16.preprocess_input(X_train)Solution / 导入 / 载入 / VGG16 / 冻结同 C86——
    7X_test = vgg16.preprocess_input(X_test)Solution / 导入 / 载入 / VGG16 / 冻结同 C86——
    8base_model = vgg16.VGG16(weights="imagenet", include_top=False,Solution / 导入 / 载入 / VGG16 / 冻结同 C86——
    9 input_shape=(32, 32, 3))Solution / 导入 / 载入 / VGG16 / 冻结同 C86——
    10base_model.trainable = FalseSolution / 导入 / 载入 / VGG16 / 冻结同 C86——
    11base_model_trimmed = keras.Sequential(base_model.layers[:-8])base_model.layers[:-8]去 8 层 → 剩块 1–3输出 (None,4,4,256)—
    12model = keras.Sequential([modelFlatten 4,096Dense(1024) 4,198,400—
    13 base_model_trimmed,modelFlatten 4,096Dense(1024) 4,198,400—
    14 layers.Flatten(),modelFlatten 4,096Dense(1024) 4,198,400—
    15 layers.Dense(1024, activation="relu"),modelFlatten 4,096Dense(1024) 4,198,400—
    16 layers.Dense(10, activation="softmax")modelFlatten 4,096Dense(1024) 4,198,400—
    17])modelFlatten 4,096Dense(1024) 4,198,400—
    18history = compile_and_fit_model(model, X_train, y_train, X_test, y_test,fit 25 轮—第 1 轮 loss 1593 → acc .2468 → 之后 acc ≈ .13 = 随机训练 acc 也 .13 → 欠拟合,不是过拟合
    19 epochs=25)fit 25 轮—第 1 轮 loss 1593 → acc .2468 → 之后 acc ≈ .13 = 随机训练 acc 也 .13 → 欠拟合,不是过拟合
    运行结果 Epoch 1/25 98/98 - 8s - 85ms/step - acc: 0.2468 - loss: 1593.2555 - val_acc: 0.1254 - val_loss: 2.5959 Epoch 2/25 98/98 - 6s - 60ms/step - acc: 0.1242 - loss: 2.3979 - val_acc: 0.1220 - val_loss: 2.3866 Epoch 3/25 98/98 - 5s - 51ms/step - acc: 0.1217 - loss: 2.3058 - val_acc: 0.1194 - val_loss: 2.3435 Epoch 4/25 98/98 - 3s - 27ms/step - acc: 0.1308 - loss: 2.2710 - val_acc: 0.1236 - val_loss: 2.3342 Epoch 5/25 98/98 - 3s - 27ms/step - acc: 0.1296 - loss: 2.2566 - val_acc: 0.1286 - val_loss: 2.3307 Epoch 6/25 98/98 - 5s - 53ms/step - acc: 0.1392 - loss: 2.2400 - val_acc: 0.1332 - val_loss: 2.29
    Cell 91E1c 画图基础
    # Solution
    
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# Solutionplot两条线都平在 acc .13
    M93 的结论
    3plot_history(history)plot两条线都平在 acc .13
    M93 的结论
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    E1d

    Solution:


    While discarding some layers generally helps reducing overfitting, discarding 8 layers is probably too much for the task in question. Some of the discarded layers may be required for detecting the patterns in the CIFAR-10 dataset, so discarding them makes the pre-trained model less capable. In fact, the execution outputs show poor results in both training and validation, which indicates underfitting in the model.

    &#x2766;

    📘 Tutorial 10(= Lab 10)· 文本情感分析:Embedding + DNN / CNN / SimpleRNN(IMDb)+ 20 newsgroups

    t10-s13903054.ipynb,93 cells。对应 Unit 10 讲义 p6–p12(IMDb 数据集、词索引、<PAD>/<START>/<UNKNOWN> = 0/1/2)、p13–p20(Embedding 层 5000×96、pad_sequences maxlen=100 默认 pre)、p21–p30(DNN Flatten 忽略词序)、p31–p40(Conv1D (k·d+1)·n、GlobalMaxPooling1D)、p41–p56(SimpleRNN (n+m+1)·n、units 扫描、dropout 扫描)、p57–p66(Tokenizer、20 newsgroups 20 类)。结果速览(val_acc / val_loss):DNN_64_D50 .8325/.6814(严重过拟合);CNN_64 .8412/.4824;CNN_64_BN .8428/.7097;CNN_64_D50 .8136/.4613;RNN_64 .7904/.6576;RNN_32 .7455(最差);RNN_16 .8262/.4743;RNN_16_D25 .8011;RNN_16_D75 .8339/.4303(val_loss 最低);20ng SimpleRNN(64) 20 轮 val_acc ≈ .29。
    读法:本 Lab 第一次处理文本。所有模型共享同一个前置:Embedding(5000, 96) 把每条评论的 100 个词索引变成 (100, 96) 的词向量序列;然后三种"读法":DNN 用 Flatten(把 9,600 个数当独立特征,丢掉词序);CNN 用 Conv1D(看相邻 3/5 个词的局部组合);RNN 用 SimpleRNN(逐词递推,有记忆)。C15(工具)、C26(DNN)、C31(CNN)、C48(RNN)、C83(20ng)逐行精讲。
    必会公式:Embedding 参数 = 词表 × 向量维 = 5000×96 = 480,000;Conv1D 参数 = (k·d+1)·n → k3 18,496、k5 30,784,输出长度 100−k+1;SimpleRNN 参数 = (n+m+1)·n → 64 10,304、32 4,128、16 1,808;Dense(1) 的参数随上游 units 变:65 / 33 / 17;BN(64) = 128 trainable + 128 non-trainable。
    三条结论:① DNN 训练 acc 1.0 但 val_loss .68——Flatten 记住了训练集却学不到词序;② CNN 的 val_acc 最高(.8428)——局部词组("not good"、"very bad")对情感判断够用;③ RNN 的 units 从 64 降到 16 val_acc 反而升(.79→.83)——SimpleRNN 在 100 步上梯度消失,大模型只会过拟合;dropout 0.75 时 val_loss 最低 .4303。
    Cell 2关闭 TF 日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2同前—env: TF_CPP_MIN_LOG_LEVEL=2每个 notebook 第一个 cell
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • sentiment analysis, and
  • using DNN, CNN, and simple RNN to process sequential data.
  • Student name: Yin Bang
    Student ID: 13903054

    The IMDb review dataset


    The IMDb movie review dataset from Internet Movie Database (IMDb, <https://www.imdb.com/>) contains movie reviews (features) and whether the reviews are positive or negative (labels).


    The dataset is often used for studying sentiment analysis, which refers to determining whether the emotional tone of a text is positive, negative, or neural.


    Let's begin by exploring the dataset. This code loads the dataset and displays its shape.

    IMDb 数据集(Unit 10 讲义 p6–p9):Keras 自带 imdb.load_data():25,000 训练 + 25,000 测试,已预处理成整数序列(不是原始文本!)。每个整数 = 词在语料库里的频率排名(1 = 最常见词 "the")。注意 X.shape 是 (25000,)——一维 object 数组,每个元素是变长的整数 list。
    Cell 6载入 IMDb 并看形状导入·绘图·输出
    from tensorflow.keras.datasets import imdb
    (X_train, y_train), (X_test, y_test) = imdb.load_data()
    print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)
    #代码作用机制·语法关联·结果易错点
    1from tensorflow.keras.datasets import imdb导入 imdb 数据集模块keras.datasets 自带——
    2(X_train, y_train), (X_test, y_test) = imdb.load_data()载入并解包返回 ((X_train, y_train), (X_test, y_test));X 是变长整数 list 的数组下载 imdb.npz(17 MB)X 不是 2D 矩阵——每条评论长度不同
    3print(X_train.shape, y_train.shape, X_test.shape, y_test.shape)打印形状—(25000,) (25000,) (25000,) (25000,)一维!不是 (25000, 100)
    运行结果 Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/imdb.npz 17464789/17464789 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step (25000,) (25000,) (25000,) (25000,)

    The labels are encoded as 0 for a negative review and 1 for a positive one. The features of an example are a list of integers, which are indices of the words. The label and features of a training example are shown below.

    词索引的三条约定(Unit 10 讲义 p10–p12):① 索引 1 开始("the"=1);② 数据里 0 = <PAD>、1 = <START>、2 = <UNKNOWN>、3 = 未用——所以 get_word_index() 返回的原始索引要 +3 才对上数据里的索引(C10 L2);③ 每条评论以 1(<START>)开头(C8 输出的第一个数就是 1)。易错:直接用 get_word_index() 不 +3 解码会全错位。
    Cell 8看第 0 条训练样本导入·绘图·输出
    print(y_train[0], X_train[0], sep="\n")
    #代码作用机制·语法关联·结果易错点
    1print(y_train[0], X_train[0], sep="\n")print(y_train[0], X_train[0], sep="\n")sep 让标签和特征分两行打印y=1(正面);X 是 [1, 14, 22, 16, 43, …] 以 1 开头第一个 1 = <START>;14 = "this"、22 = "film"(查 word_index)
    运行结果 1 [1, 14, 22, 16, 43, 530, 973, 1622, 1385, 65, 458, 4468, 66, 3941, 4, 173, 36, 256, 5, 25, 100, 43, 838, 112, 50, 670, 22665, 9, 35, 480, 284, 5, 150, 4, 172, 112, 167, 21631, 336, 385, 39, 4, 172, 4536, 1111, 17, 546, 38, 13, 447, 4, 192, 50, 16, 6, 147, 2025, 19, 14, 22, 4, 1920, 4613, 469, 4, 22, 71, 87, 12, 16, 43, 530, 38, 76, 15, 13, 1247, 4, 22, 17, 515, 17, 12, 16, 626, 18, 19193, 5, 62, 386, 12, 8, 316, 8, 106, 5, 4, 2223, 5244, 16, 480, 66, 3785, 33, 4, 130, 12, 16, 38, 619, 5, 25, 124, 51, 36, 135, 48, 25, 1415, 33, 6, 22, 12, 215, 28, 77, 52, 5, 14, 407, 16, 82, 10311, 8, 4, 107,

    The following code creates a dictionary for mapping words to indices and another dictionary for mapping indices to words.

    Cell 10建词→索引、索引→词两个字典(+3 修正)重点展开
    word_to_index = imdb.get_word_index()
    word_to_index = {k: v+3 for k, v in word_to_index.items()}
    word_to_index["<PAD>"] = 0
    word_to_index["<START>"] = 1
    word_to_index["<UNKNOWN>"] = 2
    index_to_word = {v: k for k, v in word_to_index.items()}
    #代码作用机制·语法关联·结果易错点
    1word_to_index = imdb.get_word_index()imdb.get_word_index()返回 dict {词: 频率排名},"the":1,"and":2 …下载 imdb_word_index.json这个索引没有给 PAD/START/UNK 留位
    2word_to_index = {k: v+3 for k, v in word_to_index.items()}{k: v+3 for k, v in word_to_index.items()}字典推导式:所有索引 +3,给 0/1/2 让位"the" 从 1 → 4这一步是最常见错误点:不 +3 解码会全错
    3word_to_index["<PAD>"] = 0手动加入三个特殊 token"<PAD>"=0(填充)、"<START>"=1(句首)、"<UNKNOWN>"=2(生词)—3 号保留不用
    4word_to_index["<START>"] = 1手动加入三个特殊 token"<PAD>"=0(填充)、"<START>"=1(句首)、"<UNKNOWN>"=2(生词)—3 号保留不用
    5word_to_index["<UNKNOWN>"] = 2手动加入三个特殊 token"<PAD>"=0(填充)、"<START>"=1(句首)、"<UNKNOWN>"=2(生词)—3 号保留不用
    6index_to_word = {v: k for k, v in word_to_index.items()}反转字典推导式 {v: k}:索引→词—两个字典互逆
    运行结果 Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/imdb_word_index.json 1641221/1641221 ━━━━━━━━━━━━━━━━━━━━ 0s 0us/step

    Using the dictionary that maps indices to words, this code displays the text of a training example.

    Cell 12把整数序列解码回文本基础
    text_0 = [index_to_word[i] for i in X_train[0]]
    print(" ".join(text_0))
    #代码作用机制·语法关联·结果易错点
    1text_0 = [index_to_word[i] for i in X_train[0]]列表推导式查表X_train[0] 每个整数 → index_to_word[i]词列表—
    2print(" ".join(text_0))" ".join空格拼接 this film was just brilliant …C8 的 y=1 对应这段正面评论 ✔
    运行结果 <START> this film was just brilliant casting location scenery story direction everyone's really suited the part they played and you could just imagine being there robert redford's is an amazing actor and now the same being director norman's father came from the same scottish island as myself so i loved the fact there was a real connection with this film the witty remarks throughout the film were great it was just brilliant so much that i bought the film as soon as it was released for retail and would recommend it to everyone to watch and the fly fishing was amazing really cried at the end it w

    Utility code


    This section contains some utility functions for use in the rest of the lesson.

    This code contains import statements and constant definitions. The load_and_prep_imdb() function loads the IMDb dataset, prepares the data, and returns the data in a 4-tuple: X_train, y_train, X_test, y_test.

    Cell 15常量 + load_and_prep_imdb():num_words / skip_top / pad_sequences重点展开
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.datasets import imdb
    from tensorflow.keras.preprocessing import sequence
    
    NUM_WORDS = 5000    # how many most frequent words in the corpus to use
    NUM_SKIP_WORDS = 0  # how many stop words to skip
    WV_SIZE = 96        # word vector size, 96D, each vector having 96 values
    SEQ_LEN = 100       # standardized length of text after padding/truncating
    
    def load_and_prep_imdb():
        keras.utils.set_random_seed(42)
        (X_train, y_train), (X_test, y_test) = imdb.load_data(
            num_words=NUM_WORDS, skip_top=NUM_SKIP_WORDS)
        X_train = sequence.pad_sequences(X_train, maxlen=SEQ_LEN)
        X_test = sequence.pad_sequences(X_test, maxlen=SEQ_LEN)
        return X_train, y_train, X_test, y_test
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入keras.preprocessing.sequence 提供 pad_sequences—Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
    2from tensorflow.keras import layers导入keras.preprocessing.sequence 提供 pad_sequences—Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
    3from tensorflow.keras.datasets import imdb导入keras.preprocessing.sequence 提供 pad_sequences—Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
    4from tensorflow.keras.preprocessing import sequence导入keras.preprocessing.sequence 提供 pad_sequences—Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
    6NUM_WORDS = 5000 # how many most frequent words in the corpus to useNUM_WORDS = 5000只保留最常见 5,000 词(Embedding 的行数)—越大表达力越强但参数越多
    7NUM_SKIP_WORDS = 0 # how many stop words to skipNUM_SKIP_WORDS = 0跳过最常见 N 个词("the"、"a" 等停用词);0 = 不跳——
    8WV_SIZE = 96 # word vector size, 96D, each vector having 96 valuesWV_SIZE = 96词向量维度—典型值 50–300
    9SEQ_LEN = 100 # standardized length of text after padding/truncatingSEQ_LEN = 100统一长度—评论平均长 230 词,100 会截掉后 130 个
    11def load_and_prep_imdb():定义函数无参数——
    12 keras.utils.set_random_seed(42)种子———
    13 (X_train, y_train), (X_test, y_test) = imdb.load_data(imdb.load_data(num_words=5000, skip_top=0)num_words:索引 ≥ 5000 的词被替换为 2(<UNKNOWN>);skip_top:前 N 个最常见词替换为 2X 仍是变长 list被替换的词是 2 不是删除——序列长度不变
    14 num_words=NUM_WORDS, skip_top=NUM_SKIP_WORDS)imdb.load_data(num_words=5000, skip_top=0)num_words:索引 ≥ 5000 的词被替换为 2(<UNKNOWN>);skip_top:前 N 个最常见词替换为 2X 仍是变长 list被替换的词是 2 不是删除——序列长度不变
    15 X_train = sequence.pad_sequences(X_train, maxlen=SEQ_LEN)sequence.pad_sequences(X, maxlen=100)长于 100 的截断、短于 100 的补 0;默认 padding="pre"(前面补)、truncating="pre"(前面截)X_train (25000, 100) int32默认是 pre 不是 post——对 RNN 影响很大:pre 截断保留评论结尾,pre 填充让真词都在序列末尾,RNN 读到最后才见真词
    16 X_test = sequence.pad_sequences(X_test, maxlen=SEQ_LEN)sequence.pad_sequences(X, maxlen=100)长于 100 的截断、短于 100 的补 0;默认 padding="pre"(前面补)、truncating="pre"(前面截)X_train (25000, 100) int32默认是 pre 不是 post——对 RNN 影响很大:pre 截断保留评论结尾,pre 填充让真词都在序列末尾,RNN 读到最后才见真词
    17 return X_train, y_train, X_test, y_test返回y 保持 0/1 整数(二分类不需要 one-hot)——
    pad_sequences 的四个参数(Unit 10 讲义 p24):maxlen 目标长度;padding "pre"(默认,前面补 0)或 "post"(后面补);truncating "pre"(默认,前面截)或 "post";value 填充值默认 0。本课用默认 pre 的效果:一条 50 词的评论 → [0]×50 + 原 50 词;一条 300 词的评论 → 原文第 201–300 词。为什么 pre 对 RNN 更好:RNN 最后一步的隐状态 h_100 最重要;pre 填充让真实词紧邻 h_100,而 post 填充会让 h_100 读到一堆 0 把记忆冲掉。对 CNN/DNN 无所谓(Flatten 看全部位置,Conv1D 的 GMP 取最大)。

    This function retrieves the final results in a training history, i.e. values of "loss", "val_loss", "acc", and "val_acc" in the final epoch.

    Cell 17history_final_values基础
    def history_final_values(history):
        return {k: round(v[-1], 4) for k, v in history.history.items()}
    #代码作用机制·语法关联·结果易错点
    1def history_final_values(history):同 t06——见 t06 C11
    2 return {k: round(v[-1], 4) for k, v in history.history.items()}同 t06——见 t06 C11

    This function plots a training history, including both training and validation results.

    Cell 19plot_history基础
    import matplotlib.pyplot as plt
    import pandas as pd
    
    def plot_history(history):
        df = pd.DataFrame(history.history)
        df.index = df.index + 1
        fig, axs = plt.subplots(1, 2, figsize=(8, 4))
        df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])
        df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])
        plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt同 t06——见 t06 C13
    2import pandas as pd同 t06——见 t06 C13
    4def plot_history(history):同 t06——见 t06 C13
    5 df = pd.DataFrame(history.history)同 t06——见 t06 C13
    6 df.index = df.index + 1同 t06——见 t06 C13
    7 fig, axs = plt.subplots(1, 2, figsize=(8, 4))同 t06——见 t06 C13
    8 df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])同 t06——见 t06 C13
    9 df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])同 t06——见 t06 C13
    10 plt.tight_layout()同 t06——见 t06 C13

    This function compiles and fits a model, and returns the training history.

    Cell 21compile_and_fit_model:bce + 10 轮(文本版)重点展开
    def compile_and_fit_model(model, X_train, y_train, X_test, y_test,
                              epochs=10, batch_size=256, verbose=2):
        model.compile(loss="binary_crossentropy",
                      optimizer="adam", metrics=["acc"])
        history = model.fit(X_train, y_train, epochs=epochs,
                            batch_size=batch_size, verbose=verbose,
                            validation_data=(X_test, y_test))
        return history
    #代码作用机制·语法关联·结果易错点
    1def compile_and_fit_model(model, X_train, y_train, X_test, y_test,签名epochs 默认 10(不是 20)—文本模型小、收敛快
    2 epochs=10, batch_size=256, verbose=2):签名epochs 默认 10(不是 20)—文本模型小、收敛快
    3 model.compile(loss="binary_crossentropy",loss="binary_crossentropy"IMDb 是二分类:Dense(1, sigmoid) + 0/1 标签—20ng 要改成 categorical(C89)
    4 optimizer="adam", metrics=["acc"])adam + acc———
    5 history = model.fit(X_train, y_train, epochs=epochs,fit validation_data25000/256 = 97.7 → 98 步/轮——
    6 batch_size=batch_size, verbose=verbose,fit validation_data25000/256 = 97.7 → 98 步/轮——
    7 validation_data=(X_test, y_test))fit validation_data25000/256 = 97.7 → 98 步/轮——
    8 return history返回———

    A number of models for working on the IMDb dataset are examined in this session. Training and validation results of the models are stored in a dictionary called final_values, which facilitates the display of

    results and is first created.

    Cell 23创建 final_values基础
    final_values = {}
    #代码作用机制·语法关联·结果易错点
    1final_values = {}空字典——只运行一次

    Using DNN to process sequential data

    Sequential data can be processed using a DNN. However, a DNN treats the sequential data as individual features and ignores the sequential nature or order information in the features.


    The following DNN, named "DNN_64_D50", performs sentiment analysis on the IMDb dataset, i.e. classifying the reviews to either positive or negative.

    Embedding 层是什么(Unit 10 讲义 p13–p20):一个可查找的矩阵 W ∈ ℝ^{5000×96}:输入整数 i,输出 W[i](第 i 行)。参数 5000×96 = 480,000,全部可训练——模型自己学每个词的 96 维向量。与 one-hot(5000 维稀疏)相比:① 稠密、低维;② 语义相近的词向量距离近(训练后自然涌现);③ 是 "查表" 操作而非矩阵乘法。输出 (None, 100, 96):每条评论 100 个词 × 96 维。mask_zero 默认 False:padding 的 0 也会被当成一个词学一个向量。
    Cell 26Model DNN_64_D50:Embedding → Flatten → Dense(64) → Dropout → Dense(1)重点展开
    # Model DNN_64_D50
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.Flatten(),
        layers.Dense(64, activation="relu"),
        layers.Dropout(0.5),
        layers.Dense(1, activation="sigmoid")
    ], name="DNN_64_D50")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model DNN_64_D50注释———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()加载X (25000,100) int——
    3model = keras.Sequential([Sequential———
    4 layers.Embedding(NUM_WORDS, WV_SIZE),layers.Embedding(NUM_WORDS, WV_SIZE)输入整数索引 (None,100) → 查表 → (None,100,96)480,000 参数输入必须是 int(0–4999);Embedding 是唯一接受整数输入的层
    5 layers.Flatten(),layers.Flatten()(None,100,96) → (None,9600);把 100 个词向量首尾相接当 9,600 个独立特征无参数这一步丢掉了词序:"good not bad" 和 "bad not good" 的 Flatten 结果完全一样(M25 的要点)
    6 layers.Dense(64, activation="relu"),Dense(64, relu)全连接64×9,601 = 614,464(占 56%)—
    7 layers.Dropout(0.5),Dropout(0.5)———
    8 layers.Dense(1, activation="sigmoid")Dense(1, sigmoid)二分类输出65—
    9], name="DNN_64_D50")name———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 1.0, 'loss': 0.0013, 'val_acc': 0.8325, 'val_loss': 0.6814}训练 acc 1.0 / val_loss .68——严重过拟合第 1 轮 val_acc .8374 已是峰值,之后 val_acc 不升、val_loss 翻倍
    运行结果 Epoch 1/10 98/98 - 7s - 67ms/step - acc: 0.6965 - loss: 0.5527 - val_acc: 0.8374 - val_loss: 0.3627 Epoch 2/10 98/98 - 1s - 6ms/step - acc: 0.8915 - loss: 0.2672 - val_acc: 0.8381 - val_loss: 0.3796 Epoch 3/10 98/98 - 1s - 6ms/step - acc: 0.9598 - loss: 0.1282 - val_acc: 0.8324 - val_loss: 0.4153 Epoch 4/10 98/98 - 1s - 6ms/step - acc: 0.9921 - loss: 0.0413 - val_acc: 0.8330 - val_loss: 0.4786 Epoch 5/10 98/98 - 1s - 6ms/step - acc: 0.9977 - loss: 0.0155 - val_acc: 0.8243 - val_loss: 0.5670 Epoch 6/10 98/98 - 1s - 6ms/step - acc: 0.9994 - loss: 0.0066 - val_acc: 0.8302 - val_loss: 0.5864 Epoch
    DNN 为什么过拟合:Flatten 后 9,600 维 × Dense(64) = 61 万参数,而每条评论只有 ~100 个非零词——Dense 能轻松记住"某些词共现 → 正面"。根本问题:Flatten 把 "not" 和 "good" 的位置打乱,模型学不到 "not good" ≠ "good"。
    Embedding 的输出不是 one-hot:与 t05 的 Dense 第一层对比——那边输入是 784 维手工特征,这边是 96 维可学习特征。
    Cell 27DNN 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plotval_loss 从第 1 轮起上扬
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 28DNN summary重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summaryEmbedding (None,100,96) 480,000;Flatten (None,9600) 0;Dense(64) 614,464;Dropout 0;Dense(1) 65Trainable 1,094,529;Optimizer 2,189,060 = 2T+2 ✔Embedding 的 480,000 占 44%——文本模型 Embedding 永远是大头之一
    运行结果 Model: "DNN_64_D50" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ flatten (Flatten) │ (None, [  Total params: 3,283,589 (12.53 MB)  Trainable params: 1,094,529 (4.18 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 2,189,060 (8.35 MB)

    Note that the Embedding layer has output shape (None, 100, 96). None refers to the "variable" or automatically-detected batch size. 100 is the sequence length, i.e. the length of text or number of words in each example. 96 is the size, or dimension, of the word vectors. The layer has 480,000 parameters, which can be explained by the expression: 480,000 = vocabulary size 5,000 &times; word vector size 96.

    Using CNN to process sequential data


    A CNN with 1D convolution explores relations between successive items in sequential data.


    The following code employs a CNN, named "CNN_64", to work on the IMDb dataset. There is one convolutional layer that contains 64 1D kernels of size 3. The 1D global max-pooling layer, which is often used in deep networks for language processing, reduces data size and remove a dimension in the dataset.

    Conv1D 对文本做什么(Unit 10 讲义 p31–p38):64 个 3×96 的核,每个核在 100 个词上滑动(stride 1),每个位置对 3 个连续词的 96 维向量做加权求和 + bias → 1 个标量;64 核 → (98, 64) 的特征图。每个核学一种"三元组模式"(如 "not_*_good" 的否定结构)。GlobalMaxPooling1D:对每张特征图(98 个值)取最大 → 64 维向量——"这条评论里该模式最强出现在哪",丢弃位置信息,这正是文本分类想要的(关键词在哪不重要)。对比 Flatten(DNN 用):GMP 输出固定 64 维,与序列长度无关。
    Cell 31Model CNN_64:Embedding → Conv1D(64,k3) → GlobalMaxPooling1D → Dense(1)重点展开
    # Model CNN_64
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.Conv1D(64, kernel_size=3, activation="relu"),
        layers.GlobalMaxPooling1D(),
        layers.Dense(1, activation="sigmoid")
    ], name="CNN_64")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model CNN_64注释———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Embedding(NUM_WORDS, WV_SIZE),Embedding(None,100,96)480,000—
    5 layers.Conv1D(64, kernel_size=3, activation="relu"),layers.Conv1D(64, kernel_size=3, activation="relu")64 个 3×96 核沿词序列滑动;stride 1、valid → 长度 100−3+1 = 98(None,98,64);参数 (3×96+1)×64 = 18,496Conv1D 不是 Conv2D:一维卷积的"深度"就是 embedding 维 96;参数与序列长度 100 无关
    6 layers.GlobalMaxPooling1D(),layers.GlobalMaxPooling1D()对每张特征图的 98 个值取 max → 64 维;"该模式在评论中最强处"(None,64);无参数与 MaxPooling1D(pool_size=2) 不同:那个是局部池化输出 (49,64),这个是全局到 (64,)
    7 layers.Dense(1, activation="sigmoid")Dense(1, sigmoid)64 → 165没有 Dense(64) 隐藏层——直接从池化向量到输出
    8], name="CNN_64")name———
    9history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    10final_values[model.name] = history_final_values(history)存———
    11print(final_values[model.name])打印{'acc': 0.9956, 'loss': 0.0369, 'val_acc': 0.8412, 'val_loss': 0.4824}val_acc .8412 比 DNN 高、val_loss .4824 比 DNN 低一半M35:"training history indicates overfitting"——val_loss 第 3 轮 .3389 后上扬到 .48
    运行结果 Epoch 1/10 98/98 - 10s - 103ms/step - acc: 0.7172 - loss: 0.5908 - val_acc: 0.7906 - val_loss: 0.4614 Epoch 2/10 98/98 - 1s - 9ms/step - acc: 0.8262 - loss: 0.3929 - val_acc: 0.8374 - val_loss: 0.3671 Epoch 3/10 98/98 - 1s - 8ms/step - acc: 0.8749 - loss: 0.3001 - val_acc: 0.8502 - val_loss: 0.3389 Epoch 4/10 98/98 - 1s - 13ms/step - acc: 0.9080 - loss: 0.2357 - val_acc: 0.8522 - val_loss: 0.3374 Epoch 5/10 98/98 - 1s - 7ms/step - acc: 0.9357 - loss: 0.1840 - val_acc: 0.8512 - val_loss: 0.3485 Epoch 6/10 98/98 - 1s - 8ms/step - acc: 0.9564 - loss: 0.1405 - val_acc: 0.8500 - val_loss: 0.3675 Ep
    Cell 32CNN 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot—
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 33CNN summary重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summaryConv1D (None,98,64) 18,496;GMP (None,64) 0;Dense(1) 65Trainable 498,561;Optimizer 997,124 = 2T+2 ✔Embedding 占 96%!卷积层只占 3.7%
    运行结果 Model: "CNN_64" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_1 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ conv1d (Conv1D) │ (None, [  Total params: 1,495,685 (5.71 MB)  Trainable params: 498,561 (1.90 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 997,124 (3.80 MB)

    Note that the Conv1D layer has output shape (None, 98, 64). None refers to the "variable" or automatically-detected batch size. 98 can be explained by the expression: 98 = input size 100 - kernel size 3 + 1. 64 is the number of kernels in the layer. The layer has 18,496 parameters, which can be explained by the expression: 18,496 = (kernel size 3 &times; input depth 96 + 1 bias) &times; 64 kernels.

    Practice - Question 1 of 3


    The training history of the model CNN_64 indicates overfitting. In this section, we try to mitigate overfitting and improve the model.

    Q1a


    Modify the model CNN_64 by applying batch normalization after the convolutional layer. Name the new model "CNN_64_BN", and save the training history in the final_values dictionary for later display. Plot the training history and show the model summary.

    Cell 37Q1a 学生作答:CNN_64_BN(实际改了 4 处)练习·作答
    # Model CNN_64_BN
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.Conv1D(64, kernel_size=5, activation="relu"),
        layers.BatchNormalization(),
        layers.GlobalMaxPooling1D(),
        layers.Dense(64, activation="relu"),
        layers.Dropout(0.5),
        layers.Dense(1, activation="sigmoid")
    ], name="CNN_64_BN")
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model CNN_64_BN注释———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()加载———
    4model = keras.Sequential([Sequential———
    5 layers.Embedding(NUM_WORDS, WV_SIZE),Embedding—480,000—
    6 layers.Conv1D(64, kernel_size=5, activation="relu"),Conv1D(64, kernel_size=5)kernel_size 3 → 5(题目没要求!)(None,96,64);参数 (5×96+1)×64 = 30,784偏离题目——多改了一个变量,与 CNN_64 不再是干净对照
    7 layers.BatchNormalization(),layers.BatchNormalization()题目要求的改动:对 64 张特征图按通道归一化+128 trainable + 128 non-trainable—
    8 layers.GlobalMaxPooling1D(),GlobalMaxPooling1D(None,64)——
    9 layers.Dense(64, activation="relu"),Dense(64, relu)新增隐藏层(题目没要求)4,160偏离
    10 layers.Dropout(0.5),Dropout(0.5)新增 dropout(题目没要求)—偏离
    11 layers.Dense(1, activation="sigmoid")Dense(1, sigmoid)65——
    12], name="CNN_64_BN")name="CNN_64_BN"———
    14history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    15final_values[model.name] = history_final_values(history)存———
    16print(final_values[model.name])打印{'acc': 0.9997, 'loss': 0.0029, 'val_acc': 0.8428, 'val_loss': 0.7097}val_acc 最高但 val_loss .7097 很高——过拟合依旧BN 没压住过拟合:训练 acc .9997
    运行结果 Epoch 1/10 98/98 - 13s - 135ms/step - acc: 0.6598 - loss: 0.6183 - val_acc: 0.7874 - val_loss: 0.6676 Epoch 2/10 98/98 - 10s - 98ms/step - acc: 0.8498 - loss: 0.3535 - val_acc: 0.8356 - val_loss: 0.6080 Epoch 3/10 98/98 - 1s - 7ms/step - acc: 0.9317 - loss: 0.1885 - val_acc: 0.8415 - val_loss: 0.5066 Epoch 4/10 98/98 - 1s - 8ms/step - acc: 0.9734 - loss: 0.0834 - val_acc: 0.8107 - val_loss: 0.4245 Epoch 5/10 98/98 - 1s - 7ms/step - acc: 0.9769 - loss: 0.0661 - val_acc: 0.8382 - val_loss: 0.3603 Epoch 6/10 98/98 - 1s - 13ms/step - acc: 0.9756 - loss: 0.0674 - val_acc: 0.8292 - val_loss: 0.4353
    Q1a 你的作答核对:BN 加对了,但多改了 3 处。题目说 "Modify the model CNN_64 by applying batch normalization after the convolutional layer"——只要求加一个 BN 层。你还把 kernel_size 改成 5、加了 Dense(64) 和 Dropout(0.5)。这样 CNN_64_BN 与 CNN_64 的差异不只是 BN,无法归因。考试 "modify ... to apply X" 类题,只改要求的那一处。val_acc .8428 是九模型最高,但 val_loss .7097 说明它对错误样本极度自信——BN 在 GMP 之前对 96 个位置的特征图归一化,可能放大了某些极端值。
    Cell 38CNN_64_BN 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plotval_loss 曲线波动大
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 39CNN_64_BN summary重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summaryConv1D (None,96,64) 30,784;BN (None,96,64) 256;GMP 0;Dense(64) 4,160;Dropout 0;Dense(1) 65Trainable 515,137;Non-trainable 128(BN 的 moving mean/var);Optimizer 1,030,276 = 2T+2 ✔Total = 515,137 + 128 + 1,030,276 = 1,545,541 ✔
    运行结果 Model: "CNN_64_BN" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_2 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ conv1d_1 (Conv1D) │ (None, [  Total params: 1,545,541 (5.90 MB)  Trainable params: 515,137 (1.97 MB)  Non-trainable params: 128 (512.00 B)  Optimizer params: 1,030,276 (3.93 MB)

    Q1b


    Modify the model CNN_64 by applying dropout of rate 0.5 after the convolutional layer. Name the new model "CNN_64_D50", and save the training history in the final_values dictionary for later display. Plot the training history and show the model summary.

    Cell 41Q1b 学生作答:CNN_64_D50(同样多改了)练习·作答
    # Model CNN_64_D50
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.Conv1D(64, kernel_size=5, activation="relu"),
        layers.Dropout(0.5),
        layers.GlobalMaxPooling1D(),
        layers.Dense(64, activation="relu"),
        layers.Dropout(0.5),
        layers.Dense(1, activation="sigmoid")
    ], name="CNN_64_D50")
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model CNN_64_D50同 C37———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()同 C37———
    4model = keras.Sequential([同 C37———
    5 layers.Embedding(NUM_WORDS, WV_SIZE),同 C37———
    6 layers.Conv1D(64, kernel_size=5, activation="relu"),Conv1D(64, kernel_size=5)kernel 5(None,96,64);30,784偏离
    7 layers.Dropout(0.5),layers.Dropout(0.5)题目要求:卷积后 dropout——
    8 layers.GlobalMaxPooling1D(),GMP———
    9 layers.Dense(64, activation="relu"),Dense(64)新增4,160偏离
    10 layers.Dropout(0.5),Dropout(0.5)新增—偏离
    11 layers.Dense(1, activation="sigmoid")Dense(1)65——
    12], name="CNN_64_D50")name———
    14history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    15final_values[model.name] = history_final_values(history)存———
    16print(final_values[model.name])打印{'acc': 0.9738, 'loss': 0.0729, 'val_acc': 0.8136, 'val_loss': 0.4613}val_acc 最低但 val_loss 最低(CNN 组)训练 acc .9738——dropout 让它记不全
    运行结果 Epoch 1/10 98/98 - 10s - 99ms/step - acc: 0.6490 - loss: 0.6223 - val_acc: 0.7960 - val_loss: 0.5007 Epoch 2/10 98/98 - 1s - 10ms/step - acc: 0.8348 - loss: 0.3798 - val_acc: 0.8462 - val_loss: 0.3918 Epoch 3/10 98/98 - 1s - 13ms/step - acc: 0.8865 - loss: 0.2849 - val_acc: 0.8528 - val_loss: 0.3605 Epoch 4/10 98/98 - 1s - 8ms/step - acc: 0.9170 - loss: 0.2244 - val_acc: 0.8525 - val_loss: 0.3475 Epoch 5/10 98/98 - 1s - 7ms/step - acc: 0.9382 - loss: 0.1740 - val_acc: 0.8489 - val_loss: 0.3485 Epoch 6/10 98/98 - 1s - 12ms/step - acc: 0.9554 - loss: 0.1314 - val_acc: 0.8483 - val_loss: 0.3488 E
    Q1b 同样的问题:多改了 kernel 5 / Dense(64) / 第二个 Dropout。val_loss .4613 是三个 CNN 里最低的——但这是 "k5 + 2×dropout + Dense(64)" 的组合效果,不能说 "dropout 0.5 after conv 改善了 .4824 → .4613"。正确做法:只把 C31 的 L6 后面插一行 Dropout(0.5),其余一字不改。
    Cell 42CNN_64_D50 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot—
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 43CNN_64_D50 summary重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summaryConv1D 30,784;Dropout 0;GMP 0;Dense(64) 4,160;Dropout 0;Dense(1) 65Trainable 515,009(= BN 版 − 128);Non-trainable 0;Optimizer 1,030,020Total 1,545,029 = 515,009 + 0 + 1,030,020 ✔
    运行结果 Model: "CNN_64_D50" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_3 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ conv1d_2 (Conv1D) │ (None, [  Total params: 1,545,029 (5.89 MB)  Trainable params: 515,009 (1.96 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 1,030,020 (3.93 MB)

    Q1c


    Write code to display the training and validation results in the

    final_values dictionary.

    Cell 45Q1c:显示 final_values 表(pd.DataFrame().T 写法)练习·作答
    import pandas as pd
    df = pd.DataFrame(final_values).T
    print(df)
    #代码作用机制·语法关联·结果易错点
    1import pandas as pdimport pandas———
    2df = pd.DataFrame(final_values).Tpd.DataFrame(final_values).T与 t06 的 from_dict(orient="index") 等价:DataFrame(dict) 默认 orient="columns"(键=列),.T 转置成键=行4 行 × 4 列两种写法都行;.T 更短
    3print(df)print(df)——notebook 里直接写 df 会显示 HTML 表格,print 显示纯文本
    运行结果 acc loss val_acc val_loss DNN_64_D50 1.0000 0.0013 0.8325 0.6814 CNN_64 0.9956 0.0369 0.8412 0.4824 CNN_64_BN 0.9997 0.0029 0.8428 0.7097 CNN_64_D50 0.9738 0.0729 0.8136 0.4613

    &#x2766;

    Using simple RNN to process sequential data


    A recurrent neural network, or RNN, explores the order information in sequential data using a loop-like construct and some hidden state.


    The following code uses a simple RNN, named "RNN_64_D50", to work on the IMDb dataset. The simple RNN layer has a simple RNN cell and 64 units, which is the length of the hidden state vector in the cell.

    SimpleRNN 的递推(Unit 10 讲义 p41–p48):h_t = tanh(W_x·x_t + W_h·h_{t−1} + b),x_t 是第 t 个词的 96 维向量,h 是 64 维隐状态。参数:W_x 96×64 + W_h 64×64 + b 64 = (96+64+1)×64 = 10,304。输出默认 return_sequences=False → 只返回最后一个 h_100 → (None, 64)。dropout=0.5 参数:对输入 x 做 dropout(不是 recurrent_dropout)。为什么 SimpleRNN 学不好长文本:100 步的 BPTT 里梯度连乘 W_h 100 次,|eig|<1 的方向梯度消失、>1 的爆炸——所以 SimpleRNN 实际只能记住最后 10–20 个词。这就是 Unit 11 要引入 LSTM/GRU 的原因。
    Cell 48Model RNN_64_D50:Embedding → SimpleRNN(64, dropout=0.5) → Dense(1)重点展开
    # Model RNN_64_D50
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.SimpleRNN(64, dropout=0.5),
        layers.Dense(1, activation="sigmoid")
    ], name="RNN_64_D50")
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model RNN_64_D50注释———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()加载———
    3model = keras.Sequential([Sequential———
    4 layers.Embedding(NUM_WORDS, WV_SIZE),Embedding(None,100,96)480,000—
    5 layers.SimpleRNN(64, dropout=0.5),layers.SimpleRNN(64, dropout=0.5)逐词递推 h_t = tanh(W_x x_t + W_h h_{t−1} + b);64 = 隐状态维度;dropout=0.5 对输入 x 做 dropout;return_sequences 默认 False → 只输出 h_100(None,64);参数 (96+64+1)×64 = 10,304dropout 参数 vs 层:这里是 RNN 层内部的输入 dropout;若要隐状态间 dropout 用 recurrent_dropout;不能在 RNN 前单独插 Dropout 层(会破坏序列)
    6 layers.Dense(1, activation="sigmoid")Dense(1, sigmoid)64 → 165—
    7], name="RNN_64_D50")name———
    8history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit每步 15ms(CNN 8ms)——RNN 必须串行 100 步—RNN 比 CNN 慢 2×:无法并行时间维
    9final_values[model.name] = history_final_values(history)存———
    10print(final_values[model.name])打印{'acc': 0.9554, 'loss': 0.116, 'val_acc': 0.7904, 'val_loss': 0.6576}val_acc .7904——比 CNN 低 5 个点SimpleRNN 记不住 100 步前的信息
    运行结果 Epoch 1/10 98/98 - 8s - 81ms/step - acc: 0.6380 - loss: 0.6209 - val_acc: 0.7754 - val_loss: 0.4789 Epoch 2/10 98/98 - 1s - 15ms/step - acc: 0.8292 - loss: 0.3898 - val_acc: 0.8375 - val_loss: 0.3763 Epoch 3/10 98/98 - 1s - 15ms/step - acc: 0.8675 - loss: 0.3134 - val_acc: 0.8438 - val_loss: 0.3758 Epoch 4/10 98/98 - 1s - 15ms/step - acc: 0.8835 - loss: 0.2846 - val_acc: 0.8347 - val_loss: 0.4306 Epoch 5/10 98/98 - 1s - 15ms/step - acc: 0.9034 - loss: 0.2396 - val_acc: 0.8267 - val_loss: 0.4927 Epoch 6/10 98/98 - 1s - 15ms/step - acc: 0.9175 - loss: 0.2108 - val_acc: 0.8350 - val_loss: 0.4598
    SimpleRNN 参数拆解:W_x ∈ ℝ^{96×64} = 6,144(输入→隐状态);W_h ∈ ℝ^{64×64} = 4,096(隐状态→隐状态,"循环"部分);b = 64。总 10,304。每个时间步共享同一组参数——100 步只用 10,304 个参数,这是 RNN 比 DNN(614,464)省参数的原因。
    为什么 val_acc 比 CNN 低:pad_sequences 默认 pre 填充 → 真实词在序列末尾对 RNN 其实是好事(h_100 刚读完真词);但 SimpleRNN 的 tanh 在 100 步连乘后梯度消失,前面词的信息传不到 h_100——模型实际上只"记得"最后 10–20 个词。
    Cell 49RNN 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plotval_loss 第 3 轮 .3758 后上扬
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 50RNN summary重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summarySimpleRNN (None,64) 10,304;Dense(1) 65Trainable 490,369;Optimizer 980,740Embedding 占 98%
    运行结果 Model: "RNN_64_D50" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_4 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ simple_rnn (SimpleRNN) │ (None, [  Total params: 1,471,109 (5.61 MB)  Trainable params: 490,369 (1.87 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 980,740 (3.74 MB)

    Note that the SimpleRNN layer has output shape (None, 64), where 64 is the number of units in the simple RNN cell. The layer has 10,304 parameters, which can be explained by the expression: 10,304 = (64 units + 96 features + 1 bias) &times; 64 units.

    参数拆解:10,304 = W_x (96×64 = 6,144) + W_h (64×64 = 4,096) + b (64)。输出 (None, 64):只取最后一步的隐状态。

    Practice - Question 2 of 3


    In the following, we explore some RNNs with different number of units.

    Q2a


    Modify the model RNN_64_D50, by changing the simple RNN layer to use 32 units (instead of 64 units). Name the new model "RNN_32_D50", and save the training history in the final_values dictionary for later display. Plot the training history and show the model summary.

    Cell 54Q2a 学生作答:RNN_32_D50练习·作答
    # Model RNN_32_D50
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.SimpleRNN(32, dropout=0.5),    # 64 units -> 32 units
        layers.Dense(1, activation="sigmoid")
    ], name="RNN_32_D50")
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model RNN_32_D50同 C48———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()同 C48———
    4model = keras.Sequential([同 C48———
    5 layers.Embedding(NUM_WORDS, WV_SIZE),同 C48———
    6 layers.SimpleRNN(32, dropout=0.5), # 64 units -> 32 unitsSimpleRNN(32, dropout=0.5)题目要求:64 → 32 units(None,32);参数 (32+96+1)×32 = 4,128—
    7 layers.Dense(1, activation="sigmoid")Dense(1)32 → 133(随 units 变)Dense(1) 参数 = units+1
    8], name="RNN_32_D50")name———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 0.9548, 'loss': 0.1211, 'val_acc': 0.7455, 'val_loss': 0.6908}val_acc .7455 全 9 模型最低—
    运行结果 Epoch 1/10 98/98 - 8s - 79ms/step - acc: 0.5855 - loss: 0.6683 - val_acc: 0.6825 - val_loss: 0.5983 Epoch 2/10 98/98 - 2s - 16ms/step - acc: 0.7850 - loss: 0.4732 - val_acc: 0.8136 - val_loss: 0.4349 Epoch 3/10 98/98 - 1s - 15ms/step - acc: 0.8494 - loss: 0.3584 - val_acc: 0.8257 - val_loss: 0.4060 Epoch 4/10 98/98 - 2s - 17ms/step - acc: 0.8816 - loss: 0.2948 - val_acc: 0.8272 - val_loss: 0.4251 Epoch 5/10 98/98 - 1s - 14ms/step - acc: 0.9041 - loss: 0.2440 - val_acc: 0.8284 - val_loss: 0.4425 Epoch 6/10 98/98 - 1s - 14ms/step - acc: 0.9224 - loss: 0.2038 - val_acc: 0.8246 - val_loss: 0.4319
    Q2a 你的作答核对:正确 ✔——只改了 units,注释也标了。RNN_32 是 9 个模型里 val_acc 最低的:容量太小,32 维隐状态记不住情感信息。
    Cell 55RNN_32 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot—
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 56RNN_32 summary重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summarySimpleRNN (None,32) 4,128;Dense(1) 33Trainable 484,161 = 480,000+4,128+33;Optimizer 968,324✔
    运行结果 Model: "RNN_32_D50" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_5 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ simple_rnn_1 (SimpleRNN) │ (None, [  Total params: 1,452,485 (5.54 MB)  Trainable params: 484,161 (1.85 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 968,324 (3.69 MB)

    Q2b


    Modify the model RNN_64_D50 by changing the simple RNN layer to use 16 units (instead of 64 units). Name the new model "RNN_16_D50", and save the training history in the final_values dictionary for later display. Plot the training history and show the model summary.

    Cell 58Q2b 学生作答:RNN_16_D50练习·作答
    # Model RNN_16_D50
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.SimpleRNN(16, dropout=0.5),    # 64 units -> 16 units
        layers.Dense(1, activation="sigmoid")
    ], name="RNN_16_D50")
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model RNN_16_D50同 C48———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()同 C48———
    4model = keras.Sequential([同 C48———
    5 layers.Embedding(NUM_WORDS, WV_SIZE),同 C48———
    6 layers.SimpleRNN(16, dropout=0.5), # 64 units -> 16 unitsSimpleRNN(16, dropout=0.5)64 → 16(None,16);参数 (16+96+1)×16 = 1,808—
    7 layers.Dense(1, activation="sigmoid")Dense(1)16 → 117—
    8], name="RNN_16_D50")name———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 0.9449, 'loss': 0.1479, 'val_acc': 0.8262, 'val_loss': 0.4743}val_acc .8262——比 64 和 32 都高小 RNN 反而好:参数少 → 过拟合轻
    运行结果 Epoch 1/10 98/98 - 9s - 93ms/step - acc: 0.6273 - loss: 0.6391 - val_acc: 0.7536 - val_loss: 0.5317 Epoch 2/10 98/98 - 1s - 14ms/step - acc: 0.7964 - loss: 0.4603 - val_acc: 0.8167 - val_loss: 0.4264 Epoch 3/10 98/98 - 1s - 14ms/step - acc: 0.8477 - loss: 0.3659 - val_acc: 0.8356 - val_loss: 0.3836 Epoch 4/10 98/98 - 1s - 13ms/step - acc: 0.8756 - loss: 0.3043 - val_acc: 0.8337 - val_loss: 0.4009 Epoch 5/10 98/98 - 1s - 14ms/step - acc: 0.8982 - loss: 0.2627 - val_acc: 0.8357 - val_loss: 0.4185 Epoch 6/10 98/98 - 1s - 14ms/step - acc: 0.9110 - loss: 0.2323 - val_acc: 0.8366 - val_loss: 0.4151
    Cell 59RNN_16 画图基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot—
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 60RNN_16 summary重点展开
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summarySimpleRNN (None,16) 1,808;Dense(1) 17Trainable 481,825;Optimizer 963,652✔
    运行结果 Model: "RNN_16_D50" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_6 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ simple_rnn_2 (SimpleRNN) │ (None, [  Total params: 1,445,477 (5.51 MB)  Trainable params: 481,825 (1.84 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 963,652 (3.68 MB)

    Q2c


    Write code to display the training and validation results in the

    final_values dictionary.

    Cell 62Q2c:显示表(多了一行列排序)练习·作答
    import pandas as pd
    
    df = pd.DataFrame(final_values).T
    df = df[["acc", "loss", "val_acc", "val_loss"]]
    print(df)
    #代码作用机制·语法关联·结果易错点
    1import pandas as pdimport———
    3df = pd.DataFrame(final_values).TDataFrame().T同 C457 行—
    4df = df[["acc", "loss", "val_acc", "val_loss"]]df[["acc","loss","val_acc","val_loss"]]按指定顺序选列(dict 键序可能不同)列序固定好习惯——防止字典插入顺序不同导致列乱
    5print(df)print———
    运行结果 acc loss val_acc val_loss DNN_64_D50 1.0000 0.0013 0.8325 0.6814 CNN_64 0.9956 0.0369 0.8412 0.4824 CNN_64_BN 0.9997 0.0029 0.8428 0.7097 CNN_64_D50 0.9738 0.0729 0.8136 0.4613 RNN_64_D50 0.9554 0.1160 0.7904 0.6576 RNN_32_D50 0.9548 0.1211 0.7455 0.6908 RNN_16_D50 0.9449 0.1479 0.8262 0.4743

    Q2d


    What is the number of parameters of the simple RNN layer in the model RNN_16_D50? Explain the number by writing an expression for calculating it, and describing the key terms in the expression. Write your answer in a text cell below.

    Q2d 你的作答核对:完全正确 ✔——"(16 + 96 + 1) × 16 = 1,808",还主动拆成 16×16 + 96×16 + 16 = 256 + 1,536 + 16,三项含义(recurrent / input / bias)都对。这就是 Unit 10 讲义 p51 的 (n+m+1)·n 公式。考试变式:若问 RNN_32 → (32+96+1)×32 = 4,128;若 embedding 改 128 维 → (16+128+1)×16 = 2,320。

    Solution:



    <div class='alert alert-warning' role='alert'><b>The SimpleRNN layer in RNN_16_D50 has 1,808 parameters. It is calculated as (units + features + 1) × units = (16 + 96 + 1) × 16 = 1,808, where units = 16 is the hidden state size, features = 96 is the word-vector (embedding) size, and +1 accounts for the bias. Breaking it down: recurrent weights 16×16 = 256, input weights 96×16 = 1,536, and bias 16, summing to 1,808.</b></div>

    &#x2766;

    Practice - Question 3 of 3


    In the following, we explore some RNNs with different drop rates.

    Q3a


    Modify the model RNN_16_D50, by changing the dropout rate to 0.25 (instead of 0.5). Name the new model "RNN_16_D25", and save the training history in the final_values dictionary for later display. (You needn't plot the training history or show the model summary.)

    Cell 68Q3a 学生作答:RNN_16_D25练习·作答
    # Model RNN_16_D25
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.SimpleRNN(16, dropout=0.25),   # dropout 0.5 -> 0.25
        layers.Dense(1, activation="sigmoid")
    ], name="RNN_16_D25")
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model RNN_16_D25同 C58———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()同 C58———
    4model = keras.Sequential([同 C58———
    5 layers.Embedding(NUM_WORDS, WV_SIZE),同 C58———
    6 layers.SimpleRNN(16, dropout=0.25), # dropout 0.5 -> 0.25SimpleRNN(16, dropout=0.25)0.5 → 0.25参数不变 1,808(dropout 无参数)—
    7 layers.Dense(1, activation="sigmoid")Dense(1)17——
    8], name="RNN_16_D25")name———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 0.9439, 'loss': 0.1525, 'val_acc': 0.8011, 'val_loss': 0.4833}val_acc .8011——比 D50 的 .8262 低—
    运行结果 Epoch 1/10 98/98 - 7s - 70ms/step - acc: 0.6477 - loss: 0.6211 - val_acc: 0.7581 - val_loss: 0.5158 Epoch 2/10 98/98 - 1s - 14ms/step - acc: 0.8038 - loss: 0.4396 - val_acc: 0.8190 - val_loss: 0.4157 Epoch 3/10 98/98 - 1s - 14ms/step - acc: 0.8608 - loss: 0.3336 - val_acc: 0.8390 - val_loss: 0.3758 Epoch 4/10 98/98 - 1s - 15ms/step - acc: 0.8912 - loss: 0.2770 - val_acc: 0.8398 - val_loss: 0.3807 Epoch 5/10 98/98 - 2s - 16ms/step - acc: 0.9122 - loss: 0.2345 - val_acc: 0.8356 - val_loss: 0.3928 Epoch 6/10 98/98 - 2s - 24ms/step - acc: 0.9220 - loss: 0.2116 - val_acc: 0.8218 - val_loss: 0.4233

    Q3b


    Modify the model RNN_16_D50, by changing the dropout rate to 0.75 (instead of 0.5). Name the new model "RNN_16_D75", and save the training history in the final_values dictionary for later display. (You needn't plot the training history or show the model summary.)

    Cell 70Q3b 学生作答:RNN_16_D75练习·作答
    # Model RNN_16_D75
    X_train, y_train, X_test, y_test = load_and_prep_imdb()
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.SimpleRNN(16, dropout=0.75),   # dropout 0.5 -> 0.75
        layers.Dense(1, activation="sigmoid")
    ], name="RNN_16_D75")
    
    history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1# Model RNN_16_D75同 C58———
    2X_train, y_train, X_test, y_test = load_and_prep_imdb()同 C58———
    4model = keras.Sequential([同 C58———
    5 layers.Embedding(NUM_WORDS, WV_SIZE),同 C58———
    6 layers.SimpleRNN(16, dropout=0.75), # dropout 0.5 -> 0.75SimpleRNN(16, dropout=0.75)0.5 → 0.75——
    7 layers.Dense(1, activation="sigmoid")Dense(1)17——
    8], name="RNN_16_D75")name———
    10history = compile_and_fit_model(model, X_train, y_train, X_test, y_test)fit———
    11final_values[model.name] = history_final_values(history)存———
    12print(final_values[model.name])打印{'acc': 0.9, 'loss': 0.2537, 'val_acc': 0.8339, 'val_loss': 0.4303}val_acc .8339 + val_loss .4303——RNN 组双料最佳,val_loss 全 9 模型最低训练 acc 只 .9——dropout 0.75 让模型学得慢但泛化好
    运行结果 Epoch 1/10 98/98 - 7s - 72ms/step - acc: 0.5837 - loss: 0.6659 - val_acc: 0.6783 - val_loss: 0.5960 Epoch 2/10 98/98 - 2s - 16ms/step - acc: 0.7434 - loss: 0.5285 - val_acc: 0.8107 - val_loss: 0.4395 Epoch 3/10 98/98 - 2s - 16ms/step - acc: 0.8193 - loss: 0.4132 - val_acc: 0.8274 - val_loss: 0.3955 Epoch 4/10 98/98 - 1s - 13ms/step - acc: 0.8448 - loss: 0.3633 - val_acc: 0.8380 - val_loss: 0.3800 Epoch 5/10 98/98 - 1s - 14ms/step - acc: 0.8633 - loss: 0.3295 - val_acc: 0.8422 - val_loss: 0.3780 Epoch 6/10 98/98 - 1s - 14ms/step - acc: 0.8734 - loss: 0.3109 - val_acc: 0.8468 - val_loss: 0.3656

    Q3c


    Write code to display the training and validation results in the

    final_values dictionary.

    Cell 72Q3c:显示完整 9 模型表练习·作答
    import pandas as pd
    
    df = pd.DataFrame(final_values).T
    df = df[["acc", "loss", "val_acc", "val_loss"]]
    print(df)
    #代码作用机制·语法关联·结果易错点
    1import pandas as pd同 C629 行val_acc 最高 CNN_64_BN .8428;val_loss 最低 RNN_16_D75 .4303—
    3df = pd.DataFrame(final_values).T同 C629 行val_acc 最高 CNN_64_BN .8428;val_loss 最低 RNN_16_D75 .4303—
    4df = df[["acc", "loss", "val_acc", "val_loss"]]同 C629 行val_acc 最高 CNN_64_BN .8428;val_loss 最低 RNN_16_D75 .4303—
    5print(df)同 C629 行val_acc 最高 CNN_64_BN .8428;val_loss 最低 RNN_16_D75 .4303—
    运行结果 acc loss val_acc val_loss DNN_64_D50 1.0000 0.0013 0.8325 0.6814 CNN_64 0.9956 0.0369 0.8412 0.4824 CNN_64_BN 0.9997 0.0029 0.8428 0.7097 CNN_64_D50 0.9738 0.0729 0.8136 0.4613 RNN_64_D50 0.9554 0.1160 0.7904 0.6576 RNN_32_D50 0.9548 0.1211 0.7455 0.6908 RNN_16_D50 0.9449 0.1479 0.8262 0.4743 RNN_16_D25 0.9439 0.1525 0.8011 0.4833 RNN_16_D75 0.9000 0.2537 0.8339 0.4303
    Q3c 你的作答核对:正确 ✔。全表读法(考试 "compare models" 题):① DNN 训练 1.0 / val_loss .68——Flatten 丢词序 + 过拟合最重;② CNN 组 val_acc 最高(.84)但 val_loss 分化(.46–.71)——局部 n-gram 特征对情感够用,BN/.dropout 对 val_acc 帮助小;③ RNN 组 units ↓ val_acc ↑(.79→.75→.83,非单调),dropout ↑ val_loss ↓(.4743→.4303)——SimpleRNN 容量越大越过拟合;④ 按 val_loss 选最佳:RNN_16_D75 .4303;按 val_acc:CNN_64_BN .8428。写结论时两个指标都要报。

    &#x2766;

    Extras


    In this section, we use a simple RNN to classify newsgroup messages.


    The scikit-learn library provides the 20 newsgroups text dataset, which contains about 18,000 messages in 20 newsgroups. To load the dataset, invoke the fetch_20newsgroups() function, as shown in the following code. This function returns a bunch object with these attributes (among others): a data list of text messages, a target array of newsgroup index, and a target_names list of newsgroup names. By default, fetch_20newsgroups() returns the training set of 11,314 messages. Calling fetch_20newsgroups(subset="test") returns the test set of 7,532 messages.

    20 newsgroups:18,846 条新闻组帖子,20 个类别(alt.atheism … talk.religion.misc),默认训练集 11,314 / 测试集 7,532。与 IMDb 的区别:① 原始文本(不是整数序列),所以要自己 Tokenizer;② 20 类而非 2 类 → Dense(20, softmax) + categorical_crossentropy;③ remove=("headers","footers","quotes") 去掉邮件头/脚/引用——否则模型靠 "From:" 里的信息作弊。
    Cell 75E:载入 20 newsgroups 训练集导入·绘图·输出
    from sklearn.datasets import fetch_20newsgroups
    newsgroups = fetch_20newsgroups()
    print(type(newsgroups.data), len(newsgroups.data))
    print(type(newsgroups.target), len(newsgroups.target))
    display(newsgroups.target_names)
    #代码作用机制·语法关联·结果易错点
    1from sklearn.datasets import fetch_20newsgroupsfrom sklearn.datasets import fetch_20newsgroupssklearn 自带,首次下载 ~14 MB——
    2newsgroups = fetch_20newsgroups()fetch_20newsgroups()默认 subset="train" → 11,314 条Bunch 对象—
    3print(type(newsgroups.data), len(newsgroups.data))打印 data 类型和长度data 是 list of str 11314—
    4print(type(newsgroups.target), len(newsgroups.target))打印 targettarget 是 numpy int 数组 11314—
    5display(newsgroups.target_names)display(target_names)IPython 的 display 显示富文本20 个类名列表类名按字母序 = 索引 0–19:alt.atheism=0 … talk.religion.misc=19
    运行结果 <class 'list'> 11314 <class 'numpy.ndarray'> 11314 ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']

    The code below displays the first message with index 0.

    Cell 77看第 0 条消息导入·绘图·输出
    print(newsgroups.data[0].strip())
    #代码作用机制·语法关联·结果易错点
    1print(newsgroups.data[0].strip())print(data[0].strip())strip 去首尾空白含 From:/Subject: 头部的原始帖子头部含 "Subject: WHAT car is this!?"——泄露类别信息(C83 用 remove 去掉)
    运行结果 From: lerxst@wam.umd.edu (where's my thing) Subject: WHAT car is this!? Nntp-Posting-Host: rac3.wam.umd.edu Organization: University of Maryland, College Park Lines: 15 I was wondering if anyone out there could enlighten me on this car I saw the other day. It was a 2-door sports car, looked to be from the late 60s/ early 70s. It was called a Bricklin. The doors were really small. In addition, the front bumper was separate from the rest of the body. This is all I know. If anyone can tellme a model name, engine specs, years of production, where this car is made, history, or whatever info you

    This code displays the index and name the first message's newsgroup.

    Cell 79看第 0 条消息的类别导入·绘图·输出
    target = newsgroups.target[0]
    print(target, newsgroups.target_names[target])
    #代码作用机制·语法关联·结果易错点
    1target = newsgroups.target[0]取 target[0]—7—
    2print(target, newsgroups.target_names[target])查类名target_names[7]7 rec.autos ✔ 与 "WHAT car is this" 吻合—
    运行结果 7 rec.autos

    Classifying newsgroup messages


    This code contains import statements and constant definitions.

    Cell 81E:导入 + 常量(与 IMDb 相同的三个数)基础
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.preprocessing import sequence
    from tensorflow.keras.preprocessing.text import Tokenizer
    
    NUM_WORDS = 5000  # how many most frequent words in the corpus to use
    WV_SIZE = 96      # word vector size, 96D, each vector having 96 values
    SEQ_LEN = 100     # standardized length of text after padding/truncating
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入新增 Tokenizer——
    2from tensorflow.keras import layers导入新增 Tokenizer——
    3from tensorflow.keras.preprocessing import sequence导入新增 Tokenizer——
    4from tensorflow.keras.preprocessing.text import Tokenizer导入新增 Tokenizer——
    6NUM_WORDS = 5000 # how many most frequent words in the corpus to useNUM_WORDS = 5000同 IMDb——
    7WV_SIZE = 96 # word vector size, 96D, each vector having 96 valuesWV_SIZE = 96同——
    8SEQ_LEN = 100 # standardized length of text after padding/truncatingSEQ_LEN = 100同—20ng 消息更长,100 词截断损失更大

    The following load_and_prep_20newsgroups() function loads and prepares the 20 newsgroups dataset. Note that the preprocess_text() nested function is defined as global, so it can be used both inside and outside load_and_prep_20newsgroups(). In this way, it can refer to the local tokenizer object, and can be used later for preprocessing text for making prediction in production.

    Tokenizer 的工作流(Unit 10 讲义 p57–p62):Tokenizer(NUM_WORDS):只保留频率最高的 5,000 词;fit_on_texts(X):扫一遍语料建词表(词→索引,1开始);texts_to_sequences:文本 → 整数序列(不在 top-5000 的词直接丢弃,不是映射到 <UNK>——与 IMDb 的 <UNKNOWN>=2 不同!);pad_sequences(maxlen=100):统一长度。为什么 preprocess_text 要 global:tokenizer 是 load_and_prep_20newsgroups 的局部变量,函数返回后会被回收;但预测时(C86)必须用同一个 tokenizer(同样的词→索引映射),所以用 global 把闭包暴露出来——M82 的解释。
    Cell 83load_and_prep_20newsgroups():Tokenizer + global preprocess_text重点展开
    from sklearn.datasets import fetch_20newsgroups
    
    def load_and_prep_20newsgroups():
        keras.utils.set_random_seed(42)
        X, y = fetch_20newsgroups(
            remove=("headers", "footers", "quotes"), return_X_y=True)
        tokenizer = Tokenizer(NUM_WORDS)
        tokenizer.fit_on_texts(X)
        global preprocess_text
        def preprocess_text(texts):
            texts = tokenizer.texts_to_sequences(texts)
            texts = sequence.pad_sequences(texts, maxlen=SEQ_LEN)
            return texts
        X = preprocess_text(X)
        y = keras.utils.to_categorical(y, num_classes=20)
        return X, y
    #代码作用机制·语法关联·结果易错点
    1from sklearn.datasets import fetch_20newsgroups导入———
    3def load_and_prep_20newsgroups():定义函数———
    4 keras.utils.set_random_seed(42)种子———
    5 X, y = fetch_20newsgroups(fetch_20newsgroups(remove=(...), return_X_y=True)remove 去掉邮件头/脚/引用(防止作弊);return_X_y=True 直接返回 (X, y) 而非 BunchX: list of 11,314 str;y: (11314,) intremove 很重要:不去头部的话模型靠 "From:"/"Subject:" 的格式就能拿高分
    6 remove=("headers", "footers", "quotes"), return_X_y=True)fetch_20newsgroups(remove=(...), return_X_y=True)remove 去掉邮件头/脚/引用(防止作弊);return_X_y=True 直接返回 (X, y) 而非 BunchX: list of 11,314 str;y: (11314,) intremove 很重要:不去头部的话模型靠 "From:"/"Subject:" 的格式就能拿高分
    7 tokenizer = Tokenizer(NUM_WORDS)tokenizer = Tokenizer(NUM_WORDS)创建分词器,只保留 top-5000 词—此时词表为空
    8 tokenizer.fit_on_texts(X)tokenizer.fit_on_texts(X)扫全部文本:小写化、按空格/标点切词、统计词频、建词表(1 开始)词表 ≤ 5,000fit 只能在训练集上做——用测试集 fit 是数据泄漏
    9 global preprocess_textglobal preprocess_text声明 preprocess_text 为全局名——嵌套函数能"逃出"外层函数—没有这行,函数返回后 preprocess_text 不存在(闭包被回收),C86 会 NameError
    10 def preprocess_text(texts):def preprocess_text(texts)闭包:捕获外层的 tokenizer;texts_to_sequences → pad_sequences—闭包 = 函数 + 它捕获的环境
    11 texts = tokenizer.texts_to_sequences(texts)texts_to_sequences每条文本 → 整数 list;OOV 词被丢弃(不是映射到 UNK)—与 IMDb 的区别:IMDb 的 UNK=2 是保留的;Tokenizer 默认 drop
    12 texts = sequence.pad_sequences(texts, maxlen=SEQ_LEN)pad_sequences(maxlen=100)同 IMDb(11314, 100)—
    13 return textsreturn———
    14 X = preprocess_text(X)X = preprocess_text(X)对全部文本预处理X (11314,100)—
    15 y = keras.utils.to_categorical(y, num_classes=20)to_categorical(y, 20)20 类 one-hoty (11314,20)多分类需要 one-hot 配 categorical CE
    16 return X, yreturn———
    E1a

    Implement a simple RNN model to classify the 20 newsgroups dataset. Remember that there are 20 classes and it is a multiclass classification task.

    E1b

    The following predict_newsgroup() function uses the model to predict the newsgroup of a text message. Invoke the function with some text messages that you write.

    Cell 86E1b:predict_newsgroup():预处理 → 预测 → argmax → 类名重点展开
    import numpy as np
    
    newsgroups = fetch_20newsgroups()
    
    def predict_newsgroup(model, text):
        X = preprocess_text([text])
        y = model.predict(X, verbose=0)[0]
        y = np.argmax(y)  # reverse one-hot encoding
        y_name = newsgroups.target_names[y]
        return y, y_name
    #代码作用机制·语法关联·结果易错点
    1import numpy as npimport numpyargmax——
    3newsgroups = fetch_20newsgroups()重新 fetch为了拿 target_names(C83 的 return_X_y 版没返回它)Bunch—
    5def predict_newsgroup(model, text):定义 predict_newsgroup(model, text)———
    6 X = preprocess_text([text])preprocess_text([text])注意传 list(texts_to_sequences 接受可迭代)→ (1,100)—用的必须是训练时的同一个 tokenizer——这就是 global 的意义
    7 y = model.predict(X, verbose=0)[0]model.predict(X)[0]返回 (1,20) → [0] 取第一条 → (20,)20 个概率—
    8 y = np.argmax(y) # reverse one-hot encodingnp.argmax(y)最大概率的索引 = 预测类别 0–19np.int64反向 one-hot
    9 y_name = newsgroups.target_names[y]target_names[y]索引 → 类名——
    10 return y, y_namereturn (y, y_name)元组——

    Solutions to extra exercises

    E1a
    Cell 89E1a 解答:20ng 的 SimpleRNN(20 类)重点展开
    # Solution
    
    X, y = load_and_prep_20newsgroups()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.SimpleRNN(64, dropout=0.75),
        layers.Dense(20, activation="softmax")
    ])
    
    model.compile(loss="categorical_crossentropy",
                  optimizer="adam", metrics=["acc"])
    history = model.fit(X, y, epochs=20, batch_size=256, verbose=2,
                        validation_split=0.2)
    print(history_final_values(history))
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3X, y = load_and_prep_20newsgroups()加载X (11314,100) y (11314,20)——
    4model = keras.Sequential([Sequential———
    5 layers.Embedding(NUM_WORDS, WV_SIZE),Embedding480,000——
    6 layers.SimpleRNN(64, dropout=0.75),SimpleRNN(64, dropout=0.75)64 units;dropout 0.75(从 IMDb 实验学到的最佳 rate)(None,64);10,304—
    7 layers.Dense(20, activation="softmax")Dense(20, softmax)20 类输出64×21 = 1,344不是 Dense(1,sigmoid)
    8])结束———
    10model.compile(loss="categorical_crossentropy",compile categorical_crossentropy配 one-hot y—20 类必须 categorical
    11 optimizer="adam", metrics=["acc"])compile categorical_crossentropy配 one-hot y—20 类必须 categorical
    12history = model.fit(X, y, epochs=20, batch_size=256, verbose=2,fit 20 轮 validation_split=0.211314×0.8 = 9,051 / 256 = 35.4 → 36 步/轮第 1 轮 acc .0594(≈ 1/20 随机)→ 第 6 轮 .3079validation_split 不是 validation_data(这里没有测试集)
    13 validation_split=0.2)fit 20 轮 validation_split=0.211314×0.8 = 9,051 / 256 = 35.4 → 36 步/轮第 1 轮 acc .0594(≈ 1/20 随机)→ 第 6 轮 .3079validation_split 不是 validation_data(这里没有测试集)
    14print(history_final_values(history))打印———
    运行结果 Epoch 1/20 36/36 - 8s - 231ms/step - acc: 0.0594 - loss: 3.0073 - val_acc: 0.0782 - val_loss: 2.9746 Epoch 2/20 36/36 - 1s - 18ms/step - acc: 0.1061 - loss: 2.9269 - val_acc: 0.0968 - val_loss: 2.9579 Epoch 3/20 36/36 - 1s - 14ms/step - acc: 0.1479 - loss: 2.8548 - val_acc: 0.1091 - val_loss: 2.9404 Epoch 4/20 36/36 - 1s - 14ms/step - acc: 0.1914 - loss: 2.7614 - val_acc: 0.1233 - val_loss: 2.8877 Epoch 5/20 36/36 - 1s - 14ms/step - acc: 0.2523 - loss: 2.5998 - val_acc: 0.1343 - val_loss: 2.7626 Epoch 6/20 36/36 - 1s - 14ms/step - acc: 0.3079 - loss: 2.3916 - val_acc: 0.1586 - val_loss: 2.6089
    Cell 90E1a 画图基础
    # Solution
    
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行 / plot—
    —
    3plot_history(history)Solution / 空行 / plot—
    —
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    E1b
    Cell 92E1b 解答:用三条自写文本预测基础
    # Solution
    
    for text in ["i want to buy a computer",
                 "read about romantic stories",
                 "watch a boring ball game"]:
        print(f"{text} -> {predict_newsgroup(model, text)}")
    #代码作用机制·语法关联·结果易错点
    1# SolutionSolution / 空行———
    3for text in ["i want to buy a computer",for text in [...]三条短信——
    4 "read about romantic stories",for text in [...]三条短信——
    5 "watch a boring ball game"]:for text in [...]三条短信——
    6 print(f"{text} -> {predict_newsgroup(model, text)}")f-string 调用 predict_newsgroup—"i want to buy a computer" → (4, comp.sys.mac.hardware) ✔ 合理;"read about romantic stories" → hockey ✘(没有 romantic 类别,模型乱猜);"watch a boring ball game" → hockey ✔(ball → sport)np.int64(4) 的显示是 numpy 2.x 的 repr——可 int(y) 转换
    运行结果 i want to buy a computer -> (np.int64(4), 'comp.sys.mac.hardware') read about romantic stories -> (np.int64(10), 'rec.sport.hockey') watch a boring ball game -> (np.int64(10), 'rec.sport.hockey')

    &#x2766;

    📘 Tutorial 11(= Lab 11)· Tutorial 11 — LSTM / GRU / Stacked / Bidirectional RNN 与文本生成(20 newsgroups 文本分类 + Alice/Frankenstein 生成)

    notebook: t11-s13903054.ipynb | 96 cells(44 code / 218 行)| 数据:20 newsgroups 11,314 条·20 类(remove headers/footers/quotes)| Embedding(5000,96) + SEQ_LEN 100 | 每轮 36 步(9051/256)| 五模型 + 文本生成(Alice 1,032 步 / Frankenstein 2,587 步)
    本讲定位:Lab 11 = Tutorial 11,是 Unit 10(SimpleRNN 文本分类)的直接延续,把循环层换成 LSTM → GRU → 2 层 stacked LSTM → Bidirectional LSTM,在同一份数据、同一套工具函数下做受控对照;Extras 部分把循环网络反过来用于逐词生成文本(Alice in Wonderland / Frankenstein)。讲义对应 Unit 11(LSTM/GRU 门控、stacked、bidirectional、温度采样)。
    全 lab 一条主线:五个分类模型只有第 4 行循环层不同,其余(Embedding 5000×96 → Dense(20, softmax)、categorical CE + Adam、30 轮 batch 256、validation_split 0.2)完全相同 —— 这是本 lab 最重要的实验设计思想:控制变量,只改一个因素。
    参数量速记(本 lab 所有 summary 数字均已用 numpy 独立复算,Optimizer = 2×Trainable + 2 全部成立):
    学生答案核对结果(本 lab):Q1b(GRU 31,104,含双偏置)正确;Q2b(第一层 LSTM 输出 (None,100,64),41,216)正确;Q3b(Bidir 输出 (None,128),82,432)正确;Q3c 代码(GRU 31,104 / LSTMx2 41,216+33,024 / Bidir 82,432)正确。本 lab 学生作答全部正确,没有需要纠正之处。
    Cell 2环境变量:压掉 TF 的冗余日志基础
    %env TF_CPP_MIN_LOG_LEVEL=2
    #代码作用机制·语法关联·结果易错点
    1%env TF_CPP_MIN_LOG_LEVEL=2设置环境变量 TF_CPP_MIN_LOG_LEVEL=2IPython 的 %env 魔法命令:在当前内核进程里直接设置环境变量(不必重启);TF_CPP_MIN_LOG_LEVEL=2 表示只显示 ERROR 及以上(0=全部, 1=过滤 INFO, 2=过滤 INFO+WARNING, 3=再过滤 ERROR)与 Lab 1 起每个 notebook 第一格完全相同;注意它在 import tensorflow 之前执行才对 C++ 后端日志生效——本 notebook 在 C12 才 import keras,所以顺序正确输出 env: TF_CPP_MIN_LOG_LEVEL=2。易错:若先 import tensorflow 再 %env,底层 C++ 日志已初始化,设置无效
    运行结果 env: TF_CPP_MIN_LOG_LEVEL=2

    In this lesson, you'll work on:


  • text classification and text generation, and
  • using LSTM, GRU, stacked RNN, and bidirectional RNN.
  • 本讲三个目标:① 文本分类与文本生成两类任务;② 四种循环结构(LSTM / GRU / stacked / bidirectional)。与 Unit 10 相比,SimpleRNN 已不再是主角——它只作为基线出现一次。
    Student name: Yin Bang
    Student ID: 13903054

    The 20 newsgroups text dataset


    The scikit-learn library provides the 20 newsgroups text dataset, which contains about 18,000 messages in 20 newsgroups. To load the dataset, invoke the fetch_20newsgroups() function, as shown in the following code. This function returns a bunch object with these attributes (among others): a data list of text messages, a target array of newsgroup index, and a target_names list of newsgroup names. By default, fetch_20newsgroups() returns the training set of 11,314 messages. Calling fetch_20newsgroups(subset="test") returns the test set of 7,532 messages.

    20 newsgroups vs IMDb(Lab 10):IMDb 是二分类(25000 训练 + 25000 测试,Keras 内置);20 newsgroups 是 20 类新闻组,由 scikit-learn 提供,没有官方 train/test 划分,整个 11,314 条都拿来训练(用 validation_split 切验证集)。所以本 lab 没有 X_test / y_test,评估完全依赖 val_acc。
    Cell 6加载 20 newsgroups 并查看结构重点展开
    from sklearn.datasets import fetch_20newsgroups
    newsgroups = fetch_20newsgroups()
    print(type(newsgroups.data), len(newsgroups.data))
    print(type(newsgroups.target), len(newsgroups.target))
    display(newsgroups.target_names)
    #代码作用机制·语法关联·结果易错点
    1from sklearn.datasets import fetch_20newsgroups导入数据加载函数来自 scikit-learn(不是 Keras),首次调用会联网下载 ~14 MB 压缩包到 ~/scikit_learn_data/20news_home/ 并缓存Lab 10 用 keras.datasets.imdb;这里换成了 sklearn,数据的"形状"也不同——原始字符串而非整数序列,所以要自己做 Tokenizer易错:若机器离线且无缓存会报错;本 lab C14 显式 remove 三部分
    2newsgroups = fetch_20newsgroups()下载/加载 20 newsgroups返回 sklearn.utils.Bunch(类似 dict 的对象,属性访问);默认参数:subset=all, categories=None, shuffle=True, random_state=42这里得到完整 11,314 条,含 headers/footers/quotes;C14 会用 remove 参数再取一份"干净"版本输出长度 11314
    3print(type(newsgroups.data), len(newsgroups.data))打印 data 的类型与长度type() 返回类型对象,print 显示 <class 'list'>;len() 为列表元素数data 是字符串列表,每个元素是一封完整帖子(含 From:/Subject: 等头)<class 'list'> 11314
    4print(type(newsgroups.target), len(newsgroups.target))打印 target 的类型与长度target 是 numpy.ndarray,dtype int64(在 Windows 上可能是 int32)与 data 等长(一一对应)<class 'numpy.ndarray'> 11314
    5display(newsgroups.target_names)显示 20 个组名display() 是 IPython 的富显示函数(比 print 更完整地渲染 list);target_names 是 20 个字符串的列表,索引 = 标签值C10 会用 target_names[target] 把整数标签翻回组名;C22 的 predict_newsgroup 同理输出 20 个组名,顺序固定:0 alt.atheism … 7 rec.autos … 19 talk.religion.misc
    运行结果 <class 'list'> 11314 <class 'numpy.ndarray'> 11314 ['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']
    20 newsgroups 的 Bunch 对象:fetch_20newsgroups() 默认 subset="all"(训练+测试合并,共 11,314 条)、remove=()(保留 headers/footers/quotes)、shuffle=True。三个常用属性:data(list[str],原始文本)、target(int 数组,0–19)、target_names(list[str],索引→组名)。本 lab 关注 20 类而非二分类,因此后面用 to_categorical(y, 20)。

    The code below displays the first message with index 0.

    Cell 8查看第 0 条帖子基础
    print(newsgroups.data[0].strip())
    #代码作用机制·语法关联·结果易错点
    1print(newsgroups.data[0].strip())打印第 0 条消息(去首尾空白)strip() 去掉字符串首尾的空格/换行;因为帖子文本以 \n 开头,strip 后更好看展示了原始数据"脏"的一面:From:/Subject:/Nntp-Posting-Host:/Organization:/Lines: 五行头部——这些正是 C14 要 remove 的对象(头部里有泄漏标签的线索,如 Organization: University of Maryland)输出一段关于 Bricklin 跑车的提问;组名 rec.autos(C10)
    运行结果 From: lerxst@wam.umd.edu (where's my thing) Subject: WHAT car is this!? Nntp-Posting-Host: rac3.wam.umd.edu Organization: University of Maryland, College Park Lines: 15 I was wondering if anyone out there could enlighten me on this car I saw the other day. It was a 2-door sports car, looked to be from the late 60s/ early 70s. It was called a Bricklin. The doors were really small. In addition, the front bumper was separate from the rest of the body. This is all I know. If anyone can tellme a model name, engine specs, years of production, where this car is made, history, or whatever info you

    This code displays the index and name of the first message's newsgroup.

    Cell 10第 0 条消息的标签基础
    target = newsgroups.target[0]
    print(target, newsgroups.target_names[target])
    #代码作用机制·语法关联·结果易错点
    1target = newsgroups.target[0]取第 0 条的整数标签target 是 ndarray,索引返回 numpy 标量(np.int64)后面 predict_newsgroup 返回的也是 np.int64(C32 输出里的 np.int64(4))7
    2print(target, newsgroups.target_names[target])打印标签及其组名target_names[target]:用整数索引 list[str],整数标签→可读组名的"反查表"这是全 lab 通用的解码方式;to_categorical 的反操作是 argmax(C22 L8),再查表就是组名7 rec.autos
    运行结果 7 rec.autos

    Utility code


    This section contains some utility functions for use in the rest of the lesson.


    The following code contains import statements and constant definitions.

    Cell 12导入与常量:NUM_WORDS / WV_SIZE / SEQ_LEN重点展开
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.preprocessing import sequence
    from tensorflow.keras.preprocessing.text import Tokenizer
    
    NUM_WORDS = 5000  # how many most frequent words in the corpus to use
    WV_SIZE = 96      # word vector size, 96D, each vector having 96 values
    SEQ_LEN = 100     # standardized length of text after padding/truncating
    #代码作用机制·语法关联·结果易错点
    1from tensorflow import keras导入 keras 与 layersTensorFlow 2.x 的标准导入方式;layers 子模块含 Embedding / SimpleRNN / LSTM / GRU / Bidirectional / DenseC69(文本生成部分)会重新 import 一次同样的模块——重复 import 无副作用无输出
    2from tensorflow.keras import layers导入 keras 与 layersTensorFlow 2.x 的标准导入方式;layers 子模块含 Embedding / SimpleRNN / LSTM / GRU / Bidirectional / DenseC69(文本生成部分)会重新 import 一次同样的模块——重复 import 无副作用无输出
    3from tensorflow.keras.preprocessing import sequence导入 sequence 模块tensorflow.keras.preprocessing.sequence:老式 Keras 预处理工具,含 pad_sequencesC14 L12 用 sequence.pad_sequences(texts, maxlen=SEQ_LEN);注意默认 padding/truncating 都是 pre(见 Lab 10 精讲)易错:新版本 Keras 3 推荐从 keras.preprocessing.sequence 导入,TF 2.16+ 仍保留此路径
    4from tensorflow.keras.preprocessing.text import Tokenizer导入 Tokenizer来自 tensorflow.keras.preprocessing.text;按词频建立词表,fit_on_texts 学习词表、texts_to_sequences 文本→整数序列C14 L7–L8 创建并拟合;C22 L6 与 C71 都复用这个类Tokenizer 默认 filters 会去掉所有标点;C71 文本生成用 filters="" 关闭此行为
    6NUM_WORDS = 5000 # how many most frequent words in the corpus to useNUM_WORDS = 5000词表大小:只保留语料中出现频率最高的 4,999 个词(索引 1–4999),其余忽略决定 Embedding(5000, 96) 的行数 → 480,000 参数;C69 把它重新定义为 5000(同值)易错:Keras Tokenizer 的 num_words=5000 实际保留索引 0–4999,其中 0 保留给 padding,所以有效词 4,999 个
    7WV_SIZE = 96 # word vector size, 96D, each vector having 96 valuesWV_SIZE = 96词向量维度(word vector size)决定 Embedding 输出最后一维 = 96 → 循环层的 input_depth m = 9696 不是 2 的幂,是课程统一设定
    8SEQ_LEN = 100 # standardized length of text after padding/truncatingSEQ_LEN = 100pad/truncate 后的标准序列长度决定 Embedding 输出形状 (None, 100, 96);循环层循环 100 步易错:maxlen=100 同时意味着截断和补齐——长帖只保留最后 100 个词(pre 截断),短帖在前面补 0
    三个常量决定了后面所有模型的输入形状:词表 5000 → Embedding 行数 5000;WV_SIZE 96 → 每个词的向量维度;SEQ_LEN 100 → 每条消息截/补到 100 个词,Embedding 输出 (None, 100, 96)。Lab 10 的 IMDb 也是 5000/100/96,完全同构,便于横向对比。

    The following load_and_prep_20newsgroups() function loads and prepares the 20 newsgroups dataset. Note that the preprocess_text() nested function is defined as global, so it can be used both inside and outside load_and_prep_20newsgroups(). In this way, it can refer to the local tokenizer object, and can be used later for preprocessing text for making prediction in production.

    为什么要把 preprocess_text 声明为 global:它是定义在 load_and_prep_20newsgroups() 内部的嵌套函数,正常情况下函数返回后就会消失;但它闭包捕获了局部变量 tokenizer(词表就在 tokenizer 里)。用 global 把名字提升到模块级别后,后面 C22 的 predict_newsgroup() 和任何生产环境代码都能直接调用 preprocess_text([text]),而且用的是训练时同一套词表和同一套截断规则——这是"预处理必须与训练一致"原则的工程实现。
    Cell 14load_and_prep_20newsgroups():下载、分词、pad、one-hot重点展开
    from sklearn.datasets import fetch_20newsgroups
    
    def load_and_prep_20newsgroups():
        keras.utils.set_random_seed(42)
        X, y = fetch_20newsgroups(
            remove=("headers", "footers", "quotes"), return_X_y=True)
        tokenizer = Tokenizer(NUM_WORDS)
        tokenizer.fit_on_texts(X)
        global preprocess_text
        def preprocess_text(texts):
            texts = tokenizer.texts_to_sequences(texts)
            texts = sequence.pad_sequences(texts, maxlen=SEQ_LEN)
            return texts
        X = preprocess_text(X)
        y = keras.utils.to_categorical(y, num_classes=20)
        return X, y
    #代码作用机制·语法关联·结果易错点
    1from sklearn.datasets import fetch_20newsgroups再次导入 fetch_20newsgroups与 C6 L1 重复;在函数所在 cell 顶部再写一次是为了让该 cell 可独立运行(教学习惯)若已运行过 C6,这行只是重新绑定同名对象,无副作用无输出
    3def load_and_prep_20newsgroups():定义数据准备函数(无参数)Python 函数定义语法;无参数 → 全部配置靠常量 NUM_WORDS/SEQ_LEN 与字面量 20函数返回 (X, y) 元组,调用处 X, y = load_and_prep_20newsgroups() 解包易错:忘记写 return 或返回顺序颠倒(先 y 后 X)
    4 keras.utils.set_random_seed(42)固定全局随机种子keras.utils.set_random_seed(42) 同时设置 Python random / numpy / tensorflow 三个随机源(TF ≥ 2.7)让 Tokenizer、dropout 掩码、初始化可复现;五个模型每次都重置 → 公平对照注意它不保证跨机器/跨 TF 版本完全一致(GPU 非确定性)
    5 X, y = fetch_20newsgroups(下载并取出 data/target(去头尾)remove=("headers","footers","quotes") 删除头/尾/引用行;return_X_y=True 直接返回 (data, target) 元组而非 BunchC6 拿到的含头部;这里是干净版。去掉头部还能避免"泄漏"—— Organization/Subject 里常含组名线索X 为 list[str],y 为 int64 数组;长度仍 11,314
    6 remove=("headers", "footers", "quotes"), return_X_y=True)下载并取出 data/target(去头尾)remove=("headers","footers","quotes") 删除头/尾/引用行;return_X_y=True 直接返回 (data, target) 元组而非 BunchC6 拿到的含头部;这里是干净版。去掉头部还能避免"泄漏"—— Organization/Subject 里常含组名线索X 为 list[str],y 为 int64 数组;长度仍 11,314
    7 tokenizer = Tokenizer(NUM_WORDS)创建 Tokenizer(5000)Tokenizer(NUM_WORDS):位置参数 num_words;默认 lower=True、split=' '、filters 去标点Tokenizer 对象本身没有词表——必须 fit 之后才有 word_index / index_word易错:num_words 只在 texts_to_sequences 时生效(过滤低频词),fit 时仍统计全部词
    8 tokenizer.fit_on_texts(X)在全部文本上拟合词表fit_on_texts(X):遍历 11,314 条文本,统计词频并建立 word_index(词→整数,从 1 开始,频率高的索引小)只 fit 训练文本——本 lab 没有测试集,所以 fit 全部;严格来说验证集词表也参与了 fit(轻微泄漏,课程接受)无输出;fit 后 tokenizer.word_index 可能有数万个词,但 texts_to_sequences 只会输出 <5000 的索引
    9 global preprocess_text把嵌套函数名声明为全局global preprocess_text:告诉 Python 该名字绑定到模块级命名空间,而不是外层函数的局部命名空间这是 M13 特意强调的设计:函数返回后 preprocess_text 仍然存在,且闭包仍持有 tokenizer易错:若漏写 global,load_and_prep_20newsgroups() 返回后 preprocess_text 未定义 → C22 报 NameError
    10 def preprocess_text(texts):定义嵌套函数 preprocess_text(texts)签名:接受字符串列表;闭包捕获外层的 tokenizer 与全局 SEQ_LEN之后 C14 L14 调用一次处理训练数据;C22 L6 调用一次处理待预测文本——走的是同一条路径参数名 texts(复数)提示输入是 list,而非单个 str
    11 texts = tokenizer.texts_to_sequences(texts)文本 → 整数序列tokenizer.texts_to_sequences(texts):分词、查词表、丢掉超出 num_words 的词;返回 list[list[int]],每条长度不同与 Tokenizer fit 用的是同一个对象 → 词表一致变长,例如 [ [432, 17], [88, 12, 999, 7, ...] ]
    12 texts = sequence.pad_sequences(texts, maxlen=SEQ_LEN)pad/截断到固定长度 100sequence.pad_sequences(texts, maxlen=SEQ_LEN):默认 padding="pre"(前面补 0)、truncating="pre"(从前面截断);dtype int32输出 shape (N, 100)。这与 Lab 10 完全一致易错:默认 pre 意味着长帖保留的是最后100 个词;若想保留开头需显式 padding="post", truncating="post"
    13 return texts返回处理后的矩阵返回 numpy 数组,shape (N, 100)供 L14 赋给 X,以及 C22 L6 使用
    14 X = preprocess_text(X)对全部文本做预处理,得到 X调用刚定义的嵌套函数;X 变成 (11314, 100) 的 int32 矩阵这就是五个分类模型的输入特征X.shape = (11314, 100)
    15 y = keras.utils.to_categorical(y, num_classes=20)标签 one-hot 为 20 维keras.utils.to_categorical(y, num_classes=20):整数 (11314,) → float32 (11314, 20),每行仅对应位置为 1配合 categorical_crossentropy(C20 L2)与 softmax 输出(各模型 L5)易错:num_classes 必须等于 Dense 的 units,否则形状不匹配
    16 return X, y返回 X, y返回元组;调用方解包
    本函数是分类实验的"数据母版":五个模型都从同一行 X, y = load_and_prep_20newsgroups() 开始(C27/C34/C40/C48/C56),保证数据完全一致。每次调用都 set_random_seed(42),所以五个模型的随机性是对齐的。
    数据流:11,314 条原始文本 → Tokenizer 词表 → 整数序列(变长)→ pad 到 (11314, 100) → 标签 one-hot 到 (11314, 20)。

    This function retrieves the final results in a training history, i.e. values of "loss", "val_loss", "acc", and "val_acc" in the final epoch.

    与 Lab 6 起沿用的同名工具完全相同:取 history.history 每条曲线的最后一个值并保留 4 位小数。
    Cell 16history_final_values():取最后一轮的四项指标基础
    def history_final_values(history):
        return {k: round(v[-1], 4) for k, v in history.history.items()}
    #代码作用机制·语法关联·结果易错点
    1def history_final_values(history):定义函数输入 history(keras.callbacks.History 对象),输出 dict与 Lab 6 同名工具完全一致
    2 return {k: round(v[-1], 4) for k, v in history.history.items()}字典推导式取每条曲线的末值history.history 是 dict[str, list[float]],键有 acc / loss / val_acc / val_loss;v[-1] 取最后一轮;round(…, 4) 保留 4 位小数结果形如 {'loss': 1.9076, 'acc': 0.8232, 'val_loss': 1.9076, 'val_acc': 0.5064};C62 用它构造 final_values 表易错:若用 verbose=0 训练,history 照样记录;但若EarlyStopping 恢复最佳权重,最后一轮 ≠ 最佳

    This function plots a training history, including both training and validation results.

    Cell 18plot_history():pandas 绘制 loss/acc 双图基础
    import matplotlib.pyplot as plt
    import pandas as pd
    
    def plot_history(history):
        df = pd.DataFrame(history.history)
        df.index = df.index + 1
        fig, axs = plt.subplots(1, 2, figsize=(8, 4))
        df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])
        df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])
        plt.tight_layout()
    #代码作用机制·语法关联·结果易错点
    1import matplotlib.pyplot as plt导入 matplotlib 与 pandasmatplotlib.pyplot 绑定为 plt;pandas 绑定为 pd(与 C62 L8 再次 import pd 重复,无副作用)Lab 5 用 plt.subplot(121/122),Lab 6 起改用 pandas 的 df.plot(更简洁)在 Jupyter 中 plt 图会内联显示
    2import pandas as pd导入 matplotlib 与 pandasmatplotlib.pyplot 绑定为 plt;pandas 绑定为 pd(与 C62 L8 再次 import pd 重复,无副作用)Lab 5 用 plt.subplot(121/122),Lab 6 起改用 pandas 的 df.plot(更简洁)在 Jupyter 中 plt 图会内联显示
    4def plot_history(history):定义绘图函数输入 History 对象;无返回值(副作用:画图)
    5 df = pd.DataFrame(history.history)把 history 转成 DataFramepd.DataFrame(history.history):四个键变成四列,每行一个 epoch列名 acc/loss/val_acc/val_loss 与 Keras 的 metrics 名一致若 metrics=["acc"] 写成 "accuracy",列名也会随之变化
    6 df.index = df.index + 1索引从 1 开始df.index = df.index + 1:默认索引 0..29 → 1..30,让 x 轴显示"第几轮"而非"从 0 开始"纯显示调整易错:忘了 +1 会让图上第一轮标成 0
    7 fig, axs = plt.subplots(1, 2, figsize=(8, 4))创建 1×2 子图plt.subplots(1, 2, figsize=(8, 4)):返回 fig 与 axs(两个 Axes 的数组)左图 loss,右图 acc
    8 df.plot(y=["loss", "val_loss"], grid=True, ax=axs[0])左图画 loss/val_lossdf.plot(y=[...], grid=True, ax=axs[0]):pandas 把 DataFrame 列画到指定 Axes,x 轴自动用索引(epoch)训练 loss 与验证 loss 同图,便于看是否过拟合(gap 大 = 过拟合)
    9 df.plot(y=["acc", "val_acc"], grid=True, ax=axs[1])右图画 acc/val_acc同上,画到 axs[1]本 lab 五个模型都会出现 train acc ≫ val acc(过拟合)
    10 plt.tight_layout()紧凑布局plt.tight_layout():自动调整子图间距,避免标题/标签重叠

    This function compiles and fits a model, and returns the training history.

    Cell 20compile_and_fit_model():编译 + 训练母版(30 轮 / batch 256 / val 0.2)重点展开
    def compile_and_fit_model(model, X, y, epochs=30, batch_size=256, verbose=2):
        model.compile(loss="categorical_crossentropy",
                      optimizer="adam", metrics=["acc"])
        history = model.fit(X, y, epochs=epochs, batch_size=batch_size,
                            verbose=verbose, validation_split=0.2)
        return history
    #代码作用机制·语法关联·结果易错点
    1def compile_and_fit_model(model, X, y, epochs=30, batch_size=256, verbose=2):定义函数:5 个必填 + 3 个默认参数model, X, y 必填;epochs=30, batch_size=256, verbose=2 有默认值。verbose=2 = 每轮一行(不显示进度条)与 Lab 8 的同名函数相比:那里 epochs=20 且用 validation_data;这里 epochs=30 且用 validation_split五个分类模型都用默认参数调用 → 只改模型结构
    2 model.compile(loss="categorical_crossentropy",编译:categorical CE + Adam + acc损失用 categorical_crossentropy(因 y 是 one-hot,C14 L15);优化器 adam(默认 lr 0.001);监控 acc若 y 是整数标签应改 sparse_categorical_crossentropy(Lab 5 E1a 证明二者数值相同)易错:one-hot 标签 + sparse CE 或 整数标签 + categorical CE 都会形状不匹配/报错
    3 optimizer="adam", metrics=["acc"])编译:categorical CE + Adam + acc损失用 categorical_crossentropy(因 y 是 one-hot,C14 L15);优化器 adam(默认 lr 0.001);监控 acc若 y 是整数标签应改 sparse_categorical_crossentropy(Lab 5 E1a 证明二者数值相同)易错:one-hot 标签 + sparse CE 或 整数标签 + categorical CE 都会形状不匹配/报错
    4 history = model.fit(X, y, epochs=epochs, batch_size=batch_size,训练:30 轮、batch 256、末尾 20% 验证model.fit(...) 返回 History;validation_split=0.2 在 fit 内部按顺序切分末尾 20%(在 shuffle 之前确定),每轮训练集内部会 shuffle每轮 36 步(见 note);verbose=2 输出 30 行,形如 36/36 - 1s - 14ms/step - acc: … - val_acc: …易错:validation_split 切的是末尾——若数据按类别排序,验证集会只含某几类;fetch_20newsgroups 默认 shuffle=True 所以没问题
    5 verbose=verbose, validation_split=0.2)训练:30 轮、batch 256、末尾 20% 验证model.fit(...) 返回 History;validation_split=0.2 在 fit 内部按顺序切分末尾 20%(在 shuffle 之前确定),每轮训练集内部会 shuffle每轮 36 步(见 note);verbose=2 输出 30 行,形如 36/36 - 1s - 14ms/step - acc: … - val_acc: …易错:validation_split 切的是末尾——若数据按类别排序,验证集会只含某几类;fetch_20newsgroups 默认 shuffle=True 所以没问题
    6 return history返回 History供 history_final_values / plot_history 使用
    步数计算:X 有 11,314 条,validation_split=0.2 取末尾 20%(2,263 条)作验证(不打乱),剩 9,051 条训练 → ⌈9051/256⌉ = 36 步/轮(35×256 = 8,960,最后一步 91 条)。验证集不按 batch 计步。
    与 Lab 10 的区别:Lab 10 用 validation_data=(X_test, y_test)(IMDb 有官方测试集),本 lab 用 validation_split(20ng 没有)。两者在 Keras 中互斥,不能同时给。

    The following predict_newsgroup() function uses the model to predict the newsgroup of a text message.

    Cell 22predict_newsgroup():用模型预测单条文本的组别重点展开
    import numpy as np
    
    newsgroups = fetch_20newsgroups()
    
    def predict_newsgroup(model, text):
        X = preprocess_text([text])
        y = model.predict(X, verbose=0)[0]
        y = np.argmax(y)  # reverse one-hot encoding
        y_name = newsgroups.target_names[y]
        return y, y_name
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入 numpy用于 argmax(L8)
    3newsgroups = fetch_20newsgroups()重新加载数据集(只为取 target_names)fetch_20newsgroups() 第二次调用会命中缓存;这里只需要 newsgroups.target_names 这 20 个组名若在 C14 之后全局变量 newsgroups 已被 C6 的 Bunch 占据,这行会覆盖成同样内容的 Bunch易错:若机器离线且没有缓存,这一行会报错——其实 target_names 是固定列表,可以硬编码
    5def predict_newsgroup(model, text):定义预测函数参数:已训练模型、单条字符串文本;返回 (标签整数, 组名) 元组C32 对三条消息循环调用
    6 X = preprocess_text([text])用全局 preprocess_text 预处理preprocess_text([text]):注意输入是列表(因 L10 的 texts_to_sequences 需要列表);返回 (1, 100)这里体现了 M13 的设计意图:与训练完全一致的预处理(同 tokenizer、同 pad 规则)易错:传入 str 而非 [str] 会被当成字符序列逐字处理 → 结果错误但不报错
    7 y = model.predict(X, verbose=0)[0]模型预测,取第一行model.predict(X, verbose=0) 返回 (1, 20) 概率(softmax 输出);[0] 取唯一一行 → shape (20,)verbose=0 不打印 "1/1 ━━━" 进度条
    8 y = np.argmax(y) # reverse one-hot encodingargmax 反 one-hotnp.argmax(y):20 个概率中最大的索引 = 预测类别 0–19;注释 "reverse one-hot encoding" 指的就是把概率向量还原成整数标签与训练时 to_categorical 相反返回 np.int64(C32 输出中可见)
    9 y_name = newsgroups.target_names[y]整数标签 → 组名newsgroups.target_names[y]:查表与 C10 L2 完全相同的反查方式
    10 return y, y_name返回 (整数, 组名)元组;C32 的 f-string 会直接打印
    推理路径:原始字符串 → preprocess_text([text])(与训练完全相同的分词/pad)→ (1,100) → model.predict → (1,20) 概率 → argmax → 组名。注意 L3 重新 fetch 了一次(不带 remove)只为拿到 target_names——组名顺序与 remove 无关,所以没问题。

    Text classification


    In this section, we perform text classification on the 20 newsgroups text dataset using various recurrent neural networks.

    Training and validation results of the models are stored in a dictionary called final_values, which facilitates the display of results and is first created.

    Cell 25final_values = {}:结果收集字典基础
    final_values = {}
    #代码作用机制·语法关联·结果易错点
    1final_values = {}创建空字典键 = 模型名(model.name,如 "SimpleRNN"),值 = history_final_values 返回的 dict每个模型 cell 的 L9 都执行 final_values[model.name] = …;C62 再给每个值加 recurrent_params 键并转成 DataFrame易错:若重复运行同一模型 cell,会覆盖同名键(而不是报错)——这是想要的行为

    Using simple RNN


    This code classifies the 20 newsgroups text dataset using a simple RNN named "SimpleRNN".

    Cell 27模型 1/5:SimpleRNN(64) — 基线重点展开
    X, y = load_and_prep_20newsgroups()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.SimpleRNN(64, dropout=0.5),
        layers.Dense(20, activation="softmax")
    ], name="SimpleRNN")
    
    history = compile_and_fit_model(model, X, y)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1X, y = load_and_prep_20newsgroups()加载并预处理数据调用 C14 的母版;X (11314,100) int32,y (11314,20) float32;同时重置随机种子 42五个分类模型的第一行完全相同
    2model = keras.Sequential([开始构建 Sequential 模型keras.Sequential([...], name="SimpleRNN"):列表内按顺序堆叠层;name 用于 summary 标题与 final_values 的键model.name 在 L9 用作字典键 → "SimpleRNN"易错:若忘记 name,默认名 "sequential"/"sequential_1" 会随构建次数变化,表中键名不稳定
    3 layers.Embedding(NUM_WORDS, WV_SIZE),Embedding(5000, 96)输入整数索引 (batch, 100) → 查表输出 (batch, 100, 96);参数 5000×96 = 480,000;索引 0(padding)对应的向量也在训练但通常学到接近 0所有五个模型共享同一层设定;与 Lab 10 完全一致Embedding 默认 mask_zero=False,所以 padding 位置的 0 向量也参与循环计算
    4 layers.SimpleRNN(64, dropout=0.5),SimpleRNN(64, dropout=0.5)单一循环层:每个时间步 h_t = tanh(W_x·x_t + W_h·h_{t-1} + b);只返回最后一步 h_T → (None, 64);参数 (64+96+1)×64 = 10,304;dropout=0.5 对输入随机置零(训练时)与 Lab 10 的 RNN_64_D50 结构一致(但那里是二分类)。本 lab 固定 dropout 0.5 作为五个模型的共同设置易错:dropout 不是 recurrent_dropout——前者作用于输入 x_t,后者作用于 h_{t-1};后者不能用 cuDNN 加速
    5 layers.Dense(20, activation="softmax")Dense(20, softmax)64 → 20 个 logits 再 softmax 成概率分布;参数 64×20+20 = 1,300与 categorical_crossentropy 配对(C20)
    6], name="SimpleRNN")闭合列表并命名name="SimpleRNN" 作为 Sequential 的关键字参数
    8history = compile_and_fit_model(model, X, y)编译 + 训练调用 C20:30 轮 / batch 256 / validation_split 0.2 → 36 步/轮;verbose=2输出 30 行 epoch 日志第 1 轮 10s(含图构建),之后 ~1s/轮
    9final_values[model.name] = history_final_values(history)保存最终指标final_values[model.name] = history_final_values(history) → final_values["SimpleRNN"] = {'acc': .9503, 'loss': .2446, 'val_acc': .2872, 'val_loss': 2.9572}C62 会在此 dict 上再加 recurrent_params
    10print(final_values[model.name])打印最终指标直接打印 dict输出 {'loss': 0.2446, 'acc': 0.9503, 'val_loss': 2.9572, 'val_acc': 0.2872}
    运行结果 Epoch 1/30 36/36 - 10s - 288ms/step - acc: 0.0691 - loss: 2.9932 - val_acc: 0.0862 - val_loss: 2.9649 Epoch 2/30 36/36 - 1s - 19ms/step - acc: 0.1686 - loss: 2.8554 - val_acc: 0.0999 - val_loss: 2.9390 Epoch 3/30 36/36 - 1s - 14ms/step - acc: 0.2588 - loss: 2.6837 - val_acc: 0.1206 - val_loss: 2.9169 Epoch 4/30 36/36 - 1s - 14ms/step - acc: 0.3573 - loss: 2.4479 - val_acc: 0.1555 - val_loss: 2.8102 Epoch 5/30 36/36 - 1s - 15ms/step - acc: 0.4432 - loss: 2.1728 - val_acc: 0.1821 - val_loss: 2.6764 Epoch 6/30 36/36 - 1s - 14ms/step - acc: 0.5222 - loss: 1.8979 - val_acc: 0.2187 - val_loss: 2.547
    逐行读结果:第 1 轮 acc .0691 / loss 2.9932 / val_acc .0862 / val_loss 2.9649(ln 20 ≈ 2.996 → 初始几乎是均匀猜测);第 6 轮 acc 已到 .5222 但 val_acc 只有 .2187 —— 训练集在快速 memorize,验证集跟不上。最终(C62 表):acc .9503 / loss .2446 / val_acc .2872 / val_loss 2.9572 → 五模型中 val_acc 最低、val_loss 最高、训练 acc 最高 = 典型"记住训练集但不能泛化"。
    Cell 28绘制 SimpleRNN 训练曲线基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)调用 C18 的 plot_history左图 loss/val_loss,右图 acc/val_acc,x 轴 1–30SimpleRNN 的 val_loss 几乎不降(~2.96 徘徊)而 train loss 持续下降 → 曲线张开极大
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 29SimpleRNN summary基础
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()打印模型结构表model.summary():每层一行(层名/类型、Output Shape、Param #),末尾 Total / Trainable / Non-trainable / Optimizer 四行Keras 3 风格表格(┏━┓);层名 embedding / simple_rnn 自动编号注意 SimpleRNN 输出 (None, 64):None 是 batch 维度
    运行结果 Model: "SimpleRNN" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ simple_rnn (SimpleRNN) │ (None, [  Total params: 1,474,814 (5.63 MB)  Trainable params: 491,604 (1.88 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 983,210 (3.75 MB)
    核对:Embedding 480,000 + SimpleRNN 10,304 + Dense 1,300 = Trainable 491,604 ✓;Optimizer 2×491,604+2 = 983,210 ✓;Total = 3×491,604+2 = 1,474,814 ✓。

    Note that the SimpleRNN layer has output shape (None, 64). None refers to the "variable" or automatically-detected batch size. 64 is the number of units in the simple RNN layer. The layer has 10,304 parameters, which can be explained by the expression: 10,304 = (64 units + input depth 96 + 1 bias) &times; 64 units.

    核对:SimpleRNN 参数 (units + input_depth + 1 bias) × units = (64+96+1)×64 = 161×64 = 10,304 ✓。与 Lab 10 一样,SimpleRNN 只有一组 (W_x, W_h, b),没有门。

    The model is used for making predictions for, or classifying, some simple messages below.

    Cell 32用 SimpleRNN 预测三条消息基础
    for text in ["i want to buy a computer",
                 "read about romantic stories",
                 "watch a boring ball game"]:
        print(f"{text} -> {predict_newsgroup(model, text)}")
    #代码作用机制·语法关联·结果易错点
    1for text in ["i want to buy a computer",遍历三条测试消息Python for 循环遍历 list[str];三行字符串用隐式续行(括号内换行)每条消息独立调用 predict_newsgroup;注意 seed 文本都是小写、无标点——与 Tokenizer 的 lower/filters 处理一致易错:若输入大写或带标点,Tokenizer 会自动 lower/去标点,但若词不在词表(如生僻词)会被丢弃
    2 "read about romantic stories",遍历三条测试消息Python for 循环遍历 list[str];三行字符串用隐式续行(括号内换行)每条消息独立调用 predict_newsgroup;注意 seed 文本都是小写、无标点——与 Tokenizer 的 lower/filters 处理一致易错:若输入大写或带标点,Tokenizer 会自动 lower/去标点,但若词不在词表(如生僻词)会被丢弃
    3 "watch a boring ball game"]:遍历三条测试消息Python for 循环遍历 list[str];三行字符串用隐式续行(括号内换行)每条消息独立调用 predict_newsgroup;注意 seed 文本都是小写、无标点——与 Tokenizer 的 lower/filters 处理一致易错:若输入大写或带标点,Tokenizer 会自动 lower/去标点,但若词不在词表(如生僻词)会被丢弃
    4 print(f"{text} -> {predict_newsgroup(model, text)}")打印预测结果f-string 直接格式化函数返回的元组 (np.int64(4), 'comp.sys.mac.hardware')输出三行可见 np.int64(4) 这种类型显示——若想更干净可在 predict_newsgroup 里 int(y)
    运行结果 i want to buy a computer -> (np.int64(4), 'comp.sys.mac.hardware') read about romantic stories -> (np.int64(19), 'talk.religion.misc') watch a boring ball game -> (np.int64(10), 'rec.sport.hockey')
    结果分析:① "i want to buy a computer" → 4 comp.sys.mac.hardware(勉强合理,"computer" 相关);② "read about romantic stories" → 19 talk.religion.misc(不合理——20ng 里没有"浪漫故事"组,模型只能猜);③ "watch a boring ball game" → 10 rec.sport.hockey("ball game" 更接近 baseball,但 hockey 也是体育组,算沾边)。val_acc 只有 28.7%,所以预测质量差是意料之中。

    Using LSTM


    This code classifies the 20 newsgroups text dataset using a LSTM model named "LSTM".

    Cell 34模型 2/5:LSTM(64)基础
    X, y = load_and_prep_20newsgroups()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.LSTM(64, dropout=0.5),
        layers.Dense(20, activation="softmax")
    ], name="LSTM")
    
    history = compile_and_fit_model(model, X, y)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1X, y = load_and_prep_20newsgroups()加载数据(同上)完全同 C27 L1
    2model = keras.Sequential([构建 Sequential同 C27 L2,但 name="LSTM"
    3 layers.Embedding(NUM_WORDS, WV_SIZE),Embedding(5000, 96)同 C27 L3
    4 layers.LSTM(64, dropout=0.5),LSTM(64, dropout=0.5)门控循环单元:输入门 i / 遗忘门 f / 输出门 o + 候选 g,细胞状态 c_t 沿时间线性传递(缓解梯度消失);参数 4×(64+96+1)×64 = 41,216(SimpleRNN 的 4 倍);输出 (None, 64)这是本 lab 的主角;之后 GRU/Stacked/Bidir 都在它基础上改易错:LSTM 的 dropout 同样只作用于输入,不是 recurrent_dropout
    5 layers.Dense(20, activation="softmax")Dense(20, softmax) + 命名同 C27
    6], name="LSTM")Dense(20, softmax) + 命名同 C27
    8history = compile_and_fit_model(model, X, y)训练 / 保存 / 打印同 C27 L8–L10;每轮 ~13ms/step(比 SimpleRNN 略慢)final_values["LSTM"]第 1 轮 10s 含图构建
    9final_values[model.name] = history_final_values(history)训练 / 保存 / 打印同 C27 L8–L10;每轮 ~13ms/step(比 SimpleRNN 略慢)final_values["LSTM"]第 1 轮 10s 含图构建
    10print(final_values[model.name])训练 / 保存 / 打印同 C27 L8–L10;每轮 ~13ms/step(比 SimpleRNN 略慢)final_values["LSTM"]第 1 轮 10s 含图构建
    运行结果 Epoch 1/30 36/36 - 10s - 266ms/step - acc: 0.0816 - loss: 2.9858 - val_acc: 0.0756 - val_loss: 2.9775 Epoch 2/30 36/36 - 1s - 14ms/step - acc: 0.1460 - loss: 2.8204 - val_acc: 0.1158 - val_loss: 2.6824 Epoch 3/30 36/36 - 1s - 16ms/step - acc: 0.1699 - loss: 2.5443 - val_acc: 0.1856 - val_loss: 2.4967 Epoch 4/30 36/36 - 0s - 13ms/step - acc: 0.2400 - loss: 2.3121 - val_acc: 0.2324 - val_loss: 2.2926 Epoch 5/30 36/36 - 0s - 13ms/step - acc: 0.2948 - loss: 2.1422 - val_acc: 0.2430 - val_loss: 2.2130 Epoch 6/30 36/36 - 0s - 14ms/step - acc: 0.3384 - loss: 1.9996 - val_acc: 0.2704 - val_loss: 2.111
    只讲差异:与 C27 相比仅 L4 变为 layers.LSTM(64, dropout=0.5),name 改为 "LSTM"。第 1 轮 acc .0816 / val_acc .0756;第 6 轮 acc .3384 / val_acc .2704(比 SimpleRNN 第 6 轮 val_acc .2187 高)。最终:acc .8232 / loss .5778 / val_acc .5064 / val_loss 1.9076 —— val_acc 比 SimpleRNN 高 22 个百分点。
    Cell 35绘制 LSTM 训练曲线基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot_historyLSTM 的 val_loss 持续下降到 ~1.9,val_acc 升到 ~0.5,gap 仍大但明显好于 SimpleRNN
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 36LSTM summary基础
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summary()层名 lstm(自动编号 embedding_1 / lstm);lstm 输出 (None, 64),参数 41,216
    运行结果 Model: "LSTM" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_1 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ lstm (LSTM) │ (None, [  Total params: 1,567,550 (5.98 MB)  Trainable params: 522,516 (1.99 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 1,045,034 (3.99 MB)
    核对:480,000 + 41,216 + 1,300 = Trainable 522,516 ✓;Optimizer 1,045,034 = 2T+2 ✓;Total 1,567,550 ✓。

    Note that the LSTM layer has output shape (None, 64). None refers to the "variable" or automatically-detected batch size. 64 is the number of units in the LSTM layer. The layer has 41,216 parameters, which can be explained by the expression: 41,216 = 4 &times; (64 units + input depth 96 + 1 bias) &times; 64 units.

    核对:4×(64+96+1)×64 = 4×10,304 = 41,216 ✓。系数 4 来自四个门/候选:输入门 i、遗忘门 f、输出门 o、候选状态 g(c̃),每个都有输入权重 (96×64)、循环权重 (64×64) 和偏置 (64)。Keras 默认 unit_forget_bias=True,遗忘门偏置初始化为 1(其余为 0),让训练初期梯度更容易流动。

    Practice - Question 1 of 3


    Using GRU

    Q1a


    Modify the above LSTM model to use GRU instead. Name the new model "GRU", and save the training history in the final_values dictionary for later display. Plot the training history and show the model summary.

    Cell 40Q1a 学生作答:模型 3/5 GRU(64)练习·作答
    X, y = load_and_prep_20newsgroups()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.GRU(64, dropout=0.5),
        layers.Dense(20, activation="softmax")
    ], name="GRU")
    
    history = compile_and_fit_model(model, X, y)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1X, y = load_and_prep_20newsgroups()加载数据 / 构建 / Embedding与 C34 L1–L3 完全相同
    2model = keras.Sequential([加载数据 / 构建 / Embedding与 C34 L1–L3 完全相同
    3 layers.Embedding(NUM_WORDS, WV_SIZE),加载数据 / 构建 / Embedding与 C34 L1–L3 完全相同
    4 layers.GRU(64, dropout=0.5),GRU(64, dropout=0.5)GRU 只有更新门 z 和重置门 r(无单独输出门、无单独细胞状态);Keras 默认 reset_after=True → 双偏置;参数 3×((96+64)×64 + 2×64) = 31,104;输出 (None, 64)比 LSTM 少 10,112 个参数(≈24.5%)学生答案 Q1b 正确指出双偏置
    5 layers.Dense(20, activation="softmax")Dense(20, softmax) + name="GRU"同前
    6], name="GRU")Dense(20, softmax) + name="GRU"同前
    8history = compile_and_fit_model(model, X, y)训练 / final_values["GRU"] / 打印同前输出 30 行 epoch 日志
    9final_values[model.name] = history_final_values(history)训练 / final_values["GRU"] / 打印同前输出 30 行 epoch 日志
    10print(final_values[model.name])训练 / final_values["GRU"] / 打印同前输出 30 行 epoch 日志
    运行结果 Epoch 1/30 36/36 - 3s - 79ms/step - acc: 0.0780 - loss: 2.9869 - val_acc: 0.1087 - val_loss: 2.9787 Epoch 2/30 36/36 - 1s - 19ms/step - acc: 0.1532 - loss: 2.9310 - val_acc: 0.1308 - val_loss: 2.9062 Epoch 3/30 36/36 - 0s - 13ms/step - acc: 0.1959 - loss: 2.6390 - val_acc: 0.1688 - val_loss: 2.5299 Epoch 4/30 36/36 - 0s - 13ms/step - acc: 0.2571 - loss: 2.3244 - val_acc: 0.2024 - val_loss: 2.4222 Epoch 5/30 36/36 - 0s - 13ms/step - acc: 0.3370 - loss: 2.1058 - val_acc: 0.2501 - val_loss: 2.2724 Epoch 6/30 36/36 - 0s - 13ms/step - acc: 0.4014 - loss: 1.9131 - val_acc: 0.2850 - val_loss: 2.2082
    核对 Q1a:按要求把 LSTM 换成 GRU、name="GRU"、保存 history、plot、summary —— 全部做到。
    结果:第 1 轮 acc .0780 / val_acc .1087;第 6 轮 acc .4014 / val_acc .2850(略高于同期 LSTM)。最终:acc .8454 / loss .5075 / val_acc .4680 / val_loss 2.2616 —— 比 LSTM 略差(val_acc 低 3.8 点、val_loss 高 0.35)。GRU 参数少 1/4,速度略快,但在这份数据上没有 LSTM 好。
    Cell 41绘制 GRU 训练曲线基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot_historyGRU 的 val_acc 曲线在后期停滞甚至回落(val_loss 2.26),过拟合比 LSTM 更明显
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 42GRU summary基础
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summary()gru 层输出 (None, 64),参数 31,104
    运行结果 Model: "GRU" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_2 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ gru (GRU) │ (None, [  Total params: 1,537,214 (5.86 MB)  Trainable params: 512,404 (1.95 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 1,024,810 (3.91 MB)
    核对:480,000 + 31,104 + 1,300 = Trainable 512,404 ✓;Optimizer 1,024,810 ✓;Total 1,537,214 ✓。

    Q1b


    What is the output shape of the GRU layer in this model? Explain the numbers (i.e. dimensions) in the output shape.


    What is the number of parameters of the GRU layer in this model? Explain the number by writing an expression for calculating it, and describing the key terms in the expression.


    Write your answer in a text cell below.

    Solution:



    <div class='alert alert-warning' role='alert'><b>Output shape of the GRU layer: (None, 64)


    None = batch size (variable)

    64 = number of units (hidden state dimension) of the GRU


    Number of parameters of the GRU layer: 31 104


    Kernel weights:input_dim × (3 × units) = $96 \times 192$


    Recurrent weights:units × (3 × units) = $64 \times 192$


    Bias:2 × (3 × units) = $2 \times 192$


    $96\times192 + 64\times192 + 2\times192 = 18\,432 + 12\,288 + 384 = 31\,104$


    </b></div>

    学生答案核对(Q1b)—— 正确。GRU(64) 输出 (None, 64) ✓;参数 31,104 ✓。拆解:Kernel 96×192 = 18,432;Recurrent 64×192 = 12,288;Bias 2×192 = 384 → 合计 31,104 ✓。需要补充的一点:Keras GRU 默认 reset_after=True(GPU 版 CuDNN 兼容写法),因此有两份偏置(input bias 与 recurrent bias 各 192),所以才是 2×192=384 而不是 192;若 reset_after=False 则只有 192 个 bias → 30,912。192 = 3×64 是因为 GRU 三个门(更新门 z、重置门 r、候选状态 h̃)打包在一起计算。

    &#x2766;

    Practice - Question 2 of 3


    Using stacked RNN

    Q2a


    Modify the above LSTM model to use a stack of 2 LSTM layers instead of 1 LSTM layer. Name the new model "LSTMx2", and save the training history in the final_values dictionary for later display. Plot the training history and show the model summary. (Hint: Remember to specify the argument return_sequences=True in the first LSTM layer.)

    Cell 48Q2a 学生作答:模型 4/5 LSTMx2(stacked)练习·作答
    X, y = load_and_prep_20newsgroups()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.LSTM(64, dropout=0.5, return_sequences=True),
        layers.LSTM(64, dropout=0.5),
        layers.Dense(20, activation="softmax")
    ], name="LSTMx2")
    
    history = compile_and_fit_model(model, X, y)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1X, y = load_and_prep_20newsgroups()加载数据 / 构建 / Embedding与 C34 完全相同
    2model = keras.Sequential([加载数据 / 构建 / Embedding与 C34 完全相同
    3 layers.Embedding(NUM_WORDS, WV_SIZE),加载数据 / 构建 / Embedding与 C34 完全相同
    4 layers.LSTM(64, dropout=0.5, return_sequences=True),LSTM(64, dropout=0.5, return_sequences=True)关键:return_sequences=True 让第一层输出每个时间步的 h → (None, 100, 64),而不是只给最后的 (None, 64);这样第二层才有 100 步可以循环若漏写,第一层输出 (None, 64) 会被第二层当成"1 步序列",不报错但语义完全错(讲义 Unit 11 特别强调)参数仍是 41,216(return_sequences 不改变权重数量)
    5 layers.LSTM(64, dropout=0.5),LSTM(64, dropout=0.5)第二层:输入 64 维(上一层的 h),循环 100 步,只返回最后一步 → (None, 64);参数 4×(64+64+1)×64 = 33,024两层 LSTM 参数不同(41,216 vs 33,024)是因为 input_depth 从 96 变 64
    6 layers.Dense(20, activation="softmax")Dense(20, softmax) + name="LSTMx2"同前
    7], name="LSTMx2")Dense(20, softmax) + name="LSTMx2"同前
    9history = compile_and_fit_model(model, X, y)训练 / final_values["LSTMx2"] / 打印同前;每步耗时约 2.3 倍单层
    10final_values[model.name] = history_final_values(history)训练 / final_values["LSTMx2"] / 打印同前;每步耗时约 2.3 倍单层
    11print(final_values[model.name])训练 / final_values["LSTMx2"] / 打印同前;每步耗时约 2.3 倍单层
    运行结果 Epoch 1/30 36/36 - 3s - 91ms/step - acc: 0.0661 - loss: 2.9808 - val_acc: 0.0840 - val_loss: 2.8684 Epoch 2/30 36/36 - 1s - 31ms/step - acc: 0.1145 - loss: 2.6962 - val_acc: 0.1286 - val_loss: 2.5708 Epoch 3/30 36/36 - 2s - 43ms/step - acc: 0.1686 - loss: 2.4620 - val_acc: 0.1741 - val_loss: 2.4022 Epoch 4/30 36/36 - 1s - 35ms/step - acc: 0.2183 - loss: 2.2548 - val_acc: 0.1825 - val_loss: 2.4273 Epoch 5/30 36/36 - 1s - 26ms/step - acc: 0.2448 - loss: 2.1489 - val_acc: 0.2201 - val_loss: 2.2299 Epoch 6/30 36/36 - 1s - 29ms/step - acc: 0.2690 - loss: 2.0201 - val_acc: 0.2311 - val_loss: 2.2064
    核对 Q2a:第一层 LSTM 加了 return_sequences=True(题目提示),第二层保持默认;name="LSTMx2";保存/plot/summary 齐全 —— 正确。
    结果:第 1 轮 acc .0661 / val_acc .0840;第 6 轮 acc .2690 / val_acc .2311(比单层 LSTM 慢——每步 31ms vs 13ms,因两层串行)。最终:acc .6746 / loss .9552 / val_acc .4675 / val_loss 1.9286 —— 训练 acc 只有 67%(其他四个都在 79%+),说明 30 轮不够/模型更深更难优化;val_acc 与 GRU 持平、低于单层 LSTM。注意讲义 Unit 11 的 stacked 版本只在第二层加 dropout,本 lab 学生两层都加了 0.5(题面就是"两层各 dropout 0.5"的改法)。
    Cell 49绘制 LSTMx2 训练曲线基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot_history两层 LSTM 的 train acc 曲线明显低于其他四个模型(30 轮内只到 0.67),说明容量虽大但优化更慢;val_acc 后期在 0.46–0.47 徘徊
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 50LSTMx2 summary基础
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summary()两层 LSTM 行:第一层 (None,100,64) 41,216;第二层 (None,64) 33,024;C62 用 41_216 + 33_024 作 recurrent_params
    运行结果 Model: "LSTMx2" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_3 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ lstm_1 (LSTM) │ (None, [  Total params: 1,666,622 (6.36 MB)  Trainable params: 555,540 (2.12 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 1,111,082 (4.24 MB)
    核对:480,000 + 41,216 + 33,024 + 1,300 = Trainable 555,540 ✓;Optimizer 1,111,082 ✓;Total 1,666,622 ✓。表里第一层 lstm_1 输出 (None, 100, 64)(因 return_sequences),第二层 lstm_2 输出 (None, 64)。

    Q2b


    What is the output shape of the first LSTM layer in this model? Explain the numbers (i.e. dimensions) in the output shape.


    What is the number of parameters of the first LSTM layer in this model? Explain the number by writing an expression for calculating it, and describing the key terms in the expression.


    Write your answer in a text cell below.

    Solution:



    <div class='alert alert-warning' role='alert'><b>Output shape of the first LSTM layer: (None, 100, 64)


    None = batch size

    100 = sequence length (SEQ_LEN)

    64 = number of units


    Number of parameters of the first LSTM layer: 41 216


    $$4 \times \bigl( (input\_dim + units) \times units + units \bigr)

    = 4 \times \bigl( (96 + 64) \times 64 + 64 \bigr)

    = 4 \times 10\,304

    = 41\,216$$

    </b></div>

    学生答案核对(Q2b)—— 正确。第一层 LSTM 因 return_sequences=True 输出 (None, 100, 64) ✓;参数 4×((96+64)×64+64) = 4×10,304 = 41,216 ✓(与单层 LSTM 相同,因为输入仍是 96 维)。注意学生答案里表达式写成 4 × ((input_dim + units) × units + units),展开就是 4×(input_dim×units + units×units + units),与 4×(n+m+1)×n 等价。

    &#x2766;

    Practice - Question 3 of 3


    Using bidirectional RNN

    Q3a


    Modify the above LSTM model (with 1 LSTM layer) to use a bidirectional LSTM layer. Name the new model "Bidir-LSTM", and save the training history in the final_values dictionary for later display. Plot the training history and show the model summary. (Hint: Use layers.Bidirectional(layers.LSTM(...)).)

    Cell 56Q3a 学生作答:模型 5/5 Bidir-LSTM练习·作答
    X, y = load_and_prep_20newsgroups()
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.Bidirectional(layers.LSTM(64, dropout=0.5)),
        layers.Dense(20, activation="softmax")
    ], name="Bidir-LSTM")
    
    history = compile_and_fit_model(model, X, y)
    final_values[model.name] = history_final_values(history)
    print(final_values[model.name])
    #代码作用机制·语法关联·结果易错点
    1X, y = load_and_prep_20newsgroups()加载数据 / 构建 / Embedding与 C34 完全相同
    2model = keras.Sequential([加载数据 / 构建 / Embedding与 C34 完全相同
    3 layers.Embedding(NUM_WORDS, WV_SIZE),加载数据 / 构建 / Embedding与 C34 完全相同
    4 layers.Bidirectional(layers.LSTM(64, dropout=0.5)),Bidirectional(LSTM(64, dropout=0.5))包装器:内部复制一个正向 LSTM(从 t=1→100)和一个反向 LSTM(从 t=100→1,输入被 reverse),各自独立参数;最后一步输出按 merge_mode="concat" 拼接 → (None, 128);参数 2×41,216 = 82,432与 stacked 的区别:stacked 是串行(深层),bidir 是并行(双方向);两者都可以叠加易错:Bidirectional 的反向层不是"共享权重",参数翻倍;merge_mode 可选 sum/mul/ave/concat,默认 concat
    5 layers.Dense(20, activation="softmax")Dense(20, softmax)输入变成 128 维 → 参数 128×20+20 = 2,580(其他模型是 1,300)这是 Bidir 模型 Dense 参数与其他四个不同的原因
    6], name="Bidir-LSTM")name="Bidir-LSTM"
    8history = compile_and_fit_model(model, X, y)训练 / final_values["Bidir-LSTM"] / 打印同前
    9final_values[model.name] = history_final_values(history)训练 / final_values["Bidir-LSTM"] / 打印同前
    10print(final_values[model.name])训练 / final_values["Bidir-LSTM"] / 打印同前
    运行结果 Epoch 1/30 36/36 - 3s - 95ms/step - acc: 0.0762 - loss: 2.9795 - val_acc: 0.1052 - val_loss: 2.9543 Epoch 2/30 36/36 - 1s - 20ms/step - acc: 0.1303 - loss: 2.7853 - val_acc: 0.1175 - val_loss: 2.6266 Epoch 3/30 36/36 - 1s - 20ms/step - acc: 0.1735 - loss: 2.5098 - val_acc: 0.1662 - val_loss: 2.4688 Epoch 4/30 36/36 - 1s - 20ms/step - acc: 0.2132 - loss: 2.3514 - val_acc: 0.1776 - val_loss: 2.4002 Epoch 5/30 36/36 - 1s - 21ms/step - acc: 0.2416 - loss: 2.2398 - val_acc: 0.1962 - val_loss: 2.3471 Epoch 6/30 36/36 - 1s - 22ms/step - acc: 0.2744 - loss: 2.1358 - val_acc: 0.2156 - val_loss: 2.2795
    核对 Q3a:用 layers.Bidirectional(layers.LSTM(64, dropout=0.5)) 包装,name="Bidir-LSTM",保存/plot/summary 齐全 —— 正确。
    结果:第 1 轮 acc .0762 / val_acc .1052;第 6 轮 acc .2744 / val_acc .2156。最终:acc .7937 / loss .6427 / val_acc .5250 / val_loss 1.7438 —— val_acc 与 val_loss 双料冠军。代价:参数最多(565,012)、每步 ~20ms。直觉:文本分类中"后面的词能照亮前面的词",反向读一遍提供了额外上下文。
    Cell 57绘制 Bidir-LSTM 训练曲线基础
    plot_history(history)
    #代码作用机制·语法关联·结果易错点
    1plot_history(history)plot_historyval_acc 曲线最终到 ~0.52,是五条中最高的;val_loss ~1.74 最低
    运行结果 <Figure size 800x400 with 2 Axes> [image/png]
    Cell 58Bidir-LSTM summary基础
    model.summary()
    #代码作用机制·语法关联·结果易错点
    1model.summary()summary()bidirectional 层一行显示合并后的输出形状 (None, 128) 与两个方向的总参数 82,432
    运行结果 Model: "Bidir-LSTM" ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┓ ┃ Layer (type)  ┃ Output Shape  ┃  Param # ┃ ┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━┩ │ embedding_4 (Embedding) │ (None, 100, 96) │ 480,000 │ ├─────────────────────────────────┼────────────────────────┼───────────────┤ │ bidirectional (Bidirectional) │ (None, [  Total params: 1,695,038 (6.47 MB)  Trainable params: 565,012 (2.16 MB)  Non-trainable params: 0 (0.00 B)  Optimizer params: 1,130,026 (4.31 MB)
    核对:480,000 + 82,432 + 2,580 = Trainable 565,012 ✓;Optimizer 1,130,026 ✓;Total 1,695,038 ✓。表里 bidirectional 层输出 (None, 128),参数 82,432;dense 层参数 2,580(比其他模型多 1,280)。

    Q3b


    What is the output shape of the bidirectional layer in this model? Explain the numbers (i.e. dimensions) in the output shape.


    What is the number of parameters of the bidirectional layer in this model? Explain the number by writing an expression for calculating it, and describing the key terms in the expression.


    Write your answer in a text cell below.

    Solution:



    <div class='alert alert-warning' role='alert'><b>Output shape of the bidirectional layer: (None, 128)


    None = batch size

    128 = 64 (forward) + 64 (backward)


    Number of parameters of the bidirectional layer: 82 432

    (twice a unidirectional LSTM of the same size):

    $$2 \times 41\,216 = 82\,432$$</b></div>

    学生答案核对(Q3b)—— 正确。Bidirectional 默认 merge_mode="concat",正向 64 + 反向 64 → (None, 128) ✓;参数 2×41,216 = 82,432 ✓。补充:这也就是为什么 Bidir 模型的 Dense(20) 变成 128×20+20 = 2,580,总 Trainable 565,012 比单层 LSTM 多 42,496(= 41,216 + 1,280)。

    Q3c


    Referring to the execution outputs of the above models, add the numbers of parameters in the recurrent layer(s) for the models to the final_values dictionary using the key recurrent_params. The numbers of parameters for "SimpleRNN" and "LSTM" have been added in the code below. Write code to add those for the "GRU", "LSTMx2", and "Bidir-LSTM". For stacked model "LSTMx2", use the total number of parameters in the 2 LSTM layers.


    After adding the recurrent_param values, write code to display the training and validation results in the final_values dictionary.

    Q3c 读表要点:final_values 表中 recurrent_params 列出现 10304.0 这样的小数形式,是因为 pandas 把整列转成 float64(其他列是浮点)——纯显示问题,不影响数值。
    Cell 62Q3c 学生作答:汇总五模型结果表练习·作答
    final_values["SimpleRNN"]["recurrent_params"] = 10_304
    final_values["LSTM"]["recurrent_params"] = 41_216
    
    final_values["GRU"]["recurrent_params"] = 31_104          # from model.summary()
    final_values["LSTMx2"]["recurrent_params"] = 41_216 + 33_024  # first + second LSTM
    final_values["Bidir-LSTM"]["recurrent_params"] = 82_432
    
    import pandas as pd
    display(pd.DataFrame(final_values).T)
    #代码作用机制·语法关联·结果易错点
    1final_values["SimpleRNN"]["recurrent_params"] = 10_304题目已给的 SimpleRNN / LSTM 参数10_304 / 41_216:Python 数字下划线分隔符(3.6+),纯可读性;与 summary 一致从 final_values["SimpleRNN"](C27 L9 存入)的 dict 里新增一个键
    2final_values["LSTM"]["recurrent_params"] = 41_216题目已给的 SimpleRNN / LSTM 参数10_304 / 41_216:Python 数字下划线分隔符(3.6+),纯可读性;与 summary 一致从 final_values["SimpleRNN"](C27 L9 存入)的 dict 里新增一个键
    4final_values["GRU"]["recurrent_params"] = 31_104 # from model.summary()GRU 的循环层参数31_104 = 3×((96+64)×64+2×64);来源 C42 summary
    5final_values["LSTMx2"]["recurrent_params"] = 41_216 + 33_024 # first + second LSTMLSTMx2 两层之和41_216(第一层,输入 96)+ 33_024(第二层,输入 64)= 74,240;注释 "first + second LSTM"题目要求"用两层的总数"
    6final_values["Bidir-LSTM"]["recurrent_params"] = 82_432Bidir 的循环层参数82_432 = 2×41,216(正向 + 反向,参数不共享)
    8import pandas as pd导入 pandasC18 已 import 过,这里再写一次使 cell 自包含
    9display(pd.DataFrame(final_values).T)转成 DataFrame 并转置显示pd.DataFrame(final_values):外层键(模型名)变成列、内层键(acc/loss/…)变成索引;.T 转置后每行一个模型、每列一个指标;display() 富显示输出 5 行 × 5 列表格;列顺序按字母排序 acc / loss / val_acc / val_loss / recurrent_params若某模型缺 recurrent_params 键,该格会是 NaN——本题五个都补齐了
    运行结果 acc loss val_acc val_loss recurrent_params SimpleRNN 0.9503 0.2446 0.2872 2.9572 10304.0 LSTM 0.8232 0.5778 0.5064 1.9076 41216.0 GRU 0.8454 0.5075 0.4680 2.2616 31104.0 LSTMx2 0.6746 0.9552 0.4675 1.9286 74240.0 Bidir-LSTM 0.7937 0.6427 0.5250 1.7438 82432.0
    核对 Q3c:GRU 31,104 ✓、LSTMx2 41,216+33,024 = 74,240 ✓、Bidir 82,432 ✓(全部与 summary 一致);用 pd.DataFrame(final_values).T 转置后每行一个模型 —— 正确。
    读表结论(考试可能让你解释):
    ① 泛化:Bidir .5250 > LSTM .5064 > GRU .4680 ≈ LSTMx2 .4675 > SimpleRNN .2872;val_loss 排序完全一致(1.7438 < 1.9076 < 1.9286 < 2.2616 < 2.9572)。
    ② 过拟合:所有模型 train acc ≫ val acc,SimpleRNN 最夸张(.95 vs .29);门控结构(LSTM/GRU)显著改善泛化。
    ③ 参数最多 ≠ 最好:Bidir(82k)最好,但 LSTMx2(74k)反而不及单层 LSTM(41k)—— 深度需要更多轮数/正则化才能兑现。
    ④ pandas 把 recurrent_params 列显示为 10304.0(float),因为同列有 NaN 前被统一转 float64——纯显示问题。

    &#x2766;

    Extras


    In this section, we use a recurrent network to generate text of a hopefully meaningful passage.

    Text generation

    Text can be generated word by word using a recurrent network model, which is trained to predict, or generate, the next word from a given sequence of words. To train the model, we use a long text, such as a fiction, as training examples. A training example is a run of $n+1$ consecutive words, where the first $n$ words (a sequence) are the features, and the final word is the label.


    When the model has been trained, text is generated by specifying some seed text as features to predict the next word, appending the new word to the seed text and repeating the prediction; the process continues until enough words have been generated. In text generation, we do not always select the "best" word which has the highest predicted probability. It is desirable to apply some randomness in choosing the generated word so that the generated contents have some variations.


    Let's look at the code. The following code loads the text from a file and cleans up the text.

    文本生成的核心思想(讲义 Unit 11 "Text generation"):把"下一词预测"当作 5000 类分类。训练样本 = 文本中每个长度 20 的滑动窗口(特征)+ 紧随其后的 1 个词(标签)。生成时用 seed 文本预测一个词 → 拼到 seed 末尾 → 再预测 → 循环。这就是最朴素的自回归(autoregressive)语言模型,与今天 GPT 类模型的区别只在于"单向 RNN 一次看一个状态"vs"Transformer 看整个上下文"。
    Cell 67load_and_cleanup_text():清洗 Project Gutenberg 文本重点展开
    import re
    
    START_PATTERN = r"\*\*\* START OF THE PROJECT GUTENBERG EBOOK .* \*\*\*"
    END_PATTERN = r"\*\*\* END OF THE PROJECT GUTENBERG EBOOK .* \*\*\*"
    PUNCTUATION_PATTERN = '([!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~])'
    
    def load_and_cleanup_text(filename):
        with open(filename) as f:
            text = f.read()
        start = re.search(START_PATTERN, text).end()
        stop = re.search(END_PATTERN, text).start()
        text = text[start:stop]     # remove gutenbery header and footer
        text = text.lower()         # convert to lowercase
        text = re.sub(PUNCTUATION_PATTERN, r" \1 ", text)
                                    # remove punctuation
        text = text.replace("\n", " ")   # convert end-of-lines to spaces
        text = re.sub("  +", " ", text)  # clean consecutive spaces
        text = text.strip()         # remove beginning and ending spaces
        return text
    #代码作用机制·语法关联·结果易错点
    1import re导入正则模块re:Python 标准库正则表达式下面 L3–L5 的 pattern 与 L10/L11/L14/L17 的 sub/search 都依赖它
    3START_PATTERN = r"\*\*\* START OF THE PROJECT GUTENBERG EBOOK .* \*\*\*"定义头/尾标记的正则r"\*\*\* START OF THE PROJECT GUTENBERG EBOOK .* \*\*\*":原始字符串(反斜杠不转义);\* 匹配字面星号;.* 匹配书名等任意字符Gutenberg 所有电子书都有这两行标记(新版 EBOOK、旧版 "START OF THIS PROJECT"),用于定位正文边界易错:旧版文件(如 pg11 的某些缓存)可能写 "START OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND",.* 能兜住;但 "THIS PROJECT GUTENBERG" 旧格式匹配不到
    4END_PATTERN = r"\*\*\* END OF THE PROJECT GUTENBERG EBOOK .* \*\*\*"定义头/尾标记的正则r"\*\*\* START OF THE PROJECT GUTENBERG EBOOK .* \*\*\*":原始字符串(反斜杠不转义);\* 匹配字面星号;.* 匹配书名等任意字符Gutenberg 所有电子书都有这两行标记(新版 EBOOK、旧版 "START OF THIS PROJECT"),用于定位正文边界易错:旧版文件(如 pg11 的某些缓存)可能写 "START OF THE PROJECT GUTENBERG EBOOK ALICE'S ADVENTURES IN WONDERLAND",.* 能兜住;但 "THIS PROJECT GUTENBERG" 旧格式匹配不到
    5PUNCTUATION_PATTERN = '([!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~])'定义"所有 ASCII 标点"的字符类'([!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~])':方括号内列出每个标点字符(- 放在末尾避免被当范围,\ 需双写);外层括号 = 捕获组,供 L14 的 \1 反向引用这个字符类与 string.punctuation 内容相同(32 个字符)易错:字符串里同时含单引号和双引号,用了 \' 转义——手写时容易漏
    7def load_and_cleanup_text(filename):定义清洗函数输入文件名,返回清洗后的单行字符串C77 L2 / C91 L2 调用
    8 with open(filename) as f:读取整个文件with open(filename) as f: 上下文管理器自动关闭;f.read() 一次读入全部文本(默认 UTF-8 编码;Gutenberg 文件为 UTF-8)返回 str,含 \n 与 \r\n(Windows 行尾也可能出现)易错:若用 open(filename, encoding="utf-8") 更稳妥;若文件是 latin-1 会报 UnicodeDecodeError
    9 text = f.read()读取整个文件with open(filename) as f: 上下文管理器自动关闭;f.read() 一次读入全部文本(默认 UTF-8 编码;Gutenberg 文件为 UTF-8)返回 str,含 \n 与 \r\n(Windows 行尾也可能出现)易错:若用 open(filename, encoding="utf-8") 更稳妥;若文件是 latin-1 会报 UnicodeDecodeError
    10 start = re.search(START_PATTERN, text).end()定位正文起点re.search(START_PATTERN, text).end():返回第一个匹配的 Match 对象,.end() 给出匹配子串结束位置(即 START 行末尾)text[start:] 从这里开始切易错:若匹配不到(.search 返回 None),.end() 会抛 AttributeError —— 说明文件格式不对/下载不完整
    11 stop = re.search(END_PATTERN, text).start()定位正文终点re.search(END_PATTERN, text).start():END 行起始位置text[:stop] 切到 END 之前
    12 text = text[start:stop] # remove gutenbery header and footer切除 Gutenberg 头尾text[start:stop]:切片取闭开区间 [start, stop)注释 "gutenbery" 拼写错误(应为 gutenberg),不影响运行
    13 text = text.lower() # convert to lowercase全部转小写text.lower():减少词表大小(Alice/alice/ALICE 合一)与 Tokenizer 默认 lower=True 一致(双保险)代价:生成文本全部小写、专有名词丢失
    14 text = re.sub(PUNCTUATION_PATTERN, r" \1 ", text)标点前后加空格re.sub(PUNCTUATION_PATTERN, r" \1 ", text):把每个捕获的标点替换为"空格+标点+空格",例如 alice's → alice ' s;\1 是第 1 个捕获组这样 Tokenizer 按空格分词时标点就是独立 token;C83 输出中 " , " " ! " 就来自这里注释说 remove punctuation 实际是 isolate punctuation;弯引号 ' " – 不在 ASCII 标点表内,会原样保留并粘在词上(输出中 "in that" 前的 “ 即是)
    15 # remove punctuation标点前后加空格re.sub(PUNCTUATION_PATTERN, r" \1 ", text):把每个捕获的标点替换为"空格+标点+空格",例如 alice's → alice ' s;\1 是第 1 个捕获组这样 Tokenizer 按空格分词时标点就是独立 token;C83 输出中 " , " " ! " 就来自这里注释说 remove punctuation 实际是 isolate punctuation;弯引号 ' " – 不在 ASCII 标点表内,会原样保留并粘在词上(输出中 "in that" 前的 “ 即是)
    16 text = text.replace("\n", " ") # convert end-of-lines to spaces换行 → 空格text.replace("\n", " "):把整本书压成逻辑上的一行,避免换行被当成分隔符的歧义若保留 \n,Tokenizer 默认 filters 含 \n 也会删掉,效果类似
    17 text = re.sub(" +", " ", text) # clean consecutive spaces压缩连续空格re.sub(" +", " ", text):两个及以上空格 → 一个空格(L14/L16 会产生多个空格)Tokenizer 的 split=' ' 是按单个空格切,连续空格会产生空字符串 token —— 必须压缩易错:若用 " +" 也可以(一个及以上)," +" 更保守地只压缩两个以上
    18 text = text.strip() # remove beginning and ending spaces去首尾空格strip()
    19 return text返回清洗后的文本单行长字符串,词之间单空格分隔
    为什么要清洗:Gutenberg 电子书带有版权声明/编辑信息(头)和许可协议(尾),还有大量标点、换行、连续空格。训练语言模型时这些噪音会被当成"词"学习。本函数把 Alice 原文 ~170 KB 变成一行干净小写文本。
    关键设计:标点不是删除而是用空格隔开变成独立 token(L14),这样 ''、''、'!' 能保留为词——生成的文本才会带标点(见 C83–C85 输出中的 , " ! ?)。注释 "remove punctuation" 其实不准确,实际是"分离标点"。

    These are some import statements and constant definitions.

    Cell 69导入与常量(文本生成部分)基础
    import numpy as np
    from tensorflow import keras
    from tensorflow.keras import layers
    from tensorflow.keras.preprocessing import sequence
    from tensorflow.keras.preprocessing.text import Tokenizer
    from tensorflow.keras.utils import to_categorical
    
    NUM_WORDS = 5000    # how many most frequent words in the corpus to use
    NUM_SKIP_WORDS = 0  # how many stop words to skip
    WV_SIZE = 96        # word vector size, 96D, each vector having 96 values
    SEQ_LEN = 20        # standardized length of text after padding/truncating
    #代码作用机制·语法关联·结果易错点
    1import numpy as np导入 numpy / keras / layers / sequence / Tokenizer / to_categorical与 C12 重复的部分无副作用;新增 to_categorical 直接绑定,C73 L6 用
    2from tensorflow import keras导入 numpy / keras / layers / sequence / Tokenizer / to_categorical与 C12 重复的部分无副作用;新增 to_categorical 直接绑定,C73 L6 用
    3from tensorflow.keras import layers导入 numpy / keras / layers / sequence / Tokenizer / to_categorical与 C12 重复的部分无副作用;新增 to_categorical 直接绑定,C73 L6 用
    4from tensorflow.keras.preprocessing import sequence导入 numpy / keras / layers / sequence / Tokenizer / to_categorical与 C12 重复的部分无副作用;新增 to_categorical 直接绑定,C73 L6 用
    5from tensorflow.keras.preprocessing.text import Tokenizer导入 numpy / keras / layers / sequence / Tokenizer / to_categorical与 C12 重复的部分无副作用;新增 to_categorical 直接绑定,C73 L6 用
    6from tensorflow.keras.utils import to_categorical导入 numpy / keras / layers / sequence / Tokenizer / to_categorical与 C12 重复的部分无副作用;新增 to_categorical 直接绑定,C73 L6 用
    8NUM_WORDS = 5000 # how many most frequent words in the corpus to useNUM_WORDS = 5000覆盖 C12 的同名全局变量(值相同)Embedding(5000, 96) → 480,000;Dense(5000, softmax) 输出 5000 类
    9NUM_SKIP_WORDS = 0 # how many stop words to skipNUM_SKIP_WORDS = 0要跳过的停用词数量(0 = 不跳过)本 lab 未使用;讲义版本会跳过最频繁的若干词若改为非 0,需要在 tokenize/generate 处对应实现
    10WV_SIZE = 96 # word vector size, 96D, each vector having 96 valuesWV_SIZE = 96同前
    11SEQ_LEN = 20 # standardized length of text after padding/truncatingSEQ_LEN = 20每个训练样本的输入窗口 = 20 个词;标签 = 第 21 个词C73 的滑动窗口步长 1;C81 生成时每次取 seed 末尾 20 个词与分类任务的 100 不同,不要混淆
    与 C12 相比:重新定义 NUM_WORDS=5000(同)、WV_SIZE=96(同)、SEQ_LEN=20(分类是 100,这里窗口只需 20 个词);新增 NUM_SKIP_WORDS=0(定义了但全 lab 未使用——讲义 Unit 11 的版本会用它跳过停用词)。to_categorical 在这里直接导入(分类部分用的是 keras.utils.to_categorical)。

    This function tokenizes the text, i.e. breaking the text into words.

    Cell 71tokenize_text():整本书分词重点展开
    def tokenize_text(text):
        tokenizer = Tokenizer(num_words=NUM_WORDS, filters="")
        tokenizer.fit_on_texts([text])
        token_list = tokenizer.texts_to_sequences([text])[0]
        return tokenizer, token_list
    #代码作用机制·语法关联·结果易错点
    1def tokenize_text(text):定义函数输入清洗后的全文 str;返回 (tokenizer, token_list)C77 L3 / C91 L3 调用并解包
    2 tokenizer = Tokenizer(num_words=NUM_WORDS, filters="")创建 Tokenizer(5000, filters="")num_words=5000:词表上限;filters="":不过滤任何字符;默认 lower=True、split=" "filters="" 是与 C14 的关键区别——保留标点 token
    3 tokenizer.fit_on_texts([text])在整本书上拟合词表fit_on_texts([text]):text 是单行长字符串;按空格切分后统计词频,建 word_index(索引 1 = 最频繁词)Alice 词表远超 5000(约 6,000+ 个不同 token),num_words=5000 会截断
    4 token_list = tokenizer.texts_to_sequences([text])[0]全文 → 整数序列texts_to_sequences([text]) 返回 list[list[int]](长度 1);[0] 取出唯一的内层列表 → token_list 是一个超长 list[int]这就是 C73 滑动窗口的来源注意 texts_to_sequences 会丢弃超出 num_words 的词(不是替换成 UNK),所以 token_list 的长度 < 实际词数
    5 return tokenizer, token_list返回 tokenizer 与 token_listtokenizer 含 word_index / index_word,C81 L11 用 index_word 反查词
    与分类任务的 Tokenizer 差异:① filters="" —— 不删任何字符(因为 C67 已经手动把标点隔开,如果再用默认 filters 会把标点全删掉,生成文本就没有标点了);② fit_on_texts([text]) 传的是含一个元素的列表(整本书是一个字符串),而不是按行/按句的列表。

    This function generates a dataset of examples from the text.

    Cell 73generate_text_dataset():滑动窗口造样本重点展开
    def generate_text_dataset(token_list):
        X, y = [], []
        for i in range(0, len(token_list) - SEQ_LEN):
            X.append(token_list[i: i + SEQ_LEN])
            y.append(token_list[i + SEQ_LEN])
        y = to_categorical(y, num_classes = NUM_WORDS)
        return np.array(X), np.array(y)
    #代码作用机制·语法关联·结果易错点
    1def generate_text_dataset(token_list):定义函数输入 token_list(list[int]),返回 (np.array(X), np.array(y))C77 L4 / C91 L4 调用
    2 X, y = [], []初始化两个空列表X 存窗口(每个是 20 个 int),y 存下一词(单个 int)
    3 for i in range(0, len(token_list) - SEQ_LEN):滑动窗口遍历range(0, len(token_list) - SEQ_LEN):i 从 0 到 len−21;最后一个窗口 [len−21, len−1) 20 个词 + 标签 token_list[len−1]步长 1 → 相邻样本共享 19 个词(高度重叠,是语言模型标准做法)易错:若写成 range(0, len(token_list)) 会越界;若写成 len − SEQ_LEN − 1 会少一个样本
    4 X.append(token_list[i: i + SEQ_LEN])截取 20 词窗口作为特征token_list[i : i + SEQ_LEN]:列表切片,长度 20
    5 y.append(token_list[i + SEQ_LEN])取下一个词作为标签token_list[i + SEQ_LEN]:紧跟窗口后的第 21 个词
    6 y = to_categorical(y, num_classes = NUM_WORDS)标签 one-hotto_categorical(y, num_classes=NUM_WORDS):list[int] → ndarray (N, 5000) float32配合 categorical_crossentropy(C77 L12)与 Dense(5000, softmax)内存大户:见 note
    7 return np.array(X), np.array(y)转成 numpy 数组并返回X → (N, 20) int32;y → (N, 5000) float32
    样本数:Alice 的 token_list 长度约 33,000+ → 样本数 = len − 20;1,032 步 × 32 = 33,024–34,055 条。每个样本 X[i] = token_list[i : i+20](20 个词),y[i] = token_list[i+20](第 21 个词),one-hot 成 5000 维。
    内存:y 是 (N, 5000) float32 → 33,000×5000×4 B ≈ 660 MB;Frankenstein 85,000×5000×4 ≈ 1.7 GB —— 这是为什么本 lab 不用更多数据。

    We use the text of Alice's Adventures in Wonderland by Lewis Carroll to train the model. This shell command downloads the text from the Project Gutenbery website.

    Cell 75下载 Alice in Wonderland导入·绘图·输出
    ![ -f alice.txt ] || curl -o alice.txt \
    https://www.gutenberg.org/cache/epub/11/pg11.txt
    #代码作用机制·语法关联·结果易错点
    1![ -f alice.txt ] || curl -o alice.txt \条件下载![ -f alice.txt ] || curl -o alice.txt \\ URL:shell 命令——若文件不存在([ -f ] 为假)则执行 curl;-o 指定输出文件名;行尾 \\ 续行Gutenberg 的 cache/epub/11/pg11.txt 是固定 UTF-8 纯文本版(#11 是 Alice 的编号)首次运行下载 ~170 KB(curl 进度条);再运行直接跳过。易错:无网络时首次会失败
    2https://www.gutenberg.org/cache/epub/11/pg11.txtURLProject Gutenberg 官方地址Frankenstein 是 #84(C87)
    运行结果 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 170k 100 170k 0 0 93050 0 0:00:01 0:00:01 --:--:-- 93040

    This code loads the text and prepares the dataset. Then, it creates, configures, and trains a model.

    Cell 77Alice:准备数据 + 构建 + 训练生成模型重点展开
    keras.utils.set_random_seed(42)
    text = load_and_cleanup_text("alice.txt")
    tokenizer, token_list = tokenize_text(text)
    X, y = generate_text_dataset(token_list)
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.LSTM(128, dropout=0.2),
        layers.Dense(NUM_WORDS, activation="softmax")
    ])
    
    model.compile(loss="categorical_crossentropy", optimizer="adam",
                  metrics=["acc"])
    history = model.fit(X, y, epochs=20, batch_size=32)
    #代码作用机制·语法关联·结果易错点
    1keras.utils.set_random_seed(42)固定随机种子keras.utils.set_random_seed(42)让 LSTM 初始化、dropout 掩码、fit 的 shuffle 可复现;但 sample_word 里的 np.random(C79 L6)不受其影响——除非在生成前再 set_seed
    2text = load_and_cleanup_text("alice.txt")读取并清洗文本调用 C67 → 单行 str
    3tokenizer, token_list = tokenize_text(text)分词调用 C71 → tokenizer(含词表)、token_list(list[int])
    4X, y = generate_text_dataset(token_list)生成数据集调用 C73 → X (N,20)、y (N,5000)Alice:N ≈ 33,000–34,000
    6model = keras.Sequential([构建 Sequential(无 name)生成模型不需要 name(没有 final_values 表)
    7 layers.Embedding(NUM_WORDS, WV_SIZE),Embedding(5000, 96)480,000 参数;输出 (batch, 20, 96)
    8 layers.LSTM(128, dropout=0.2),LSTM(128, dropout=0.2)4×(128+96+1)×128 = 115,200;输出 (batch, 128)——只取最后一步的 h 作为"整段 20 词的语义摘要"128 单元比分类模型(64)大一倍,因为要预测 5000 类而非 20 类
    9 layers.Dense(NUM_WORDS, activation="softmax")Dense(5000, softmax)128 → 5000 类概率;参数 645,000(占模型 52%)。这就是"词表越大输出层越贵"的直观例子与 categorical_crossentropy 配对
    10])闭合层列表] 结束传给 Sequential 的列表;本模型没有 name 参数
    12model.compile(loss="categorical_crossentropy", optimizer="adam",编译categorical CE + Adam + acc(acc = 下一词预测准确率,训练指标)无 validation 参数 → history 只有 acc/loss 两条曲线
    13 metrics=["acc"])编译categorical CE + Adam + acc(acc = 下一词预测准确率,训练指标)无 validation 参数 → history 只有 acc/loss 两条曲线
    14history = model.fit(X, y, epochs=20, batch_size=32)训练 20 轮、batch 32N/32 → 1,032 步/轮;无 validation_split/validation_data;verbose 默认 1(Keras 3 显示 ━━━ 进度条)输出 20 行;每轮 ~6ms/step → 约 6–11 sacc 从 .08 升到约 .47;loss 从 6.35 降到约 1.5
    运行结果 Epoch 1/20 1032/1032 ━━━━━━━━━━━━━━━━━━━━ 8s 6ms/step - acc: 0.0799 - loss: 6.3481 Epoch 2/20 1032/1032 ━━━━━━━━━━━━━━━━━━━━ 11s 6ms/step - acc: 0.1363 - loss: 5.3311 Epoch 3/20 1032/1032 ━━━━━━━━━━━━━━━━━━━━ 6s 6ms/step - acc: 0.1606 - loss: 4.9351 Epoch 4/20 1032/1032 ━━━━━━━━━━━━━━━━━━━━ 10s 6ms/step - acc: 0.1893 - loss: 4.6012 Epoch 5/20 1032/1032 ━━━━━━━━━━━━━━━━━━━━ 7s 6ms/step - acc: 0.2086 - loss: 4.3202 Epoch 6/20 [
    模型结构:Embedding(5000,96) → LSTM(128, dropout 0.2) → Dense(5000, softmax)。参数:480,000 + 4×(128+96+1)×128 = 115,200 + 128×5000+5000 = 645,000 → Trainable 1,240,200(Dense 占 52%!);Optimizer 2,480,402;Total 3,720,602。
    训练:无验证集(纯生成任务,acc 只是"下一词预测准确率"),20 轮 batch 32 → 1,032 步/轮;第 1 轮 acc .0799 / loss 6.3481(ln 5000 ≈ 8.52,初始应接近此值,6.35 说明第一轮内已快速学习);最终 acc ≈ .47(讲义 .4667)。
    与分类模型的区别:LSTM 128 单元(非 64)、dropout 0.2(非 0.5)、无 validation_split、Dense 5000(非 20)。

    The sample_word() function below selects, or samples, a word from the available words with predicted probabilities. The temperature parameter is a value between 0.0 and 1.0. A small temperature value further emphasizes the highest predicted probability and makes word selection more deterministic, while a large temperature value lets word selection follow the predicted probabilities with relatively more variations.

    温度采样(temperature sampling)是本 lab 最值得理解的算法之一,详见 C79 的逐行精讲与下方"重点展开"。一句话:T→0 接近 argmax(保守、重复),T→∞ 接近均匀分布(随机、混乱)。
    Cell 79sample_word():温度采样重点展开
    def sample_word(preds, temperature):
        preds = np.asarray(preds).astype("float64")
        preds = np.log(preds + np.finfo("float64").eps) / temperature
        exp_preds = np.exp(preds)
        preds = exp_preds / np.sum(exp_preds)
        probs = np.random.multinomial(1, preds, 1)
        return np.argmax(probs)
    #代码作用机制·语法关联·结果易错点
    1def sample_word(preds, temperature):定义函数输入 preds(5000 维概率向量)、temperature(标量);返回选中的词索引 intC81 L10 调用
    2 preds = np.asarray(preds).astype("float64")转成 float64 数组np.asarray(preds).astype("float64"):兼容 list/tensor 输入;float64 让下一步 log 更精确float32 的 log 在 p 接近 0 时误差较大
    3 preds = np.log(preds + np.finfo("float64").eps) / temperaturelog 概率除以温度np.log(preds + eps) / T:eps = np.finfo("float64").eps ≈ 2.2e-16,防止 log(0) = -inf;除以 T 是温度的核心操作log 空间相加 / T 等价于 p^(1/T)易错:若 T = 0 → 除零 → -inf/inf → NaN;M78 说 T 在 (0, 1],实际也可以 >1
    4 exp_preds = np.exp(preds)取指数np.exp:回到线性空间,此时各值 ∝ p^(1/T)
    5 preds = exp_preds / np.sum(exp_preds)归一化成概率分布/ np.sum(exp_preds):使总和为 1(multinomial 要求 p 之和 ≤ 1 + 容差)这就是重新做了一次 softmax
    6 probs = np.random.multinomial(1, preds, 1)多项分布采样一次np.random.multinomial(1, p', 1):n=1 次试验,p' 概率向量,size=1 → 返回 shape (1, 5000) 的 one-hot 行与 np.random.choice(5000, p=p') 等价但更"教科书"易错:p' 之和若因浮点误差 > 1 会抛 ValueError;L5 的归一化通常足够
    7 return np.argmax(probs)返回被选中词的索引np.argmax(probs):one-hot 中 1 的位置返回 numpy int64,C81 L11 用它查 index_word
    重点展开:温度采样的数学。设模型输出概率 p(5000 维 softmax),温度 T。代码计算 p' ∝ exp(log(p)/T) = p^(1/T),即对概率做 1/T 次幂再归一化:
    • T = 1 → p' = p(原分布)
    • T → 0 → p^(很大) → 最大概率的词几乎独占 → 等价 argmax(C85 的 T=0.2 输出出现 "the queen's croquet - ground chapter ix" 重复两次,就是这种退化)
    • T > 1 → 分布被"压平" → 低概率词有更多机会(更随机)
    逐行:L2 转成 numpy float64(避免 float32 的 log 精度问题);L3 np.log(preds + eps)——加 eps(≈2.2e-16)防止 log(0);L4–L5 重新 softmax(数值稳定:减 max 在这里没做,但 log 概率 ≤ 0 所以 exp ≤ 1 不会溢出);L6 np.random.multinomial(1, p', 1):做一次多项试验,返回 one-hot 行向量;L7 argmax 把 one-hot 还原成索引。

    This function actually generates the words using the trained model.

    Cell 81generate_text():自回归生成重点展开
    def generate_text(seed_text, num_gen_words, model, tokenizer, temperature):
        padding = ". " * SEQ_LEN  # handle too short seed text
        seed_text = padding + seed_text
        text = seed_text
        for i in range(num_gen_words):
            token_list = tokenizer.texts_to_sequences([seed_text])[0]
            token_list = token_list[-SEQ_LEN:]
            token_list = np.reshape(token_list, (1, SEQ_LEN))
            probs = model.predict(token_list, verbose=0)[0]
            word_idx = sample_word(probs, temperature)
            word = tokenizer.index_word[word_idx] if word_idx > 0 else ""
            seed_text += word + " "
            text += word + " "
        return text[len(padding):]
    #代码作用机制·语法关联·结果易错点
    1def generate_text(seed_text, num_gen_words, model, tokenizer, temperature):定义函数参数:seed_text(起始文本)、num_gen_words(生成词数)、model、tokenizer、temperature;返回生成的完整字符串C83–C85 / C93–C95 调用,分别用 T = 1.0 / 0.5 / 0.2
    2 padding = ". " * SEQ_LEN # handle too short seed text构造填充串". " * SEQ_LEN:字符串重复 20 次 → ". . . . … "(40 个字符,20 个 "." token)C67 已把 "." 隔成独立 token,Tokenizer 能识别
    3 seed_text = padding + seed_text把填充拼到 seed 前面保证 seed 至少 20 个 token;". " 在 Alice 语料中是高频 token,对模型是"中性"上下文
    4 text = seed_text初始化输出文本text 记录从 seed 开始(含填充)的完整串;最后 L14 会切掉填充
    5 for i in range(num_gen_words):循环生成 num_gen_words 次每次生成一个词200 词 → 200 次 predict(每次 ~10ms)
    6 token_list = tokenizer.texts_to_sequences([seed_text])[0]seed 文本 → token 序列tokenizer.texts_to_sequences([seed_text])[0]:用 C71 的同一个 tokenizer(词表一致)每轮重新分词整个 seed_text(越来越长)——效率不高但简单正确
    7 token_list = token_list[-SEQ_LEN:]只保留最后 20 个 tokentoken_list[-SEQ_LEN:]:模型输入固定 20 步,所以只看最近的 20 个词这就是"上下文窗口";生成的词越早越会被"遗忘"
    8 token_list = np.reshape(token_list, (1, SEQ_LEN))整形成 (1, 20)np.reshape(token_list, (1, SEQ_LEN)):list → shape (1, 20) 的数组,匹配 Embedding 输入 (batch, 20)若 L2–L3 没填充而 seed 不足 20 词,这里 reshape 会报错
    9 probs = model.predict(token_list, verbose=0)[0]预测下一词概率分布model.predict(..., verbose=0)[0]:(1, 5000) → (5000,)
    10 word_idx = sample_word(probs, temperature)温度采样选一个词索引调用 C79
    11 word = tokenizer.index_word[word_idx] if word_idx > 0 else ""索引 → 词tokenizer.index_word[word_idx] if word_idx > 0 else "":index_word 是 {1: "the", 2: "and", …};索引 0 不是词(padding),所以返回空串若 word_idx 为 0(理论上 softmax 输出层索引 0 对应的"词"不存在,但模型仍可能给它概率)→ 空串,相当于跳过易错:index_word 不含 0 键,不判断会 KeyError
    12 seed_text += word + " "把新词追加到 seed_text下一轮的上下文包含刚生成的词 → 自回归
    13 text += word + " "同时追加到 texttext 是最终返回的完整记录
    14 return text[len(padding):]去掉开头填充后返回text[len(padding):]:切掉前 40 个字符返回 str(C83 输出可见两端引号)
    逐轮循环的过程(以 seed "good morning "、SEQ_LEN 20 为例):① 前置 20 个 ". " 填充 → seed 共 22 个 token;② 每轮 texts_to_sequences → 取最后 20 个 → reshape (1,20) → predict → 5000 维概率 → sample_word 选一个词 → 查 index_word → 拼到 seed_text 和 text 末尾;③ 重复 num_gen_words 次;④ 返回时去掉开头的 ". . . " 填充。
    为什么要填充:seed 太短(2 个词)时 texts_to_sequences 后取 [-20:] 只有 2 个 token,reshape (1,20) 会报错;填充 ". " 保证至少 20 个 token。

    Three passages are generated below, with temperature values of 1.0, 0.5 and 0.2.

    Cell 83生成样例 1:temperature = 1.0基础
    generate_text("good morning ", 200, model, tokenizer, 1.0)
    #代码作用机制·语法关联·结果易错点
    1generate_text("good morning ", 200, model, tokenizer, 1.0)生成 200 词,T=1.0位置参数顺序:seed, num_gen_words, model, tokenizer, temperature输出 200 词的 Alice 风格文本
    运行结果 'good morning , “in that , you ! ” “no , mostly means , ” mine is a pig ? ” said the mock turtle it . “i believe it to begin . ” “i give it directed of me at that ? ” said the mouse , in fact : she came back again , “—for i can’t listen it over here , ” said the king , “but he seems to drive things begins as well i am if i never wish i _ is a simpleton of here , and then , i know it , ” the king said , in an soldiers , which was gone , and noticed with the right over . presently the white rabbit continued to notice “the little dish of the hall cheered , and had suppressed . ’ sighing an uncomf
    读输出:T=1.0 完全按模型概率采样——句法大体通顺("said the mock turtle"、"said the king" 这些 Alice 高频短语),但语义跳跃、出现 _(原文中的省略/占位符被当作词)和断裂的引号。对比 C84(0.5)与 C85(0.2)。
    Cell 84生成样例 2:temperature = 0.5基础
    generate_text("good morning ", 200, model, tokenizer, 0.5)
    #代码作用机制·语法关联·结果易错点
    1generate_text("good morning ", 200, model, tokenizer, 0.5)生成 200 词,T=0.5同上,仅温度不同
    运行结果 'good morning , turning on the moment , splash ! she was very doubt , and she went on in a trembling voice of hers that the other , and was sitting on the cakes , and was immediately suppressed by the officers of the court - hole there was a large piece of white kid gloves , and the baby was jumping away on their slates and she had fallen her back . “oh , there was no fancy to say it , ” she began , and alice was quite sleepy to listen . alice thought she had never found her one , but she tried her to pieces of the game of the door of the garden , and the words “eat jumping on had left off , a
    读输出:T=0.5 → p^2,高概率词权重被放大——句子更"像"Alice("she was very doubt", "the white rabbit"),随机性降低但仍偶有不通顺处。这通常是文字生成最常用的温度区间。
    Cell 85生成样例 3:temperature = 0.2基础
    generate_text("good morning ", 200, model, tokenizer, 0.2)
    #代码作用机制·语法关联·结果易错点
    1generate_text("good morning ", 200, model, tokenizer, 0.2)生成 200 词,T=0.2同上,仅温度不同
    运行结果 'good morning she began on her hands , and the hatter was a white rabbit was sitting on the other birds , and the other was sitting on the middle of the court . the queen was a little - shaped later editions continued and the puppy made out of the court of the court - hole chapter viii . the queen’s croquet - ground chapter ix . the queen’s croquet - ground chapter ix . ” the queen smiled and passed on . the queen’s - party chapter x . the lobster quadrille the queen of hearts , and the party was jumping on to settling that a little pattering of little party chapter viii . the queen’s soldiers
    读输出:T=0.2 → p^5,接近 argmax——出现明显的重复循环:"the queen's croquet - ground chapter ix . the queen's croquet - ground chapter ix ."(章节标题在原文中多次出现,成了高频吸引子)。温度过低的语言模型都会陷入这种退化。
    E1a

    Create another model to be trained using the text of Frankenstein, by Mary Wollstonecraft Shelley. The text can be downloaded using the following shell command.

    Cell 87E1a 前置:下载 Frankenstein导入·绘图·输出
    ![ -f frankenstein.txt ] || curl -o frankenstein.txt \
    https://www.gutenberg.org/cache/epub/84/pg84.txt
    #代码作用机制·语法关联·结果易错点
    1![ -f frankenstein.txt ] || curl -o frankenstein.txt \条件下载同 C75,文件名 frankenstein.txt首次下载 ~438 KB(约 Alice 的 2.6 倍)
    2https://www.gutenberg.org/cache/epub/84/pg84.txtURLGutenberg #84
    运行结果 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 438k 100 438k 0 0 186k 0 0:00:02 0:00:02 --:--:-- 186k
    E1b

    Generate 3 passages using this model with temperature values of 1.0, 0.5, and 0.2.

    Solutions to extra exercises

    E1a
    Cell 91E1a 学生作答:Frankenstein 模型练习·作答
    keras.utils.set_random_seed(42)
    text = load_and_cleanup_text("frankenstein.txt")
    tokenizer, token_list = tokenize_text(text)
    X, y = generate_text_dataset(token_list)
    
    model = keras.Sequential([
        layers.Embedding(NUM_WORDS, WV_SIZE),
        layers.LSTM(128, dropout=0.2),
        layers.Dense(NUM_WORDS, activation="softmax")
    ])
    
    model.compile(loss="categorical_crossentropy", optimizer="adam",
                  metrics=["acc"])
    history = model.fit(X, y, epochs=20, batch_size=32)
    #代码作用机制·语法关联·结果易错点
    1keras.utils.set_random_seed(42)种子 / 读文本 / 分词 / 造数据集与 C77 L1–L4 相同,只是文件名换成 frankenstein.txt;tokenizer 和 token_list 变量被覆盖注意:从这行之后,全局 model / tokenizer / history 都是 Frankenstein 版本——若想再用 Alice 模型必须重新训练
    2text = load_and_cleanup_text("frankenstein.txt")种子 / 读文本 / 分词 / 造数据集与 C77 L1–L4 相同,只是文件名换成 frankenstein.txt;tokenizer 和 token_list 变量被覆盖注意:从这行之后,全局 model / tokenizer / history 都是 Frankenstein 版本——若想再用 Alice 模型必须重新训练
    3tokenizer, token_list = tokenize_text(text)种子 / 读文本 / 分词 / 造数据集与 C77 L1–L4 相同,只是文件名换成 frankenstein.txt;tokenizer 和 token_list 变量被覆盖注意:从这行之后,全局 model / tokenizer / history 都是 Frankenstein 版本——若想再用 Alice 模型必须重新训练
    4X, y = generate_text_dataset(token_list)种子 / 读文本 / 分词 / 造数据集与 C77 L1–L4 相同,只是文件名换成 frankenstein.txt;tokenizer 和 token_list 变量被覆盖注意:从这行之后,全局 model / tokenizer / history 都是 Frankenstein 版本——若想再用 Alice 模型必须重新训练
    6model = keras.Sequential([模型结构与 C77 完全相同Embedding(5000,96) + LSTM(128, 0.2) + Dense(5000) → 1,240,200 参数E1a 题意是"另一个模型",不是"更好的模型",所以不改结构是合理的
    7 layers.Embedding(NUM_WORDS, WV_SIZE),模型结构与 C77 完全相同Embedding(5000,96) + LSTM(128, 0.2) + Dense(5000) → 1,240,200 参数E1a 题意是"另一个模型",不是"更好的模型",所以不改结构是合理的
    8 layers.LSTM(128, dropout=0.2),模型结构与 C77 完全相同Embedding(5000,96) + LSTM(128, 0.2) + Dense(5000) → 1,240,200 参数E1a 题意是"另一个模型",不是"更好的模型",所以不改结构是合理的
    9 layers.Dense(NUM_WORDS, activation="softmax")模型结构与 C77 完全相同Embedding(5000,96) + LSTM(128, 0.2) + Dense(5000) → 1,240,200 参数E1a 题意是"另一个模型",不是"更好的模型",所以不改结构是合理的
    10])模型结构与 C77 完全相同Embedding(5000,96) + LSTM(128, 0.2) + Dense(5000) → 1,240,200 参数E1a 题意是"另一个模型",不是"更好的模型",所以不改结构是合理的
    12model.compile(loss="categorical_crossentropy", optimizer="adam",编译同 C77
    13 metrics=["acc"])编译同 C77
    14history = model.fit(X, y, epochs=20, batch_size=32)训练 20 轮 batch 322,587 步/轮输出 20 行;总训练时间约 7 分钟
    运行结果 Epoch 1/20 2587/2587 ━━━━━━━━━━━━━━━━━━━━ 18s 6ms/step - acc: 0.0753 - loss: 6.2511 Epoch 2/20 2587/2587 ━━━━━━━━━━━━━━━━━━━━ 16s 6ms/step - acc: 0.1418 - loss: 5.3209 Epoch 3/20 2587/2587 ━━━━━━━━━━━━━━━━━━━━ 21s 6ms/step - acc: 0.1642 - loss: 4.9718 Epoch 4/20 2587/2587 ━━━━━━━━━━━━━━━━━━━━ 20s 6ms/step - acc: 0.1793 - loss: 4.7059 Epoch 5/20 2587/2587 ━━━━━━━━━━━━━━━━━━━━ 20s 6ms/step - acc: 0.1932 - loss: 4.4786 Epoch 6/20
    核对 E1a:结构与 C77 完全一致,只换了文件名 —— 符合题意("Create another model to be trained using the text of Frankenstein")。
    结果:token_list 约 83,000–85,000 → 2,587 步/轮(≈ Alice 的 2.5 倍);每轮 ~18–21 s;第 1 轮 acc .0753 / loss 6.2511;最终 acc ≈ .40(讲义 .3969),比 Alice 低——Frankenstein 词汇更丰富、句式更复杂,20 轮不够学得同样好。
    E1b
    Cell 93E1b 生成样例 1:Frankenstein,T = 1.0基础
    generate_text("good morning ", 200, model, tokenizer, 1.0)
    #代码作用机制·语法关联·结果易错点
    1generate_text("good morning ", 200, model, tokenizer, 1.0)生成 200 词,T=1.0与 C83 相同调用方式,但 model/tokenizer 已是 Frankenstein 版
    运行结果 'good morning , “if i neither hope that he exertions who would satisfy my delay home if you inhabit us . “every bleak object me against me ; but , with the expanse , if a burning pace had set been moved ; and i sat still cold , and a more manners or a frementi , but he did a well hand ; when i seek no hand , was exactly apparently emotions , no mischief ; it was a secondary around ; i had already destroyed the half situations with one which i hardly expressed so great . ” i know ; “and someone , very more dreadful a folly and heavenly story , may give you sufficient to be whom the object of ou
    读输出:T=1.0,词汇明显更"哥特"("bleak object"、"burning pace"、"dreadful a folly"、"heavenly story"),仍有 T=1 特有的跳跃和生造词("frementi")。
    Cell 94E1b 生成样例 2:Frankenstein,T = 0.5基础
    generate_text("good morning ", 200, model, tokenizer, 0.5)
    #代码作用机制·语法关联·结果易错点
    1generate_text("good morning ", 200, model, tokenizer, 0.5)生成 200 词,T=0.5"i was unable to rise … i was unable to solve" —— 第一人称忏悔语气是 Frankenstein 的标志
    运行结果 'good morning , i was benevolent longer , i perceived it and a poor of the inhabitants , and i was obliged to reason . i was a windings of the spot , and the sun shone in the hands of the inn , but i was unable to rise , and i was unable to solve them and converse with them , and i was so unable to bestow . my father was thus , and i wished to speak , as i might infuse a student in a wild eye and despondency and ecstasy of the moulding of the intense and affection with delight and the youth of his intentions in natural place , but i saw the sunshine of the distemper—elizabeth , who , however ,
    Cell 95E1b 生成样例 3:Frankenstein,T = 0.2基础
    generate_text("good morning ", 200, model, tokenizer, 0.2)
    #代码作用机制·语法关联·结果易错点
    1generate_text("good morning ", 200, model, tokenizer, 0.2)生成 200 词,T=0.2接近 argmax,高频短语反复出现
    运行结果 'good morning i was silent and fears to my own cabin and the squalidness of the events which i inhabited , and i was unable to join them and proceeded . i took my hand , therefore , that i was unable to call on board a criminal cloud upon me . i had no conception , but a thousand times i had always been putting me to leave the most horrible for ever endured . i was alone , i was alone . i was unable to solve myself and converse with the cabin . i was a boy to destroy him and put , and i was well acquainted with a repulsive and , and a long time forth to the match . i walked up and down the mou
    读输出:T=0.2 再次出现重复退化("i was alone , i was alone . i was unable to solve myself"),与 Alice 的 C85 现象一致——这是温度采样的固有特性,与语料无关。

    &#x2766;

    📚 全课程 Tutorial 总结:11 个 Lab 一张图

    覆盖 t01–t11 共 389 个代码 cell、2,642 行代码(逐行精讲 0 遗漏)。本部分把散落在 11 个 notebook 里的通用套路、API 速查、实验结论、错误词典汇总成一份复习卡片;所有参数量与 Optimizer 数字均已独立复算。

    1. 十一周的一条主线

    t01 NumPy 语法→ t02–t04 全连接:XOR / 手算前向 / 回归→ t05 分类 + one-hot→ t06–t07 宽度·深度·正则·Dropout·BN→ t08–t09 CNN · 迁移学习→ t10–t11 RNN · LSTM · 文本生成
    每个 notebook 的固定骨架
    %env TF_CPP_MIN_LOG_LEVEL=2 imports + 常量(NUM_WORDS / WV_SIZE / SEQ_LEN …) load_and_prep_xxx() → X, y history_final_values() / plot_history() compile_and_fit_model(model, X, y, epochs, batch_size) model = keras.Sequential([...], name="ExpName") history = compile_and_fit_model(...); final_values[name] = ... plot_history(history); model.summary()
    贯穿全课程的四条铁律
    1. 控制变量:每组实验只改一个因素(宽度 / 深度 / dropout / BN / 循环层类型),其余全部固定。
    2. 参数量公式:Dense (n+1)·m;Conv (K·K·d+1)·n;SimpleRNN (n+m+1)·n;LSTM 4(n+m+1)·n;GRU 3((n+m)n+2n);BN 4n;Embedding V·d。
    3. Optimizer = 2×Trainable + 2(Adam 的 m、v 两个矩 + 两个迭代计数);Total = 3×Trainable + 2。
    4. 训练 loss 含正则项(L1/L2 activity_regularizer),正则模型之间比较要用 val_loss,不能比训练 loss。

    2. Keras 逐行精讲中反复出现的 API 速查

    #API / 写法一句话含义首次出现最容易错的地方
    1%env TF_CPP_MIN_LOG_LEVEL=2压掉 TF 的 INFO/WARNING 日志t01必须在 import tensorflow 之前执行
    2keras.utils.set_random_seed(42)同时固定 Python / NumPy / TF 随机源t02不保证跨机器/跨 GPU 一致
    3load_data(path).get("x")np.load 字典式访问t02返回 np.lib.npyio.NpzFile,不是 dict
    4set_weights([W, b])手动给 Dense 层写入权重(形状必须匹配)t03W 形状 (in, out),b 形状 (out,)
    5(n,k) @ (k,m)矩阵乘法形状规则t03np.dot 对一维数组会降维
    6model.compile(loss, optimizer, metrics)配置损失/优化器/监控指标t02metrics 名决定 history 键名("acc" vs "accuracy")
    7model.fit(..., validation_split=0.2)取训练集末尾 20% 做验证(不打乱)t05与 validation_data 互斥;切末尾而非随机
    8validation_data=(X_test, y_test)显式指定验证集t08每轮评估一次,不计入训练步
    9steps = ⌈N_train / batch_size⌉每轮步数t05N_train 是切掉验证后的数量
    10to_categorical(y, num_classes)整数 → one-hott05配 categorical_crossentropy;配 sparse CE 会报错
    11sparse_categorical_crossentropy直接吃整数标签t05 E1a与 one-hot 版逐位相同结果
    12np.argmax(y_pred, axis=1)概率 → 类别t05axis=1 按行;axis=0 会按列
    13history.historydict[str, list[float]],每键一条曲线t05只有 compile 里列出的 metrics 才有
    14pd.DataFrame(history.history)曲线 → DataFrame 便于画图t06索引 +1 让 epoch 从 1 开始
    15activity_regularizer=regularizers.l1(λ)对输出激活加 L1 惩罚t06训练 loss 含惩罚项;kernel_regularizer 作用于权重
    16layers.Dropout(p)训练时随机置零并 ×1/(1−p)(inverted dropout)t07推理时自动关闭;p 过大(.75 只在隐藏层)反而不收敛
    17layers.BatchNormalization()γ、β 可训练 + moving mean/var 不可训练 = 4×unitst07Dense→BN→Activation 顺序更好;BN 单独放第一层可能崩
    18kernel_initializer="he_normal"std = √(2/fan_in),配 ReLUt07Glorot 默认 std = √(2/(fan_in+fan_out))
    19layers.Conv2D(n, k, activation)输出 I−K+1(valid, stride 1)t08输入必须 4D (batch, H, W, C)
    20layers.Flatten()多维 → 一维,参数 0t08输出维度 = H×W×C,往往是 Dense 参数爆炸的来源
    21applications.MobileNetV2(include_top=False, weights="imagenet")加载无分类头的预训练卷积基t09输入必须 128/160/192/224 之一;@32 → (1,1,1024) 无效
    22base_model.trainable = False冻结卷积基(特征提取)t09要在 add 之后再设;先 compile 再冻结无效
    23image_dataset_from_directory(..., labels="inferred", validation_split=0.3, subset="both")从文件夹读图并自动打标t09macOS 的 ._ 垃圾文件会被当成图片;删掉再运行
    24layers.Rescaling(1/255) / Resizing(224)模型内做归一化/缩放(随模型保存)t09与 preprocess_input 二选一,不要叠加
    25Tokenizer(num_words).fit_on_texts建词表(索引 1 = 最高频)t10num_words 在 texts_to_sequences 才生效
    26pad_sequences(maxlen)默认 padding="pre"、truncating="pre"t10长序列保留最后 maxlen 个词
    27layers.Embedding(V, d)整数 → d 维向量,参数 V×dt10mask_zero=False 时 padding 向量也参与计算
    28layers.SimpleRNN(n) / LSTM(n) / GRU(n)只返回最后一步 h → (None, n)t10–t11dropout 作用于输入,recurrent_dropout 不能用 cuDNN
    29LSTM(n, return_sequences=True)返回每一步 h → (None, T, n)t11stacked 中间层必须加,否则下一层只看到 1 步
    30layers.Bidirectional(layer)正反向拼接 → (None, 2n),参数翻倍t11下一层 Dense 输入维度变成 2n
    31model.predict(X, verbose=0)推理,返回概率t05verbose=0 才不打印 "1/1 ━━━" 进度条
    32np.random.multinomial(1, p, 1)按概率向量采样一个 one-hott11p 之和必须为 1(浮点容差内)

    3. 十一个 Lab 的实验结论速览(考试与项目复盘直接用)

    #数据 / 任务做了什么关键结论(数字)学生在作答中被指出的问题
    t01无 TF;Python list / NumPy切片、reshape、axis、列表推导式所有后续代码的语法底座;reshape(-1, 784) 中 -1 自动推断无
    t02XOR 4 样本第一个 Keras 模型;ln 2 ≈ 0.6931 的来源2-4-1 结构;初始 loss ≈ 0.693(二分类随机猜测);训练后 → 0无
    t03手算前向传播NumPy 复现 Dense 前向、set_weights、σ=0.68997448(n,k)@(k,m) 形状规则;手算与 Keras 输出逐位一致无
    t04回归(8 个同构实验)宽度/深度/激活/优化器对照;513 参数MAE 与 MSE 不可直接比较;Adam lr 太小收敛慢、太大震荡无
    t05MNIST 15,000/2,500 + wine 4,898softmax + categorical CE;Q1a 二分类(奇偶);Q2a wine 11 类64-64-10 参数 55,050;奇偶版 54,465(少 585);第 1 轮 val_acc .8392 / .9032;sparse 与 categorical 逐位相同Q1c 未引用性能数字;E1b batch 32→256 非干净对照
    t06MNIST 6,000/1,000(ratio .1)宽度 32→512、深度 1→2 层;L1/L2 activity regularizer1×512 val_loss .2012 最佳(407,050 参数);L1 1×512 λ=1e-6 → .1657;重训测试 [.1700, .9460];L2 2×512 λ=1e-7 → .1615无
    t07同 t06Dropout 位置与比例;BN 两种放法;He 初始化只隐藏层 D75 反而差(.1955);加输入层 3×D50 .1392 最佳;3×D75 .3762 不收敛;BN Dense→BN→Act .1659 > BN→Dense .1924;BN 重训 [.2229, .9410] 不如 dropout;He 与 Glorot 在噪声范围内无
    t08MNIST 6,000(4D 28×28×1)Conv2D 1/2/3 层、BN、Dropout;summary 读法2×64_K3x3:Conv 640+36,928、Flatten 36,864、Dense(32) 1,179,680(占 97%)、Trainable 1,217,578;3 层 3×D75 val_loss .0952 全 Lab 最佳;BN 单放第一层 .6767 崩Q3b 表缺 2×D25 行
    t09CIFAR-10 25,000/5,000 + 猫狗 40 张MobileNetV2 特征提取;UpSampling/Resizing 到 128/224;数据增强@32 → .21 无效;Resize 128 .853 / 224 .852;猫狗 .4167(全预测 0)→ 加 Flip/Rotation .8333;Trainable 51,382,273 + Non-trainable 3,228,864;VGG-16 @32 ≈ .63 过拟合;去 block5 更好、去 block4 欠拟合 .13M31 "resizing 更好"按 val_loss 不成立,建议写 comparable;C43/C44 自加排查 cell 做法正确
    t10IMDb 25,000 + 20ng 11,314Embedding + DNN / Conv1D / SimpleRNN;E1 20ng 20 类Embedding 480,000;CNN_64_BN val_acc .8428 最高;RNN_16_D75 val_loss .4303 最低(.8339);RNN_32 .7455 最低;SimpleRNN 64/32/16 = 10,304/4,128/1,808;pad 默认 preQ1a/Q1b 多改了 kernel 5、Dense(64)、第二个 Dropout → 破坏控制变量
    t1120ng 11,314 + Alice/FrankensteinLSTM / GRU / stacked / Bidir 对照;温度采样文本生成Bidir val_acc .5250 / val_loss 1.7438 双料冠军 > LSTM .5064 > GRU .4680 ≈ LSTMx2 .4675 ≫ SimpleRNN .2872;41,216 / 31,104 / 74,240 / 82,432;生成模型 1,240,200(Dense 645,000 占 52%);Alice 1,032 步 acc≈.47,Frank 2,587 步 ≈.40;T=.2 重复退化全部正确

    4. 错误信息词典:这十一周里你(很可能)会遇到的报错

    形状类
    • ValueError: Shapes (None, 1) and (None, 10) are incompatible —— 标签 one-hot 维度与 Dense 输出不一致;检查 to_categorical(num_classes=) 是否等于 Dense units(t05)。
    • Input 0 of layer "conv2d" is incompatible: expected ndim=4, found ndim=2 —— Conv2D 需要 (batch,H,W,C),漏了 reshape(-1,28,28,1)(t08)。
    • cannot reshape array of size X into shape (1,20) —— 生成文本时 seed 不足 SEQ_LEN 且没填充(t11 C81 L2–L3 的作用)。
    • matmul: Input operand 1 has a mismatch in its core dimension —— (n,k)@(k,m) 中 k 不相等;检查 Dense 输入维度(t03)。
    值 / 参数类
    • AttributeError: 'NoneType' object has no attribute 'end' —— Gutenberg 文件头正则没匹配到(re.search 返回 None),文件下载不完整或格式不同(t11 C67 L10)。
    • ValueError: probabilities do not sum to 1(multinomial)—— 温度采样后没归一化或浮点误差;按 C79 L5 除以 sum(t11)。
    • KeyError: 0(index_word)—— 预测到索引 0(padding),要像 C81 L11 那样判断 >0(t11)。
    • UserWarning: ... input size is not in (128,160,192,224) —— MobileNet 分辨率不合法,输出 (1,1,1024) 无效,要 UpSampling/Resizing(t09)。
    • Found 80 files belonging to 2 classes(期望 40)—— macOS ._xxx.jpg 元数据垃圾被当成图片;!find . -name "._*" -delete(t09 C43/C44)。
    逻辑类(不报错但结果错)
    • 训练 acc 很高、val_acc 很低 —— 过拟合;加 Dropout / L1-L2 / 数据增强,或减小模型(t06–t11 都出现过)。
    • loss 不降、acc ≈ 1/类别数 —— 学习率过大 / BN 放错位置(t08 BN1 .6767)/ 初始化不当(t07 3×D75 .3762)。
    • 加了正则化后训练 loss 反而比没加还高 —— 正常:训练 loss 含惩罚项;请比较 val_loss(t06)。
    • stacked RNN 效果反而变差 —— 可能漏了 return_sequences=True,第二层只看到 1 步(t11 Q2a 提示);或轮数不够(t11 LSTMx2 acc .67)。
    • 生成的文本反复重复同一句 —— 温度太低接近 argmax;调到 0.5–1.0(t11 C85/C95)。
    环境类
    • NameError: preprocess_text is not defined —— 嵌套函数忘了 global(t11 C14 L9)。
    • fetch_20newsgroups 联网失败 —— 首次需联网;之后命中 ~/scikit_learn_data 缓存(t11 C6)。
    • curl 下载失败 / 文件 0 字节 —— 删掉残缺文件再运行 ![ -f … ] || curl(t11 C75/C87)。
    • GPU 上 LSTM 突然变慢几十倍 —— 用了 recurrent_dropout 或非默认 activation,无法走 cuDNN 内核。

    5. 自测:能脱口而出才算过关

    Q1 LSTM(64) 输入 96 维,参数多少?换成 GRU?Bidirectional?
    4×(64+96+1)×64 = 41,216;GRU 3×((96+64)×64+2×64) = 31,104;Bidir 2×41,216 = 82,432,且下一层 Dense 输入变 128。
    Q2 summary 显示 Trainable 491,604,Optimizer 和 Total 分别是多少?
    Optimizer = 2×491,604+2 = 983,210;Total = 491,604+983,210 = 1,474,814。
    Q3 11,314 条数据、validation_split 0.2、batch 256,每轮多少步?验证集多少条?
    验证 = ⌊11,314×0.2⌋ = 2,263(末尾);训练 9,051 → ⌈9,051/256⌉ = 36 步。
    Q4 为什么 t08 的 Conv 模型里 Dense(32) 参数高达 1,179,680?
    t08 的 2x64_K3x3(两层 3×3 卷积,28→26→24)Flatten = 24×24×64 = 36,864 → Dense(32):36,864×32+32 = 1,179,680,占 Trainable 1,217,578 的 97%。Flatten 把整张特征图展开后接 Dense,参数 = (H×W×C)×units 随分辨率平方增长——这正是 t10 改用 GlobalMaxPooling1D(参数 0)替代 Flatten 的动机。
    Q5 温度采样 T=0.2 的输出为什么会重复?如何避免?
    p^(1/0.2) = p^5 把概率集中到最高频词,高频短语成为吸引子;调高 T(0.5–1.0)或用 top-k / nucleus 采样。
    Q6 同样是 MNIST,t06 的 1×512 val_loss .2012、t08 的 3×D75 .0952,为什么 CNN 好这么多?
    全连接把 784 像素当独立特征;Conv 利用局部相关性与平移不变性,参数少、归纳偏置强。
    Q7 t09 猫狗 .4167 → .8333 的关键改动是什么?为什么有效?
    加 RandomFlip + RandomRotation(0.1) 数据增强。40 张图太少,冻结的 MobileNet 头部 Dense(1024)+Dense(1) 很快记住训练集(全预测 0);增强扩大了有效样本量。
    Q8 t05 E1a 为什么 sparse 与 categorical CE 结果逐位相同?
    两者数学等价,只是标签编码不同;one-hot 只是把 argmax 位置写成 1。
    Q9 stacked LSTM 第二层参数为什么是 33,024 而不是 41,216?
    输入从 Embedding 的 96 维变成上一层的 h(64 维):4×(64+64+1)×64。
    Q10 生成模型 Dense(5000) 占总参数 52%,有什么降低成本思路?
    减小词表、tie Embedding 与输出层权重、层次 softmax、或改用 subword(BPE)词表。
    如何用这份精讲复习:① 先看每个 notebook 的 intro(定位 + 参数量速记);② 对着逐行表回看自己的 notebook,重点看每行"易错点"列标红的内容;③ 练习题核对你的答案与 绿色核对框,被标 warn 的几处(t05 Q1c/E1b、t08 Q3b、t09 M31、t10 Q1a/Q1b)要想清楚为什么;④ 考前用本节 §3 结论表与 §5 自测做快速回忆。