我想在我的神经网络训练期间调整采样率来测试一些东西,看看会发生什么。为了实现这一点,我的想法是使用相同的计算图为每次迭代创建一个新的损失和优化器。
def optimize(self, negative_sampling_rate):
return tf.train.GradientDescentOptimizer(self.learning_rate).minimize(self.calc_loss(negative_sampling_rate))
def calc_loss(self, negative_sampling_rate):
return tf.reduce_mean(tf.nn.nce_loss(
weights=self.graph.prediction_weights,
biases=self.graph.prediction_bias,
labels=self.graph.labels,
inputs=self.graph.hidden,
num_sampled=negative_sampling_rate,
num_classes=self.graph.prediction_weights.shape[1])
)
def train(self, batch_inputs, batch_labels, negative_sampling_rate):
feed_dict = {self.graph.X: batch_inputs, self.graph.labels: batch_labels}
_, loss_val = self.session.run(
[self.optimize(negative_sampling_rate), self.calc_loss(negative_sampling_rate)], feed_dict=feed_dict
)
return loss_val
但我有点担心优化器。我听说优化器有内部变量,这些变量在每次训练迭代时改变。是对所有优化器还是仅对某些优化器都是如此?如果是这样,哪些优化器可用于此方法?
然后应该像这样训练神经网络:
for step in range(training_steps):
NN.train(inputs, labels, compute_sampling_rate(step))
请您参考如下方法:
首先,在不给优化器带来问题的情况下,改变nce损失中的样本数量应该没问题。一些优化器存储的内部变量与图中可训练变量的历史梯度有关。
其次,如果您确实出于某种原因想要重置优化器的状态,我的方法是将优化器置于可变范围内。每当我想重置它时,我都会运行 reset_optimizer 操作。
reset_optimizer = tf.no_op()
with tf.variable_scope('optimizer'):
train_op = optimizer(learning_rate).minimize(loss)
opt_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, "optimizer")
if len(opt_vars): # check if optimzer state needs resetting
reset_optimizer = variables_initializer(opt_vars))
