我正在尝试使用tensorflow.plugins.hparams调整神经网络的超参数。
在此link中,给出了有关如何使用该函数调整超参数的建议代码。
在所提供的链接中可见,可以使用以下内容:
HP_NUM_UNITS = hp.HParam('num_units', hp.Discrete([16, 32]))
HP_DROPOUT = hp.HParam('dropout', hp.RealInterval(0.1, 0.2))
HP_OPTIMIZER = hp.HParam('optimizer', hp.Discrete(['adam', 'sgd']))
METRIC_ACCURACY = 'accuracy'
with tf.summary.create_file_writer('logs/hparam_tuning').as_default():
hp.hparams_config(
hparams=[HP_NUM_UNITS, HP_DROPOUT, HP_OPTIMIZER],
metrics=[hp.Metric(METRIC_ACCURACY, display_name='Accuracy')],
)
def train_test_model(hparams):
model = tf.keras.models.Sequential([
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(hparams[HP_NUM_UNITS], activation=tf.nn.relu),
tf.keras.layers.Dropout(hparams[HP_DROPOUT]),
tf.keras.layers.Dense(10, activation=tf.nn.softmax),
])
model.compile(
optimizer=hparams[HP_OPTIMIZER],
loss='sparse_categorical_crossentropy',
metrics=['accuracy'],
)
model.fit(x_train, y_train, epochs=1) # Run with 1 epoch to speed things up for demo purposes
_, accuracy = model.evaluate(x_test, y_test)
return accuracy
我将重点放在下一行,因为这是我想做的事情的参考。 该行:
tf.keras.layers.Dense(hparams[HP_NUM_UNITS], activation=tf.nn.relu),
我最终想要做的是创建一堆具有不同学习率,衰减率,beta_1和beta_2值等的不同类型的优化器。这是我试图做的事情:
HP_LR = hp.HParam('learning_rate',hp.Discrete([0.01,0.005,0.001,0.0005,0.0001,0.00005,0.00001,0.000005,0.000001,0.0000005,0.0000001]))
HP_MOM1 = hp.HParam('momentum_beta1',hp.Discrete([0.9,0.99,0.999,0.9999,0.99999]))
HP_MOM2 = hp.HParam('beta2',hp.Discrete([0.99,0.999,0.9999,0.99999,0.999999]))
HP_BOOL = hp.HParam('amsgrad',hp.Discrete(['True','False']))
METRIC_LOSS = 'dl_tf_loss'
with tf.summary.create_file_writer('logs/hparam_tuning').as_default():
hp.hparams_config(hparams=[HP_LR, HP_MOM1, HP_MOM2, HP_BOOL],metrics=[hp.Metric(METRIC_LOSS, display_name='Loss')],)
那很好,但是我尝试做
sgd=keras.optimizers.SGD(hparams[HP_LR], decay=0, momentum=hparams[HP_MOM1], nesterov=hparams[HP_BOOL])
,我收到以下错误消息:
KeyError Traceback (most recent call last)
<ipython-input-53-1ff09e6440a9> in <module>()
----> 1 sgd=keras.optimizers.SGD(hparams[HP_LR], decay=0, momentum=hparams[HP_MOM1], nesterov=hparams[HP_BOOL])
2 #RMSprop=keras.optimizers.RMSprop(lr=hparams[HP_LR], rho=0.9, epsilon=None, decay=0.0)
3 #adam=keras.optimizers.Adam(lr=hparams[HP_LR], beta_1=hparams[HP_MOM1], beta_2=hparams[HP_MOM2], epsilon=None, decay=0.0, amsgrad=hparams[HP_BOOL])
4
5 #HP_OPTIMIZER = hp.HParam('optimizers', hp.Discrete([sgd, RMSprop,adam]))
KeyError: HParam(name='learning_rate', domain=Discrete([1e-07, 5e-07, 1e-06, 5e-06, 1e-05, 5e-05, 0.0001, 0.0005, 0.001, 0.005, 0.01]), display_name=None, description=None)
如果有人能让我理解如何使用不同的学习率,衰减等来创建一堆不同的优化器,我将不胜感激。
谢谢!
答案 0 :(得分:0)
这不是真正的答案,但评论太久了。
我遇到了类似的问题。当HParams字典在到达model_fn时通过张量流估计器传递时,您将无法再使用定义的导入的HP_ *键来查找它们。我不知道是否与复制它们有关,但是如果您不将它们通过model_fn传递,则效果很好。
在张量流的Keras模型上使用Ray Tune时,我也遇到同样的问题。我通过将tune config解析为我的超级参数来解决,直到最后可能的时刻。
使用HParam的跨文件似乎确实存在问题,但我不确定是什么真正原因。