【调参工具】微软自动调参工具—NNI

参考链接:
微软自动调参工具—NNI—安装与使用教程(附错误解决)
nni官方文档

总结一下步骤

1.pip安装nni

pip install nni

2.配置search_space.json,config.yml, model.py 三个文件

在这里插入图片描述

  1. 创建search_space.json文件,定义我们的超参数和搜索范围
{
	# 这里我定义了三个超参数
    "dropout_rate": {"_type": "uniform", "_value": [0.3, 0.6]},
    "embedding_unit": {"_type": "choice", "_value": [32, 64]},
    "activation_type": {"_type": "choice", "_value": ["softmax","tanh", "swish"]}
}
  1. 配置config.yaml
authorName: default
experimentName: example_mnist
trialConcurrency: 1 # 根据自己的GPU个数设置trail的并发数
maxExecDuration: 10h # 整个NNI自动调参的时间
maxTrialNum: 10  
#choice: local, remote, pai
trainingServicePlatform: local
searchSpacePath: search_space.json # 上面定义的search_space.json文件
#choice: true, false
useAnnotation: false
tuner:
  builtinTunerName: TPE
  classArgs:
    #choice: maximize, minimize
    optimize_mode: maximize # 优化方向,向nni报告我们的结果,如果报告结果是test_acc/准确率,那optimize_mode就选maximize。如果报告结果是loss,optimize_mode就选minimize
trial:
  command: python mnist.py # 这里要改成自己运行的model文件
  codeDir: .
  gpuNum: 0
  1. 修改model.py模型文件,添加以下代码
import nni
from tensorflow.keras.callbacks import Callback

# 默认参数
params = {
    'embedding_unit': 8,
    'activation_type': 'softmax',
    'dropout_rate': 0.1,
} # 这里的参数在后面添加到模型中,以params['dropout_rate']等替换原来的参数
tuner_params = nni.get_next_parameter() # 获得下一组搜索空间中的参数
params.update(tuner_params) # 更新参数
#-------------------------------------------------
# 这里是原来的模型
model = Sequential()
model.add(Embedding(max_features, params['embedding_unit'])) # 第一个参数
model.add(Dropout(params['dropout_rate'])) # 第二个参数
model.add(Bidirectional(LSTM(32)))
model.add(Dense(11, activation=params['activation_type'])) # 第三个参数
print(model.summary())
#-------------------------------------------------
# 定义callback函数,用于Keras的model.fit里报告中间结果 
class ReportIntermediates(Callback):
    """
    Callback class for reporting intermediate accuracy metrics.
    This callback sends accuracy to NNI framework every 100 steps,
    so you can view the learning curve on web UI.
    If an assessor is configured in experiment's YAML file,
    it will use these metrics for early stopping.
    """
    def on_epoch_end(self, epoch, logs=None):
        """Reports intermediate accuracy to NNI framework"""
        # TensorFlow 2.0 API reference claims the key is `val_acc`, but in fact it's `val_accuracy`
        if 'val_acc' in logs:
            nni.report_intermediate_result(logs['val_acc']) # 这里汇报中间结果,用的是acc,所以上面的optimize_mode是maximize
        else:
            nni.report_intermediate_result(logs['val_accuracy'])

history = model.fit(x_train, y_train , epochs=5, batch_size=32, validation_data=[x_test, y_test], validation_freq=1,callbacks=[ReportIntermediates()],)
#----------
score = model.evaluate(x_test, y_test) # score是准确率
nni.report_final_result(score[1]) # 向nni报告最终结果
  1. 命令行运行config.yml
nnictl create --config config.yml -p 8889

-p代表使用的端口号。
在这里插入图片描述

  1. 打开一个上面给出的url
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

  2. 在命令行使用nnictl stop停止调参


一些调参方法

参考:https://zhuanlan.zhihu.com/p/90374910

一般来说,相同搜索次数下,随机搜索>网格搜索,因为随机搜索所搜索的参数空间更大,更可能获得更好的评估结果,当然这并不绝对,也没有明确理论证明,只是经验法则而已。二者的实现有sklearn的gridsearchcv和randomsearchcv,一般来说一组参数做一次交叉验证看结果来评估当前参数的好坏。

一般我们把随机搜索作为各种其他超参数优化的baseline,它同时可以给其它超参数优化方法提供先验信息,比如随机搜索到某个区域的参数表现最好,再用网格搜索在这个区域暴力搜索,另外还可以提供随机性跳出局部最优。

  • 1
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岁月漫长_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值