NNI GridSearch示例
NNI 小白入门 GridSearch示例
使用最简单的GridSearch进行演示
参考本博客前,需要先浏览过NNI的官网,了解大致流程
BatchTuner参考另一篇 添https://blog.csdn.net/weixin_44110392/article/details/113065226
运行代码框架
a simple implement of linear regression
不用在意线性回归的实现
假如需要调参的是 batch_size, epochs_number, learning_rate
为了方便演示,假设上面三个参数从给定的范围中选取,所以使用BatchTuner
参数范围:
epochs = [i for i in range(10, 20)] batch_sizes = [i for i in range(10, 20, 5)] learning_rates = [i*0.001 for i in range(1,3)]
NNI配置
config.yml
NNI 环境配置
- trialConcurrency: 并发数量
- Trail-command: 每一次执行程序的命令
authorName: default
experimentName: example_Linear_Regression
trialConcurrency: 5
maxExecDuration: 1h
#choice: local, remote, pai
trainingServicePlatform: local
searchSpacePath: search_space.json
#choice: true, false
useAnnotation: false
tuner:builtinTunerName: GridSearch
trial:command: python3 linear_regression.pycodeDir: .gpuNum: 0
logDir: .
search_space.json
参数的搜索空间
本例中使用GridSearch,所以就是不同的参数组的笛卡尔积锁构成的参数空间
- 下面是GridSearch要求的参数规范
'''GridSearchTuner will search all the possible configures that the user define in the searchSpace.The only acceptable types of search space are ``choice``, ``quniform``, ``randint``Type ``choice`` will select one of the options. Note that it can also be nested.Type ``quniform`` will receive three values [``low``, ``high``, ``q``],where [``low``, ``high``] specifies a range and ``q`` specifies the interval.It will be sampled in a way that the first sampled value is ``low``,and each of the following values is 'interval' larger than the value in front of it.Type ``randint`` gives all possible intergers in range[``low``, ``high``). Note that ``high`` is not included.'''
下面给出一个例子
{"epochs": {"_type": "randint","_value": [10, 20]},"batch_size": {"_type": "quniform","_value": [10, 20, 5]},"learning_rate":{"_type":"quniform","_value": [0.001, 0.004, 0.001]}
}
执行文件
- main函数
- log是为了方便debug
- nni.get_next_parameter()得到tuner中的下一组参数
- 由于我写的参数是用dict的形式存储,所以我先生成了一组默认参数然后用读取到的参数update
- train函数
- 要在开始的时候用读入的参数初始化parameters
- 最后要report_final_reault(),这里读入的数值会在最终的交互界面上画图
- 其余函数与NNI无关
import torch as t
import numpy as np
import random
import nni
import loggingLOG = logging.getLogger('linear_regression')np.random.seed(1)
random.seed(1)def generate_date(true_w, true_b, num_examples):'''generate synthetic data'''x = np.random.normal(0, 1, (num_examples, len(true_w)))y = np.dot(x, true_w) + true_b# add noisey += np.random.normal(0, 0.01, y.shape)return t.Tensor(x), t.Tensor(y)def data_iter(batch_size, features, labels):'''reading data iteration by iteration'''num_examples = len(labels)indices = list(range(num_examples))# examples are read at randomrandom.shuffle(indices)for i in range(0, num_examples, batch_size):batch_indices = np.array(indices[i:min(i + batch_size, num_examples)])yield features[batch_indices], labels[batch_indices]def loss_func(y_hat, y):'''square loss'''return (y_hat - y)**2 / 2def sgd(params, lr, batch_size):'''minibatch stochastic gradient descent'''with t.no_grad():for param in params:param -= lr * param.grad / batch_sizeparam.grad.zero_()def linreg(X, w, b):"""The linear regression model."""return t.matmul(X, w) + bdef train(ARGS, features, labels):lr = ARGS['learning_rate']num_epochs = ARGS['epochs']net = linregloss = loss_funcbatch_size = ARGS['batch_size']w = t.Tensor([1, 1])w.requires_grad_(True)b = t.Tensor([0])b.requires_grad_(True)for epoch in range(num_epochs):for X, y in data_iter(batch_size, features, labels):l = loss(net(X, w, b), y) # Minibatch loss in `X` and `y`# Compute gradient on `l` with respect to [`w`, `b`]l.sum().backward()sgd([w, b], lr,batch_size) # Update parameters using their gradient# with t.no_grad():# train_l = loss(net(features, w, b), labels)# print(f'epoch {epoch + 1}, loss {float(train_l.mean()):f}')res_loss = loss(net(features, w, b), labels)# print(w, b)loss_mean = res_loss.mean()nni.report_final_result(float(loss_mean))def generate_default_params():"""Generate default hyper parameters"""return {"epochs": 10, "batch_size": 10, "learning_rate": 0.003}if __name__ == "__main__":# generate datatrue_w = [2, -3.4]true_b = 4.2features, labels = generate_date(true_w=true_w,true_b=true_b,num_examples=200)# get parameters from tunerRECEIVED_PARAMS = nni.get_next_parameter()LOG.debug(RECEIVED_PARAMS)PARAMS = generate_default_params()PARAMS.update(RECEIVED_PARAMS)# traintrain(PARAMS, features, labels)
NNI GridSearch示例相关推荐
- 微软自动调参工具—NNI安装与快速上手,AutoML必备工具
文章目录 概述 直观的看看里面有什么 安装方法 NNI 快速入门与超参优化 设置超参数的搜索范围 配置config.yaml 听说点进蝈仔帖子的都喜欢点赞加关注~~ 老规矩官网送上: https:// ...
- 微软自动调参工具—NNI—安装与使用教程(附错误解决)
简介 NNI是微软的开源自动调参的工具.人工调参实在是太麻烦了,最近试了下水,感觉还不错,能在帮你调参的同时,把可视化的工作一起给做了,简单明了.然后感觉很多博客写的并不是很明白,所以打算自己补充一下 ...
- 微软自动调参工具 NNI 使用事例教程
第一步:安装 nni的安装通过pip命令就可以安装了.并且提供了example供参考学习. 系统配置要求:tensorflow,python >= 3.5 # 安装nnipython3 -m p ...
- Neural Network Intelligence (NNI) | 自动特征工程AutoFE示例程序
一.安装NNI和依赖 pip install nni pip install sklearn 不建议在Win10下面装NNI,因为需要c++14.0很麻烦. 另外 nni==2.2 二.数据集 下载地 ...
- NNI 示例 BatchTuner
NNI 小白入门 使用最简单的BatchTuner进行演示 参考本博客前,需要先浏览过NNI的官网,了解大致流程 GridSearch 参考另一篇 https://blog.csdn.net/weix ...
- Neural Network Intelligence (NNI) | PyTorch-CiFar10 项目示例+常用pytorch版本模型全家福
一.环境 NNI version: 2.1 Python version: 3.8.3 Pytorch version: 1.6.0 二.代码 1.main.py '''Train CIFAR10 w ...
- 自动调参NNI nnictl 支持的命令
nnictl 介绍 nnictl是一个命令行工具,用来控制 NNI Experiment,如启动.停止.继续 Experiment,启动.停止 NNIBoard 等等. 命令 nnictl 支持的命令 ...
- 微软开源的自动机器学习工具上新了:NNI概览及新功能详解
作者 | 宋驰 来源 | 微软研究院AI头条(ID: MSRAsia) 2018年9月,微软亚洲研究院发布了第一版 NNI (Neural Network Intelligence) ,目前已在 Gi ...
- 微软开源自动机器学习工具 – NNI安装与使用
微软开源自动机器学习工具 – NNI安装与使用 NNI的众多特点 开启你的第一次NNI之旅 · 安装 · 三步准备实验 (1) 准备搜索空间 (2) 准备实验代码 (3)定义实验配置 · 一行命令开始 ...
最新文章
- 时间立即同步命令_Redis复制:主从同步
- 关于前后端分离我的理解
- leetcode 岛屿的个数
- linux笔记_20150825_linux下的软件工具唠叨下
- Jstatd命令(Java Statistics Monitoring Daemon)
- Linux 系统检测工具
- 设置jstree只展示到2级_你做的私域流量属于什么级别?80%的商家都还只在第2级...
- HDU.1007 Quoit Design
- 为什么说 C++ 太复杂?有必要这么复杂吗?| 原力计划
- 识别图片并可视化_数据可视化3大发展方向
- Java基础知识梳理(五)从源码了解字符串
- nacos默认用户名密码_Docker下,两分钟极速体验Nacos配置中心
- 猿创征文|程序猿乘风破浪 Python Pygame 原创小游戏【源码+解析】
- 伤感的英文单词[转帖]
- Warning: Accessing non-existent property ‘cd‘ of module exports inside circular dependency
- qt android刘海屏状态栏,安卓手机刘海屏算抄袭苹果iPhone X吗?真相了
- Maven-POM.xml
- 春招大厂上岸学长带你有效春招找工作
- java浅谈线程安全之锁
- Python中办公软件(创建excel)