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))
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [1, 2.0, "three"]
新建变量 ls,一个含 3 项的 list
方括号 [ ] 构造 list;Python list 可混装 int / float / str——它只是"指向对象的指针数组",不要求元素同类型
ls 后续被 C9/C11/C13 反复使用;输出 [1, 2.0, 'three']
打印显示单引号,是 repr 形式,不是内容变了
2
print(ls)
打印整个列表
print 对 list 调用其 __repr__,所以显示方括号
结果 [1, 2.0, 'three']
想看元素不带括号要循环打印
3
print(type(ls))
查看类型
type() 返回对象的类型对象;Python 一切皆对象
<class 'list'>
type 只看"外壳",不看元素类型
4
print(len(ls))
求长度(项数)
len() 是内置函数,返回 list 的 item 数
输出 3
len 不等于"最大下标",最大下标 = 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
#
代码
作用
机制·语法
关联·结果
易错点
1
print(ls)
再次打印 ls
与 C7 L2 相同
[1, 2.0, 'three']
—
2
print(f"{ls[0]=}, {ls[1]=}") # index is 0-based; index 0 -> first item
深挖 · 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
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [0, 1, 2, 3, 4, 5, 6]
重建 ls 为 0–6
用连续整数初始化;覆盖 C7 的 ls
之后所有切片基于这个新列表
变量被整体重新赋值,旧 list 不受影响
2
print(ls)
打印原列表
—
[0, 1, 2, 3, 4, 5, 6]
—
3
print(f"{ls[2:6] = }") # from index 2 (included) to index 6 (excluded)
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)
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [1, 2, 3]
新建 3 项 list
—
ls=[1,2,3]
—
2
print(ls)
打印
—
[1, 2, 3]
—
3
ls[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)
4
print(ls)
打印
—
[10, 2, 3]
—
5
ls.append(40) # append item at the end
末尾追加 40
append 是 list 的方法,原地修改,返回 None
ls=[10,2,3,40]
ls = ls.append(40) 会把 ls 变成 None!
6
print(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!
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
#
代码
作用
机制·语法
关联·结果
易错点
1
for i in range(10): # from 0 (included) to 10 (excluded)
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=" ")
#
代码
作用
机制·语法
关联·结果
易错点
1
for i in range(5, 10): # from 5 (included) to 10 (excluded)
循环 5..9
range(start, stop):包含 start、不包含 stop
5 个值
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=" ")
#
代码
作用
机制·语法
关联·结果
易错点
1
for i in range(5, 10, 2): # in steps of 2
循环 5,7,9
range(start, stop, step):从 5 起每次 +2,直到 <10
3 个值
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)
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # an existing sequence
0–9 的序列
—
ls
—
2
squares = [] # for keeping result
建空列表存结果
必须先建容器,再往里放
squares=[]
忘建空列表 → NameError
3
for item in ls:
遍历每一项
for item in ls:item 依次绑定每个元素
—
—
4
squares.append(item * item) # put to result
计算并追加
item*item 是表达式;append 原地放入
squares 增长
—
5
print(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)
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] # an existing sequence
同上
—
ls
—
2
squares = [item * item for item in ls]
推导式
[表达式 for 项 in 序列]:先执行 for,对每个 item 求表达式,收集为新 list
与 C21 结果完全相同
方括号不能少——少了变成生成器表达式(惰性)
3
print(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)])
#
代码
作用
机制·语法
关联·结果
易错点
1
print([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])
#
代码
作用
机制·语法
关联·结果
易错点
1
print([n * n for n in range(10) if n % 2 == 1])
推导式 + if
n % 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.
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.
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)])
#
代码
作用
机制·语法
关联·结果
易错点
1
def is_prime(n):
定义函数
def 定义;参数 n;函数体缩进
—
—
2
for i in range(2, int(n ** 0.5 + 1)):
只需试到 √n
range(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
8
print ([n for n in range (2,1001) if is_prime (n)])
推导式调用函数
[n for n in range(2,1001) if is_prime(n)]:表达式就是 n 本身;if 里可以调用函数
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.
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
#
代码
作用
机制·语法
关联·结果
易错点
1
print(f"{arr.size=}") # number of items in array
size
元素总个数(所有维相乘:2×3)
6
size ≠ len;len(arr) 返回第 0 维长度 = 2
2
print(f"{arr.shape=}") # dimensions of array
shape
每一维的长度组成的 tuple
(2, 3)
shape 是 tuple 不是 list;(3,) 才是"一维 3 个",(3) 只是 3
3
print(f"{arr.ndim=}") # number of dimensions, 1D or 2D etc
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.
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.
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
#
代码
作用
机制·语法
关联·结果
易错点
1
a[:, 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
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`.
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);
运行结果
<Figure size 640x480 with 1 Axes>
[image/png]
❦
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)
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [1, 2, 3, 4, 5]
建 1–5 并打印
—
[1,2,3,4,5]
—
2
print(ls)
建 1–5 并打印
—
[1,2,3,4,5]
—
3
del ls[1] # remove the 2nd item, i.e. with index 1
按下标删除
del ls[1]:语句,删除该项,后面的元素前移
—
del 不返回值
4
print(ls)
打印
—
[1,3,4,5]
—
5
ls.pop() # remove item at the end
弹出末项
pop() 默认弹出最后一项并返回它(这里没接返回值)
—
pop(i) 可弹任意位置;对空 list pop 报 IndexError
6
print(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!
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [1, 2, 3]
建并打印
—
[1,2,3]
—
2
print(ls)
建并打印
—
[1,2,3]
—
3
ls.extend([40, 50]) # add two items in-place
追加多个
extend 原地把另一个可迭代对象的每个元素追加进来;返回 None
ls 被修改
ls = ls.extend(...) → None;ls.append([40,50]) 会变成嵌套 [[…],[40,50]]
4
print(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
#
代码
作用
机制·语法
关联·结果
易错点
1
ls = [1, 2, 3]
建并打印
—
[1,2,3]
—
2
print(ls)
建并打印
—
[1,2,3]
—
3
ls2 = ls + [40, 50] # add two items and put result to ls2
拼接并赋给 ls2
ls + [40,50] 创建新 list,ls 不变
ls2=[1,2,3,40,50]
与 extend 对比:+ 不改原列表、extend 改
4
print(ls) # ls is not modified!
打印两者
—
ls 仍 [1,2,3],ls2 含新项
—
5
print(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.
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"])
#
代码
作用
机制·语法
关联·结果
易错点
1
print(d["one"])
按键取值
d[key]:键不存在会 KeyError(与 set 的 in 不同)
1
安全取值用 d.get(key, 默认)
2
print("four" in d)
键是否存在
in 检查的是键不是值
False
—
3
d["four"] = 4 # add an item as the key doesn't exist
新增键值
给不存在的键赋值 = 添加
—
给存在的键赋值 = 覆盖
4
print("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.
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)
#
代码
作用
机制·语法
关联·结果
易错点
1
import numpy as np
导入
—
—
—
2
arr = np.arange(12)
0–11
—
arr 一维
—
3
np.random.seed(42) # reproducible random results
固定种子
让 shuffle 结果可复现
—
—
4
np.random.shuffle(arr) # shuffle in-place, i.e. modify arr
原地打乱
shuffle 原地修改(返回 None)
arr 变为随机排列
arr = np.random.shuffle(arr) → None!
5
arr = arr.reshape((3, 4))
整形 3×4
—
[[10 9 0 8],[5 2 1 11],[4 7 3 6]]
—
6
print(arr)
打印
—
—
—
7
print(f"{arr.max() = }") # max of whole array; same as np.max(arr)
整体最大
arr.max() 无 axis → 所有元素;≡ np.max(arr)
np.int64(11)
—
8
print(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])
9
print(f"{arr.max(axis=1) = }") # max of every row; np.max(arr, axis=1)
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.
# 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 个数不同
2
import numpy as np
同 C85 结构
arange(9) → shuffle → reshape(3,3);打印
[[7 1 5],[0 8 2],[4 3 6]]
seed 42 下 9 个数打乱的结果与 12 个数不同
3
arr = np.arange(9)
同 C85 结构
arange(9) → shuffle → reshape(3,3);打印
[[7 1 5],[0 8 2],[4 3 6]]
seed 42 下 9 个数打乱的结果与 12 个数不同
4
np.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 个数不同
5
np.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 个数不同
6
arr = arr.reshape((3, 3))
同 C85 结构
arange(9) → shuffle → reshape(3,3);打印
[[7 1 5],[0 8 2],[4 3 6]]
seed 42 下 9 个数打乱的结果与 12 个数不同
7
print(arr)
同 C85 结构
arange(9) → shuffle → reshape(3,3);打印
[[7 1 5],[0 8 2],[4 3 6]]
seed 42 下 9 个数打乱的结果与 12 个数不同
8
print(f"{np.mean(arr) = }") # mean of whole array; same as arr.mean()
必须在 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]
#
代码
作用
机制·语法
关联·结果
易错点
1
import matplotlib.pyplot as plt
导入绘图模块
惯例 import matplotlib.pyplot as plt;pyplot 是"状态机式"接口——后面的 plot/xlabel 都作用在"当前图"上
—
不是 import matplotlib
2
y = [1, 3, 2, 4]
y 数据
普通 list 即可,不必转 ndarray
[1, 3, 2, 4]
—
3
plt.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
#
代码
作用
机制·语法
关联·结果
易错点
1
import numpy as np
导入 NumPy
—
—
—
2
x = np.linspace(0, 2 * np.pi, 1000)
生成 1000 个等距 x
np.linspace(start, stop, num):两端都包含,精确 num 个点(与 arange 不同:arange 是按步长、stop 不含、浮点有误差)
x shape (1000,),0 到 2π
要"刚好 n 个点"用 linspace;要"固定步长"用 arange
3
y = np.sin(x) # NumPy vectorization
向量化算 sin
np.sin(x) 对数组每个元素逐一运算(C 层循环),不用写 for——这就是向量化
y shape (1000,)
对 list 用 np.sin 会先转成数组;math.sin 只接受标量
4
plt.plot(x, y)
画 x-y
给出 x 时按 (x[i], y[i]) 连线
平滑正弦
—
5
plt.xlabel("x")
轴标签与标题
xlabel / ylabel / title 都是字符串;作用在当前 axes
—
ylabel 写 "sin(x)" 带括号没问题
6
plt.ylabel("sin(x)")
轴标签与标题
xlabel / ylabel / title 都是字符串;作用在当前 axes
—
ylabel 写 "sin(x)" 带括号没问题
7
plt.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");
#
代码
作用
机制·语法
关联·结果
易错点
1
import numpy as np
同 C10
—
—
—
2
x = np.linspace(0, 2 * np.pi, 1000)
同 C10
—
—
—
3
plt.plot(x, np.sin(x), label="sin(x)")
第一条带 label
label="sin(x)" 只是登记名字,不会自动显示
—
忘了调用 legend 则 label 无效
4
plt.plot(x, np.cos(x), label="cos(x)")
第二条带 label
同一 axes 上再 plot → 叠加,颜色自动换成第二种
—
—
5
plt.legend() # show the legend of labels
显示图例
plt.legend() 读取所有已登记的 label 画图例框;默认自动找空白位置
图例出现
label 含下标线可用 r"$\sin x$" LaTeX 语法
6
plt.xlabel("x")
x 标签、标题 + 分号
同 C10
—
—
7
plt.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");
#
代码
作用
机制·语法
关联·结果
易错点
1
import numpy as np
导入
—
—
—
2
x = np.linspace(0, 2 * np.pi, 20) # 20 points for better view
20 个点
散点要少点才看得清每个点
—
—
3
plt.plot(x, np.sin(x), "or", label="sin(x)") # "o" --> big dots; "r" -> red
plot + 格式串
第三个位置参数 "or" = marker "o"(大圆点、不连线)+ color "r"(红);格式串顺序任意 "ro" 也行
红色圆点
"o" 本身就不连线;"-" 才是线;"-o" 是线+点
4
plt.scatter(x, np.cos(x), label="cos(x)")
scatter
plt.scatter(x, y) 专用散点函数;默认实心蓝点
蓝色圆点
scatter 点大小用 s=,plot 用 markersize=
5
plt.legend() # show the legend of labels
legend / xlabel / title / 分号
L5 legend 显示图例;L6 x 轴标签;L7 标题 + 分号抑制 Out[]
分号 = notebook 专有:抑制 Out[] 输出
6
plt.xlabel("x")
legend / xlabel / title / 分号
L5 legend 显示图例;L6 x 轴标签;L7 标题 + 分号抑制 Out[]
分号 = notebook 专有:抑制 Out[] 输出
7
plt.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 ()
运行结果
<Figure size 640x480 with 1 Axes>
[image/png]
❦
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.
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)
—
—
3
import numpy as np
导入 NumPy
—
—
—
4
from tensorflow import keras
导入 Keras
from tensorflow import keras:Keras 已内置于 TensorFlow 2.x;统一用 keras.xxx 前缀
—
单独 import keras 会装独立的 Keras 3 包,API 有差异——本课一律从 tensorflow 导入
运行结果
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".
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");
#
代码
作用
机制·语法
关联·结果
易错点
1
import matplotlib.pyplot as plt
导入
—
—
—
2
plt.plot(history.history["loss"])
画 300 个 loss
history.history["loss"] 是长度 300 的 list,plot(y) 自动以轮次为 x
loss 在约 200 轮内稳定降到 ≈0
—
3
plt.xlabel("Epochs")
轴标签 + 分号
—
—
—
4
plt.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.
运行结果
<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())
运行结果
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]
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 的四个点),这里是数值证据。
运行结果
<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())
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.
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.
运行结果
<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?
Q2c 你的作答核对:1. No ✔(50 轮时 loss 仍在 0.3–0.4);2. Yes ✔(200 轮后接近 0);3. "Around 200 epochs" ✔——与 C49 的 loss 曲线吻合(前 50 轮缓慢,100–200 轮快速下降,之后趋平)。
❦
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
#
代码
作用
机制·语法
关联·结果
易错点
1
import matplotlib.pyplot as plt
导入
—
—
—
2
import numpy as np
导入
—
—
—
3
x = np.linspace(0, 2 * np.pi, 1000)
x
linspace 1000 点
—
—
4
plt.figure(figsize=[8, 4])
设图幅大小
plt.figure(figsize=[宽, 高]),单位英寸;默认 (6.4, 4.8)
8×4 英寸
要在 subplot 之前调用,否则会开新图
5
plt.subplot(1, 2, 1) # 1 row, 2 columns, do 1st plot; same as subplot(121)
plt.subplot(1, 2, 2) # 1 row, 2 columns, do 2nd plot; same as subplot(122)
定位第 2 个子图
切到右格
当前 axes = 右子图
忘记切换会把两条线画在同一格
11
plt.plot(x, np.cos(x))
右图画 cos
—
—
—
12
plt.xlabel("x")
右图画 cos
—
—
—
13
plt.ylabel("cos(x)")
右图画 cos
—
—
—
14
plt.title("The cosine function")
右图画 cos
—
—
—
15
plt.tight_layout() # fit layout and spacing
tight_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 格
—
—
2
import matplotlib.pyplot as plt
导入 / x / 图幅 9×3
更宽的图容纳 3 格
—
—
3
import numpy as np
导入 / x / 图幅 9×3
更宽的图容纳 3 格
—
—
4
x = np.linspace(0, 2 * np.pi, 1000)
导入 / x / 图幅 9×3
更宽的图容纳 3 格
—
—
5
plt.figure(figsize=[9, 3])
第 1 格 sin
subplot(1,3,1)
—
—
6
plt.subplot(1, 3, 1) # same as subplot(131)
第 1 格 sin
subplot(1,3,1)
—
—
7
plt.plot(x, np.sin(x))
第 1 格 sin
subplot(1,3,1)
—
—
8
plt.xlabel("x")
第 1 格 sin
subplot(1,3,1)
—
—
9
plt.ylabel("sin(x)")
第 1 格 sin
subplot(1,3,1)
—
—
10
plt.title("The sine function")
第 2 格 cos
subplot(1,3,2)
—
—
11
plt.subplot(1, 3, 2) # same as subplot(132)
第 2 格 cos
subplot(1,3,2)
—
—
12
plt.plot(x, np.cos(x))
第 2 格 cos
subplot(1,3,2)
—
—
13
plt.xlabel("x")
第 2 格 cos
subplot(1,3,2)
—
—
14
plt.ylabel("cos(x)")
第 2 格 cos
subplot(1,3,2)
—
—
15
plt.title("The cosine function")
第 3 格 tan
subplot(1,3,3)
—
—
16
plt.subplot(1, 3, 3) # same as subplot(133)
第 3 格 tan
subplot(1,3,3)
—
—
17
plt.plot(x, np.tan(x))
第 3 格 tan
subplot(1,3,3)
—
—
18
plt.xlabel("x")
第 3 格 tan
subplot(1,3,3)
—
—
19
plt.ylabel("tan(x)")
第 3 格 tan
subplot(1,3,3)
—
—
20
plt.title("The tangent function")
第 3 格 tan
subplot(1,3,3)
—
—
21
plt.ylim([-10, 10])
tan 的 ylim
只对当前(第 3)子图生效——ylim 作用于当前 axes
第 3 格 y 轴 ±10
若放在 subplot 之前会错位到别的格
22
plt.tight_layout()
tight_layout
—
—
—
运行结果
<Figure size 900x300 with 3 Axes>
[image/png]
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 C2
IPython 魔术命令设环境变量,过滤 INFO/WARNING
env: 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)
#
代码
作用
机制·语法
关联·结果
易错点
1
import numpy as np
导入
—
—
—
2
a = np.array([1, 2, 3])
a
一维数组 shape (3,)——t01 C46 强调过 (3,) 是 tuple
[1 2 3]
(3,) 不是 (3,1):前者是向量,后者是 3×1 矩阵
3
b = np.array([10, 20, 30])
b
—
[10 20 30]
—
4
print(a, a.shape)
打印
同时打印形状,确认都是一维
(3,) (3,)
—
5
print(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)
#
代码
作用
机制·语法
关联·结果
易错点
1
print(a + 100)
a + 100
广播:标量 100 被视为与 a 同形,逐元素相加
[101 102 103]
这其实就是 z = w·x + b 里加偏置 b 的 NumPy 版本(b 是标量/长度 1)
2
print(a + b)
a + b
同形数组逐元素相加
[11 22 33]
形状不同会广播或报错
3
print(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×10 + 2×20 + 3×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))
#
代码
作用
机制·语法
关联·结果
易错点
1
print(a @ b)
@ 运算符
a @ b(Python 3.5+)= 矩阵乘法运算符,对一维向量即点积:1×10+2×20+3×30 = 140
Let's turn to matrix product. The code below creates two matrices: a 2×3 matrix called c and a 3×2 matrix called d. Recall that the matrix product operation requires that the last dimension of the first matrix (here 3 in 2×3 of c) equals the first dimension of the second matrix (here 3 in 3×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)
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×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×10 + 2×30 + 3×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。自己算一遍再对输出。
深挖 · 形状规则是 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)
#
代码
作用
机制·语法
关联·结果
易错点
1
result = c @ d + 9000
result = c @ d + 9000
运算优先级:@ 先于 +;c@d 得 (2,2),再加标量 → 逐元素加
[[9220 9280] [9490 9640]]
写成 c @ (d + 9000) 结果不同——括号位置决定语义
2
print(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).
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.
运行结果
/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]]
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
#
代码
作用
机制·语法
关联·结果
易错点
1
import numpy as np
导入
—
—
—
2
a = np.array(list("abcde")) # array of 5 strings
建字符串数组
list("abcde") 把字符串拆成字符 list → np.array 得 dtype '
['a' 'b' 'c' 'd' 'e']
dtype 由内容推断;数字数组会推断 int/float
3
print(a)
打印
—
—
—
4
print(a[0]) # use an integer in indexing
a[0]
单个整数索引 → 取一个元素(标量)
'a'
—
5
print(a[0:2]) # use a slice in indexing
a[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
#
代码
作用
机制·语法
关联·结果
易错点
1
ix = [0, 1, 2]
ix = [0,1,2]
一个普通 list,当作"整数数组"使用(NumPy 接受 list)
—
—
2
print(a[ix]) # use an integer array in indexing
a[ix]
用一个数组做索引:按 ix 中的每个下标去 a 取元素,组成新数组;长度 = len(ix)
['a' 'b' 'c']
结果长度由索引数组决定,不由 a 决定
3
print(a[[0, 1, 2]]) # use an integer array in indexing
a[[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]])
#
代码
作用
机制·语法
关联·结果
易错点
1
print(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)
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).
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.
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)
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.
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)
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`.
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.
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.
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.
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 (≥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)
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
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()
#
代码
作用
机制·语法
关联·结果
易错点
1
from tensorflow import keras
导入 keras
from tensorflow import keras
—
—
2
from tensorflow.keras.datasets import boston_housing
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).
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.
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()
#
代码
作用
机制·语法
关联·结果
易错点
1
import 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 的实验结果为准:不做归一化效果差很多
6
def normalize_features(X_train, X_test):
定义归一化函数
参数是 train 和 test 两组特征;返回两组新数组
—
—
7
mean = X_train.mean(axis=0) # 13 mean values of features
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.
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
标记注释
—
—
—
3
plot_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 × (13 + 1) = 224 trainable parameters. Similarly, the second layer has 16 × (16 + 1) = 272 trainable parameters; the third layer has 1 × (16 + 1) = 17 trainable parameters.
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.
运行结果
<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))
#
代码
作用
机制·语法
关联·结果
易错点
1
from tensorflow import keras
同 C17(少一行注释,其余相同)
sigmoid 两层 + linear
—
控制变量:只换优化器
2
from tensorflow.keras import layers
同 C17(少一行注释,其余相同)
sigmoid 两层 + linear
—
控制变量:只换优化器
3
from tensorflow.keras.datasets import boston_housing
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.
运行结果
<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))
#
代码
作用
机制·语法
关联·结果
易错点
1
from tensorflow import keras
同 C17(少注释行)
导入 / seed / 载入 / 归一化 / Sequential(
—
—
2
from tensorflow.keras import layers
同 C17(少注释行)
导入 / seed / 载入 / 归一化 / Sequential(
—
—
3
from tensorflow.keras.datasets import boston_housing
运行结果
<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))
#
代码
作用
机制·语法
关联·结果
易错点
1
from tensorflow import keras
同 C17(sigmoid 两层)
—
—
控制变量:只换损失
2
from tensorflow.keras import layers
同 C17(sigmoid 两层)
—
—
控制变量:只换损失
3
from tensorflow.keras.datasets import boston_housing
运行结果
<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" 题若遇到不同损失函数,一定要写这一句。
❦
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.
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.
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,
运行结果
<Figure size 640x480 with 1 Axes>
[image/png]
❦
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()])
#
代码
作用
机制·语法
关联·结果
易错点
1
N = 10
N = 10
只看前 10 个
—
—
2
y_pred = model.predict(X_test[:N], verbose=0)
predict 前 10 个
X_test[:N] (10,11) → 输出 (10,1)
y_pred
—
3
print("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 字符
4
print("Predicted:", *[f"{x:4.1f}" for x in y_pred.ravel()])
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.
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
—
—
—
2
from tensorflow import keras
同 C17
—
—
—
3
from tensorflow.keras import layers
同 C17
—
—
—
4
from tensorflow.keras.datasets import boston_housing
运行结果
<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
—
—
—
2
from tensorflow import keras
同 C17
—
—
—
3
from tensorflow.keras import layers
同 C17
—
—
—
4
from tensorflow.keras.datasets import boston_housing
运行结果
<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
—
—
—
2
from tensorflow import keras
同 C17
—
—
—
3
from tensorflow.keras import layers
同 C17
—
—
—
4
from tensorflow.keras.datasets import boston_housing
运行结果
<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.
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×28 image, and consists of 28×28 = 784 grayscale pixels.
The following code loads the dataset, and prints the dimensions and data type of the dataset.
# 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);
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.
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.
参数手算(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
注释 / 空行
—
—
—
3
plot_history(history)
调用 plot_history
history 是 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.
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.
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:
运行结果
<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).
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]}")
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."
❦
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.
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.
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
注释
—
—
—
2
def 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,
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.
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.
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.
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.
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.
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.
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.
# 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
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)
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.
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
运行结果
Evaluation of model 2x512_retrain [0.22696872055530548, 0.9490000009536743]
❦
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
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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
l1_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.
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.
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
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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
l2_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).
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.
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.
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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
final_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)
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))
history = model.fit(X_train, y_train, epochs=50, batch_size=256,
fit 无 split
6000 样本
{'acc': 1.0, 'loss': 0.0025}
同 t06 C88
13
verbose=0) # no validation_split
fit 无 split
6000 样本
{'acc': 1.0, 'loss': 0.0025}
同 t06 C88
14
print(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))
#
代码
作用
机制·语法
关联·结果
易错点
1
print("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.
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.
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"),
...
])
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.)
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
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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
bn_final_values = {}
空字典
BN 组单独存
—
只运行一次
The first model, 2x512_BN_AA, is implemented in this code.
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.
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.
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
运行结果
Evaluation of model 2x512_BN_BA_retrain [0.22287023067474365, 0.9409999847412109]
❦
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".
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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
he_final_values = {}
空字典
He 组
—
只运行一次
E1b
Write code to display the training and validation results in the he_final_values dictionary.
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.
history = model.fit(X_train, y_train, epochs=epochs,
fit 用 validation_data=(X_test, y_test)
每轮末在 X_test 上评估;不用 validation_split
6000/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_split
6000/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_split
6000/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.
The following 3 models have 1 convolutional layer, but they have different numbers of kernels in a layer -- 16, 32, and 64 3×3 kernels, respectively.
Model 1x16_K3x3: 1 convolutional layer of 16 3×3 kernels
Model 1x32_K3x3: 1 convolutional layer of 32 3×3 kernels
Model 1x64_K3x3: 1 convolutional layer of 64 3×3 kernels
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×3 kernels
Model 2x32_K3x3: 2 convolutional layers each of 32 3×3 kernels
Model 2x64_K3x3: 2 convolutional layers each of 64 3×3 kernels
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×28 1-channel (i.e. grayscale) images.
Consider the first convolutional layer of 64 3×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 × (kernel size 3×3 × 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.
<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>
❦
Model 2x64_K3x3, which has 2 convolutional layers and 64 3×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×3 kernels, with batch norm after both convolutional layers
Model 2x64_K3x3_BN1: 2 convolutional layers each of 64 3×3 kernels, with batch norm after the first convolutional layer
Model 2x64_K3x3_BN2: 2 convolutional layers each of 64 3×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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
bn_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).
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.
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.
Q2b 你的作答核对:正确 ✔。结论(M45):"batch norm works well after, rather than within, a bunch of convolutional layers"——注意 BN 组没有一个超过无 BN 的 .1473:在 6000 样本 + 20/30 轮的设定下,BN 的正则效果不如 dropout。
❦
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×3 kernels, with 0.25 dropout in each convolutional layer
Model 2x64_K3x3_2xD50: 2 convolutional layers each of 64 3×3 kernels, with 0.5 dropout in each convolutional layer
Model 2x64_K3x3_2xD75: 2 convolutional layers each of 64 3×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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
drop_final_values = {}
空字典
—
—
只运行一次
The first model, 2x64_K3x3_2xD25, is implemented as follows. The model is trained in 20 epochs (the default).
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.
Q3b 你的作答核对:代码正确,但表缺一行。M58 的结论 "higher dropout rates (0.5 and 0.75) have slightly better results" 是对比 D25 .2044 得出的——你提交的表里没有 D25,读者无法验证这句话。建议:交作业前 "Restart & Run All" 确保所有 cell 按序执行。
❦
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.
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×3 kernels
Model 3x64_K3x3_BN3: 3 convolutional layers each of 64 3×3 kernels, with batch norm after the third convolutional layer
Model 3x64_K3x3_3xD75: 3 convolutional layers each of 64 3×3 kernels, with 0.75 dropout in each convolutional layer
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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
extra_final_values = {}
空字典
—
—
只运行一次
The first model, 3x64_K3x3, is implemented as follows.
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.
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.
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.
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×32×3 specified in the MobileNet model creation.
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×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.
Both models with up-sampling have good performance. Among the two, the model that up-samples input to 128×128 works better than the one that up-samples input to 224×224.
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).
from google.colab import drive
drive.mount('/content/drive')
#
代码
作用
机制·语法
关联·结果
易错点
1
from google.colab import drive
from google.colab import drive
Colab 专有模块;本地 Jupyter 会 ImportError
—
只在 Colab 能跑——C35 用 try/except 包起来
2
drive.mount('/content/drive')
drive.mount("/content/drive")
把 Drive 挂载到 VM 的 /content/drive;首次会弹授权窗口
Mounted at /content/drive
授权后 Drive 文件在 /content/drive/MyDrive/...
运行结果
Mounted at /content/drive
❦
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.
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.
运行结果
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.
The Google drive is disconnected, as it is no longer needed.
Cell 39卸载 Drive基础
try:
drive.flush_and_unmount()
except:
pass
#
代码
作用
机制·语法
关联·结果
易错点
1
try:
try + drive.flush_and_unmount()
把缓存写回 Drive 并卸载
无输出
已解压完,不再需要 Drive
2
drive.flush_and_unmount()
try + drive.flush_and_unmount()
把缓存写回 Drive 并卸载
无输出
已解压完,不再需要 Drive
3
except:
except: pass
非 Colab 环境 drive 未定义 → NameError → 忽略
—
pass = 什么都不做
4
pass
except: 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.
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)
运行结果
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")
运行结果
<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.
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.
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")
#
代码
作用
机制·语法
关联·结果
易错点
1
import matplotlib.pyplot as plt
画布
—
—
—
3
plt.figure(figsize=(10, 10))
画布
—
—
—
4
for 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.
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.
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")
#
代码
作用
机制·语法
关联·结果
易错点
1
import matplotlib.pyplot as plt
同 C57
—
2 张红字
3
plt.figure(figsize=(10, 10))
同 C57
—
2 张红字
4
for 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×32×3 specified in the VGG16 model creation, and the setting of the VGG16 model to be not trainable.
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.
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.)
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."
运行结果
<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.
运行结果
<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.
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.
运行结果
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/imdb.npz
[1m17464789/17464789[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 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.
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()}
#
代码
作用
机制·语法
关联·结果
易错点
1
word_to_index = imdb.get_word_index()
imdb.get_word_index()
返回 dict {词: 频率排名},"the":1,"and":2 …
下载 imdb_word_index.json
这个索引没有给 PAD/START/UNK 留位
2
word_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 解码会全错
3
word_to_index["<PAD>"] = 0
手动加入三个特殊 token
"<PAD>"=0(填充)、"<START>"=1(句首)、"<UNKNOWN>"=2(生词)
—
3 号保留不用
4
word_to_index["<START>"] = 1
手动加入三个特殊 token
"<PAD>"=0(填充)、"<START>"=1(句首)、"<UNKNOWN>"=2(生词)
—
3 号保留不用
5
word_to_index["<UNKNOWN>"] = 2
手动加入三个特殊 token
"<PAD>"=0(填充)、"<START>"=1(句首)、"<UNKNOWN>"=2(生词)
—
3 号保留不用
6
index_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
[1m1641221/1641221[0m [32m━━━━━━━━━━━━━━━━━━━━[0m[37m[0m [1m0s[0m 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))
#
代码
作用
机制·语法
关联·结果
易错点
1
text_0 = [index_to_word[i] for i in X_train[0]]
列表推导式查表
X_train[0] 每个整数 → index_to_word[i]
词列表
—
2
print(" ".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.
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
#
代码
作用
机制·语法
关联·结果
易错点
1
from tensorflow import keras
导入
keras.preprocessing.sequence 提供 pad_sequences
—
Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
2
from tensorflow.keras import layers
导入
keras.preprocessing.sequence 提供 pad_sequences
—
Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
3
from tensorflow.keras.datasets import imdb
导入
keras.preprocessing.sequence 提供 pad_sequences
—
Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
4
from tensorflow.keras.preprocessing import sequence
导入
keras.preprocessing.sequence 提供 pad_sequences
—
Keras 3 推荐用 keras.utils.pad_sequences,旧路径仍可用
6
NUM_WORDS = 5000 # how many most frequent words in the corpus to use
NUM_WORDS = 5000
只保留最常见 5,000 词(Embedding 的行数)
—
越大表达力越强但参数越多
7
NUM_SKIP_WORDS = 0 # how many stop words to skip
NUM_SKIP_WORDS = 0
跳过最常见 N 个词("the"、"a" 等停用词);0 = 不跳
—
—
8
WV_SIZE = 96 # word vector size, 96D, each vector having 96 values
WV_SIZE = 96
词向量维度
—
典型值 50–300
9
SEQ_LEN = 100 # standardized length of text after padding/truncating
history = model.fit(X_train, y_train, epochs=epochs,
fit validation_data
25000/256 = 97.7 → 98 步/轮
—
—
6
batch_size=batch_size, verbose=verbose,
fit validation_data
25000/256 = 97.7 → 98 步/轮
—
—
7
validation_data=(X_test, y_test))
fit validation_data
25000/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 = {}
#
代码
作用
机制·语法
关联·结果
易错点
1
final_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.
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 × 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.
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 × input depth 96 + 1 bias) × 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.
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.
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.
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) × 64 units.
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])
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])
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.
<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>
❦
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.)
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.)
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.
The code below displays the first message with index 0.
Cell 77看第 0 条消息导入·绘图·输出
print(newsgroups.data[0].strip())
#
代码
作用
机制·语法
关联·结果
易错点
1
print(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.
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
#
代码
作用
机制·语法
关联·结果
易错点
1
from tensorflow import keras
导入
新增 Tokenizer
—
—
2
from tensorflow.keras import layers
导入
新增 Tokenizer
—
—
3
from tensorflow.keras.preprocessing import sequence
导入
新增 Tokenizer
—
—
4
from tensorflow.keras.preprocessing.text import Tokenizer
导入
新增 Tokenizer
—
—
6
NUM_WORDS = 5000 # how many most frequent words in the corpus to use
NUM_WORDS = 5000
同 IMDb
—
—
7
WV_SIZE = 96 # word vector size, 96D, each vector having 96 values
WV_SIZE = 96
同
—
—
8
SEQ_LEN = 100 # standardized length of text after padding/truncating
SEQ_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.
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.
运行结果
<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)}")
"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')
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.
The code below displays the first message with index 0.
Cell 8查看第 0 条帖子基础
print(newsgroups.data[0].strip())
#
代码
作用
机制·语法
关联·结果
易错点
1
print(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.
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
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.
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
#
代码
作用
机制·语法
关联·结果
易错点
1
def 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 = 每轮一行(不显示进度条)
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.
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) × 64 units.
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)}")
运行结果
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])
#
代码
作用
机制·语法
关联·结果
易错点
1
X, y = load_and_prep_20newsgroups()
加载数据(同上)
完全同 C27 L1
2
model = 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)
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 × (64 units + input depth 96 + 1 bias) × 64 units.
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])
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
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])
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)
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])
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
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.
读表结论(考试可能让你解释): ① 泛化: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——纯显示问题。
❦
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.
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
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)
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.
Gutenberg 的 cache/epub/11/pg11.txt 是固定 UTF-8 纯文本版(#11 是 Alice 的编号)
首次运行下载 ~170 KB(curl 进度条);再运行直接跳过。易错:无网络时首次会失败
2
https://www.gutenberg.org/cache/epub/11/pg11.txt
URL
Project 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)
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.
位置参数顺序: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)。
运行结果
'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"),随机性降低但仍偶有不通顺处。这通常是文字生成最常用的温度区间。
运行结果
'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.
运行结果
% 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)
运行结果
'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")。
"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 ,
运行结果
'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 现象一致——这是温度采样的固有特性,与语料无关。