首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在神经网络模型上设置优化求解器

在神经网络模型上设置优化求解器
EN

Stack Overflow用户
提问于 2020-04-12 02:24:47
回答 1查看 337关注 0票数 0

我在Jupyter笔记本中使用Keras框架开发了一个经过训练的神经网络模型。这是一个回归问题,我试图使用大约14个输入变量或特征来预测输出变量。作为下一步,我想最小化我的输出,并希望确定这14个输入将采用什么配置/值来获得最小的输出值。

因此,本质上,我希望将经过训练的模型对象作为我在求解器中的目标函数,并对输入变量进行一系列约束,以优化/最小化目标。什么是最好的Python解算器,可以帮助我做到这一点?

提前感谢!

EN

回答 1

Stack Overflow用户

发布于 2020-04-12 02:54:37

因此您已经有了经过训练的模型,我们可以将其视为f(x) = y

将其最小化的标准SciPy方法被适当地命名为scipy.optimize.minimize

要使用它,您只需调整您的f(x) = y函数以适应SciPy使用的API。也就是说,第一个函数参数是要优化的params列表。第二个参数是可选的,可以包含为整个优化(即您训练的模型)固定的任何args

代码语言:javascript
复制
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函数:

代码语言:javascript
复制
# 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库是hyperopthttps://github.com/hyperopt/hyperopt

假设你已经有了一些训练和评分代码,例如:

代码语言:javascript
复制
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来调整参数,如学习率、辍学或激活选择:

代码语言:javascript
复制
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中。一个流行的选择是hyperashttps://github.com/maxpumperla/hyperas

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61161713

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档