我在Jupyter笔记本中使用Keras框架开发了一个经过训练的神经网络模型。这是一个回归问题,我试图使用大约14个输入变量或特征来预测输出变量。作为下一步,我想最小化我的输出,并希望确定这14个输入将采用什么配置/值来获得最小的输出值。
因此,本质上,我希望将经过训练的模型对象作为我在求解器中的目标函数,并对输入变量进行一系列约束,以优化/最小化目标。什么是最好的Python解算器,可以帮助我做到这一点?
提前感谢!
发布于 2020-04-12 02:54:37
因此您已经有了经过训练的模型,我们可以将其视为f(x) = y。
将其最小化的标准SciPy方法被适当地命名为scipy.optimize.minimize。
要使用它,您只需调整您的f(x) = y函数以适应SciPy使用的API。也就是说,第一个函数参数是要优化的params列表。第二个参数是可选的,可以包含为整个优化(即您训练的模型)固定的任何args。
def score_trained_model(params, args):
# Get the model from the fixed args.
model = args[0]
# Run the model on the params, return the output.
return model_predict(model, params)有了这个,加上最初的猜测,您现在可以使用minimize函数:
# Nelder-Mead is my go-to to start with.
# But it doesn't take advantage of the gradient.
# Something that does, e.g. BGFS, may perform better for your case.
method = 'Nelder-Mead'
# All zeros is fine, but improving this initial guess can help.
guess_params = [0]*14
# Given a trained model, optimize the inputs to minimize the output.
optim_params = scipy.optimize.minimize(
score_trained_model,
guess_params,
args=(trained_model,),
method=method,
)可以为某些优化方法提供约束和界限。对于Nelder-Mead,这是不受支持的,但当违反约束时,您只会返回一个非常大的错误。
更老的答案。
OP想要优化输入,x,而不是超参数。
听起来你想要做超参数优化。我选择的Python库是hyperopt:https://github.com/hyperopt/hyperopt
假设你已经有了一些训练和评分代码,例如:
def train_and_score(args):
# Unpack args and train your model.
model = make_model(**args)
trained = train_model(model, **args)
# Return the output you want to minimize.
return score_model(trained)您可以轻松地使用hyperopt来调整参数,如学习率、辍学或激活选择:
from hyperopt import fmin, hp, tpe, space_eval
space = {
'lr': hp.loguniform('lr', np.log(0.01), np.log(0.5)),
'dropout': hp.uniform('dropout', 0, 1),
'activation': hp.choice('activation', ['relu', 'sigmoid']),
}
# Minimize the training score over the space.
trials = Trials()
best = fmin(train_and_score, space, trials=trials, algo=tpe.suggest, max_evals=100)
# Print details about the best results and hyperparameters.
print(best)
print(space_eval(space, best))还有一些库可以帮助你将其直接集成到Keras中。一个流行的选择是hyperas:https://github.com/maxpumperla/hyperas
https://stackoverflow.com/questions/61161713
复制相似问题