本文共 1552 字,大约阅读时间需要 5 分钟。
如果你想只更新权重矩阵的一个子集(例如一些行或列)。这种情况下神经网络只利用这个子集来进行前向传播,那么成本函数(cost function),只应取决于迭代过程中使用的权重的子集。
举一个自然语言处理中的例子:
例如,如果你想学习一个查找表(lookup table),来做词嵌入,每一行是一个词向量。在每个迭代中,更新的参数应该只是在向前传播中使用到的那些行。对应于theano函数,为查找表定义一个共享变量:
lookup_table = theano.shared(matrix_ndarray)
通过一个整数向量索引获取表的一个子集。
subset = lookup_table[vector_of_indices]
从现在开始,只使用subset
,不使用lookup_table[vector_of_indices]
。后者在求grad
时可能创建新变量。
定义成本函数:
cost = something that depends on subsetg = theano.grad(cost, subset)
为更新参数有两种方法:要么使用inc_subtensor
或set_subtensor
。推荐使用inc_subtensor
。
updates = inc_subtensor(subset, g*lr)
updates = set_subtensor(subset, subset + g*lr)
在这里:
f = theano.function(..., updates=[(lookup_table, updates)])
注意:++划重点!!!++ 上面只计算了subset的grad。也可以计算整个lookup_table的grad,区别就是计算得到的梯度gradient只在用来前向传播的那些行为非零值。如果用随机梯度下降算法SGD来更新参数的话,除了额外的计算外没有其他区别,只是其中有一些梯度为0(那些在前向传播中没有用到的行,即词向量)。但是,如果你想使用一个不同的优化方法如rmsprop或Hessian-Free优化,就会有问题。
小结: In general, it would be better to compute the gradient only w.r.t. to those lookup table rows or columns which are actually used during the forward propagation.
另: 其他深度学习优化方法近期会专门写一篇博客介绍。
转载地址:http://jnoji.baihongyu.com/