Unverified Commit 91d9a797 authored by Yuge Zhang's avatar Yuge Zhang Committed by GitHub
Browse files

Adopt symbolic links in Chinese documentation (#4345)


Co-authored-by: default avatarjiahangxu <jiahangxu@microsoft.com>
parent 0e0ee86d
.. 9f6356515c6d61bd4fc181248802970d
#################
剪枝(V2版本)
#################
......
../../en_US/Compression/v2_pruning_algo.rst
\ No newline at end of file
../../en_US/Compression/v2_scheduler.rst
\ No newline at end of file
GBDTSelector
------------
GBDTSelector 基于 `LightGBM <https://github.com/microsoft/LightGBM>`__,这是一个基于树学习算法的梯度提升框架。
当将数据传递到 GBDT 模型时,该模型将构建提升树。 特征的重要性来自于构造时的分数,其表达了每个特征在模型构造提升决策树时有多有用。
可使用此方法作为 Feature Selector 中较强的基准,特别是在使用 GBDT 模型进行分类或回归时。
当前,支持的 ``importance_type`` 有 ``split`` 和 ``gain``。 未来会支持定制 ``importance_type``,也就是说用户可以定义如何计算 ``特征分数``。
用法
^^^^^
首先,安装依赖项:
.. code-block:: bash
pip install lightgbm
然后
.. code-block:: python
from nni.feature_engineering.gbdt_selector import GBDTSelector
# 下载数据
...
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# 初始化 selector
fgs = GBDTSelector()
# 拟合数据
fgs.fit(X_train, y_train, ...)
# 获取重要的特征
# 此处会返回重要特征的索引。
print(fgs.get_selected_features(10))
...
也可在 ``/examples/feature_engineering/gbdt_selector/`` 目录找到示例。
**fit 函数参数要求**
*
**X** (数组,必需) - 训练的输入样本,shape = [n_samples, n_features]
*
**y** (数组,必需) - 目标值 (分类中为标签,回归中为实数),shape = [n_samples].
*
**lgb_params** (dict, 必需) - lightgbm 模型参数。 详情参考 `这里 <https://lightgbm.readthedocs.io/en/latest/Parameters.html>`__
*
**eval_ratio** (float, 必需) - 数据大小的比例 用于从 self.X 中拆分出评估和训练数据。
*
**early_stopping_rounds** (int, 必需) - lightgbm 中的提前终止设置。 详情参考 `这里 <https://lightgbm.readthedocs.io/en/latest/Parameters.html>`__。
*
**importance_type** (str, 必需) - 可为 'split' 或 'gain'。 'split' 表示 '结果包含特征在模型中使用的次数' 而 'gain' 表示 '结果包含此特征拆分出的总收益'。 详情参考 `这里 <https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html#lightgbm.Booster.feature_importance>`__。
*
**num_boost_round** (int, 必需) - 提升的轮数。 详情参考 `这里 <https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.train.html#lightgbm.train>`__.
**get_selected_features 函数参数的要求**
**topk** (int, 必需) - 想要选择的 k 个最好的特征。
../../en_US/FeatureEngineering/GBDTSelector.rst
\ No newline at end of file
GradientFeatureSelector
-----------------------
GradientFeatureSelector 的算法来源于 `Feature Gradients: Scalable Feature Selection via Discrete Relaxation <https://arxiv.org/pdf/1908.10382.pdf>`__。
GradientFeatureSelector,基于梯度搜索算法
的特征选择。
1) 该方法扩展了一个近期的结果,
即在亚线性数据中通过展示计算能迭代的学习(即,在迷你批处理中),在 **线性的时间空间中** 的特征数量 D 及样本大小 N。
2) 这与在搜索领域的离散到连续的放松一起,可以在非常 **大的数据集** 上进行 **高效、基于梯度** 的搜索算法。
3) 最重要的是,此算法能在特征和目标间为 N > D 和 N < D 都找到 **高阶相关性**,这与只考虑一种情况和交互式的方法所不同。
用法
^^^^^
.. code-block:: python
from nni.feature_engineering.gradient_selector import FeatureGradientSelector
# 下载数据
...
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# 初始化 selector
fgs = FeatureGradientSelector(n_features=10)
# 拟合数据
fgs.fit(X_train, y_train)
# 获取重要的特征
# 此处会返回重要特征的索引。
print(fgs.get_selected_features())
...
也可在 ``/examples/feature_engineering/gradient_feature_selector/`` 目录找到示例。
**FeatureGradientSelector 构造函数的参数**
*
**order** (int, 可选, 默认为 4) - 要包含的交互顺序。 较高的顺序可能会更准确,但会增加运行时间。 12 是允许的顺序的最大值。
*
**penatly** (int, 可选, 默认为 1) - 乘以正则项的常数。
*
**n_features** (int, 可选, 默认为 None) - 如果为 None,会自动根据搜索来选择特征的数量。 否则,表示要选择的最好特征的数量。
*
**max_features** (int, 可选, 默认为 None) - 如果不为 None,会使用 'elbow method' 来确定以 max_features 为上限的特征数量。
*
**learning_rate** (float, 可选, 默认为 1e-1) - 学习率
*
**init** (<em x-id="3">zero, on, off, onhigh, offhigh, 或 sklearn, 可选, 默认为zero</em>) - 如何初始化向量分数。 默认值为 'zero'。
*
**n_epochs** (int, 可选, 默认为 1) - 要运行的 Epoch 数量
*
**shuffle** (bool, 可选, 默认为 True) - 在 Epoch 之前需要随机化 "rows"。
*
**batch_size** (int, 可选, 默认为 1000) - 一次处理的 "rows" 数量。
*
**target_batch_size** (int, 可选, 默认为 1000) - 累计梯度的 "rows" 数量。 当行数过多无法读取到内存中,但估计精度所需。
*
**classification** (bool, 可选, 默认为 True) - 如果为 True,为分类问题,否则是回归问题。
*
**ordinal** (bool, 可选, 默认为 True) - 如果为 True,是有序的分类。 需要 classification 也为 True。
*
**balanced** (bool, 可选, 默认为 True) - 如果为 True,优化中每类的权重都一样,否则需要通过支持来对每类加权。 需要 classification 也为 True。
*
**prerocess** (str, 可选, 默认为 'zscore') - 'zscore' 是将数据中心化并归一化的党委方差,'center' 表示仅将数据均值调整到 0。
*
**soft_grouping** (bool, 可选, 默认为 True) - 如果为 True,将同一来源的特征分组到一起。 用于支持分组或组内特征的稀疏性。
*
**verbose** (int, 可选, 默认为 0) - 控制拟合时的信息详细程度。 设为 0 表示不打印,1 或更大值表示打印详细数量的步骤。
*
**device** (str, 可选, 默认为 'cpu') - 'cpu' 表示在 CPU 上运行,'cuda' 表示在 GPU 上运行。 在 GPU 上运行得更快
**fit 函数参数要求**
*
**X** (数组,必需) - 训练的输入样本,shape = [n_samples, n_features]
*
**y** (数组,必需) - 目标值 (分类中为标签,回归中为实数),shape = [n_samples].
*
**groups** (数组, 可选, 默认为 None) - 必需选择为一个单元的列的分组。 例如, [0,0,1,2] 指定前两列是组的一部分。 形状是 [n_features]。
**get_selected_features 函数参数的要求**
目前,**get_selected_features** 函数没有参数。
../../en_US/FeatureEngineering/GradientFeatureSelector.rst
\ No newline at end of file
NNI 中的特征工程
============================
我们很高兴的宣布,基于 NNI 的特征工程工具发布了试用版本。该版本仍处于试验阶段,根据使用反馈会进行改进。 诚挚邀请您使用、反馈,或有更多贡献。
当前支持以下特征选择器:
* `GradientFeatureSelector <./GradientFeatureSelector.rst>`__
* `GBDTSelector <./GBDTSelector.rst>`__
这些 Selector 适用于结构化的数据(也就是不适用于图像,语音和文本数据)。
另外,Selector 仅用于特征选择。 如果需要:
1) 在特征选择时,通过 NNI 生成高阶的组合特征;
2) 使用分布式资源;
可以尝试 :githublink:`本示例 <examples/feature_engineering/auto-feature-engineering>`。
如何使用
-----------
.. code-block:: python
from nni.feature_engineering.gradient_selector import FeatureGradientSelector
# from nni.feature_engineering.gbdt_selector import GBDTSelector
# 下载数据
...
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)
# 初始化 selector
fgs = FeatureGradientSelector(...)
# 拟合数据
fgs.fit(X_train, y_train)
# 获取重要的特征
# 此处会返回重要特征的索引。
print(fgs.get_selected_features(...))
...
使用内置 Selector 时,需要 ``import`` 对应的特征选择器,并 ``initialize``。 可在 Selector 中调用 ``fit`` 函数来传入数据。 之后,可通过 ``get_seleteced_features`` 来获得重要的特征。 不同 Selector 的函数参数可能不同,在使用前需要先检查文档。
如何定制
-----------------
NNI 内置了**最先进的** 特征工程算法的 Selector。 NNI 也支持定制自己的特征 Selector。
如果要实现定制的特征 Selector,需要:
#. 继承基类 FeatureSelector
#. 实现 *fit* 和 *get_selected_features* 函数
#. 与 sklearn 集成 (可选)
示例如下:
**1. 继承基类 FeatureSelector**
.. code-block:: python
from nni.feature_engineering.feature_selector import FeatureSelector
class CustomizedSelector(FeatureSelector):
def __init__(self, ...):
...
**2. 实现 fit 和 get_selected_features 函数**
.. code-block:: python
from nni.tuner import Tuner
from nni.feature_engineering.feature_selector import FeatureSelector
class CustomizedSelector(FeatureSelector):
def __init__(self, ...):
...
def fit(self, X, y, **kwargs):
"""
将数据拟合到 FeatureSelecto
参数
------------
X : numpy 矩阵
训练输入样本,形状为 [n_samples, n_features]。
y: numpy 矩阵
目标值 (分类中的类标签,回归中为实数)。 形状是 [n_samples]。
"""
self.X = X
self.y = y
...
def get_selected_features(self):
"""
获取重要的特征
Returns
-------
list :
返回重要特征的索引。
"""
...
return self.selected_features_
...
**3. 与 sklearn 集成**
``sklearn.pipeline.Pipeline`` 可将模型连接在一起,例如特征选择,规范化,以及分类、回归,来组成一个典型的机器学习问题工作流。
下列步骤可帮助集成 sklearn,将定制的特征 Selector 作为管道的模块。
#. 继承类 *sklearn.base.BaseEstimator*
#. 实现 *BaseEstimator* 中的 *get_params* 和 *set_params* 函数
#. 继承类 *sklearn.feature_selection.base.SelectorMixin*
#. 实现 *SelectorMixin* 中的 *get_support, transform* 和 *inverse_transform* 函数
示例如下:
**1. 继承类 BaseEstimator 及其函数**
.. code-block:: python
from sklearn.base import BaseEstimator
from nni.feature_engineering.feature_selector import FeatureSelector
class CustomizedSelector(FeatureSelector, BaseEstimator):
def __init__(self, ...):
...
def get_params(self, ...):
"""
为此 estimator 获取参数
"""
params = self.__dict__
params = {key: val for (key, val) in params.items()
if not key.endswith('_')}
return params
def set_params(self, **params):
"""
为此 estimator 设置参数
"""
for param in params:
if hasattr(self, param):
setattr(self, param, params[param])
return self
**2. 继承 SelectorMixin 类及其函数**
.. code-block:: python
from sklearn.base import BaseEstimator
from sklearn.feature_selection.base import SelectorMixin
from nni.feature_engineering.feature_selector import FeatureSelector
class CustomizedSelector(FeatureSelector, BaseEstimator, SelectorMixin):
def __init__(self, ...):
...
def get_params(self, ...):
"""
为此 estimator 获取参数
"""
params = self.__dict__
params = {key: val for (key, val) in params.items()
if not key.endswith('_')}
return params
def set_params(self, **params):
"""
为此 estimator 设置参数
"""
for param in params:
if hasattr(self, param):
setattr(self, param, params[param])
return self
def get_support(self, indices=False):
"""
获取 mask,整数索引或选择的特征。
参数
----------
indices : bool
默认值:false。 如果为 True,返回值为整数数组,否则为布尔的 mask。
Returns
-------
list :
返回 support: 从特征向量中选择保留的特征索引。
如果 indices 为 False,布尔数据的形状为 [输入特征的数量],如果元素为 True,表示保留相对应的特征。
如果 indices 为 True,整数数组的形状为 [输出特征的数量],值表示
输入特征向量中的索引。
"""
...
return mask
def transform(self, X):
"""将 X 减少为选择的特征。
参数
----------
X : array
形状为 [n_samples, n_features]
Returns
-------
X_r : array
形状为 [n_samples, n_selected_features]
仅输入选择的特征
"""
...
return X_r
def inverse_transform(self, X):
"""
反转变换操作
参数
----------
X : array
形状为 [n_samples, n_selected_features]
Returns
-------
X_r : array
形状为 [n_samples, n_original_features]
"""
...
return X_r
与 sklearn 继承后,可如下使用特征 Selector:
.. code-block:: python
from sklearn.linear_model import LogisticRegression
# 下载数据
...
X_train, y_train = ...
# 构造 a pipeline
pipeline = make_pipeline(XXXSelector(...), LogisticRegression())
pipeline = make_pipeline(SelectFromModel(ExtraTreesClassifier(n_estimators=50)), LogisticRegression())
pipeline.fit(X_train, y_train)
# 分数
print("Pipeline Score: ", pipeline.score(X_train, y_train))
基准测试
---------
``Baseline`` 表示没有进行特征选择,直接将数据传入 LogisticRegression。 此基准测试中,仅用了 10% 的训练数据作为测试数据。 对于 GradientFeatureSelector,仅使用了前 20 个特征。 下列指标是在给定测试数据和标签上的平均精度。
.. list-table::
:header-rows: 1
:widths: auto
* - 数据集
- 所有特征 + LR (acc, time, memory)
- GradientFeatureSelector + LR (acc, time, memory)
- TreeBasedClassifier + LR (acc, time, memory)
- #训练次数
- #特征数量
* - colon-cancer
- 0.7547, 890ms, 348MiB
- 0.7368, 363ms, 286MiB
- 0.7223, 171ms, 1171 MiB
- 62
- 2,000
* - gisette
- 0.9725, 215ms, 584MiB
- 0.89416, 446ms, 397MiB
- 0.9792, 911ms, 234MiB
- 6,000
- 5,000
* - avazu
- 0.8834, N/A, N/A
- N/A, N/A, N/A
- N/A, N/A, N/A
- 40,428,967
- 1,000,000
* - rcv1
- 0.9644, 557ms, 241MiB
- 0.7333, 401ms, 281MiB
- 0.9615, 752ms, 284MiB
- 20,242
- 47,236
* - news20.binary
- 0.9208, 707ms, 361MiB
- 0.6870, 565ms, 371MiB
- 0.9070, 904ms, 364MiB
- 19,996
- 1,355,191
* - real-sim
- 0.9681, 433ms, 274MiB
- 0.7969, 251ms, 274MiB
- 0.9591, 643ms, 367MiB
- 72,309
- 20,958
此基准测试的 `下载地址 <https://www.csie.ntu.edu.tw/~cjlin/libsvmtools/datasets/>`__。
代码可参考 ``/examples/feature_engineering/gradient_feature_selector/benchmark_test.py``。
参考和反馈
----------------------
* 在Github 中 `提交此功能的 Bug <https://github.com/microsoft/nni/issues/new?template=bug-report.rst>`__
* 在Github 中 `提交新功能或请求改进 <https://github.com/microsoft/nni/issues/new?template=enhancement.rst>`__
* 了解 NNI 中 :githublink:`NAS 的更多信息 <docs/zh_CN/NAS/Overview.rst>`
* 了解 NNI 中 :githublink:`模型压缩的更多信息 <docs/zh_CN/Compression/Overview.rst>`
* 了解更多关于 NNI 中 :githublink:`超参调优的更多信息 <docs/zh_CN/Tuner/BuiltinTuner.rst>`\ ;
../../en_US/FeatureEngineering/Overview.rst
\ No newline at end of file
Retiarii API 参考
======================
.. contents::
内联 Mutation API
--------------------
.. autoclass:: nni.retiarii.nn.pytorch.LayerChoice
:members:
.. autoclass:: nni.retiarii.nn.pytorch.InputChoice
:members:
.. autoclass:: nni.retiarii.nn.pytorch.ValueChoice
:members:
.. autoclass:: nni.retiarii.nn.pytorch.ChosenInputs
:members:
.. autoclass:: nni.retiarii.nn.pytorch.Repeat
:members:
.. autoclass:: nni.retiarii.nn.pytorch.Cell
:members:
图 Mutation API
-------------------
.. autoclass:: nni.retiarii.Mutator
:members:
.. autoclass:: nni.retiarii.Model
:members:
.. autoclass:: nni.retiarii.Graph
:members:
.. autoclass:: nni.retiarii.Node
:members:
.. autoclass:: nni.retiarii.Edge
:members:
.. autoclass:: nni.retiarii.Operation
:members:
Evaluators
----------
.. autoclass:: nni.retiarii.evaluator.FunctionalEvaluator
:members:
.. autoclass:: nni.retiarii.evaluator.pytorch.lightning.LightningModule
:members:
.. autoclass:: nni.retiarii.evaluator.pytorch.lightning.Classification
:members:
.. autoclass:: nni.retiarii.evaluator.pytorch.lightning.Regression
:members:
Oneshot Trainers
----------------
.. autoclass:: nni.retiarii.oneshot.pytorch.DartsTrainer
:members:
.. autoclass:: nni.retiarii.oneshot.pytorch.EnasTrainer
:members:
.. autoclass:: nni.retiarii.oneshot.pytorch.ProxylessTrainer
:members:
.. autoclass:: nni.retiarii.oneshot.pytorch.SinglePathTrainer
:members:
探索 Strategies
----------------------
.. autoclass:: nni.retiarii.strategy.Random
:members:
.. autoclass:: nni.retiarii.strategy.GridSearch
:members:
.. autoclass:: nni.retiarii.strategy.RegularizedEvolution
:members:
.. autoclass:: nni.retiarii.strategy.TPEStrategy
:members:
.. autoclass:: nni.retiarii.strategy.PolicyBasedRL
:members:
Retiarii Experiments
--------------------
.. autoclass:: nni.retiarii.experiment.pytorch.RetiariiExperiment
:members:
.. autoclass:: nni.retiarii.experiment.pytorch.RetiariiExeConfig
:members:
工具
---------
.. autofunction:: nni.retiarii.serialize
\ No newline at end of file
../../en_US/NAS/ApiReference.rst
\ No newline at end of file
NAS 基准测试
==============
.. toctree::
:hidden:
示例用法 <BenchmarksExample>
介绍
------------
为了提高 NAS 算法的可复现性并降低对计算资源的需求,研究者们提出了一系列 NAS 基准测试如 `NAS-Bench-101 <https://arxiv.org/abs/1902.09635>`_, `NAS-Bench-201 <https://arxiv.org/abs/2001.00326>`_, `NDS <https://arxiv.org/abs/1905.13214>`_ 等等。 NNI 为用户提供了查询接口来获取这些基准测试。 只需要几行代码,研究者就可以通过使用这些基准测试容易且公平地评估他们的 NAS 算法。
先决条件
-------------
* 准备目录来保存基准测试的数据库。 默认情况下,目录为 ``${HOME}/.nni/nasbenchmark`` 。 可以将其放在任意位置, 并在导入 NNI 之前指定 ``NASBENCHMARK_DIR`` 通过 ``export NASBENCHMARK_DIR=/path/to/your/nasbenchmark``.
* 通过 ``pip3 install peewee`` 命令安装 ``peewee``,NNI 用其连接数据库。
准备数据
----------------
为了避免存储和法规问题,NNI 不提供数据库。 尝试以下步骤:
#.
将 NNI 克隆到机器上并进入 ``examples/nas/benchmarks`` 目录。
.. code-block:: bash
git clone -b ${NNI_VERSION} https://github.com/microsoft/nni
cd nni/examples/nas/benchmarks
将 ``${NNI_VERSION}`` 替换为发布的版本或分支名称,例如:``v2.0``。
#.
通过 ``pip3 install -r xxx.requirements.txt`` 安装依赖。 ``xxx`` 可以是 ``nasbench101``\ ,``nasbench201`` ,``nds``。
#. 通过 ``./xxx.sh`` 生成数据库。 存储数据库的目录可以通过环境变量 ``NASBENCHMARK_DIR`` 设置,默认为 ``~/.nni/nasbenchmark``。 注意 NAS-Bench-201 数据库将从 google drive 被下载。
确保至少有 10GB 的可用磁盘空间,运行过程可能需要几个小时。
示例用法
--------------
请参考 `Benchmarks API 的示例用法 <./BenchmarksExample.rst>`_。
NAS-Bench-101
-------------
* `论文链接 <https://arxiv.org/abs/1902.09635>`__
* `开源地址 <https://github.com/google-research/nasbench>`__
NAS-Bench-101 包含 423,624 个独立的神经网络,再加上 4 个 Epoch (4, 12, 36, 108) 时的变化,以及每个都要训练 3 次。 这是基于 Cell 的搜索空间,通过枚举最多 7 个有向图的运算符来构造并堆叠 Cell,连接数量不超过 9 个。 除了第一个 (必须为 ``INPUT`` ) 和最后一个运算符 (必须为 ``OUTPUT`` ),可选的运算符有 ``CONV3X3_BN_RELU`` , ``CONV1X1_BN_RELU`` 和 ``MAXPOOL3X3`` 。
注意,NAS-Bench-101 消除了非法的 Cell(如,从输入到输出没有路径,或存在冗余的计算)。 此外,同构的 Cell 会被去掉,即,所有的 Cell 从计算上看是一致的。
API 文档
^^^^^^^^^^^^^^^^^
.. autofunction:: nni.nas.benchmarks.nasbench101.query_nb101_trial_stats
.. autoattribute:: nni.nas.benchmarks.nasbench101.INPUT
.. autoattribute:: nni.nas.benchmarks.nasbench101.OUTPUT
.. autoattribute:: nni.nas.benchmarks.nasbench101.CONV3X3_BN_RELU
.. autoattribute:: nni.nas.benchmarks.nasbench101.CONV1X1_BN_RELU
.. autoattribute:: nni.nas.benchmarks.nasbench101.MAXPOOL3X3
.. autoclass:: nni.nas.benchmarks.nasbench101.Nb101TrialConfig
.. autoclass:: nni.nas.benchmarks.nasbench101.Nb101TrialStats
.. autoclass:: nni.nas.benchmarks.nasbench101.Nb101IntermediateStats
.. autofunction:: nni.nas.benchmarks.nasbench101.graph_util.nasbench_format_to_architecture_repr
.. autofunction:: nni.nas.benchmarks.nasbench101.graph_util.infer_num_vertices
.. autofunction:: nni.nas.benchmarks.nasbench101.graph_util.hash_module
NAS-Bench-201
-------------
* `论文链接 <https://arxiv.org/abs/2001.00326>`__
* `开源 API <https://github.com/D-X-Y/NAS-Bench-201>`__
* `实现 <https://github.com/D-X-Y/AutoDL-Projects>`__
NAS-Bench-201 是单元格的搜索空间,并将张量当作节点,运算符当作边。 搜索空间包含了 4 个节点所有密集连接的有向图,共有 15,625 个候选项。 每个操作符都是从预定义的运算符集(\ ``NONE``\ ,``SKIP_CONNECT``\ ,``CONV_1X1``\ ,``CONV_3X3`` 和``AVG_POOL_3X3``\ )中选出的。 训练方法根据数据集 (CIFAR-10, CIFAR-100, ImageNet) 和 Epoch 数量 (12 和 200),而有所不同。 每个架构和训练方法的组合会随机重复 1 到 3 次。
API 文档
^^^^^^^^^^^^^^^^^
.. autofunction:: nni.nas.benchmarks.nasbench201.query_nb201_trial_stats
.. autoattribute:: nni.nas.benchmarks.nasbench201.NONE
.. autoattribute:: nni.nas.benchmarks.nasbench201.SKIP_CONNECT
.. autoattribute:: nni.nas.benchmarks.nasbench201.CONV_1X1
.. autoattribute:: nni.nas.benchmarks.nasbench201.CONV_3X3
.. autoattribute:: nni.nas.benchmarks.nasbench201.AVG_POOL_3X3
.. autoclass:: nni.nas.benchmarks.nasbench201.Nb201TrialConfig
.. autoclass:: nni.nas.benchmarks.nasbench201.Nb201TrialStats
.. autoclass:: nni.nas.benchmarks.nasbench201.Nb201IntermediateStats
NDS
---
* `论文链接 <https://arxiv.org/abs/1905.13214>`__
* `开源地址 <https://github.com/facebookresearch/nds>`__
*On Network Design Spaces for Visual Recognition* 发布了来自多个模型系列,超过 100,000 个配置(模型加超参组合)的统计,包括 vanilla (受 VGG 启发的松散前馈网络), ResNet 和 ResNeXt (残差基本模块和残差瓶颈模块) 以及 NAS 单元格 (遵循 NASNet, Ameoba, PNAS, ENAS 和 DARTS 的设计)。 大部分配置只采用固定的随机种子训练一次,但少部分会训练两到三次。
NNI 会将不同配置的结果存到单个数据库中,而不是单独的文件中,以便从各个维度进行比较。 在实现上,``model_family`` 用来保存模型类型,``model_spec`` 用来保存构建模型所需的参数,在使用 NAS 时,``cell_spec`` 保存运算符和连接的详细信息,``generator`` 表示配置生成的采样策略。 详情可参考 API 文档。
可用的运算符
-------------------
NDS 中可用的运算符列表。
.. autoattribute:: nni.nas.benchmarks.nds.constants.NONE
.. autoattribute:: nni.nas.benchmarks.nds.constants.SKIP_CONNECT
.. autoattribute:: nni.nas.benchmarks.nds.constants.AVG_POOL_3X3
.. autoattribute:: nni.nas.benchmarks.nds.constants.MAX_POOL_3X3
.. autoattribute:: nni.nas.benchmarks.nds.constants.MAX_POOL_5X5
.. autoattribute:: nni.nas.benchmarks.nds.constants.MAX_POOL_7X7
.. autoattribute:: nni.nas.benchmarks.nds.constants.CONV_1X1
.. autoattribute:: nni.nas.benchmarks.nds.constants.CONV_3X3
.. autoattribute:: nni.nas.benchmarks.nds.constants.CONV_3X1_1X3
.. autoattribute:: nni.nas.benchmarks.nds.constants.CONV_7X1_1X7
.. autoattribute:: nni.nas.benchmarks.nds.constants.DIL_CONV_3X3
.. autoattribute:: nni.nas.benchmarks.nds.constants.DIL_CONV_5X5
.. autoattribute:: nni.nas.benchmarks.nds.constants.SEP_CONV_3X3
.. autoattribute:: nni.nas.benchmarks.nds.constants.SEP_CONV_5X5
.. autoattribute:: nni.nas.benchmarks.nds.constants.SEP_CONV_7X7
.. autoattribute:: nni.nas.benchmarks.nds.constants.DIL_SEP_CONV_3X3
API 文档
^^^^^^^^^^^^^^^^^
.. autofunction:: nni.nas.benchmarks.nds.query_nds_trial_stats
.. autoclass:: nni.nas.benchmarks.nds.NdsTrialConfig
.. autoclass:: nni.nas.benchmarks.nds.NdsTrialStats
.. autoclass:: nni.nas.benchmarks.nds.NdsIntermediateStats
../../en_US/NAS/Benchmarks.rst
\ No newline at end of file
DARTS
=====
介绍
------------
这篇论文 `DARTS: Differentiable Architecture Search <https://arxiv.org/abs/1806.09055>`__ 通过以可区分的方式制定任务来解决体系结构搜索的可伸缩性挑战。 此方法基于架构的连续放松的表示,从而允许在架构搜索时能使用梯度下降。
作者的代码可以在小批量中交替优化网络权重和体系结构权重。 还进一步探讨了使用二阶优化(unroll)来替代一阶,来提高性能的可能性。
NNI 的实现是基于 `官方实现 <https://github.com/quark0/darts>`__ 和 `热门的第三方 repo <https://github.com/khanrc/pt.darts>`__。 NNI 上的 DARTS 设计为可用于任何搜索空间。 与原始论文一样,为 CIFAR10 实现了 CNN 的搜索空间,来作为 DARTS 的实际示例。
重现结果
--------------------
上述示例旨在重现本文中的结果,我们进行了一阶和二阶优化实验。 由于时间限制,我们仅从第二阶段重新训练了 *一次最佳架构*。 我们的结果目前与论文的结果相当。 稍后会增加更多结果
.. list-table::
:header-rows: 1
:widths: auto
* -
- 论文中
- 重现
* - 一阶(CIFAR10)
- 3.00 +/- 0.14
- 2.78
* - 二阶(CIFAR10)
- 2.76 +/- 0.09
- 2.80
示例
--------
CNN 搜索空间
^^^^^^^^^^^^^^^^
:githublink:`示例代码 <examples/nas/darts>`
.. code-block:: bash
#如果未克隆 NNI 代码。 如果代码已被克隆,请忽略此行并直接进入代码目录。
git clone https://github.com/Microsoft/nni.git
# 搜索最优结构
cd examples/nas/darts
python3 search.py
# 训练最优结构
python3 retrain.py --arc-checkpoint ./checkpoints/epoch_49.json
参考
---------
PyTorch
^^^^^^^
.. autoclass:: nni.algorithms.nas.pytorch.darts.DartsTrainer
:members:
局限性
-----------
* DARTS 不支持 DataParallel,若要支持 DistributedDataParallel,则需要定制。
../../en_US/NAS/DARTS.rst
\ No newline at end of file
ENAS
====
介绍
------------
`Efficient Neural Architecture Search via Parameter Sharing <https://arxiv.org/abs/1802.03268>`__ 这篇论文使用子模型之间的参数共享来加速NAS进程。 在 ENAS 中,Contoller 学习在大的计算图中搜索最有子图的方式来发现神经网络。 Controller 通过梯度策略训练,从而选择出能在验证集上有最大期望奖励的子图。 同时对与所选子图对应的模型进行训练,以最小化规范交叉熵损失。
NNI 基于官方的 `Tensorflow <https://github.com/melodyguan/enas>`_ 实现,包括通用的强化学习的 Controller,以及能交替训练目标网络和 Controller 的 Trainer。 根据论文,也对 CIFAR10 实现了 Macro 和 Micro 搜索空间来展示如何使用 Trainer。 NNI 中从头训练的代码还未完成,当前还没有重现结果。
示例
--------
CIFAR10 Macro/Micro 搜索空间
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
:githublink:`示例代码 <examples/nas/enas>`
.. code-block:: bash
#如果未克隆 NNI 代码。 如果代码已被克隆,请忽略此行并直接进入代码目录。
git clone https://github.com/Microsoft/nni.git
# 搜索最优结构
cd examples/nas/enas
# 在 macro 搜索空间中搜索
python3 search.py --search-for macro
# 在 micro 搜索空间中搜索
python3 search.py --search-for micro
# 查看更多的搜索选择
python3 search.py -h
参考
---------
PyTorch
^^^^^^^
.. autoclass:: nni.algorithms.nas.pytorch.enas.EnasTrainer
:members:
../../en_US/NAS/ENAS.rst
\ No newline at end of file
执行引擎
=================
执行引擎(Execution engine)用于运行 Retiarii 实验。 NNI 支持三种执行引擎,用户可以根据自己的模型 mutation 定义类型和跨模型优化的需求选择特定的引擎。
* **纯 Python 执行引擎(Pure-python execution engine)** 是默认引擎,它支持 `内联 mutation API <./MutationPrimitives.rst>`__ 表示的模型空间。
* **基于图的执行引擎(Graph-based execution engine)** 支持使用 `内联 mutation APIs <./MutationPrimitives.rst>`__ 和由 `mutators <./Mutators.rst>`__ 表示的模型空间。 它要求用户的模型由 `TorchScript <https://pytorch.org/docs/stable/jit.html>`__ 解析。
* **CGO执行引擎(CGO execution engine)** 具有与 **基于图形的执行引擎** 相同的要求和能力。 但未来将支持跨模型的优化,这使得模型空间的探索变得更快。
纯 Python 执行引擎
----------------------------
纯 Python 执行引擎是默认引擎,如果用户是 NNI NAS 的新手,我们建议使用这个执行引擎。 纯 Python 执行引擎在内联突变 API 的范围内发挥了神奇作用,而不会触及用户模型的其余部分。 因此,它对用户模型的要求最低。
现在需要一个步骤来使用这个引擎。
1. 在整个 PyTorch 模型之外添加 ``@nni.retiarii.model_wrapper`` 装饰器。
.. note:: 在 PyTorch 模型中,您应该始终使用 ``super().__init__()`` 而不是 ``super(MyNetwork, self).__init__()`` ,因为后者在模型装饰器上存在问题。
基于图的执行引擎
----------------------------
对于基于图形的执行引擎,它使用 `TorchScript <https://pytorch.org/docs/stable/jit.html>`__ 将用户定义的模型转换为图形表示(称为图形 IR),其中的每个实例化模块模型转换为子图。 然后将突变应用到图上,生成新的图。 每个新图被转换回 PyTorch 代码并在用户指定的训练服务上执行。
在某些情况下,用户可能会发现 ``@basic_unit`` 非常有帮助。 ``@basic_unit`` 这里意味着模块将不会被转换为子图,而是将其转换为单个图形节点作为基本单元。
``@basic_unit`` 通常在以下情况下使用:
* 当用户想要调整模块的初始化参数时使用 ``valueChoice``,然后用 ``@ basic_unit`` 装饰模块。 例如,在 ``self.conv = MyConv(kernel_size=nn.ValueChoice([1, 3, 5]))`` 中,``MyConv`` 应该被修饰。
* 当模块无法被成功解析为子图,用 ``@basic_unit`` 装饰模块。 解析失败可能是由于复杂的控制流造成的。 目前 Retiarii 不支持 adhoc 循环,如果在一个模块的前向有 adhoc 循环,这个类应该被装饰成可序列化的模块。 例如,下面的 ``MyModule`` 应该被装饰起来。
.. code-block:: python
@basic_unit
class MyModule(nn.Module):
def __init__(self):
...
def forward(self, x):
for i in range(10): # <- adhoc loop
...
* 一些内联突变 API 要求其处理的模块用 ``@basic_unit`` 来装饰。 例如,提供给 ``LayerChoice`` 的用户自定义的模块作为候选操作应该被装饰。
使用基于图的执行引擎需要三个步骤:
1. 如果你的模型中有 ``@nni.retiarii.model_wrapper``,请移除。
2. 将 ``config.execution_engine = 'base'`` 添加到 ``RetiariiExeConfig``。 ``execution_engine`` 的默认值是 'py',即纯 Python 执行引擎。
3. 必要时按照上述准则添加 ``@basic_unit``。
对于导出最佳模型,基于图的执行引擎支持通过运行 ``exp.export_top_models(formatter='code')`` 来导出最佳模型的源代码。
CGO 执行引擎
--------------------
CGO 执行引擎在基于图的执行引擎基础上进行跨模型的优化。 这个执行引擎将在 `v2.4 发布 <https://github.com/microsoft/nni/issues/3813>`__。
../../en_US/NAS/ExecutionEngines.rst
\ No newline at end of file
Multi-trial NAS 的探索策略
=====================================================
探索策略的用法
-----------------------------
要使用探索策略,用户只需将探索策略实例化,并将实例化的对象传递给 ``RetiariiExperiment``。 示例如下:
.. code-block:: python
import nni.retiarii.strategy as strategy
exploration_strategy = strategy.Random(dedup=True) # dedup=False 如果不希望有重复数据删除
支持的探索策略
--------------------------------
NNI 提供了以下 multi-trial NAS 的探索策略。 用户还可以 `自定义新的探索策略 <./WriteStrategy.rst>`__。
.. list-table::
:header-rows: 1
:widths: auto
* - 名字
- 算法简介
* - `随机策略 <./ApiReference.rst#nni.retiarii.strategy.Random>`__
- 从搜索空间中随机选择模型 (``nni.retiarii.strategy.Random``)
* - `网格搜索 <./ApiReference.rst#nni.retiarii.strategy.GridSearch>`__
- 使用网格搜索算法从用户定义的模型空间中采样新模型。 (``nni.retiarii.strategy.GridSearch``)
* - `正则进化 <./ApiReference.rst#nni.retiarii.strategy.RegularizedEvolution>`__
- 使用 `正则进化算法 <https://arxiv.org/abs/1802.01548>`__ 从生成的模型中生成新模型 (``nni.retiarii.strategy.RegularizedEvolution``)
* - `TPE 策略 <./ApiReference.rst#nni.retiarii.strategy.TPEStrategy>`__
- 使用 `TPE 算法 <https://papers.nips.cc/paper/2011/file/86e8f7ab32cfd12577bc2619bc635690-Paper.pdf>`__ 从用户定义的模型空间中生成新模型 (``nni.retiarii.strategy.TPEStrategy``)
* - `RL 策略 <./ApiReference.rst#nni.retiarii.strategy.PolicyBasedRL>`__
- 使用 `PPO 算法 <https://arxiv.org/abs/1707.06347>`__ 从用户定义的模型空间中生成新模型 (``nni.retiarii.strategy.PolicyBasedRL``)
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment