第 6 章 · 反向传播
搭第一个有两层的深层网络,让误差一层层往回走。
这一章把前面所有零件装成一个两层网络,并用反向传播(backpropagation)训练它。任务是红绿灯:三盏灯的亮灭组合决定该走还是该停,网络只输出一个数。代码先确认数据形状——输入是 6 行 3 列的矩阵,标签是长度 6 的向量——再逐条取样本,用点积算预测、用平方误差衡量差多少。接着加一层隐藏层:3 个输入经 weights_0_1 变成 4 个隐藏值,过 relu 把负数截成 0,再由 weights_1_2 汇总成一个预测。难点在于隐藏层拿不到标准答案,它的 delta 只能从输出层反推:先乘 weights_1_2 的转置,再乘 relu 的导数,让原本关闭的单元不接收误差。这些步骤都用矩阵乘法写,两层权重同时更新,误差在几十轮里掉到千分之一以下。
读完应该能回答
- 为什么训练时要一条一条喂样本,而不是一次把整个数据集算完?
- relu 在隐藏层做了什么,它的导数为什么只是「是否大于 0」?
- 隐藏层没有自己的目标值,它的 delta 是从哪里来的?
- 更新权重时为什么能用一个矩阵乘法代替双重循环?
- 这里的总误差是求和还是求平均,用的时候要注意什么?
容易想错的地方
- 这一格用的是 layer_2_delta 等于真值减预测、更新用加号;第 4、5 章写的是预测减真值配减号,两者等价,读之前先确认符号。
- 取样本要写成 streetlights[i:i+1],保留 1 行 3 列的二维形状;写成 streetlights[i] 变成一维,后面矩阵乘的维度就对不上。
- relu2deriv 接收的是 relu 的输出而不是它的输入,返回 True 或 False 再当数字用:结果为 0 的隐藏单元这一轮完全不更新。
- layer_2_error 累加的是所有样本误差之和而不是平均,数值会随样本数放大,不能直接和单样本误差比较。
先把数据摆成矩阵:6 条街灯记录、每行 3 盏灯,标签是 6 个 0 或 1。这一格只用第一条数据训练 20 轮,预测从 -0.2 向 0 靠,误差从 0.04 往下掉——矩阵写法下的更新和前面完全一样:dot 求预测,delta 定方向,输入乘 delta 给出每个权重的步长。
import numpy as np weights = np.array([0.5,0.48,-0.7]) alpha = 0.1 streetlights = np.array( [ [ 1, 0, 1 ], [ 0, 1, 1 ], [ 0, 0, 1 ], [ 1, 1, 1 ], [ 0, 1, 1 ], [ 1, 0, 1 ] ] ) walk_vs_stop = np.array( [ 0, 1, 0, 1, 1, 0 ] ) input = streetlights[0] # [1,0,1] goal_prediction = walk_vs_stop[0] # equals 0... i.e. "stop" for iteration in range(20): prediction = input.dot(weights) error = (goal_prediction - prediction) ** 2 delta = prediction - goal_prediction weights = weights - (alpha * (input * delta)) print("Error:" + str(error) + " Prediction:" + str(prediction))
Error:0.03999999999999998 Prediction:-0.19999999999999996 Error:0.025599999999999973 Prediction:-0.15999999999999992 Error:0.01638399999999997 Prediction:-0.1279999999999999 Error:0.010485759999999964 Prediction:-0.10239999999999982 Error:0.006710886399999962 Prediction:-0.08191999999999977 Error:0.004294967295999976 Prediction:-0.06553599999999982 Error:0.002748779069439994 Prediction:-0.05242879999999994 Error:0.0017592186044416036 Prediction:-0.04194304000000004 Error:0.0011258999068426293 Prediction:-0.03355443200000008 Error:0.0007205759403792803 Prediction:-0.02684354560000002 Error:0.0004611686018427356 Prediction:-0.021474836479999926 Error:0.0002951479051793508 Prediction:-0.01717986918399994 Error:0.00018889465931478573 Prediction:-0.013743895347199997 Error:0.00012089258196146188 Prediction:-0.010995116277759953 Error:7.737125245533561e-05 Prediction:-0.008796093022207963 Error:4.951760157141604e-05 Prediction:-0.007036874417766459 Error:3.169126500570676e-05 Prediction:-0.0056294995342132115 Error:2.028240960365233e-05 Prediction:-0.004503599627370569 Error:1.298074214633813e-05 Prediction:-0.003602879701896544 Error:8.307674973656916e-06 Prediction:-0.002882303761517324
Building Our Neural Network
先验证 NumPy 的逐元素规则:a*b 是对应位置相乘,a*0.5 是整体缩放。后面所有更新式都建立在这条规则上——权重减掉 alpha 乘一个同形状的数组,才能一个式子同时改掉所有参数。
import numpy as np a = np.array([0,1,2,1]) b = np.array([2,2,2,3]) print(a*b) #elementwise multiplication print(a+b) #elementwise addition print(a * 0.5) # vector-scalar multiplication print(a + 0.5) # vector-scalar addition
[0 2 4 3] [2 3 4 4] [0. 0.5 1. 0.5] [0.5 1.5 2.5 1.5]
Learning the whole dataset!
加上外层循环遍历整个数据集:每条样本更新一次权重,6 条走完算一轮,error_for_all_lights 把 6 条误差加起来当作这一轮的进度。逐条更新意味着后面的样本用的是已被前面样本改过的权重,误差会因此起伏,但几十轮之后整体是下降的。
import numpy as np weights = np.array([0.5,0.48,-0.7]) alpha = 0.1 streetlights = np.array( [[ 1, 0, 1 ], [ 0, 1, 1 ], [ 0, 0, 1 ], [ 1, 1, 1 ], [ 0, 1, 1 ], [ 1, 0, 1 ] ] ) walk_vs_stop = np.array( [ 0, 1, 0, 1, 1, 0 ] ) input = streetlights[0] # [1,0,1] goal_prediction = walk_vs_stop[0] # equals 0... i.e. "stop" for iteration in range(40): error_for_all_lights = 0 for row_index in range(len(walk_vs_stop)): input = streetlights[row_index] goal_prediction = walk_vs_stop[row_index] prediction = input.dot(weights) error = (goal_prediction - prediction) ** 2 error_for_all_lights += error delta = prediction - goal_prediction weights = weights - (alpha * (input * delta)) print("Prediction:" + str(prediction)) print("Error:" + str(error_for_all_lights) + "\n")
Prediction:-0.19999999999999996 Prediction:-0.19999999999999996 Prediction:-0.5599999999999999 Prediction:0.6160000000000001 Prediction:0.17279999999999995 Prediction:0.17552 Error:2.6561231104 Prediction:0.14041599999999999 Prediction:0.3066464 Prediction:-0.34513824 Prediction:1.006637344 Prediction:0.4785034751999999 Prediction:0.26700416768 Error:0.9628701776715985 Prediction:0.213603334144 Prediction:0.5347420299776 Prediction:-0.26067345110016 Prediction:1.1319428845096962 Prediction:0.6274723921901568 Prediction:0.25433999330650114 Error:0.5509165866836797 Prediction:0.20347199464520088 Prediction:0.6561967149569552 Prediction:-0.221948503950995 Prediction:1.166258650532124 Prediction:0.7139004922542389 Prediction:0.21471099528371604 Error:0.36445836852222424 Prediction:0.17176879622697283 Prediction:0.7324724146523222 Prediction:-0.19966478845083285 Prediction:1.1697769945341199 Prediction:0.7719890116601171 Prediction:0.17297997428859369 Error:0.2516768662079895 Prediction:0.13838397943087496 Prediction:0.7864548139561468 Prediction:-0.1836567869927348 Prediction:1.163248019006011 Prediction:0.8148799260629888 Prediction:0.1362897844408577 Error:0.17797575048089034 Prediction:0.10903182755268614 Prediction:0.8273717796510367 Prediction:-0.17037324196481937 Prediction:1.1537962739591756 Prediction:0.8481754931254761 Prediction:0.1059488041691444 Error:0.12864460733422164 Prediction:0.0847590433353155 Prediction:0.859469609749935 Prediction:-0.1585508402022421 Prediction:1.1438418857156731 Prediction:0.8746623946770374 Prediction:0.08148074110264475 Error:0.09511036950476208 Prediction:0.06518459288211581 Prediction:0.8850633823431538 Prediction:-0.14771905585408038 Prediction:1.1341830033853888 Prediction:0.8959860107828534 Prediction:0.0619780399014222 Error:0.07194564247043436 Prediction:0.04958243192113776 Prediction:0.9056327614440267 Prediction:-0.13768337501215525 Prediction:1.1250605910610996 Prediction:0.9132624284442169 Prediction:0.04653264583708144 Error:0.05564914990717743 Prediction:0.03722611666966513 Prediction:0.922234066504699 Prediction:-0.12834662236261596 Prediction:1.116526024487899 Prediction:0.9273167105424409 Prediction:0.03435527296969987 Error:0.04394763937673939 Prediction:0.027484218375759886 Prediction:0.9356694192994068 Prediction:-0.11964712469387503 Prediction:1.1085678053734553 Prediction:0.9387866868342218 Prediction:0.024792915481941458 Error:0.035357967050948465 Prediction:0.019834332385553155 Prediction:0.946566624680628 Prediction:-0.11153724870006754 Prediction:1.1011550767549563 Prediction:0.948176009263518 Prediction:0.017315912033043404 Error:0.02890700056547436 Prediction:0.013852729626434732 Prediction:0.9554239432448665 Prediction:-0.10397589092234266 Prediction:1.0942524239871314 Prediction:0.9558862588907013 Prediction:0.011498267782398985 Error:0.023951660591138853 Prediction:0.009198614225919194 Prediction:0.9626393189117293 Prediction:-0.09692579020989642 Prediction:1.087824783849832 Prediction:0.9622390773804066 Prediction:0.006998674002545002 Error:0.020063105176016144 Prediction:0.005598939202035996 Prediction:0.9685315005838672 Prediction:-0.09035250869077546 Prediction:1.0818389613301889 Prediction:0.9674926590701334 Prediction:0.003544193999268516 Error:0.016952094519447087 Prediction:0.0028353551994148157 Prediction:0.9733561723362383 Prediction:-0.0842239920152223 Prediction:1.0762639960116431 Prediction:0.9718545378681842 Prediction:0.0009168131382832068 Error:0.014420818295271236 Prediction:0.0007334505106265654 Prediction:0.9773186039296565 Prediction:-0.07851033295953944 Prediction:1.0710711494147542 Prediction:0.9754916865567282 Prediction:-0.0010574652271341245 Error:0.012331739998443648 Prediction:-0.0008459721817072885 Prediction:0.9805836929862668 Prediction:-0.07318360881847627 Prediction:1.066233777045345 Prediction:0.9785385598617921 Prediction:-0.0025173975573930946 Error:0.010587393171639842 Prediction:-0.002013918045914484 Prediction:0.9832839794497644 Prediction:-0.06821774801198803 Prediction:1.0617271739912904 Prediction:0.9811035235627523 Prediction:-0.0035735447350425317 Error:0.009117233405426495 Prediction:-0.002858835788034024 Prediction:0.9855260569025094 Prediction:-0.06358841060413677 Prediction:1.05752842286588 Prediction:0.9832740020092452 Prediction:-0.004313918034364962 Error:0.00786904226904208 Prediction:-0.003451134427491974 Prediction:0.9873957068535818 Prediction:-0.059272877470408075 Prediction:1.0536162524729626 Prediction:0.9851206027353137 Prediction:-0.004808501248434842 Error:0.006803273214640502 Prediction:-0.0038468009987478735 Prediction:0.9889620124129692 Prediction:-0.05524994626077355 Prediction:1.049970908776931 Prediction:0.9867004228010665 Prediction:-0.005112871449710697 Error:0.005889303541837786 Prediction:-0.004090297159768559 Prediction:0.9902806551018011 Prediction:-0.051499833441728114 Prediction:1.0465740376293469 Prediction:0.9880596998997442 Prediction:-0.0052710974096659285 Error:0.0051029252561172675 Prediction:-0.004216877927732746 Prediction:0.9913965574535352 Prediction:-0.048004082062078055 Prediction:1.043408578143574 Prediction:0.9892359385403211 Prediction:-0.005318059364078823 Error:0.004424644608684828 Prediction:-0.0042544474912630525 Prediction:0.992346001517791 Prediction:-0.044745474990504665 Prediction:1.0404586655589985 Prediction:0.9902596156014837 Prediction:-0.005281305317687134 Error:0.0038385124412518303 Prediction:-0.0042250442541497055 Prediction:0.9931583274383705 Prediction:-0.041707953394155776 Prediction:1.0377095425371112 Prediction:0.9911555487826897 Prediction:-0.005182536193432452 Error:0.0033313054558089675 Prediction:-0.004146028954745959 Prediction:0.9938572955409696 Prediction:-0.03887654022599941 Prediction:1.0351474779634813 Prediction:0.9919439948626794 Prediction:-0.00503879377425797 Error:0.0028919416227737734 Prediction:-0.004031035019406375 Prediction:0.9944621787695098 Prediction:-0.03623726848360008 Prediction:1.032759692455092 Prediction:0.9926415313729495 Prediction:-0.004863410672429416 Error:0.002511053608117256 Prediction:-0.003890728537943533 Prediction:0.9949886390193969 Prediction:-0.03377711399894662 Prediction:1.0305342898820642 Prediction:0.9932617646389992 Prediction:-0.004666769772712614 Error:0.0021806703520253884 Prediction:-0.003733415818170091 Prediction:0.9954494302702878 Prediction:-0.03148393251909879 Prediction:1.0284601943056741 Prediction:0.9938158986070053 Prediction:-0.004456911151490314 Error:0.0018939739123713475 Prediction:-0.003565528921192253 Prediction:0.9958549628928723 Prediction:-0.029346400840475826 Prediction:1.0265270918125804 Prediction:0.9943131920358295 Prediction:-0.004240016908292479 Error:0.0016451096996342332 Prediction:-0.0033920135266339822 Prediction:0.9962137566721563 Prediction:-0.02735396176499221 Prediction:1.0247253767906936 Prediction:0.9947613261560856 Prediction:-0.004020798285770878 Error:0.0014290353984827077 Prediction:-0.003216638628616701 Prediction:0.9965328046163073 Prediction:-0.025496772653362886 Prediction:1.0230461022472208 Prediction:0.9951667005089379 Prediction:-0.0038028045995257484 Error:0.0012413985592149145 Prediction:-0.003042243679620596 Prediction:0.996817865235065 Prediction:-0.023765657359234325 Prediction:1.0214809338160067 Prediction:0.995534671160774 Prediction:-0.0035886696105582767 Error:0.0010784359268087556 Prediction:-0.0028709356884466207 Prediction:0.9970736974585198 Prediction:-0.022152061336940452 Prediction:1.0200221071408409 Prediction:0.9958697426723416 Prediction:-0.0033803078583175654 Error:0.0009368896209360312 Prediction:-0.0027042462866540516 Prediction:0.9973042495523706 Prediction:-0.02064800972530455 Prediction:1.018662388355171 Prediction:0.9961757229433927 Prediction:-0.0031790709774033414 Error:0.0008139366504753339 Prediction:-0.002543256781922673 Prediction:0.9975128111306469 Prediction:-0.019246068219762574 Prediction:1.0173950374076535 Prediction:0.9964558482449631 Prediction:-0.0029858720226535913 Error:0.0007071291752624441 Prediction:-0.002388697618122871 Prediction:0.9977021355600483 Prediction:-0.01793930655497516 Prediction:1.0162137740080082 Prediction:0.9967128843019345 Prediction:-0.0028012842268006904 Error:0.0006143435674831474 Prediction:-0.0022410273814405524 Prediction:0.9978745386023716 Prediction:-0.016721264429884947 Prediction:1.0151127459893812 Prediction:0.9969492081270097 Prediction:-0.0026256193329783125 Error:0.00053373677328488
Our First "Deep" Neural Network
第一次出现两层结构:layer_0 是输入,layer_1 等于 relu(layer_0 乘 weights_0_1) 是隐藏层,layer_2 等于 layer_1 乘 weights_1_2 是输出。relu 写成 (x>0)*x,负数归零、正数保留,让隐藏层能把某些输入组合整段屏蔽掉;权重用 2*random-1 随机取在 -1 到 1 之间,每个隐藏单元的起点因此各不相同。
import numpy as np np.random.seed(1) def relu(x): return (x > 0) * x alpha = 0.2 hidden_size = 4 streetlights = np.array( [[ 1, 0, 1 ], [ 0, 1, 1 ], [ 0, 0, 1 ], [ 1, 1, 1 ] ] ) walk_vs_stop = np.array([[ 1, 1, 0, 0]]).T weights_0_1 = 2*np.random.random((3,hidden_size)) - 1 weights_1_2 = 2*np.random.random((hidden_size,1)) - 1 layer_0 = streetlights[0] layer_1 = relu(np.dot(layer_0,weights_0_1)) layer_2 = np.dot(layer_1,weights_1_2)
Backpropagation in Code
训练主循环。每条样本先前向算出 layer_2 并累加平方误差;反向先得 layer_2_delta(真值减预测),乘上 weights_1_2 的转置就是把输出端的误差摊回隐藏层,再乘 relu2deriv 只留下被激活的单元;最后两个矩阵乘一次更新两层权重。误差每 10 轮打印一次,从 0.63 一路降到 0.0003 附近,说明两层确实一起学到了东西。
import numpy as np np.random.seed(1) def relu(x): return (x > 0) * x # returns x if x > 0 # return 0 otherwise def relu2deriv(output): return output>0 # returns 1 for input > 0 # return 0 otherwise alpha = 0.2 hidden_size = 4 weights_0_1 = 2*np.random.random((3,hidden_size)) - 1 weights_1_2 = 2*np.random.random((hidden_size,1)) - 1 for iteration in range(60): layer_2_error = 0 for i in range(len(streetlights)): layer_0 = streetlights[i:i+1] layer_1 = relu(np.dot(layer_0,weights_0_1)) layer_2 = np.dot(layer_1,weights_1_2) layer_2_error += np.sum((layer_2 - walk_vs_stop[i:i+1]) ** 2) layer_2_delta = (walk_vs_stop[i:i+1] - layer_2) layer_1_delta=layer_2_delta.dot(weights_1_2.T)*relu2deriv(layer_1) weights_1_2 += alpha * layer_1.T.dot(layer_2_delta) weights_0_1 += alpha * layer_0.T.dot(layer_1_delta) if(iteration % 10 == 9): print("Error:" + str(layer_2_error))
Error:0.6342311598444467 Error:0.35838407676317513 Error:0.0830183113303298 Error:0.006467054957103705 Error:0.0003292669000750734 Error:1.5055622665134859e-05
One Iteration of Backpropagation
一次迭代的展开版,每一步单独写成变量便于对照:error 只用来观察,真正驱动更新的是 delta;weight_delta_1_2 是 layer_1 转置乘 layer_2_delta,含义是「每个隐藏值对每条输出权重该负多少责」;weight_delta_0_1 用 layer_0 转置乘 layer_1_delta,同一个道理把误差继续往前摊一层。
import numpy as np np.random.seed(1) def relu(x): return (x > 0) * x def relu2deriv(output): return output>0 lights = np.array( [[ 1, 0, 1 ], [ 0, 1, 1 ], [ 0, 0, 1 ], [ 1, 1, 1 ] ] ) walk_stop = np.array([[ 1, 1, 0, 0]]).T alpha = 0.2 hidden_size = 3 weights_0_1 = 2*np.random.random((3,hidden_size)) - 1 weights_1_2 = 2*np.random.random((hidden_size,1)) - 1 layer_0 = lights[0:1] layer_1 = np.dot(layer_0,weights_0_1) layer_1 = relu(layer_1) layer_2 = np.dot(layer_1,weights_1_2) error = (layer_2-walk_stop[0:1])**2 layer_2_delta=(layer_2-walk_stop[0:1]) layer_1_delta=layer_2_delta.dot(weights_1_2.T) layer_1_delta *= relu2deriv(layer_1) weight_delta_1_2 = layer_1.T.dot(layer_2_delta) weight_delta_0_1 = layer_0.T.dot(layer_1_delta) weights_1_2 -= alpha * weight_delta_1_2 weights_0_1 -= alpha * weight_delta_0_1
Putting it all Together
和 [9] 同一个网络,但 delta 换成 layer_2 减真值、更新改用减号,打印出来的误差序列一模一样——这就是两种符号写法等价的证据。可以把这一格和 [11] 对照着看,确认加号配「真值减预测」与减号配「预测减真值」是同一件事。
import numpy as np np.random.seed(1) def relu(x): return (x > 0) * x # returns x if x > 0 # return 0 otherwise def relu2deriv(output): return output>0 # returns 1 for input > 0 # return 0 otherwise streetlights = np.array( [[ 1, 0, 1 ], [ 0, 1, 1 ], [ 0, 0, 1 ], [ 1, 1, 1 ] ] ) walk_vs_stop = np.array([[ 1, 1, 0, 0]]).T alpha = 0.2 hidden_size = 4 weights_0_1 = 2*np.random.random((3,hidden_size)) - 1 weights_1_2 = 2*np.random.random((hidden_size,1)) - 1 for iteration in range(60): layer_2_error = 0 for i in range(len(streetlights)): layer_0 = streetlights[i:i+1] layer_1 = relu(np.dot(layer_0,weights_0_1)) layer_2 = np.dot(layer_1,weights_1_2) layer_2_error += np.sum((layer_2 - walk_vs_stop[i:i+1]) ** 2) layer_2_delta = (layer_2 - walk_vs_stop[i:i+1]) layer_1_delta=layer_2_delta.dot(weights_1_2.T)*relu2deriv(layer_1) weights_1_2 -= alpha * layer_1.T.dot(layer_2_delta) weights_0_1 -= alpha * layer_0.T.dot(layer_1_delta) if(iteration % 10 == 9): print("Error:" + str(layer_2_error))
Error:0.6342311598444467 Error:0.35838407676317513 Error:0.0830183113303298 Error:0.006467054957103705 Error:0.0003292669000750734 Error:1.5055622665134859e-05