第 3 章 · 前向传播
一条权重、一个输入,先把「预测」这件事看清。
这一章要把「神经网络做预测」从一行乘法扩展到一般情形。最小的网络只有一个输入和一个权重(weight),预测就是把两者相乘;当输入变成脚趾数、胜率、球迷数三个量时,每个输入要配一个权重,网络把「输入乘权重」逐项相加,NumPy 里这一步就是点积(dot)。再往下,输出也可以不止一个:一个输入对多个输出时,每个权重分别乘同一个输入;多个输入对多个输出时,权重排成矩阵,每一行做一次点积。代码最后把两个这样的矩阵串起来——第一层的输出当作第二层的输入——得到的是一个有隐藏层(hidden layer)的网络。整章没有学习,权重全是手写的,要看清的只有一件事:无论网络多深,每一层做的都是「加权求和,再传给下一层」,形状对得上就能一直算下去。
读完应该能回答
- 一个输入一个权重时,预测值是怎么算出来的?
- 有多个输入时,为什么要把各自乘积加起来,而不是相乘?
- 多个输出时,权重矩阵的一行代表什么?
- 为什么第二层的输入可以直接用第一层的输出?
- NumPy 的 dot 对两个矩阵的形状有什么要求?
容易想错的地方
- w_sum 要求两个向量长度相等且一一对应,输入和权重的顺序错位不会报错,只会算出一个看似正常的错答案。
- 手写版和 NumPy 版权重矩阵的书写方向不同:手写版一行是一个输出,NumPy 版要先转置,一列才是一个输出。
- 串联两层时,中间隐藏值的维度必须同时对上前后两个权重矩阵,转置正是为了迁就 dot 的行列约定。
- 这一章的输出永远是加权和,没有激活函数也没有阈值,所以预测值可以超出 0 到 1 的范围,别当成概率。
What is a Neural Network?
整个网络只有一个权重 0.1,预测就是输入乘权重:8.5 只脚得到 0.85,末尾的 1e-16 只是浮点误差。把「网络」压成一次乘法,是为了让人看到权重才是网络学到的全部东西。
# The network: weight = 0.1 def neural_network(input, weight): prediction = input * weight return prediction # How we use the network to predict something: number_of_toes = [8.5, 9.5, 10, 9] input = number_of_toes[0] pred = neural_network(input,weight) print(pred)
0.8500000000000001
Making a Prediction with Multiple Inputs
Complete Runnable Code
输入变成三个量,w_sum 做的是对应位置相乘再相加,也就是加权求和;权重第三个值为 0,意味着球迷数这一项此刻完全不影响预测。0.98 可以手算核对:8.5×0.1 + 0.65×0.2 + 1.2×0。
def w_sum(a,b): assert(len(a) == len(b)) output = 0 for i in range(len(a)): output += (a[i] * b[i]) return output weights = [0.1, 0.2, 0] def neural_network(input, weights): pred = w_sum(input,weights) return pred # This dataset is the current # status at the beginning of # each game for the first 4 games # in a season. # toes = current number of toes # wlrec = current games won (percent) # nfans = fan count (in millions) toes = [8.5, 9.5, 9.9, 9.0] wlrec = [0.65, 0.8, 0.8, 0.9] nfans = [1.2, 1.3, 0.5, 1.0] # Input corresponds to every entry # for the first game of the season. input = [toes[0],wlrec[0],nfans[0]] pred = neural_network(input,weights) print(pred)
0.9800000000000001
NumPy Code
同一件事用 input.dot(weights) 写,点积把循环藏进了底层;结果与手写版逐位相同,说明 dot 就是 w_sum。权重向量长度必须等于输入长度,否则这一行直接报形状错误。
import numpy as np weights = np.array([0.1, 0.2, 0]) def neural_network(input, weights): pred = input.dot(weights) return pred toes = np.array([8.5, 9.5, 9.9, 9.0]) wlrec = np.array([0.65, 0.8, 0.8, 0.9]) nfans = np.array([1.2, 1.3, 0.5, 1.0]) # Input corresponds to every entry # for the first game of the season. input = np.array([toes[0],wlrec[0],nfans[0]]) pred = neural_network(input,weights) print(pred)
0.9800000000000001
Making a Prediction with Multiple Outputs
这里反过来:一个输入(胜率 0.65),三个权重,输出三个预测,ele_mul 把同一个输入分别乘每个权重。0.195、0.13、0.585 分别是三条独立预测,它们共享同一个输入却不互相干扰。
# Instead of predicting just # whether the team won or lost, # now we're also predicting whether # they are happy/sad AND the percentage # of the team that is hurt. We are # making this prediction using only # the current win/loss record. def ele_mul(number,vector): output = [0,0,0] assert(len(output) == len(vector)) for i in range(len(vector)): output[i] = number * vector[i] return output weights = [0.3, 0.2, 0.9] def neural_network(input, weights): pred = ele_mul(input,weights) return pred wlrec = [0.65, 0.8, 0.8, 0.9] input = wlrec[0] pred = neural_network(input,weights) print(pred)
[0.195, 0.13, 0.5850000000000001]
Predicting with Multiple Inputs & Outputs
权重从向量升级成矩阵,vect_mat_mul 对每一行做一次点积,所以一行对应一个输出、一列对应一个输入。0.555 = 8.5×0.1 + 0.65×0.1 + 1.2×(-0.3),负权重的作用是把某个输入的影响往下拉。
#toes %win #fans weights = [ [0.1, 0.1, -0.3], #hurt? [0.1, 0.2, 0.0], #win? [0.0, 1.3, 0.1] ] #sad? def w_sum(a,b): assert(len(a) == len(b)) output = 0 for i in range(len(a)): output += (a[i] * b[i]) return output def vect_mat_mul(vect,matrix): assert(len(vect) == len(matrix)) output = [0,0,0] for i in range(len(vect)): output[i] = w_sum(vect,matrix[i]) return output def neural_network(input, weights): pred = vect_mat_mul(input,weights) return pred # This dataset is the current # status at the beginning of # each game for the first 4 games # in a season. # toes = current number of toes # wlrec = current games won (percent) # nfans = fan count (in millions) toes = [8.5, 9.5, 9.9, 9.0] wlrec = [0.65,0.8, 0.8, 0.9] nfans = [1.2, 1.3, 0.5, 1.0] # Input corresponds to every entry # for the first game of the season. input = [toes[0],wlrec[0],nfans[0]] pred = neural_network(input,weights) print(pred)
[0.555, 0.9800000000000001, 0.9650000000000001]
Predicting on Predictions
把两个矩阵接起来:ih_wgt 先按输入的三个量算出三个隐藏值,hp_wgt 再把隐藏值变成三个预测。中间结果 hid 既不是原始输入也不是答案,它是对输入的重新组合,这是网络变「深」的起点,只是这一层仍然全是线性的。
#toes %win #fans ih_wgt = [ [0.1, 0.2, -0.1], #hid[0] [-0.1,0.1, 0.9], #hid[1] [0.1, 0.4, 0.1] ] #hid[2] #hid[0] hid[1] hid[2] hp_wgt = [ [0.3, 1.1, -0.3], #hurt? [0.1, 0.2, 0.0], #win? [0.0, 1.3, 0.1] ] #sad? weights = [ih_wgt, hp_wgt] def neural_network(input, weights): hid = vect_mat_mul(input,weights[0]) pred = vect_mat_mul(hid,weights[1]) return pred toes = [8.5, 9.5, 9.9, 9.0] wlrec = [0.65,0.8, 0.8, 0.9] nfans = [1.2, 1.3, 0.5, 1.0] # Input corresponds to every entry # for the first game of the season. input = [toes[0],wlrec[0],nfans[0]] pred = neural_network(input,weights) print(pred)
[0.21350000000000002, 0.14500000000000002, 0.5065]
NumPy Version
数值和上一格完全相同,区别只在权重写成「一行一个输入」再转置,这样 input.dot(W) 的维度才对得上:3 维输入乘 3×3 矩阵得 3 维,再乘第二次得 3 个输出。转置改的是排列方式,不改含义。
import numpy as np #toes %win #fans ih_wgt = np.array([ [0.1, 0.2, -0.1], #hid[0] [-0.1,0.1, 0.9], #hid[1] [0.1, 0.4, 0.1]]).T #hid[2] # hid[0] hid[1] hid[2] hp_wgt = np.array([ [0.3, 1.1, -0.3], #hurt? [0.1, 0.2, 0.0], #win? [0.0, 1.3, 0.1] ]).T #sad? weights = [ih_wgt, hp_wgt] def neural_network(input, weights): hid = input.dot(weights[0]) pred = hid.dot(weights[1]) return pred toes = np.array([8.5, 9.5, 9.9, 9.0]) wlrec = np.array([0.65,0.8, 0.8, 0.9]) nfans = np.array([1.2, 1.3, 0.5, 1.0]) input = np.array([toes[0],wlrec[0],nfans[0]]) pred = neural_network(input,weights) print(pred)
[0.2135 0.145 0.5065]
A Quick Primer on NumPy
import numpy as np a = np.array([0,1,2,3]) # a vector b = np.array([4,5,6,7]) # another vector c = np.array([[0,1,2,3], # a matrix [4,5,6,7]]) d = np.zeros((2,4)) # (2x4 matrix of zeros) e = np.random.rand(2,5) # random 2x5 # matrix with all numbers between 0 and 1 print(a) print(b) print(c) print(d) print(e)
[0 1 2 3] [4 5 6 7] [[0 1 2 3] [4 5 6 7]] [[0. 0. 0. 0.] [0. 0. 0. 0.]] [[0.40221396 0.5714968 0.68579318 0.73326444 0.42793703] [0.19555759 0.20401945 0.21708259 0.95738529 0.42907317]]
print(a * 0.1) # multiplies every number in vector "a" by 0.1 print(c * 0.2) # multiplies every number in matrix "c" by 0.2 print(a * b) # multiplies elementwise between a and b (columns paired up) print(a * b * 0.2) # elementwise multiplication then multiplied by 0.2 print(a * c) # since c has the same number of columns as a, this performs # elementwise multiplication on every row of the matrix "c" print(a * e) # since a and e don't have the same number of columns, this # throws a "Value Error: operands could not be broadcast together with.."
[[0. 0. 0. 0.]] [[0. 0. 0.]]
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-11-7608a210c62a> in <module>()
3 print(c * 0.2) # multiplies every number in matrix "c" by 0.2
4
----> 5 print(a * b) # multiplies elementwise between a and b (columns paired up)
6
7 print(a * b * 0.2) # elementwise multiplication then multiplied by 0.2
ValueError: operands could not be broadcast together with shapes (1,4) (4,3)
a = np.zeros((1,4)) # vector of length 4 b = np.zeros((4,3)) # matrix with 4 rows & 3 columns c = a.dot(b) print(c.shape)
(1, 3)
这一组例子专讲 dot 的形状规则:前一个的列数必须等于后一个的行数,结果形状是「前行数 × 后列数」;最后一例 5×4 乘 5×6 正因为列数不等于行数而报错。搭网络时先对形状,能省掉大半调试时间。
a = np.zeros((2,4)) # matrix with 2 rows and 4 columns b = np.zeros((4,3)) # matrix with 4 rows & 3 columns c = a.dot(b) print(c.shape) # outputs (2,3) e = np.zeros((2,1)) # matrix with 2 rows and 1 columns f = np.zeros((1,3)) # matrix with 1 row & 3 columns g = e.dot(f) print(g.shape) # outputs (2,3) h = np.zeros((5,4)).T # matrix with 4 rows and 5 columns i = np.zeros((5,6)) # matrix with 6 rows & 5 columns j = h.dot(i) print(j.shape) # outputs (4,6) h = np.zeros((5,4)) # matrix with 5 rows and 4 columns i = np.zeros((5,6)) # matrix with 5 rows & 6 columns j = h.dot(i) print(j.shape) # throws an error
(2, 3) (2, 3) (4, 6)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-13-37331c0fca7f> in <module>()
19 h = np.zeros((5,4)) # matrix with 5 rows and 4 columns
20 i = np.zeros((5,6)) # matrix with 5 rows & 6 columns
---> 21 j = h.dot(i)
22 print(j.shape) # throws an error
ValueError: shapes (5,4) and (5,6) not aligned: 4 (dim 1) != 5 (dim 0)