Microsoft NNI 样例分析

NNI 样例分析

NNI (Neural Network Intelligence) 是微软亚洲研究院开源的自动机器学习工具。

分析样例:nni/examples/trials/mnist-tfv2

配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# 作者名字
authorName: StevenOS
# 实验名称
experimentName: Test
# 定义trial的数量,一般不大于空闲GPU的数量
trialConcurrency: 1
# 定义此实验的最长执行时间,单位有:s, m, h, d
maxExecDuration: 1h
# 最大trail的数量
maxTrialNum: 10
# choices: local, remote, pai
# 运行此nni服务的位置:
# local: 本地
# remote: ssh链接到的远程计算机
# pai: 提交任务到微软开源的 OpenPAI 上。
trainingServicePlatform: local
# 搜索空间路径
searchSpacePath: search_space.json
# 定义使用标记来分析代码并生成搜索空间。使用Annotation则设置为true
useAnnotation: false


tuner:
44# 系统Tuner的名字
44# choices: TPE, Random, Anneal, Evolution, BatchTuner, MetisTuner,
44# GPTuner, SMAC (SMAC should be installed through nnictl)
builtinTunerName: TPE
# Tuner算法的参数
classArgs:
# choices: maximize, minimize
optimize_mode: maximize

# trail配置
trial:
4# trial执行命令
command: python3 mnist.py
# 代码相对路径
codeDir: .
# 设置GPU个数
gpuNum: 0

代码

参数定义

1
2
3
4
5
6
7
params = {
"dropout_rate": 0.5,
"conv_size": 5,
"hidden_size": 1024,
"batch_size": 32,
"learning_rate": 1e-4,
}

获取参数

1
2
3
4
5
model = MnistModel(
conv_size=params["conv_size"],
hidden_size=params["hidden_size"],
dropout_rate=params["dropout_rate"],
)

模型训练

1
2
3
4
5
6
7
8
9
model.fit(
x_train,
y_train,
batch_size=params["batch_size"],
epochs=10,
verbose=0,
callbacks=[ReportIntermediates()],
validation_data=(x_test, y_test),
)

加载数据集

1
2
3
4
5
6
7
8
def load_dataset():
"""Download and reformat MNIST dataset"""
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
x_train = x_train[..., tf.newaxis]
x_test = x_test[..., tf.newaxis]
return (x_train, y_train), (x_test, y_test)

提交中间结果

主要代码:

nni.report_intermediate_result()

1
2
3
4
5
6
def on_epoch_end(self, epoch, logs=None):
"""Reports intermediate accuracy to NNI framework"""
if "val_acc" in logs:
nni.report_intermediate_result(logs["val_acc"])
else:
nni.report_intermediate_result(logs["val_accuracy"])

提交最终结果

主要代码

nni.report_final_result()

1
2
3
loss, accuracy = model.evaluate(x_test, y_test, verbose=0)
nni.report_final_result(accuracy) # send final accuracy to NNI tuner and web UI
_logger.info("Final accuracy reported: %s", accuracy)

实现

  1. 从配置文件中的searchSpacePath中读取超级参数和搜索范围字典文件:search_space.json
  2. 获得命令行参数,或者采用默认参数
  3. 加载参数,用以产生 2D 图表
  4. 若需要将每次实验结果上报,则使用:
    nni.report_intermediate_result(metric)
  5. 若要上报最终结果(以此最终结果作为参数选择的参考),则使用:
    nni.report_final_result(metric)
  6. 每次 Trial 重复实现,直到达到配置文件中的maxTrialNum

结果

打赏
  • 版权声明: 本博客采用 Apache License 2.0 许可协议。
    转载请注明出处: https://ryzenx.com/2020/05/NNI-example/

谢谢你的喜欢~

支付宝
微信