python深度学习第三章有一个波士顿房价的内容分析。
其中,计算所有轮次中的 K 折验证分数平均值
average_mae_history = [
np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
这个代码不太好直接理解,换个角度,等价于如下代码:
mean = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]
print('mean - ', mean)
z = []
for i in range(num_epochs):
temp = []
for j in all_mae_histories:
temp.append(j[i])
z.append(np.mean(temp))
print('mean z ', z)
上面代码是来自stackoverflow中有人提问,下面的回答的。比起之前的代码更加好理解。
我们查看all_mean_history(我自己命名的是all_mae_score):
发现是里面有4个数组,每个数组包含500个数据。我们从书中可以了解到
上述代码是4折交叉验证(k=4),而每折交叉验证都要500次完整训练(epochs=500),所以,all_mae_score包含四个数组,每个数组都包含一折交叉验证的数据,也就是500个数据
至于为什么for循环是epochs在外面,all_mae_history在里面,因为我们最终要画图,图的横坐标是epoch,也就是说,每个epoch为横坐标,该epoch对应的4折mae的平均值为纵坐标
可以看到,横坐标是epoch,就像小标题写的那样,表示每个轮次(epoch)中的K折验证分数平均值。所以必然epoch是外循环了。
如果我们对最开始的代码扣细点,可以这么理解:
我们的average_mae_history是个数组,所以average_mae_history=[ ]
然后我们是要循环num_epochs次,故代码:for i in range(num_epochs)
而每个epoch我们都要计算4折交叉验证的输出,所以我们需要遍历4个交叉验证的输出数据数组,取得对应epoch的值,所以:x[i] for x in all_mae_histories
,然后每次epoch对应的4个数据又构成了一个数组,所以加个中括号:[x[i] for x in all_mae_histories]
,然后我们调用mean方法对每个epoch对应数组值求平均,所以:np.mean()
又来了。最终输出的average_mae_history是一个包含500个数据的数组。代表500个epoch对应的4折交叉验证数据平均值,然后我们再画图。