Neural Network Libraries

Neural Network Libraries は、研究、開発、製品化のための深層学習フレームワークです。このフレームワークはデスクトップパソコン、 HPC クラスター、組込機器や商用サーバーといった、どんなマシン上でも動作することを目指しています。

このドキュメントでは、 Python API と C++ API の使い方、開発者のためのコントリビューションガイド、またソフトウェアライセンスについて解説します。Python API は、深層学習システムの迅速な試作と実験により適している一方、C++ API は、推論や学習アルゴリズムを組込機器やサーバー上へデプロイすることに適しています ( 現在ドキュメントを準備中です ) 。このフレームワークは、モジュール性と拡張性を念頭に設計されています。コミュニティのコントリビューターは、ニューラルネットワークの新しいオペレーターまたは最適化モジュール、そして特定機器に特化したニューラルネットワークモジュールの実装を拡張機能として追加することが可能です。

Python パッケージ

C++11 コアをベースに作られた Python API は、ニューラルネットワークの設計の柔軟性を最大化し、迅速な試作と実験を促します。NNabla は Python 3.5 で動作します。

Python パッケージのインストール

NNabla Python パッケージのインストール方法は 3 通りあります。

CUDA/cudNNを含む環境の設定や、OSごとのインストール方法については`こちら <https://nnabla.org/ja/install/>`_をご覧ください。

pip コマンドを使用してインストールする

NNabla Python パッケージは PYPI でホスティングされており、多くのプラットフォーム向けのパッケージを提供しています。Python とそのパッケージ・マネージメント・システム pip ( そして推奨されるオプションとして CUDA ) を使い慣れているなら、次の pip インストールガイドをご覧ください。OS 別のもう少し詳細なセットアップ方法は次の章を参照してください。

PIP を使用した NNabla パッケージのインストール

注 : 各 OS の依存関係については OS 別ワークフロー を参照ください。

NNabla パッケージを pip インストールします。

pip install nnabla

: 確実に最新バージョンをインストールしたい場合は、あらかじめ pip uninstall - y nnabla で以前インストールされたものをアンインストールすることを試してください。

次に、以下を実行して稼働するか確認してください。

python -c "import nnabla"
2018-06-26 15:20:16,759 [nnabla][INFO]: Initializing CPU extension...
NNabla CUDA 拡張パッケージのインストール

PIP を使用した NNabla CUDA 拡張機能パッケージのインストール を参照してください。

サンプルを実行

サンプル をダウンロードするか ( ダウンロード後 unzip ) 、NNabla Examples リポジトリ からクローン、MNIST フォルダへ移動してください。

cd nnabla-examples/image-classification/mnist-collection/

MNIST classification を実行してください。

python classification.py

CUDA/cuDNN で MNIST classification を実行してください。

python classification.py -c cudnn
OS 別ワークフロー
Linux へのインストール
前提条件

このインストールの手順では、ほとんどの Linux 64-bit システムに pip を使用して NNabla をインストールする方法を説明します。

提供するバイナリパッケージをサポートしている Python のバージョンは 3.5 ( 推奨できません )、3.6、3.7 です。Python のディストリビューションとして Miniconda を使うことを推奨します。Miniconda の Python をインストールする簡単な手順は、次の通りです。

wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
bash Miniconda3-latest-Linux-x86_64.sh -b -p {installation path e.g. ~/miniconda}
# You have to set an environment variable PATH accordingly
# to enable the installed ``Python`` and the ``conda`` system.
echo 'export PATH=<installation path>/bin:$PATH' >> ~/.bashrc
# Restart your bash or source ~/.bashrc

# Switch the default Python version
conda install -y python={version number e.g. 3.6}
インストール

PIP を使用した NNabla パッケージのインストール を参照してください。

FAQ
Q. 他の linux ディストリビューションを使いたいのですが、どうしたらいいでしょうか?

We actually tested other linux distributions and versions; Ubuntu 16.04, 18.04, 20.04, CentOS 7, 8 on various environments; Baremetal server, AWS instance, and/or Docker machine. Thus, you can install in almost the same way described here. The details of how-to-install for each are coming soon.

Windows へのインストール
前提条件

Windows 8.1 64bit と Windows 10 64bit の環境でテスト済みです。

インストールには次のソフトウェアが必要です。

  • 必要なソフトウェア

    • Python 3.6 以上 : PIP

    • Microsoft Visual C++ 2015 再頒布可能パッケージ

  • 推奨

    • CUDA ツールキットと cuDNN ( CUDA GPU をお使いの場合 )

環境のセットアップ
Python

この説明では、 Miniconda を使用します。

ここ から Windows 用のバイナリをダウンロードして、インストールしてください。

次に、コマンドプロンプトから必要なパッケージをインストールしてください。

> conda install scipy scikit-image ipython

プロキシを使用しているネットワークでセットアップに失敗する場合は、プロキシサーバーの環境変数を設定して、再度インストールを試してください。

> SET HTTP_PROXY=http://(enter the address of the http proxy server here)
> SET HTTPS_PROXY=https://(enter the address of the https proxy server here)
Microsoft Visual C++ 2015 再頒布可能パッケージ

ここ からダウンロードして、インストールしてください。

CUDA と cuDNN のライブラリ

NVIDIA GPU を使用している場合は、次のソフトウェアをインストールすることで、実行スピードが飛躍的に向上します。

CUDA ツールキット

cuDNN

cuDNN をインストールするために、 bin、 include、 lib を C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v{CUDA_VERSION} へコピーしてください。

CUDA 拡張パッケージの互換性のある cuDNN バージョンのリスト を参照してください。

インストール

PIP を使用した NNabla パッケージのインストール を参照してください。

FAQ
Q. Scikit-image のインストールに時間がかかります。

環境によっては、長い時間がかかることがあります。しばらくお待ちください。

Q. インストール中、 Scipy のインストールに失敗します。

“pip install nnabla” の前に “conda install” を使って scipy をインストールしてください。

macOS へのインストール

注 : macOS の環境とマシンのテスト範囲は非常に限られています。何らかの問題に直面した場合は、その問題をお知らせください。

前提条件

macOS Sierra 上でのインストールはテスト済みです。

インストールには次のソフトウェアが必要です。

  • Python 3.6 以上 ( Anaconda または Miniconda を使った Python のセットアップを推奨します ) 。

    • pip ( Conda Python にバンドルされています )

    • wheel ( Conda Python にバンドルされています )

    • setuptools ( Conda Python にバンドルされています。場合によっては、 pip install -U --no-deps setuptools で setuptools のバージョンアップが必要となります。 )

インストール

PIP を使用した NNabla パッケージのインストール を参照してください ( macOS 用の CUDA 拡張のバイナリパッケージはありません。ソースコードからのビルド を参照してください ) 。

Multi-GPU 互換の NNabla パッケージをインストールする

NNabla 上の分散学習のような multi-GPU 実行を可能にするために、NNabla パッケージの特別版をインストールする必要があります。インストール方法については Multi-GPU サポートのインストール を参照してください。

ソースコードからインストールする

ソースコードからのビルドに関するドキュメントは GitHub リポジトリ ( build または build_distributed ) へ移動しました。

Docker で実行

Python API チュートリアル

以下のドキュメントは、現在 Github で公開中の Jupyter notebook を利用した NNabla チュートリアル の一覧です。ステップ・バイ・ステップで実行したい場合は、以下のリンクから手順を参照してください。

サンプルで学ぶ NNabla

このチュートリアルでは、簡単な手書きの数字を分類するタスクを例に、ニューラルネットワークの学習を行うスクリプトの書き方を見ていきます。

注 : このチュートリアルでは、 scikit-learnmatplotlib がインストールされた Python 環境が必要です。

まず、依存関係を準備しましょう。

import nnabla as nn

import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S
from nnabla.monitor import tile_images

import numpy as np
import matplotlib.pyplot as plt
import tiny_digits
%matplotlib inline

np.random.seed(0)
imshow_opt = dict(cmap='gray', interpolation='nearest')
2017-06-26 23:09:49,971 [nnabla][INFO]: Initializing CPU extension...

tiny_digits モジュールはこのフォルダにあります。このモジュールは、scikit-learn で利用可能な手書き数字のデータセット ( MNIST ) をロードするためのユーティリティーを提供します。

ロジスティック回帰

まず、ロジスティック回帰のための計算グラフを定義するところから始めます。 ( ロジスティック回帰の詳細は付録 A を参照してください。 )

学習は勾配降下法を用いて行われます。勾配は得られた誤差をバックプロパゲーションしていく ( backprop ) ことで算出されます。

トイ・データセットの準備

ここではこのサンプルで用いるデータセットの準備を行います。

digits = tiny_digits.load_digits(n_class=10)
tiny_digits.plot_stats(digits)
Num images: 1797
Image shape: (8, 8)
Labels: [0 1 2 3 4 5 6 7 8 9]
_images/by_examples_8_1.png

次のブロックでは、データセットから画像やラベルをミニバッチ分だけ返すデータローダーを作成します。このデータセットはこのサンプル用に利用しているものであり、 NNabla の一部ではないことに注意してください。

data = tiny_digits.data_iterator_tiny_digits(digits, batch_size=64, shuffle=True)
2017-06-26 23:09:50,545 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:09:50,546 [nnabla][INFO]: Using DataSourceWithMemoryCache
2017-06-26 23:09:50,546 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:09:50,547 [nnabla][INFO]: On-memory
2017-06-26 23:09:50,547 [nnabla][INFO]: Using DataIterator

ミニバッチは次のようになります。imglabelnumpy.ndarray として得られます。

img, label = data.next()
plt.imshow(tile_images(img), **imshow_opt)
print("labels: {}".format(label.reshape(8, 8)))
print("Label shape: {}".format(label.shape))
labels: [[ 2.  8.  2.  6.  6.  7.  1.  9.]
 [ 8.  5.  2.  8.  6.  6.  6.  6.]
 [ 1.  0.  5.  8.  8.  7.  8.  4.]
 [ 7.  5.  4.  9.  2.  9.  4.  7.]
 [ 6.  8.  9.  4.  3.  1.  0.  1.]
 [ 8.  6.  7.  7.  1.  0.  7.  6.]
 [ 2.  1.  9.  6.  7.  9.  0.  0.]
 [ 5.  1.  6.  3.  0.  2.  3.  4.]]
Label shape: (64, 1)
_images/by_examples_12_1.png
計算グラフの準備

NNabla では 誤差逆伝播法を用いる勾配降下法の最適化について 2 つの手法を提供しています。1 つは静的グラフで、もう 1 つは動的グラフによるものです。初めに、静的な方から見ていきましょう。

# Forward pass
x = nn.Variable(img.shape)  # Define an image variable
with nn.parameter_scope("affine1"):
    y = PF.affine(x, 10)  # Output is 10 class

このコードブロックは NNabla のグラフ作成機能の中で最も重要な特徴の 1 つである パラメータスコープの使い方 を示しています。1 行目で入力変数 x を定義します。2 行目で パラメータスコープ を作成します。 そして、3 行目で x に対してaffine変換 PF.affine を適用して、その結果を保持する変数 y を作ります。ここで、 PF ( parametric_function ) モジュールは ( 重みを含む ) affine変換、( カーネルを含む ) 畳み込み、( スケール因子など ) バッチ正規化のような、学習によって更新したいパラメータを含む関数を提供します。これらの関数を パラメトリック関数 といいます。 パラメータは関数呼び出しで作られ、ランダムに初期化され、 parameter_scope コンテキストを使って "affine1" という名前で登録されます。

# Building a loss graph
t = nn.Variable(label.shape)  # Define an target variable
loss = F.mean(F.softmax_cross_entropy(y, t))  # Softmax Xentropy fits multi-class classification problems

上記の残りの行では、目的関数を定義して、グラフの終端にロス関数を追加しています。静的グラフを構築しても、定義した計算は実際には実行されませんが、出力変数の状態は推測されることに注意してください。したがって、この時にそれぞれの変数の状態を調べることができます。

print("Printing shapes of variables")
print(x.shape)
print(y.shape)
print(t.shape)
print(loss.shape)  # empty tuple means scalar
Printing shapes of variables
(64, 1, 8, 8)
(64, 10)
(64, 1)
()
静的グラフの実行

グラフの終端である変数にある forward() メソッドを呼び出すことによって、グラフで定義された計算を実行することができます。入力は .d アクセサによってセットすることができます。このアクセサは numpy.ndarray として CPU から配列を受け取ります。

# Set data
x.d = img
t.d = label
# Execute a forward pass
loss.forward()
# Showing results
print("Prediction score of 0-th image: {}".format(y.d[0]))
print("Loss: {}".format(loss.d))
Prediction score of 0-th image: [  9.75851917   6.49118519  16.47323608  -1.36296904  -0.78583491
   4.08872032   7.84134388   2.42956853   3.31485462   3.61868763]
Loss: 10.6016616821

ネットワークはランダムに初期化されるので、この時点では出力は意味をなしません。

グラフによるバックプロパゲーション

parameter_scope に登録されることによって管理されるパラメータはディクショナリとして get_parameters() によってクエリできます。

print(nn.get_parameters())
OrderedDict([('affine1/affine/W', <Variable((64, 10), need_grad=True) at 0x7fa0ba361d50>), ('affine1/affine/b', <Variable((10,), need_grad=True) at 0x7fa0ba361ce8>)])

バックプロパゲーションを実行する前に、すべてのパラメータの勾配をゼロに初期化しておきます。

for param in nn.get_parameters().values():
    param.grad.zero()

そうすると、グラフの終端の変数で backward() メソッドを呼び出すことでバックプロパゲーションを実行することができます。

# Compute backward
loss.backward()
# Showing gradients.
for name, param in nn.get_parameters().items():
    print(name, param.shape, param.g.flat[:20])  # Showing first 20.
affine1/affine/W (64, 10) [  0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   0.00000000e+00   0.00000000e+00
   0.00000000e+00   0.00000000e+00   4.98418584e-02   8.72317329e-03
  -4.06671129e-02  -4.68742661e-02   2.52632981e-09   7.86017510e-04
   9.06870365e-02  -1.56249944e-02  -1.56217301e-02  -3.12499963e-02]
affine1/affine/b (10,) [ 0.42710391 -0.01852455  0.07369987 -0.04687012 -0.07798236 -0.03664626
  0.01651323 -0.1249291  -0.11862005 -0.09374455]

勾配は Variable の grad フィールドに格納されます。 .g アクセサは numpy.ndarray フォーマットで grad フィールドにアクセスするために使うことができます。

パラメータの最適化 ( = ニューラルネットワークの学習 )

パラメータを最適化するために、( ここでは S と名付けられた ) solver モジュールを用意しています。solver モジュールには、SGD 、モメンタム項をもつ SGD 、 Adam など、たくさんの最適化手法の実装が含まれています。以下のブロックは SGD solver を作り、ロジスティック回帰に用いるパラメータをそれにセットします。

# Create a solver (gradient-based optimizer)
learning_rate = 1e-3
solver = S.Sgd(learning_rate)
solver.set_parameters(nn.get_parameters())  # Set parameter variables to be updated.

次のブロックでは、最適化ループの 中で行われる 1 回分のステップを示しています。solver.zero_grad() は、上記で示したようにすべてのパラメータに対して .grad.zero() を呼び出すことと同じです。 バックプロパゲーションを実行したあとで、SGD solver クラスで実装されている重み減衰 ( Weight Decay ) を適用しています。そして最後に、勾配降下法によってパラメータを更新します。数式としては以下のようになります。

\[\theta \leftarrow \theta - \eta \nabla_{\theta} L(\theta, X_{\mathrm minibatch})\]

このとき \(\eta\) は学習率を表しています。

# One step of training
x.d, t.d = data.next()
loss.forward()
solver.zero_grad()  # Initialize gradients of all parameters to zero.
loss.backward()
solver.weight_decay(1e-5)  # Applying weight decay as an regularization
solver.update()
print(loss.d)
12.9438686371

次のブロックは最適化ステップをループによって繰り返しています。これによりロスが減少していくのが分かります。

for i in range(1000):
    x.d, t.d = data.next()
    loss.forward()
    solver.zero_grad()  # Initialize gradients of all parameters to zero.
    loss.backward()
    solver.weight_decay(1e-5)  # Applying weight decay as an regularization
    solver.update()
    if i % 100 == 0:  # Print for each 10 iterations
        print(i, loss.d)
0 12.6905069351
100 3.17041015625
200 1.60036706924
300 0.673069953918
400 0.951370298862
500 0.724424362183
600 0.361597299576
700 0.588107347488
800 0.28792989254
900 0.415006935596
予測

次のコードは学習の結果を示しています。

x.d, t.d = data.next()  # Here we predict images from training set although it's useless.
y.forward()  # You can execute a sub graph.
plt.imshow(tile_images(x.d), **imshow_opt)
print("prediction:")
print(y.d.argmax(axis=1).reshape(8, 8))  # Taking a class index based on prediction score.
prediction:
[[5 0 1 9 0 1 3 3]
 [2 4 1 7 4 5 6 5]
 [7 7 9 7 9 0 7 3]
 [5 3 7 6 6 8 0 9]
 [0 1 3 5 5 5 4 9]
 [1 0 0 8 5 1 8 8]
 [7 5 0 7 6 9 0 0]
 [0 6 2 6 4 4 2 6]]
_images/by_examples_36_1.png
動的グラフのサポート

これは NNabla で計算グラフを実行するもう一つの方法です。この例では動的グラフの有用性を示しきれていませんが、その片鱗を伝えることができればと思います。

次のブロックでは、後に使うために計算グラフを構築するための関数を定義しています。

def logreg_forward(x):
    with nn.parameter_scope("affine1"):
        y = PF.affine(x, 10)
    return y

def logreg_loss(y, t):
    loss = F.mean(F.softmax_cross_entropy(y, t))  # Softmax Xentropy fits multi-class classification problems
    return loss

計算グラフの作成と同時にそのグラフで定義された計算を実行するためには、下記のブロックで示すように nnabla.auto_forward() コンテキストを使う必要があります。これにより、グラフ内で各演算を行う関数が呼び出された瞬間にその演算が実行されます。 ( また、グローバルで auto-forward 状態にするために nnabla.set_auto_forward(auto) を使うこともできます。 )

x = nn.Variable(img.shape)
t = nn.Variable(label.shape)
x.d, t.d = data.next()
with nn.auto_forward():  # Graph are executed
    y = logreg_forward(x)
    loss = logreg_loss(y, t)
print("Loss: {}".format(loss.d))
plt.imshow(tile_images(x.d), **imshow_opt)
print("prediction:")
print(y.d.argmax(axis=1).reshape(8, 8))
Loss: 0.43071603775
prediction:
[[9 3 5 0 1 9 9 2]
 [5 6 6 2 7 5 1 1]
 [3 7 7 6 0 8 3 8]
 [0 6 4 6 0 6 9 9]
 [6 1 2 5 8 3 2 4]
 [1 4 4 0 5 7 1 7]
 [7 8 9 5 8 3 7 8]
 [5 7 5 3 3 0 0 7]]
_images/by_examples_41_1.png

バックプロパゲーションは動的に作られたグラフでも実行できます。

solver.zero_grad()
loss.backward()
多層パーセプトロン ( MLP )

このセクションでは、多層パーセプトロン ( MLP ) を表す計算グラフの構築、およびその学習を行う例を見ていきます。

始める前に、ロジスティック回帰のサンプルで登録したすべてのパラメータを消去します。

nn.clear_parameters()  # Clear all parameters

10 クラスの分類問題を解くために、任意の深さと幅をもつ MLP を構築する関数を定義します。

def mlp(x, hidden=[16, 32, 16]):
    hs = []
    with nn.parameter_scope("mlp"):  # Parameter scope can be nested
        h = x
        for hid, hsize in enumerate(hidden):
            with nn.parameter_scope("affine{}".format(hid + 1)):
                h = F.tanh(PF.affine(h, hsize))
                hs.append(h)
        with nn.parameter_scope("classifier"):
            y = PF.affine(h, 10)
    return y, hs
# Construct a MLP graph
y, hs = mlp(x)
print("Printing shapes")
print("x: {}".format(x.shape))
for i, h in enumerate(hs):
    print("h{}:".format(i + 1), h.shape)
print("y: {}".format(y.shape))
Printing shapes
x: (64, 1, 8, 8)
h1: (64, 16)
h2: (64, 32)
h3: (64, 16)
y: (64, 10)
# Training
loss = logreg_loss(y, t)  # Reuse logreg loss function.

# Copied from the above logreg example.
def training(steps, learning_rate):
    solver = S.Sgd(learning_rate)
    solver.set_parameters(nn.get_parameters())  # Set parameter variables to be updated.
    for i in range(steps):
        x.d, t.d = data.next()
        loss.forward()
        solver.zero_grad()  # Initialize gradients of all parameters to zero.
        loss.backward()
        solver.weight_decay(1e-5)  # Applying weight decay as an regularization
        solver.update()
        if i % 100 == 0:  # Print for each 10 iterations
            print(i, loss.d)


# Training
training(1000, 1e-2)
0 2.42193937302
100 1.83251476288
200 1.49943637848
300 1.30751883984
400 1.00974023342
500 0.904026031494
600 0.873289525509
700 0.725554704666
800 0.614291608334
900 0.555113613605
# Showing responses for each layer
num_plot = len(hs) + 2
gid = 1

def scale01(h):
    return (h - h.min()) / (h.max() - h.min())

def imshow(img, title):
    global gid
    plt.subplot(num_plot, 1, gid)
    gid += 1
    plt.title(title)
    plt.imshow(img, **imshow_opt)
    plt.axis('off')

plt.figure(figsize=(2, 5))
imshow(x.d[0, 0], 'x')
for hid, h in enumerate(hs):
    imshow(scale01(h.d[0]).reshape(-1, 8), 'h{}'.format(hid + 1))
imshow(scale01(y.d[0]).reshape(2, 5), 'y')
_images/by_examples_52_0.png
CUDA による高速な畳み込みニューラルネットワークの実行

ここでは、 CUDA を利用できる GPU を用いた CNN の高速な実行例を見ていきます。

nn.clear_parameters()
def cnn(x):
    with nn.parameter_scope("cnn"):  # Parameter scope can be nested
        with nn.parameter_scope("conv1"):
            c1 = F.tanh(PF.batch_normalization(
                PF.convolution(x, 4, (3, 3), pad=(1, 1), stride=(2, 2))))
        with nn.parameter_scope("conv2"):
            c2 = F.tanh(PF.batch_normalization(
                PF.convolution(c1, 8, (3, 3), pad=(1, 1))))
            c2 = F.average_pooling(c2, (2, 2))
        with nn.parameter_scope("fc3"):
            fc3 = F.tanh(PF.affine(c2, 32))
        with nn.parameter_scope("classifier"):
            y = PF.affine(fc3, 10)
    return y, [c1, c2, fc3]

NNabla で CUDA を利用するためには、まず、 nnabla-ext-cuda パッケージをインストールする必要があります。 インストールガイド を参照してください。CUDA エクステンションをインストールしたあと、グラフを作成する前にコンテキストを指定することによって、簡単に CUDA での実行に切り替えることができます。 cuDNN コンテキストは計算の高速実行が可能であることから、使用を強く推奨します。 コンテキストのクラスは nn.Context() によってインスタンス化できますが、コンテキストの記述子を指定することはユーザーにとって少し複雑かもしれません。そこで、 nnabla.ext_utils モジュールにある helper 関数 get_extension_context() を使ってコンテキストを作ることを推奨します。 NNabla は最初の引数 ( 拡張名 ) に渡されるコンテキストの指示子として cpu や cudnn を公式にサポートしています。 注 : cuDNN コンテキストを全体的なデフォルトのコンテキストとしてセットすることによって、作成された関数や solver は cuDNN モード (より好ましい ) でインスタンスが作られます。また、 nn.context_scope() を使うことでコンテキストを指定することができます。詳細は API リファレンス を参照してください。

# Run on CUDA
from nnabla.ext_utils import get_extension_context
cuda_device_id = 0
ctx = get_extension_context('cudnn', device_id=cuda_device_id)
print("Context: {}".format(ctx))
nn.set_default_context(ctx)  # Set CUDA as a default context.
y, hs = cnn(x)
loss = logreg_loss(y, t)
2017-06-26 23:09:54,555 [nnabla][INFO]: Initializing CUDA extension...
2017-06-26 23:09:54,731 [nnabla][INFO]: Initializing cuDNN extension...
Context: Context(backend='cpu|cuda', array_class='CudaCachedArray', device_id='0', compute_backend='default|cudnn')
training(1000, 1e-1)
0 2.34862923622
100 1.00527024269
200 0.416576713324
300 0.240603536367
400 0.254562884569
500 0.206138283014
600 0.220851421356
700 0.161689639091
800 0.230873346329
900 0.121101222932
# Showing responses for each layer
num_plot = len(hs) + 2
gid = 1
plt.figure(figsize=(2, 8))
imshow(x.d[0, 0], 'x')
imshow(tile_images(hs[0].d[0][:, None]), 'conv1')
imshow(tile_images(hs[1].d[0][:, None]), 'conv2')
imshow(hs[2].d[0].reshape(-1, 8), 'fc3')
imshow(scale01(y.d[0]).reshape(2, 5), 'y')
_images/by_examples_59_0.png

nn.save_parameters は HDF5 フォーマットで parameter_scope に登録されたパラメータを書き出します。それは後述のサンプルで使用します。

path_cnn_params = "tmp.params.cnn.h5"
nn.save_parameters(path_cnn_params)
2017-06-26 23:09:56,132 [nnabla][INFO]: Parameter save (hdf5): tmp.params.cnn.h5
回帰型ニューラルネットワーク ( Elman RNN )

これは回帰型ニューラルネットワークの学習のサンプルです。

nn.clear_parameters()
def rnn(xs, h0, hidden=32):
    hs = []
    with nn.parameter_scope("rnn"):
        h = h0
        # Time step loop
        for x in xs:
            # Note: Parameter scopes are reused over time
            # which means parameters are shared over time.
            with nn.parameter_scope("x2h"):
                x2h = PF.affine(x, hidden, with_bias=False)
            with nn.parameter_scope("h2h"):
                h2h = PF.affine(h, hidden)
            h = F.tanh(x2h + h2h)
            hs.append(h)
        with nn.parameter_scope("classifier"):
            y = PF.affine(h, 10)
    return y, hs

この操作には特に意味はなく、デモを意図しています。画像を 2 × 2 のグリッドに分けて、それらを連続的に RNN に与えます。

def split_grid4(x):
    x0 = x[..., :4, :4]
    x1 = x[..., :4, 4:]
    x2 = x[..., 4:, :4]
    x3 = x[..., 4:, 4:]
    return x0, x1, x2, x3
hidden = 32
seq_img = split_grid4(img)
seq_x = [nn.Variable(subimg.shape) for subimg in seq_img]
h0 = nn.Variable((img.shape[0], hidden))  # Initial hidden state.
y, hs = rnn(seq_x, h0, hidden)
loss = logreg_loss(y, t)
# Copied from the above logreg example.
def training_rnn(steps, learning_rate):
    solver = S.Sgd(learning_rate)
    solver.set_parameters(nn.get_parameters())  # Set parameter variables to be updated.
    for i in range(steps):
        minibatch = data.next()
        img, t.d = minibatch
        seq_img = split_grid4(img)
        h0.d = 0  # Initialize as 0
        for x, subimg in zip(seq_x, seq_img):
            x.d = subimg
        loss.forward()
        solver.zero_grad()  # Initialize gradients of all parameters to zero.
        loss.backward()
        solver.weight_decay(1e-5)  # Applying weight decay as an regularization
        solver.update()
        if i % 100 == 0:  # Print for each 10 iterations
            print(i, loss.d)

training_rnn(1000, 1e-1)
0 2.62527275085
100 0.780260562897
200 0.486522495747
300 0.289345681667
400 0.249717146158
500 0.538961410522
600 0.276877015829
700 0.159639537334
800 0.249660402536
900 0.0925596579909
# Showing responses for each layer
num_plot = len(hs) + 2
gid = 1
plt.figure(figsize=(2, 8))
imshow(x.d[0, 0], 'x')
for hid, h in enumerate(hs):
    imshow(scale01(h.d[0]).reshape(-1, 8), 'h{}'.format(hid + 1))
imshow(scale01(y.d[0]).reshape(2, 5), 'y')
_images/by_examples_69_0.png
シャムネットワーク

このサンプルは、深層学習を使って 2 次元に、画像を分類別のデータセットに埋め込む方法を示しています。また、事前に学習されたネットワークを再利用する方法も説明しています。

初めに、 CNN のサンプルで学習されたパラメータをロードします。

nn.clear_parameters()
# Loading CNN pretrained parameters.
_ = nn.load_parameters(path_cnn_params)
2017-06-26 23:09:57,838 [nnabla][INFO]: Parameter load (<built-in function format>): tmp.params.cnn.h5

埋め込み関数を定義します。ネットワーク構造やパラメータの階層は以前の CNN のサンプルと同じであることに注意してください。これにより、保存したパラメータを再利用したり、パラメータをファインチューンしたりすることができます。

def cnn_embed(x, test=False):
    # Note: Identical configuration with the CNN example above.
    # Parameters pretrained in the above CNN example are used.
    with nn.parameter_scope("cnn"):
        with nn.parameter_scope("conv1"):
            c1 = F.tanh(PF.batch_normalization(PF.convolution(x, 4, (3, 3), pad=(1, 1), stride=(2, 2)), batch_stat=not test))
        with nn.parameter_scope("conv2"):
            c2 = F.tanh(PF.batch_normalization(PF.convolution(c1, 8, (3, 3), pad=(1, 1)), batch_stat=not test))
            c2 = F.average_pooling(c2, (2, 2))
        with nn.parameter_scope("fc3"):
            fc3 = PF.affine(c2, 32)
    # Additional affine for map into 2D.
    with nn.parameter_scope("embed2d"):
        embed = PF.affine(c2, 2)
    return embed, [c1, c2, fc3]

def siamese_loss(e0, e1, t, margin=1.0, eps=1e-4):
    dist = F.sum(F.squared_error(e0, e1), axis=1)  # Squared distance
    # Contrastive loss
    sim_cost = t * dist
    dissim_cost = (1 - t) * \
        (F.maximum_scalar(margin - (dist + eps) ** (0.5), 0) ** 2)
    return F.mean(sim_cost + dissim_cost)

2 つの CNN を作成し、上記で定義したコントラスティブロス関数で 2 つの CNN の出力を比較します。ここで、両方の CNN が同じパラメータの階層構造を有していることに注意してください。これはすなわち、両方のネットワークは利用するパラメータを共有しているということを意味します。

x0 = nn.Variable(img.shape)
x1 = nn.Variable(img.shape)
t = nn.Variable((img.shape[0],))  # Same class or not
e0, hs0 = cnn_embed(x0)
e1, hs1 = cnn_embed(x1)  # NOTE: parameters are shared
loss = siamese_loss(e0, e1, t)
def training_siamese(steps):
    for i in range(steps):
        minibatchs = []
        for _ in range(2):
            minibatch = data.next()
            minibatchs.append((minibatch[0].copy(), minibatch[1].copy()))
        x0.d, label0 = minibatchs[0]
        x1.d, label1 = minibatchs[1]
        t.d = (label0 == label1).astype(np.int).flat
        loss.forward()
        solver.zero_grad()  # Initialize gradients of all parameters to zero.
        loss.backward()
        solver.weight_decay(1e-5)  # Applying weight decay as an regularization
        solver.update()
        if i % 100 == 0:  # Print for each 10 iterations
            print(i, loss.d)
learning_rate = 1e-2
solver = S.Sgd(learning_rate)
with nn.parameter_scope("embed2d"):
    # Only 2d embedding affine will be updated.
    solver.set_parameters(nn.get_parameters())
training_siamese(2000)
# Decay learning rate
solver.set_learning_rate(solver.learning_rate() * 0.1)
training_siamese(2000)
0 0.150528043509
100 0.186870157719
200 0.149316266179
300 0.207163512707
400 0.171384960413
500 0.190256178379
600 0.138507723808
700 0.0918073058128
800 0.159692272544
900 0.0833697617054
1000 0.0839115008712
1100 0.104669973254
1200 0.0776312947273
1300 0.114788673818
1400 0.120309025049
1500 0.107732802629
1600 0.070114441216
1700 0.101728007197
1800 0.114350572228
1900 0.118794307113
0 0.0669310241938
100 0.0553173273802
200 0.0829797014594
300 0.0951051414013
400 0.128303915262
500 0.102963000536
600 0.0910559669137
700 0.0898950695992
800 0.119949311018
900 0.0603067912161
1000 0.105748720467
1100 0.108760476112
1200 0.0820947736502
1300 0.0971114039421
1400 0.0836166366935
1500 0.0899554267526
1600 0.109069615602
1700 0.0921652168036
1800 0.0759357959032
1900 0.100669950247

学習に用いた画像の埋め込みの結果を可視化してみましょう。同一クラスに属する画像は互いに近くに埋め込まれていることが分かります。

all_image = digits.images[:512, None]
all_label = digits.target[:512]
x_all = nn.Variable(all_image.shape)
x_all.d = all_image
with nn.auto_forward():
    embed, _ = cnn_embed(x_all, test=True)
plt.figure(figsize=(16, 9))
for i in range(10):
    c = plt.cm.Set1(i / 10.)  # Maybe it doesn't work in an older version of Matplotlib where color map lies in [0, 256)
    plt.plot(embed.d[all_label == i, 0].flatten(), embed.d[
             all_label == i, 1].flatten(), '.', c=c)
plt.legend(map(str, range(10)))
plt.grid()
_images/by_examples_81_0.png
付録
A. ロジスティック回帰

ここでは、最も簡単なニューラルネットワークであるロジスティック回帰 ( 1 層のパーセプトロン ) の学習の方法を説明します。ロジスティック回帰は線形分類問題 \(f : {\cal R}^{D\times 1} \rightarrow {\cal R}^{K\times 1}\)

\[\mathbf f(\mathbf x, \mathbf \Theta) = \mathbf W \mathbf x + \mathbf b\]

で、 \(\mathbf x \in {\cal R}^{D \times 1}\) はベクトルへ平坦化された入力画像、 \(t \in \{0, 1, \cdots, K\}\) は目標ラベル、 \(\mathbf W \in {\cal R}^{K \times D}\) は重み行列、 \(\mathbf b \in {\cal R}^{K \times 1}\) はバイアスベクトル、 \(\mathbf \Theta \equiv \left\{\mathbf W, \mathbf b\right\}\) です。 Loss 関数は

\[\mathbf L(\mathbf \Theta, \mathbf X) = \frac{1}{N} \sum_{\mathbf x, t \subset \mathbf X} -log \left(\left[\sigma\left(f(\mathbf x, \mathbf \Theta)\right)\right]_{t}\right)\]

のように定義されます。ここで、 \(\mathbf X \equiv \left\{\mathbf x_1, t_1, \cdots, \mathbf x_N, t_N\right\}\) はネットワークが学習に用いるデータセットを表し、 \(\sigma(\mathbf z)\)\(\frac{\exp(-\mathbf z)}{\sum_{z \subset \mathbf z} \exp(-z)}\) のように定義されたソフトマックス演算で、 \(\left[\mathbf z\right]_i\)\(\mathbf z\) の i 番目の要素を表しています。

NNabla Python API デモ・チュートリアル

はじめに、 nnabla およびいくつかの役に立つツールをインポートしましょう。

# python2/3 compatibility
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import nnabla as nn  # Abbreviate as nn for convenience.

import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
2017-09-27 14:00:30,785 [nnabla][INFO]: Initializing CPU extension...
NdArray

NdArray は多次元配列のデータコンテナーです。NdArray はデバイス ( 例 CPU、CUDA ) やタイプ ( 例 uint8、float32 ) に依存せず、タイプおよびデバイスは使用される際に暗黙でキャストまたは転送されます。以下のとおり、 (2, 3, 4) の 形状の NdArray を作成します。

a = nn.NdArray((2, 3, 4))

以下のように、内部に保持している値を表示することができます。値は初期化されず、デフォルトで float32 として生成されます。

print(a.data)
[[[  9.42546995e+24   4.56809286e-41   8.47690058e-38   0.00000000e+00]
  [  7.38056336e+34   7.50334969e+28   1.17078231e-32   7.58387310e+31]
  [  7.87001454e-12   9.84394250e-12   6.85712044e+22   1.81785692e+31]]

 [[  1.84681296e+25   1.84933247e+20   4.85656319e+33   2.06176836e-19]
  [  6.80020530e+22   1.69307638e+22   2.11235872e-19   1.94316151e-19]
  [  1.81805047e+31   3.01289097e+29   2.07004908e-19   1.84648795e+25]]]

アクセサである .datanumpy.ndarray として NdArray の値への参照を返します。次のように NumPy API を使うことによって、これらの値を変えることができます。

print('[Substituting random values]')
a.data = np.random.randn(*a.shape)
print(a.data)
print('[Slicing]')
a.data[0, :, ::2] = 0
print(a.data)
[Substituting random values]
[[[ 0.36133638  0.22121875 -1.5912329  -0.33490974]
  [ 1.35962474  0.2165522   0.54483992 -0.61813235]
  [-0.13718799 -0.44104072 -0.51307833  0.73900551]]

 [[-0.59464753 -2.17738533 -0.28626776 -0.45654735]
  [ 0.73566747  0.87292582 -0.41605178  0.04792296]
  [-0.63856047  0.31966645 -0.63974309 -0.61385244]]]
[Slicing]
[[[ 0.          0.22121875  0.         -0.33490974]
  [ 0.          0.2165522   0.         -0.61813235]
  [ 0.         -0.44104072  0.          0.73900551]]

 [[-0.59464753 -2.17738533 -0.28626776 -0.45654735]
  [ 0.73566747  0.87292582 -0.41605178  0.04792296]
  [-0.63856047  0.31966645 -0.63974309 -0.61385244]]]

上記の演算はすべてホストデバイス ( CPU ) で行われていることに注意してください。すべての値を定数で埋めたい場合、 NdArray の .zero 、および .fill メソッドを用いてより効率的に行うことができます。データが要求されるとき ( ニューラルネットワークの計算がデータを要求するとき、あるいは、 Python によって NumPy 配列が要求されるとき ) 、それらの値は遅延評価されます。充填演算は特定のデバイス ( 例 CUDA GPU ) 内で実行され、デバイス設定を指定するとより効率的に演算が行われます。これについては後ほど説明します。

a.fill(1)  # Filling all values with one.
print(a.data)
[[[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]

 [[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]]

NumPy 配列オブジェクトから直接 NdArray インスタンスを作ることができます。

b = nn.NdArray.from_numpy_array(np.ones(a.shape))
print(b.data)
[[[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]

 [[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]]

NdArray は Variable クラスで使用され、ニューラルネットワークの命令型計算でも使用されます。これらについては、後述の章で説明します。

Variable

Variable クラスは、ニューラルネットワークを構築するときに使用されます。ニューラルネットワークは、計算の最小ユニットの演算を定義する Function ( 別名 演算子や層、 Function クラスは後述します ) であるエッジと、 Function の入力 / 出力の値を保持している Variable を表すノードで構成されるグラフとして記述されます。このグラフを “計算グラフ” と呼びます。

NNabla では、計算グラフのノードである Variable は 2 つの NdArray を保持しています。1 つは ( 順方向に計算グラフを実行する ) Forward propagation 中に、 Function の入力値や出力値を格納するためのもので、ニューラルネットワークのパラメータ ( 重み ) へのエラー信号をグラフ上で逆方向に伝播する ) back propagation 中に、エラー信号 ( 勾配 ) を格納するためのものです。 NNabla では、1 つ目を データ と呼び、2 つ目を 勾配 と呼びます。

次の行で、 (2, 3, 4) の形状の Variable インスタンスを作ります。このインスタンスは NdArray として データ勾配 を持っています。 need_grad フラグは、False にセットされた場合に backprop 中の不必要な勾配計算を省くために使われます。

x = nn.Variable([2, 3, 4], need_grad=True)
print('x.data:', x.data)
print('x.grad:', x.grad)
x.data: <NdArray((2, 3, 4)) at 0x7f575caf4ea0>
x.grad: <NdArray((2, 3, 4)) at 0x7f575caf4ea0>

以下により、形状を取得することができます。

x.shape
(2, 3, 4)

データ勾配NdArray なので、 .data アクセサをもつ NdArray のようにその値への参照を取得することができますが、 データ勾配 をそれぞれ .d.g プロパティで参照することもできます。

print('x.data')
print(x.d)
x.d = 1.2345  # To avoid NaN
assert np.all(x.d == x.data.data), 'd: {} != {}'.format(x.d, x.data.data)
print('x.grad')
print(x.g)
x.g = 1.2345  # To avoid NaN
assert np.all(x.g == x.grad.data), 'g: {} != {}'.format(x.g, x.grad.data)

# Zeroing grad values
x.grad.zero()
print('x.grad (after `.zero()`)')
print(x.g)
x.data
[[[  9.42553452e+24   4.56809286e-41   8.32543479e-38   0.00000000e+00]
  [             nan              nan   0.00000000e+00   0.00000000e+00]
  [  3.70977305e+25   4.56809286e-41   3.78350585e-44   0.00000000e+00]]

 [[  5.68736600e-38   0.00000000e+00   1.86176378e-13   4.56809286e-41]
  [  4.74367616e+25   4.56809286e-41   5.43829710e+19   4.56809286e-41]
  [  0.00000000e+00   0.00000000e+00   2.93623372e-38   0.00000000e+00]]]
x.grad
[[[  9.42576510e+24   4.56809286e-41   9.42576510e+24   4.56809286e-41]
  [  9.27127763e-38   0.00000000e+00   9.27127763e-38   0.00000000e+00]
  [  1.69275966e+22   4.80112800e+30   1.21230330e+25   7.22962302e+31]]

 [[  1.10471027e-32   4.63080422e+27   2.44632805e+20   2.87606258e+20]
  [  4.46263300e+30   4.62311881e+30   7.65000750e+28   3.01339003e+29]
  [  2.08627352e-10   1.03961868e+21   7.99576678e+20   1.74441223e+22]]]
x.grad (after .zero())
[[[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]

 [[ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]
  [ 0.  0.  0.  0.]]]

NdArray のように、 Variable は NumPy 配列から作ることもできます。

x2 = nn.Variable.from_numpy_array(np.ones((3,)), need_grad=True)
print(x2)
print(x2.d)
x3 = nn.Variable.from_numpy_array(np.ones((3,)), np.zeros((3,)), need_grad=True)
print(x3)
print(x3.d)
print(x3.g)
<Variable((3,), need_grad=True) at 0x7f572a5242c8>
[ 1.  1.  1.]
<Variable((3,), need_grad=True) at 0x7f572a5244a8>
[ 1.  1.  1.]
[ 0.  0.  0.]

Variable では、計算グラフ内の値を格納することだけでなく、計算グラフをトレースするために親エッジ ( Function ) を指すことも重要な役割です。ここでは、 x は何の繋がりも持っていません。そのため、 .parent プロパティは None を返します。

print(x.parent)
None
Function

上述のとおり、 Function は計算グラフの演算部分を定義します。モジュール nnabla.functions は様々な Function ( 例 Convolution、 Affine や ReLU ) を提供します。 API リファレンスガイド で利用可能な Function リストを参照してください。

import nnabla.functions as F

例えば、ここでは、入力 Variable に対して要素ごとに Sigmoid Function の出力を計算し、すべての値の和をとる計算グラフを定義するとしましょう。 (これはどのように動作するかを説明するのには十分簡単な例ですが、ニューラルネットワーク学習のコンテキストにおいては意味のない例です。後述でニューラルネットワークの例を示します。)

sigmoid_output = F.sigmoid(x)
sum_output = F.reduce_sum(sigmoid_output)

nnabla.functions では、 Function API は 1 つ ( または複数 ) の Variable と引数 ( あれば ) を取り、 1 つ ( または複数 ) の出力 Variable を返します。 .parent は、それを作成した Function インスタンスを指します。ここではグラフを定義しただけなので、計算は行われないことに注意してください。 ( これは NNabla の計算グラフ API のデフォルトの動作です。グラフ定義中に実際の計算を開始することも可能であり、これは “Dynamic モード” と呼ばれます ( 後ほど説明します ) 。

print("sigmoid_output.parent.name:", sigmoid_output.parent.name)
print("x:", x)
print("sigmoid_output.parent.inputs refers to x:", sigmoid_output.parent.inputs)
sigmoid_output.parent.name: Sigmoid
x: <Variable((2, 3, 4), need_grad=True) at 0x7f572a51a778>
sigmoid_output.parent.inputs refers to x: [<Variable((2, 3, 4), need_grad=True) at 0x7f572a273a48>]
print("sum_output.parent.name:", sum_output.parent.name)
print("sigmoid_output:", sigmoid_output)
print("sum_output.parent.inputs refers to sigmoid_output:", sum_output.parent.inputs)
sum_output.parent.name: ReduceSum
sigmoid_output: <Variable((2, 3, 4), need_grad=True) at 0x7f572a524638>
sum_output.parent.inputs refers to sigmoid_output: [<Variable((2, 3, 4), need_grad=True) at 0x7f572a273a48>]

グラフの末端 Variable で .forward() を呼び出すことで、計算グラフにおける forward propagation を実行します。

sum_output.forward()
print("CG output:", sum_output.d)
print("Reference:", np.sum(1.0 / (1.0 + np.exp(-x.d))))
CG output: 18.59052085876465
Reference: 18.5905

.backward() は、グラフ乗で back propagation を行います。 NNabla の backprop アルゴリズムでは、入力 Variable に対して勾配を積算しているので、ここでは、backprop の前に 勾配 の値を 0 に初期化します。

x.grad.zero()
sum_output.backward()
print("d sum_o / d sigmoid_o:")
print(sigmoid_output.g)
print("d sum_o / d x:")
print(x.g)
d sum_o / d sigmoid_o:
[[[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]

 [[ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]
  [ 1.  1.  1.  1.]]]
d sum_o / d x:
[[[ 0.17459197  0.17459197  0.17459197  0.17459197]
  [ 0.17459197  0.17459197  0.17459197  0.17459197]
  [ 0.17459197  0.17459197  0.17459197  0.17459197]]

 [[ 0.17459197  0.17459197  0.17459197  0.17459197]
  [ 0.17459197  0.17459197  0.17459197  0.17459197]
  [ 0.17459197  0.17459197  0.17459197  0.17459197]]]

NNabla は主にニューラルネットワークの学習と推論に焦点を当てて開発されています。ニューラルネットワークには、 Convolution、 Affine ( 別名 全結合、 Dense 、など ) のように、計算ブロックと付随して学習可能なパラメータがあります。 NNabla では、学習可能なパラメータも Variable オブジェクトとして表されています。入力 Variable と同様に、それらのパラメータ Variable も Function に渡すことによって使われます。例えば、 Affine 関数は入力、重み、そしてバイアスを入力として受け取ります。

x = nn.Variable([5, 2])  # Input
w = nn.Variable([2, 3], need_grad=True)  # Weights
b = nn.Variable([3], need_grad=True)  # Biases
affine_out = F.affine(x, w, b)  # Create a graph including only affine

上記の例は、 B = 5 ( バッチサイズ ) および D = 2 ( 次元 ) の入力を受け取り、それを D’ = 3 出力、すなわち (B , D’) 出力にマップします。

ここで、パラメータ Variable ( w と b ) に対してだけ need_grad=True をセットしました。 x は非パラメータ Variable で、計算グラフのルートです。従って、 x は勾配計算が必要ありません。これにより、 x に対する勾配計算は最初のaffineでは実行されず、不必要なバックプロパゲーションの計算を省くことができます。

次の部分で、データをセットし、勾配を初期化し、それから順方向の計算と逆方向の計算を行います。

# Set random input and parameters
x.d = np.random.randn(*x.shape)
w.d = np.random.randn(*w.shape)
b.d = np.random.randn(*b.shape)
# Initialize grad
x.grad.zero()  # Just for showing gradients are not computed when need_grad=False (default).
w.grad.zero()
b.grad.zero()

# Forward and backward
affine_out.forward()
affine_out.backward()
# Note: Calling backward at non-scalar Variable propagates 1 as error message from all element of outputs. .

affine_out が Affine の出力を保持します。

print('F.affine')
print(affine_out.d)
print('Reference')
print(np.dot(x.d, w.d) + b.d)
F.affine
[[-0.17701732  2.86095762 -0.82298267]
 [-0.75544345 -1.16702223 -2.44841242]
 [-0.36278027 -3.4771595  -0.75681627]
 [ 0.32743117  0.24258983  1.30944324]
 [-0.87201929  1.94556415 -3.23357344]]
Reference
[[-0.1770173   2.86095762 -0.82298267]
 [-0.75544345 -1.16702223 -2.44841242]
 [-0.3627803  -3.4771595  -0.75681627]
 [ 0.32743117  0.24258983  1.309443  ]
 [-0.87201929  1.94556415 -3.23357344]]

結果として重みとバイアスの勾配は次のようになります。

print("dw")
print(w.g)
print("db")
print(b.g)
dw
[[ 3.10820675  3.10820675  3.10820675]
 [ 0.37446201  0.37446201  0.37446201]]
db
[ 5.  5.  5.]

need_grad が False にセットされているため、 x の勾配は変わりません。

print(x.g)
[[ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]
 [ 0.  0.]]
Parametric function

Function の入力としてのパラメータを考えることにより、計算グラフの表現性と柔軟性が高まります。しかし、学習できる Function それぞれに対してすべてのパラメータを定義することは、ニューラルネットワークを定義するユーザーにとって面倒です。 NNabla では、学習できるモデルは通常、最適化可能なパラメータをもつ Function を構成することによって作られます。 これらの Function は "Parametric function" と呼ばれています。 Parametric function API は、様々な Parametric function と学習できるモデルを構成するためのインターフェイスを提供します。

Parametric function を使うために、以下のようにインポートを行います。

import nnabla.parametric_functions as PF

最適化可能なパラメータをもつ Function は以下のように作ることができます。

with nn.parameter_scope("affine1"):
    c1 = PF.affine(x, 3)

1 行目で parameter scope を作っています。そして、 2 行目で PF.affine - affine変換 - を x に対して適用し、その結果を保持する変数 c1 を作っています。パラメータは関数呼び出しで作られ、ランダムに初期化され、 parameter_scope コンテキストを使って “affine1” という名前で登録されます。関数 nnabla.get_parameters() で登録されたパラメータを取得することができます。

nn.get_parameters()
OrderedDict([('affine1/affine/W',
              <Variable((2, 3), need_grad=True) at 0x7f572822f0e8>),
             ('affine1/affine/b',
              <Variable((3,), need_grad=True) at 0x7f572822f138>)])

The name= argument of any PF function creates the equivalent parameter space to the above definition of PF.affine transformation as below. It could save the space of your Python code. The nnabla.parameter_scope is more useful when you group multiple parametric functions such as Convolution-BatchNormalization found in a typical unit of CNNs.

c1 = PF.affine(x, 3, name='affine1')
nn.get_parameters()
OrderedDict([('affine1/affine/W',
              <Variable((2, 3), need_grad=True) at 0x7f572822f0e8>),
             ('affine1/affine/b',
              <Variable((3,), need_grad=True) at 0x7f572822f138>)])

出力およびパラメータの形状 ( 上記のとおり ) が affine 変換の出力サイズ ( 上記の例では出力サイズは 3 ) により自動的に決まるということは注目すべき点です。これにより、簡単にグラフを作ることができます。

c1.shape
(5, 3)

( 特に意味のない例ですが ) パラメータのスコープは次のように入れ子にすることができます。

with nn.parameter_scope('foo'):
    h = PF.affine(x, 3)
    with nn.parameter_scope('bar'):
        h = PF.affine(h, 4)

結果として以下が作成されます。

nn.get_parameters()
OrderedDict([('affine1/affine/W',
              <Variable((2, 3), need_grad=True) at 0x7f572822f0e8>),
             ('affine1/affine/b',
              <Variable((3,), need_grad=True) at 0x7f572822f138>),
             ('foo/affine/W',
              <Variable((2, 3), need_grad=True) at 0x7f572822fa98>),
             ('foo/affine/b',
              <Variable((3,), need_grad=True) at 0x7f572822fae8>),
             ('foo/bar/affine/W',
              <Variable((3, 4), need_grad=True) at 0x7f572822f728>),
             ('foo/bar/affine/b',
              <Variable((4,), need_grad=True) at 0x7f572822fdb8>)])

また、 get_parameters()parameter_scope で使用できます。例えば、

with nn.parameter_scope("foo"):
    print(nn.get_parameters())
OrderedDict([('affine/W', <Variable((2, 3), need_grad=True) at 0x7f572822fa98>), ('affine/b', <Variable((3,), need_grad=True) at 0x7f572822fae8>), ('bar/affine/W', <Variable((3, 4), need_grad=True) at 0x7f572822f728>), ('bar/affine/b', <Variable((4,), need_grad=True) at 0x7f572822fdb8>)])

nnabla.clear_parameters() により、スコープの中で登録されたパラメータを消去することができます。

with nn.parameter_scope("foo"):
    nn.clear_parameters()
print(nn.get_parameters())
OrderedDict([('affine1/affine/W', <Variable((2, 3), need_grad=True) at 0x7f572822f0e8>), ('affine1/affine/b', <Variable((3,), need_grad=True) at 0x7f572822f138>)])
多層パーセプトロンのサンプル

次のブロックは、 2 層の完全結合のニューラルネットワーク ( 多層パーセプトロン ) によって、2 次元の入力から 1 次元の出力を予測するための計算グラフを作ります。

nn.clear_parameters()
batchsize = 16
x = nn.Variable([batchsize, 2])
with nn.parameter_scope("fc1"):
    h = F.tanh(PF.affine(x, 512))
with nn.parameter_scope("fc2"):
    y = PF.affine(h, 1)
print("Shapes:", h.shape, y.shape)
Shapes: (16, 512) (16, 1)

結果として次のようなパラメータ Variable が作成されます。

nn.get_parameters()
OrderedDict([('fc1/affine/W',
              <Variable((2, 512), need_grad=True) at 0x7f572822fef8>),
             ('fc1/affine/b',
              <Variable((512,), need_grad=True) at 0x7f572822f9a8>),
             ('fc2/affine/W',
              <Variable((512, 1), need_grad=True) at 0x7f572822f778>),
             ('fc2/affine/b',
              <Variable((1,), need_grad=True) at 0x7f572822ff98>)])

上記で説明したように、末端の Variable で順方向メソッドを呼び出すことで順方向パスを実行することができます。

x.d = np.random.randn(*x.shape)  # Set random input
y.forward()
print(y.d)
[[-0.05708594]
 [ 0.01661986]
 [-0.34168088]
 [ 0.05822293]
 [-0.16566885]
 [-0.04867431]
 [ 0.2633169 ]
 [ 0.10496549]
 [-0.01291842]
 [-0.09726256]
 [-0.05720493]
 [-0.09691752]
 [-0.07822668]
 [-0.17180404]
 [ 0.11970415]
 [-0.08222144]]

ニューラルネットワークの学習では、 backprop を用いた勾配降下法によって loss の値を最小化する必要があります。 NNabla では、 loss 関数は単一の Function であり、 Function モジュールに含まれます。

# Variable for label
label = nn.Variable([batchsize, 1])
# Set loss
loss = F.reduce_mean(F.squared_error(y, label))

# Execute forward pass.
label.d = np.random.randn(*label.shape)  # Randomly generate labels
loss.forward()
print(loss.d)
1.9382084608078003

上記のとおり、 NNabla で backward を実行するとルートの Variable で勾配を蓄積します。そのため、 backprop の前にパラメータ Variable の勾配を初期化する必要があります ( 別途 Solver APIで簡単な方法を説明します ) 。

# Collect all parameter variables and init grad.
for name, param in nn.get_parameters().items():
    param.grad.zero()
# Gradients are accumulated to grad of params.
loss.backward()
Imperative モード

backprop を実行すると、勾配はパラメータ Variable の grad 領域に保持されます。次のブロックでは、基本的な勾配降下法でパラメータを更新します。

for name, param in nn.get_parameters().items():
    param.data -= param.grad * 0.001  # 0.001 as learning rate

上記の計算は、ニューラルネットワークを実行するための NNabla の “ Imperative モード” の例です。通常、 NNabla Function ( nnabla.functions のインスタンス ) は入力として Variable を取ります。 ( Variable の代わりに ) NNabla Function への入力として少なくとも 1 つの NdArray が与えられると、 Function の計算はすぐに開始し、出力として Variable を返す代わりに NdArray を返します。上記の例で、NNabla Function F.mul_scalarF.sub2 がそれぞれオーバーライドされた演算子 *-= によって呼び出されます。

つまり、 NNabla の “ Imperative モード ” は計算グラフを作成しませんが、NumPy のように使うことができます。もし CUDA のようなデバイスアクセラレーションが有効ならば、それにより高速化された NumPy のように使うことができます。 Parametric function は NdArray 入力でも使うことができます。次のブロックでは、簡単な Imperative 実行の例を説明します。

# A simple example of imperative mode.
xi = nn.NdArray.from_numpy_array(np.arange(4).reshape(2, 2))
yi = F.relu(xi - 1)
print(xi.data)
print(yi.data)
[[0 1]
 [2 3]]
[[ 0.  0.]
 [ 1.  2.]]

右辺から左辺への in-place な代入は、 = 演算子では適切に行えないことに注意してください。 例えば、 xNdArray であるとき、 x = x + 1 により x の値が増加するわけでは ありません。 その代わりに、 x がもともと参照されていた NdArray とは異なる、右辺で新たに作成された NdArray を左辺の x は参照します。

NdArrays の in-place な操作には、 in-place なアサインメント演算子 +=-=*=/= を使用できます。 copy_from メソッドにより、既存の NdArray から他の既存の NdArray に値をコピーすることもできます。例えば、NdArray である x を 1 増加させるには x.copy_from(x+1) で行うことができます。もし、デバイスのコンテキストが nnabla.set_default_contextnnabla.context_scope を使って明示されていれば、コピーはデバイスアクセラレーションを用いて行われます。

# The following doesn't perform substitution but assigns a new NdArray object to `xi`.
# xi = xi + 1

# The following copies the result of `xi + 1` to `xi`.
xi.copy_from(xi + 1)
assert np.all(xi.data == (np.arange(4).reshape(2, 2) + 1))

# Inplace operations like `+=`, `*=` can also be used (more efficient).
xi += 1
assert np.all(xi.data == (np.arange(4).reshape(2, 2) + 2))
Solver

NNabla は nnabla.solvers モジュールでは、パラメータを最適化するために確率的勾配降下法アルゴリズムを提供します。上記で説明したパラメータの更新はこの Solver API で置き換えることができ、この API はより簡単であり、大抵の場合より速いです。

from nnabla import solvers as S
solver = S.Sgd(lr=0.00001)
solver.set_parameters(nn.get_parameters())
# Set random data
x.d = np.random.randn(*x.shape)
label.d = np.random.randn(*label.shape)

# Forward
loss.forward()

以下の solver メソッドを呼び出し、勾配領域を 0 で埋めたあと、 backprop を呼び出します。

solver.zero_grad()
loss.backward()

次のブロックでは、通常の SGD 更新則を使ってパラメータを更新します (上記の Imperative の例と同様 ) 。

solver.update()
トイ問題を利用した学習の例

以下の関数のようなベクトルのノルムの計算を回帰する問題を考えます。

def vector2length(x):
    # x : [B, 2] where B is number of samples.
    return np.sqrt(np.sum(x ** 2, axis=1, keepdims=True))

次のように、 matplotlib の contour plot により、この変換をビジュアライズします。

# Data for plotting contour on a grid data.
xs = np.linspace(-1, 1, 100)
ys = np.linspace(-1, 1, 100)
grid = np.meshgrid(xs, ys)
X = grid[0].flatten()
Y = grid[1].flatten()

def plot_true():
    """Plotting contour of true mapping from a grid data created above."""
    plt.contourf(xs, ys, vector2length(np.hstack([X[:, None], Y[:, None]])).reshape(100, 100))
    plt.axis('equal')
    plt.colorbar()

plot_true()
_images/python_api_98_0.png

これらを予測する深層ニューラルネットワークを定義します。

def length_mlp(x):
    h = x
    for i, hnum in enumerate([4, 8, 4, 2]):
        h = F.tanh(PF.affine(h, hnum, name="fc{}".format(i)))
    y = PF.affine(h, 1, name='fc')
    return y
nn.clear_parameters()
batchsize = 100
x = nn.Variable([batchsize, 2])
y = length_mlp(x)
label = nn.Variable([batchsize, 1])
loss = F.reduce_mean(F.squared_error(y, label))

for ループを使って 5 層の深層 MLP を作成しました。わずか 3 行のコードだけで無限に深いニューラルネットワークを作成可能です。次のブロックでは、学習済み関数を視覚化するための helper 関数を追加します。

def predict(inp):
    ret = []
    for i in range(0, inp.shape[0], x.shape[0]):
        xx = inp[i:i + x.shape[0]]
        # Imperative execution
        xi = nn.NdArray.from_numpy_array(xx)
        yi = length_mlp(xi)
        ret.append(yi.data.copy())
    return np.vstack(ret)

def plot_prediction():
    plt.contourf(xs, ys, predict(np.hstack([X[:, None], Y[:, None]])).reshape(100, 100))
    plt.colorbar()
    plt.axis('equal')

続いて、 solver オブジェクトを作成します。この分野でもっともよく使用される SGD アルゴリズムの 1 つである Adam オプティマイザーを使います。

from nnabla import solvers as S
solver = S.Adam(alpha=0.01)
solver.set_parameters(nn.get_parameters())

次の関数は真のシステムにより無限にデータを生成します。

def random_data_provider(n):
    x = np.random.uniform(-1, 1, size=(n, 2))
    y = vector2length(x)
    return x, y

次のブロックでは、 2000 回の学習ステップ ( SGD による更新 ) を実行します。

num_iter = 2000
for i in range(num_iter):
    # Sample data and set them to input variables of training.
    xx, ll = random_data_provider(batchsize)
    x.d = xx
    label.d = ll
    # Forward propagation given inputs.
    loss.forward(clear_no_need_grad=True)
    # Parameter gradients initialization and gradients computation by backprop.
    solver.zero_grad()
    loss.backward(clear_buffer=True)
    # Apply weight decay and update by Adam rule.
    solver.weight_decay(1e-6)
    solver.update()
    # Just print progress.
    if i % 100 == 0 or i == num_iter - 1:
        print("Loss@{:4d}: {}".format(i, loss.d))
Loss@   0: 0.6976373195648193
Loss@ 100: 0.08075223118066788
Loss@ 200: 0.005213144235312939
Loss@ 300: 0.001955194864422083
Loss@ 400: 0.0011660841992124915
Loss@ 500: 0.0006421314901672304
Loss@ 600: 0.0009330055327154696
Loss@ 700: 0.0008817618945613503
Loss@ 800: 0.0006205961108207703
Loss@ 900: 0.0009072928223758936
Loss@1000: 0.0008160348515957594
Loss@1100: 0.0011569359339773655
Loss@1200: 0.000837412488181144
Loss@1300: 0.0011542742140591145
Loss@1400: 0.0005833200993947685
Loss@1500: 0.0009848927147686481
Loss@1600: 0.0005141657311469316
Loss@1700: 0.0009339841199107468
Loss@1800: 0.000950580753851682
Loss@1900: 0.0005430278833955526
Loss@1999: 0.0007046313839964569

メモリ使用法の最適化 : 上記の更新で、 .forward()clear_no_need_grad= オプション付きで呼び出され、 .backward()clear_buffer= オプション付きで呼び出されていることがわかります。順方向の Variable のバッファーの データ はすべて Function の勾配を計算するときのために保持しなければならないバックプロパゲーションアルゴリズムの性質のため、ニューラルネットワークの学習は、通常莫大なメモリを消費します。単純な実装では、 NdArray オブジェクトが参照されなくなるまで ( つまり、グラフが消去されるまで ) 存在するすべての Variable データ勾配 を保持します。 .forward().backward() にある clear_* オプションを指定することで、その後の計算によって参照されない データ勾配 のメモリをクリアする ( 消去する ) ことができ、メモリの消費を節約することができます。 ( このとき、実際にはメモリを解放しません。メモリの確保 / 解放のオーバヘッドを回避するために、デフォルトでメモリプールエンジンを使っています。) 参照されなくなったバッファーは、その後の計算で再利用できます。詳細は Variable のドキュメントを参照してください。次の loss.forward(clear_buffer=True) はどんな中間 Variable の データ もクリアすることに注意してください。もしデバッグやログなどの目的で中間 Variable に興味のある方は、下記のように特定の Variable のバッファーをクリアするのを防ぐために、 .persistent フラグを使うことができます。

loss.forward(clear_buffer=True)
print("The prediction `y` is cleared because it's an intermediate variable.")
print(y.d.flatten()[:4])  # to save space show only 4 values
y.persistent = True
loss.forward(clear_buffer=True)
print("The prediction `y` is kept by the persistent flag.")
print(y.d.flatten()[:4])  # to save space show only 4 value
The prediction y is cleared because it's an intermediate variable.
[  2.27279830e-04   6.02164946e-05   5.33679675e-04   2.35557582e-05]
The prediction y is kept by the persistent flag.
[ 1.0851264   0.87657517  0.79603785  0.40098712]

次のように正解と予測関数の視覚化により、予測がかなりうまく行われていることを確認することができました。

plt.subplot(121)
plt.title("Ground truth")
plot_true()
plt.subplot(122)
plt.title("Prediction")
plot_prediction()
_images/python_api_113_0.png

nnabla.save_parameters によって学習されたパラメータを保存し、 nnabla.load_parameters によって読み込むことができます。

path_param = "param-vector2length.h5"
nn.save_parameters(path_param)
# Remove all once
nn.clear_parameters()
nn.get_parameters()
2017-09-27 14:00:40,544 [nnabla][INFO]: Parameter save (.h5): param-vector2length.h5
OrderedDict()
# Load again
nn.load_parameters(path_param)
print('\n'.join(map(str, nn.get_parameters().items())))
2017-09-27 14:00:40,564 [nnabla][INFO]: Parameter load (<built-in function format>): param-vector2length.h5
('fc0/affine/W', <Variable((2, 4), need_grad=True) at 0x7f576328df48>)
('fc0/affine/b', <Variable((4,), need_grad=True) at 0x7f57245f2868>)
('fc1/affine/W', <Variable((4, 8), need_grad=True) at 0x7f576328def8>)
('fc1/affine/b', <Variable((8,), need_grad=True) at 0x7f5727ee5c78>)
('fc2/affine/W', <Variable((8, 4), need_grad=True) at 0x7f5763297318>)
('fc2/affine/b', <Variable((4,), need_grad=True) at 0x7f5727d29908>)
('fc3/affine/W', <Variable((4, 2), need_grad=True) at 0x7f57632973b8>)
('fc3/affine/b', <Variable((2,), need_grad=True) at 0x7f57632974a8>)
('fc/affine/W', <Variable((2, 1), need_grad=True) at 0x7f57632974f8>)
('fc/affine/b', <Variable((1,), need_grad=True) at 0x7f5763297598>)

save および load 関数はパラメータスコープ内で使用できます。

with nn.parameter_scope('foo'):
    nn.load_parameters(path_param)
print('\n'.join(map(str, nn.get_parameters().items())))
2017-09-27 14:00:40,714 [nnabla][INFO]: Parameter load (<built-in function format>): param-vector2length.h5
('fc0/affine/W', <Variable((2, 4), need_grad=True) at 0x7f576328df48>)
('fc0/affine/b', <Variable((4,), need_grad=True) at 0x7f57245f2868>)
('fc1/affine/W', <Variable((4, 8), need_grad=True) at 0x7f576328def8>)
('fc1/affine/b', <Variable((8,), need_grad=True) at 0x7f5727ee5c78>)
('fc2/affine/W', <Variable((8, 4), need_grad=True) at 0x7f5763297318>)
('fc2/affine/b', <Variable((4,), need_grad=True) at 0x7f5727d29908>)
('fc3/affine/W', <Variable((4, 2), need_grad=True) at 0x7f57632973b8>)
('fc3/affine/b', <Variable((2,), need_grad=True) at 0x7f57632974a8>)
('fc/affine/W', <Variable((2, 1), need_grad=True) at 0x7f57632974f8>)
('fc/affine/b', <Variable((1,), need_grad=True) at 0x7f5763297598>)
('foo/fc0/affine/W', <Variable((2, 4), need_grad=True) at 0x7f5763297958>)
('foo/fc0/affine/b', <Variable((4,), need_grad=True) at 0x7f57632978b8>)
('foo/fc1/affine/W', <Variable((4, 8), need_grad=True) at 0x7f572a51ac78>)
('foo/fc1/affine/b', <Variable((8,), need_grad=True) at 0x7f5763297c78>)
('foo/fc2/affine/W', <Variable((8, 4), need_grad=True) at 0x7f5763297a98>)
('foo/fc2/affine/b', <Variable((4,), need_grad=True) at 0x7f5763297d68>)
('foo/fc3/affine/W', <Variable((4, 2), need_grad=True) at 0x7f5763297e08>)
('foo/fc3/affine/b', <Variable((2,), need_grad=True) at 0x7f5763297ea8>)
('foo/fc/affine/W', <Variable((2, 1), need_grad=True) at 0x7f5763297f48>)
('foo/fc/affine/b', <Variable((1,), need_grad=True) at 0x7f5763297cc8>)
!rm {path_param}  # Clean ups

NNabla モデルのファインチューニングチュートリアル

ここでは、 nnabla の学習済みモデルを使用してファインチューニングを実行する方法を説明します。

モデルを読み込む

モデルの読み込みは非常に簡単です。 必要なのは 2 行だけです。

from nnabla.models.imagenet import ResNet18
model = ResNet18()

引数としてモデルの名前を指定することにより、 ResNet34ResNet50 などの他の ResNet モデルを選択できます。もちろん、他の学習済みモデルを選択することも可能です。 ドキュメント をご覧ください。

: ResNet18 を初めて使用する場合、nnabla は自動的に https://nnabla.org から重みをダウンロードします。これは数分かかる場合があります。

データセット

このチュートリアルでは、ファインチューニング用のデータセットとして Caltech101 を使用します。 Caltech101 は合計 9,000 を超えるオブジェクト画像で構成され、各画像は 101 の異なるカテゴリの 1 つ、または “clutter” カテゴリに属します。単純な分類としては 101 のカテゴリの画像を使用します。

データセットを自動的にダウンロードして nnabla_data に保存できる、 caltech101_data.py という名前のスクリプトを用意しました。

独自のデータセットと、データを読み込むことができる DataIterator がある場合は、代わりにそれを使用できます。

run caltech101_data.py
batch_size = 32  # we set batch_size = 32
all_data = data_iterator_caltech101(batch_size)

caltech101 には学習と検証のための個別のデータがないため、 手動 で分割する必要があります。ここでは、データセットを次のように分割します。 80% を学習、そして 20% を検証。

num_samples = all_data.size
num_train_samples = int(0.8 * num_samples)  # Take 80% for training, and the rest for validation.
num_class = 101
data_iterator_train = all_data.slice(
        rng=None, slice_start=0, slice_end=num_train_samples)
data_iterator_valid = all_data.slice(
        rng=None, slice_start=num_train_samples, slice_end=num_samples)

これでモデルとデータが用意できました !

オプショナル : データセット内の画像の確認

データセットにどのような画像があるか見てみましょう。 に、 DataIterator メソッドで画像を取得します。

import matplotlib.pyplot as plt
%matplotlib inline
images, labels = data_iterator_train.next()
sample_image, sample_label = images[0], labels[0]
plt.imshow(sample_image.transpose(1,2,0))
plt.show()
print("image_shape: {}".format(sample_image.shape))
print("label_id: {}".format(sample_label))
_images/model_finetuning_11_0.png
image_shape: (3, 128, 128)
label_id: [94]
グラフ作成の準備

基本的なモジュールのインポートから始めましょう。

import nnabla as nn

# Optional: If you want to use GPU
from nnabla.ext_utils import get_extension_context
ctx = get_extension_context("cudnn")
nn.set_default_context(ctx)
ext = nn.ext_utils.import_extension_module("cudnn")
ネットワークの入力 Variable を作成する

次に、入力 Variable を作成します。

channels, image_height, image_width = sample_image.shape  # use info from the image we got

# input variables for the validation network
image_valid = nn.Variable((batch_size, channels, image_height, image_width))
label_valid = nn.Variable((batch_size, 1))
input_image_valid = {"image": image_valid, "label": label_valid}

# input variables for the training network
image_train = nn.Variable((batch_size, channels, image_height, image_width))
label_train = nn.Variable((batch_size, 1))
input_image_train = {"image": image_train, "label": label_train}
学習済みモデルを使用して学習用グラフを作成する

モデルの API リファレンス を参照すると、 use_up_to オプションがあることがわかります。モデルを呼び出す時に、事前定義された文字列の 1 つを指定すると、指定した層まで計算グラフが作成されます。例えば、 ResNet18 の場合、グラフの最後の層として次のいずれかを選択できます。

  • ‘classifier’ ( デフォルト ) : 分類のための最後の Affine 層の出力。

  • ‘pool’ : 最終的な Global Average Pooling 出力。

  • ‘lastconv’ : ReLU 活性化なしの Global Average Pooling の入力。

  • ‘lastconv+relu’ : ‘lastconv’ ReLU 活性化。

ファインチューニングでは、上位層のみを新しい ( 学習されていない ) 層に置き換え、下位層を学習済み重みで再利用するのが一般的です。また、学習済みモデルは、 1000 のカテゴリを持つ ImageNet の分類タスクで学習されているため、 分類 層の出力には、現在のデータセットに適合しない出力形状 ( batch_size、1000 ) があります。このため、ここでは元のグラフにおける Global Average Pooling 層に対応する プール 層までグラフを作成し、 101 カテゴリ分類のために Affine ( 全結合 ) レイヤに繋げます。ファインチューニングでは、新しく追加された層 ( この場合は最後の Affine 層 ) の重みのみを学習するのが一般的ですが、このチュートリアルでは、グラフ内の すべて の層の重みを更新します。また、学習用グラフを作成するときは、 training = True に設定する必要があります。

import nnabla.parametric_functions as PF

y_train = model(image_train, force_global_pooling=True, use_up_to="pool", training=True)
with nn.parameter_scope("finetuning_fc"):
    pred_train = PF.affine(y_train, 101)  # adding the affine layer to the graph.

: モデルに対して想定している入力形状と異なる場合は、 force_global_pooling = True を指定する必要があります。 model.input_shape と入力して、モデルのデフォルトの入力形状を確認できます。

モデルを使用して検証用グラフを作成する

ほぼ同様の方法で検証用グラフを作成できます。 training フラグを False に変更するだけです。

y_valid = model(image_valid,
                force_global_pooling=True, use_up_to="pool", training=False)
with nn.parameter_scope("finetuning_fc"):
    pred_valid = PF.affine(y_valid, 101)
pred_valid.persistent = True  # to keep the value when get `forward(clear_buffer=True)`-ed.
ロスと分類誤差計算のための関数を定義する
import nnabla.functions as F


def loss_function(pred, label):
    """
        Compute loss.
    """
    loss = F.mean(F.softmax_cross_entropy(pred, label))
    return loss

loss_valid = loss_function(pred_valid, label_valid)
top_1_error_valid = F.mean(F.top_n_error(pred_valid, label_valid))
loss_train = loss_function(pred_train, label_train)
top_1_error_train = F.mean(F.top_n_error(pred_train, label_train))
Solver を準備する
import nnabla.solvers as S

solver = S.Momentum(0.01)  # you can choose others as well

solver.set_parameters(nn.get_parameters())
イテレーションのための設定
num_epoch = 10  # arbitrary
one_epoch = data_iterator_train.size // batch_size
max_iter = num_epoch * one_epoch
val_iter = data_iterator_valid.size // batch_size
ファインチューニング前のパフォーマンス

モデルがどれほど 良く 機能するかを見てみましょう。最後の Affine 層を除いて、すべての重みが ImageNet で学習済みであることに注意してください。 まず、モデルのパフォーマンスを示す関数を準備します。

def run_validation(pred_valid, loss_valid, top_1_error_valid,
                   input_image_valid, data_iterator_valid,
                   with_visualized=False, num_visualized=3):
    assert num_visualized < pred_valid.shape[0], "too many images to plot."
    val_iter = data_iterator_valid.size // pred_valid.shape[0]
    ve = 0.
    vloss = 0.
    for j in range(val_iter):
        v_image, v_label = data_iterator_valid.next()
        input_image_valid["image"].d = v_image
        input_image_valid["label"].d = v_label
        nn.forward_all([loss_valid, top_1_error_valid], clear_no_need_grad=True)
        vloss += loss_valid.d.copy()
        ve += top_1_error_valid.d.copy()

    vloss /= val_iter
    ve /= val_iter

    if with_visualized:
        ind = 1
        random_start = np.random.randint(pred_valid.shape[0] - num_visualized)
        fig = plt.figure(figsize=(12., 12.))
        for n in range(random_start, random_start + num_visualized):
            sample_image, sample_label = v_image[n], v_label[n]
            ax = fig.add_subplot(1, num_visualized, ind)
            ax.imshow(sample_image.transpose(1,2,0))
            with nn.auto_forward():
                predicted_id = np.argmax(F.softmax(pred_valid)[n].d)
            result = "true label_id: {} - predicted as {}".format(str(sample_label[0]), str(predicted_id))
            ax.set_title(result)
            ind += 1
        fig.show()

    return ve, vloss
_, _ = run_validation(pred_valid, loss_valid, top_1_error_valid, input_image_valid, data_iterator_valid, with_visualized=True)
_images/model_finetuning_29_1.png

ご覧いただける様に、モデルは画像を適切に分類できません。 それでは、ファインチューニングを始めて、パフォーマンスがどのように向上するか見てみましょう。

ファインチューニングを開始する

学習用の monitor を準備しましょう。

from nnabla.monitor import Monitor, MonitorSeries, MonitorTimeElapsed
monitor = Monitor("tmp.monitor")
monitor_loss = MonitorSeries("Training loss", monitor, interval=200)
monitor_err = MonitorSeries("Training error", monitor, interval=200)
monitor_vloss = MonitorSeries("Test loss", monitor, interval=200)
monitor_verr = MonitorSeries("Test error", monitor, interval=200)
# Training-loop
for i in range(max_iter):
    image, label = data_iterator_train.next()
    input_image_train["image"].d = image
    input_image_train["label"].d = label
    nn.forward_all([loss_train, top_1_error_train], clear_no_need_grad=True)

    monitor_loss.add(i, loss_train.d.copy())
    monitor_err.add(i, top_1_error_train.d.copy())

    solver.zero_grad()
    loss_train.backward(clear_buffer=True)

    # update parameters
    solver.weight_decay(3e-4)
    solver.update()

    if i % 200 == 0:
        ve, vloss = run_validation(pred_valid, loss_valid, top_1_error_valid,
                                   input_image_valid, data_iterator_valid,
                                   with_visualized=False, num_visualized=3)

        monitor_vloss.add(i, vloss)
        monitor_verr.add(i, ve)
2019-07-05 14:26:26,885 [nnabla][INFO]: iter=199 {Training loss}=1.5021580457687378
2019-07-05 14:26:26,887 [nnabla][INFO]: iter=199 {Training error}=0.3345312476158142
2019-07-05 14:26:28,756 [nnabla][INFO]: iter=200 {Test loss}=2.975713219355654
2019-07-05 14:26:28,756 [nnabla][INFO]: iter=200 {Test error}=0.5384837962962963
2019-07-05 14:26:50,249 [nnabla][INFO]: iter=399 {Training loss}=0.22022955119609833
2019-07-05 14:26:50,250 [nnabla][INFO]: iter=399 {Training error}=0.053437501192092896
2019-07-05 14:26:52,256 [nnabla][INFO]: iter=400 {Test loss}=0.12045302835327608
2019-07-05 14:26:52,257 [nnabla][INFO]: iter=400 {Test error}=0.029513888888888888
2019-07-05 14:27:14,151 [nnabla][INFO]: iter=599 {Training loss}=0.0659928247332573
2019-07-05 14:27:14,152 [nnabla][INFO]: iter=599 {Training error}=0.012500000186264515
2019-07-05 14:27:16,175 [nnabla][INFO]: iter=600 {Test loss}=0.08744175952893717
2019-07-05 14:27:16,175 [nnabla][INFO]: iter=600 {Test error}=0.02199074074074074
2019-07-05 14:27:38,097 [nnabla][INFO]: iter=799 {Training loss}=0.03324155509471893
2019-07-05 14:27:38,098 [nnabla][INFO]: iter=799 {Training error}=0.0054687499068677425
2019-07-05 14:27:40,120 [nnabla][INFO]: iter=800 {Test loss}=0.07678695395588875
2019-07-05 14:27:40,121 [nnabla][INFO]: iter=800 {Test error}=0.02025462962962963
2019-07-05 14:28:02,041 [nnabla][INFO]: iter=999 {Training loss}=0.019672293215990067
2019-07-05 14:28:02,042 [nnabla][INFO]: iter=999 {Training error}=0.0017187499906867743
2019-07-05 14:28:04,064 [nnabla][INFO]: iter=1000 {Test loss}=0.06333287184437116
2019-07-05 14:28:04,065 [nnabla][INFO]: iter=1000 {Test error}=0.017361111111111112
2019-07-05 14:28:25,984 [nnabla][INFO]: iter=1199 {Training loss}=0.009992362931370735
2019-07-05 14:28:25,985 [nnabla][INFO]: iter=1199 {Training error}=0.0003124999930150807
2019-07-05 14:28:28,008 [nnabla][INFO]: iter=1200 {Test loss}=0.06950318495984431
2019-07-05 14:28:28,008 [nnabla][INFO]: iter=1200 {Test error}=0.015625
2019-07-05 14:28:49,954 [nnabla][INFO]: iter=1399 {Training loss}=0.007941835559904575
2019-07-05 14:28:49,955 [nnabla][INFO]: iter=1399 {Training error}=0.0003124999930150807
2019-07-05 14:28:51,978 [nnabla][INFO]: iter=1400 {Test loss}=0.06711215277512868
2019-07-05 14:28:51,979 [nnabla][INFO]: iter=1400 {Test error}=0.016203703703703703
2019-07-05 14:29:13,898 [nnabla][INFO]: iter=1599 {Training loss}=0.008225565776228905
2019-07-05 14:29:13,899 [nnabla][INFO]: iter=1599 {Training error}=0.0007812500116415322
2019-07-05 14:29:15,923 [nnabla][INFO]: iter=1600 {Test loss}=0.06447940292181792
2019-07-05 14:29:15,923 [nnabla][INFO]: iter=1600 {Test error}=0.016203703703703703
2019-07-05 14:29:37,850 [nnabla][INFO]: iter=1799 {Training loss}=0.005678100511431694
2019-07-05 14:29:37,850 [nnabla][INFO]: iter=1799 {Training error}=0.0
2019-07-05 14:29:39,873 [nnabla][INFO]: iter=1800 {Test loss}=0.06282947226255028
2019-07-05 14:29:39,873 [nnabla][INFO]: iter=1800 {Test error}=0.01678240740740741
2019-07-05 14:30:01,795 [nnabla][INFO]: iter=1999 {Training loss}=0.006834140978753567
2019-07-05 14:30:01,796 [nnabla][INFO]: iter=1999 {Training error}=0.00046874998952262104
2019-07-05 14:30:03,818 [nnabla][INFO]: iter=2000 {Test loss}=0.05948294078310331
2019-07-05 14:30:03,818 [nnabla][INFO]: iter=2000 {Test error}=0.014467592592592593

ご覧いただける様に、ファインチューニングが進むにつれて、 loss とエラー率は減少しています。ファインチューニング後の分類結果を見てみましょう。

_, _ = run_validation(pred_valid, loss_valid, top_1_error_valid, input_image_valid, data_iterator_valid, with_visualized=True)
_images/model_finetuning_36_0.png

これで、モデルが画像を適切に分類できるようになりました。

更にファインチューニング

finetuning.py という名前の便利なスクリプトがあります。これを使用することで、 独自のオリジナルのデータセットでも 、様々なモデルでファインチューニングを試すことができます。

これを行うには、独自のデータセットを準備し、いくつかの前処理を行う必要があります。 以下にその方法を説明します。

独自のデータセットを準備する

画像の分類に使用できる画像がたくさんあるとします。データを特定の方法で整理する必要があります。ここでは、他のデータセットである Stanford Dogs Dataset について説明します。 まず、公式ページにアクセスして、 images.tar をダウンロードします ( リンクは こちら です ) 。次に、アーカイブを展開すると、 Images という名前のディレクトリが表示されます。そのディレクトリ内には多くのサブディレクトリがあり、各サブディレクトリには 1 つのカテゴリに属する画像が格納されています。例えば、ディレクトリ n02099712-Labrador_retriever には、ラブラドールレトリバーの画像のみが含まれています。従って、独自のデータセットを使用する場合は、次のように画像とディレクトリを同じ様に整理する必要があります。

parent_directory
├── subdirectory_for_category_A
│   ├── image_0.jpg
│   ├── image_1.jpg
│   ├── image_2.jpg
│   ├── ...
│
├── subdirectory_for_category_B
│   ├── image_0.jpg
│   ├── ...
│
├── subdirectory_for_category_C
│   ├── image_0.jpg
│   ├── ...
│
├── subdirectory_for_category_D
│   ├── image_0.jpg
│   ├── ...
│
 ...

各カテゴリの画像の数は異なる場合があり、完全に同じである必要はありません。 独自データセットを配置したら、準備完了です!

NNabla CLI を使用して画像分類データセットを作成する

データセットを準備して整理したら、次に行う必要があるのは、 finetuning.py で使用される .csv ファイルを作成するだけです。そのために、 NNabla の Python コマンドラインインターフェース を使用できます。 次のように入力してください。

nnabla_cli create_image_classification_dataset -i <path to parent directory> -o <output directory which contains "preprocessed" images> -c <number of channels> -w <width> -g <height> -m <padding or trimming> -s <whether apply shuffle or not> -f1 <name of the output csv file for training data> -f2 <name of the output csv file for test data> -r2 <ratio(%) of test data to training data>

Stanford Dogs Dataset でこれを行うと、以下のようになります。

nnabla_cli create_image_classification_dataset -i Images -o arranged_images -c 3 -w 128 -g 128 -m padding -s true -f1 stanford_dog_train.csv -f2 stanford_dog_test.csv -r2 20

出力 .csv ファイルは、 -o オプションで指定したものと同じディレクトリに保存されることに注意してください。 詳細については、 ドキュメント を参照してください。

上記のコマンドを実行した後、データセットのファインチューニングを開始できます。

ファインチューニングを実行

必要なのは、 1 行を入力することだけです。

python finetuning.py --model <model name> --train-csv <.csv file containing training data>  --test-csv <.csv file containing test data>

データセットのファインチューニングを実行します!

run finetuning.py --model ResNet34 --epoch 10 --train-csv ~/nnabla_data/stanford_dog_arranged/stanford_dog_train.csv --test-csv ~/nnabla_data/stanford_dog_arranged/stanford_dog_test.csv --shuffle True
推論のためにファインチューニングの結果を使用する方法の例

ファインチューニングが終了したら、推論に使用しましょう! 上記のスクリプトは、指定した特定のイテレーターごとにパラメータを保存しました。そこで、学習したものと同じモデルを呼び出して、今度はファインチューニングされたパラメータを次のように使用します。

from nnabla.models.imagenet import ResNet34
import nnabla as nn

param_path = "params_XXX.h5"  # specify the path to the saved parameter (.h5)

model = ResNet34()
batch_size = 1  # just for inference
input_shape = (batch_size, ) + model.input_shape

次に、入力 Variable と推論用のネットワークを定義します。スクリプトのファインチューニングと全く同じ方法で、ネットワークを構築する必要があることに注意してください ( レイヤ構成、パラメータ名など... ) 。

x = nn.Variable(input_shape)  # input Variable
pooled = model(x, use_up_to="pool", training=False)
with nn.parameter_scope("finetuning"):
    with nn.parameter_scope("last_fc"):
        pred = PF.affine(pooled, 120)

上記でファインチューニングしたパラメータを読み込みます。 nn.load_parameters() を使用してパラメータを読み込むことができます。これを呼び出すと、 params.h5 に格納されているパラメータがグローバルスコープに格納されます。 nn.get_parameters() を使用して、 nn.load_parameters() の前後でパラメータが異なることを確認できます。

nn.load_parameters(param_path)  # load the finetuned parameters.
pred.forward()

デバッグ

Deep neural networks are going deeper and deeper every year, requiring more components in the networks. Such complexity often misleads us to mal-configure the networks that can turn out be critical. Even if we correctly configure a neural network as desired, we may still want to find out its performance bottleneck, e.g., from which layer(s) the computational bottleneck comes.

In this debugging tutorial, we introduce the following ways to deal with such cases:

  1. 変数の visit メソッド

  2. pretty-print

  3. 簡単なグラフビューアー

  4. プロファイリング・ユーティリティー

  5. value tracer

それぞれのテクニックについて説明しますが、まず、次のような参照モデルを準備しましょう。

# If you run this notebook on Google Colab, uncomment and run the following to set up dependencies.
# !pip install nnabla-ext-cuda100
# !git clone https://github.com/sony/nnabla.git
# %cd nnabla/tutorial
# Python2/3 compatibility
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import numpy as np
import nnabla as nn
import nnabla.logger as logger
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S

def block(x, maps, test=False, name="block"):
    h = x
    with nn.parameter_scope(name):
        with nn.parameter_scope("in-block-1"):
            h = PF.convolution(h, maps, kernel=(3, 3), pad=(1, 1), with_bias=False)
            h = PF.batch_normalization(h, batch_stat=not test)
            h = F.relu(h)
        with nn.parameter_scope("in-block-2"):
            h = PF.convolution(h, maps // 2, kernel=(3, 3), pad=(1, 1), with_bias=False)
            h = PF.batch_normalization(h, batch_stat=not test)
            h = F.relu(h)
        with nn.parameter_scope("in-block-3"):
            h = PF.convolution(h, maps, kernel=(3, 3), pad=(1, 1), with_bias=False)
            h = PF.batch_normalization(h, batch_stat=not test)

        if h.shape[1] != x.shape[1]:
            with nn.parameter_scope("skip"):
                s = PF.convolution(x, maps, kernel=(3, 3), pad=(1, 1), with_bias=False)
                s = PF.batch_normalization(s, batch_stat=not test)

    return F.relu(h + s)

def network(x, maps=16, test=False):
    h = x
    h = PF.convolution(h, maps, kernel=(3, 3), pad=(1, 1), name="first-conv", with_bias=False)
    h = PF.batch_normalization(h, batch_stat=not test, name="first-bn")
    h = F.relu(h)
    for l in range(4):
        h = block(h, maps * 2 ** (l + 1), name="block-{}".format(l))
        h = F.max_pooling(h, (2, 2))
    h = F.average_pooling(h, h.shape[2:])
    pred = PF.affine(h, 100, name="pred")
    return pred
visit メソッド

変数の visit メソッドは、引数としてラムダ、関数、または呼び出し可能なオブジェクトをとり、変数が順方向でトラバースできる NNabla 関数経由で呼び出されます。説明より使い方を見る方が簡単です。

まず最初に、呼び出し可能なクラスを定義します。

class PrintFunc(object):
    def __call__(self, nnabla_func):
        print("==========")
        print(nnabla_func.info.type_name)
        print(nnabla_func.inputs)
        print(nnabla_func.outputs)
        print(nnabla_func.info.args)

この呼び出し可能なオブジェクトは、たとえば畳み込み ( コンボリューション ) や ReLU などの NNabla 関数をとるので、ユーザーはその関数から情報を得ることができます。

nn.clear_parameters()  # this call is just in case to do the following code again

x = nn.Variable.from_numpy_array(np.random.randn(*[4, 3, 128, 128]))
pred = network(x)
pred.visit(PrintFunc())

This is the low-level API to see the graph information as you want by hand.

PPrint

PPrint method is one of the instantiation of the visit method. We can see the graph structure in the topological (forward) order in details. Here is a usage to see detailed information of a graph.

nn.clear_parameters()  # call this in case you want to run the following code agian

x = nn.Variable.from_numpy_array(np.random.randn(*[4, 3, 128, 128]))
pred = network(x)

# pprint
from nnabla.utils.inspection import pprint
pprint(pred, summary=True, forward=True, backward=True)
簡単なグラフビューアー

visit メソッドは、グラフで使われる各関数に関する情報を得るのにとても役立ちますが、例えばどの変数がどの変数に結合しているかといった、ネットワーク全体の構成の詳細を見るのは困難です。そこで、視覚的にネットワーク全体の構成を示すグラフビューアーを用いて、より効率的にデバッグできるようにします。次のコードで示すように、グラフビューアーを使うことは簡単です。

nn.clear_parameters()  # call this in case you want to run the following code agian

x = nn.Variable([4, 3, 128, 128])
pred = network(x)
import nnabla.experimental.viewers as V

graph = V.SimpleGraph(verbose=False)
graph.view(pred)

visit メソッドの場合と同様により詳細な情報を見たい場合は、 verbose オプションを True に変えてください。

graph = V.SimpleGraph(verbose=True)
graph.view(pred)

これで詳細な情報が見ることができます !

このビューアーは主に Python でコードを書きたい NNabla ユーザー向けのためであり、より美しいネットワークを見てみたい、そのようなネットワークを試したい方は Neural Network Console をご利用いただき、https://dl.sony.com/ をご覧ください。

Profiling Utils

基本的に、この機能は、速度における全統計量やどの関数がボトルネックになっているかを知りたい 開発者向け です。 NNabla では簡単なプロファイリングツールを用意されています。ネットワークの準備ができたら、Loss 関数や solver のようなネットワークを学習するための他のコンポーネントを備えることを推奨します。

To create the profiler and see the results, run the following codes.

nn.clear_parameters()  # call this in case you want to run the following code agian

# Context
from nnabla.ext_utils import get_extension_context
device = "cudnn"
ctx = get_extension_context(device)
nn.set_default_context(ctx)

# Network
x = nn.Variable.from_numpy_array(np.random.randn(*[4, 3, 128, 128]))
t = nn.Variable([4, 1])
pred = network(x)
loss = F.mean(F.softmax_cross_entropy(pred, t))

# Solver
solver = S.Momentum()
solver.set_parameters(nn.get_parameters())

# Profiler
from nnabla.utils.profiler import GraphProfiler
B = GraphProfiler(loss, solver=solver, device_id=0, ext_name=device, n_run=100)
B.run()
print("Profile finished.")

# Report
from nnabla.utils.profiler import GraphProfilerCsvWriter
with open("./profile.csv", "w") as f:
    writer = GraphProfilerCsvWriter(B, file=f)
    writer.write()
print("Report is prepared.")

You can also find TimeProfiler to profile, but it is more fine-grained in measureing execution time.

With TimeProfiler, you can put a callback function to the forward and/or backward method in the training loop.

Value Tracer

We sometimes want to check if there exsits NaN/Inf. NanInfTracer is a convenient way to check if one of all layers in a graph has NaN/Inf value.

# Create graph again just in case
nn.clear_parameters()  # call this in case you want to run the following code agian

# Try to switch these two
x = nn.Variable.from_numpy_array(np.random.randn(*[4, 3, 64, 64]))
#x = nn.Variable([4, 3, 64, 64])
pred = network(x)

# NanInfTracer
from nnabla.utils.inspection import NanInfTracer
nit = NanInfTracer(trace_inf=True, trace_nan=True, need_details=True)

with nit.trace():
    # Try to comment either of these two or both
    pred.forward(function_post_hook=nit.forward_post_hook)
    pred.backward(function_post_hook=nit.backward_post_hook)

print(nit.check())

NNabla における静的 vs 動的ニューラルネットワーク

NNabla では、静的ニューラルと動的ニューラルネットワークを定義することができます。静的ニューラルネットワークは固定した層の構造、つまり、静的計算グラフを持ちます。対照的に、動的ニューラルネットワークは、例えばそれぞれのミニバッチに対してランダムに層をドロップするような動的計算グラフを使います。

このチュートリアルでは、 2 つの計算グラフを比較します。

%matplotlib inline
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S

import numpy as np
np.random.seed(0)

GPU = 0  # ID of GPU that we will use
2017-06-26 23:10:05,832 [nnabla][INFO]: Initializing CPU extension...
データセットの読み込み

まず、 scikit-learn から数字のデータセットをセットアップしましょう。

from tiny_digits import *

digits = load_digits()
data = data_iterator_tiny_digits(digits, batch_size=16, shuffle=True)
2017-06-26 23:10:06,042 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:10:06,043 [nnabla][INFO]: Using DataSourceWithMemoryCache
2017-06-26 23:10:06,044 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:10:06,044 [nnabla][INFO]: On-memory
2017-06-26 23:10:06,045 [nnabla][INFO]: Using DataIterator

このデータセットにあるサンプルは、それぞれ 8 x 8 サイズのグレースケール画像で、 01、 … 、 9 の 10 クラスの 1 つに属しています。

img, label = data.next()
print(img.shape, label.shape)
(16, 1, 8, 8) (16, 1)
ネットワークの定義

例として、 ( 不必要に深層である ) 深層 CNN を定義します。

def cnn(x):
    """Unnecessarily Deep CNN.

    Args:
        x : Variable, shape (B, 1, 8, 8)

    Returns:
        y : Variable, shape (B, 10)
    """
    with nn.parameter_scope("cnn"):  # Parameter scope can be nested
        with nn.parameter_scope("conv1"):
            h = F.tanh(PF.batch_normalization(
                PF.convolution(x, 64, (3, 3), pad=(1, 1))))
        for i in range(10):  # unnecessarily deep
            with nn.parameter_scope("conv{}".format(i + 2)):
                h = F.tanh(PF.batch_normalization(
                    PF.convolution(h, 128, (3, 3), pad=(1, 1))))
        with nn.parameter_scope("conv_last"):
            h = F.tanh(PF.batch_normalization(
                PF.convolution(h, 512, (3, 3), pad=(1, 1))))
            h = F.average_pooling(h, (2, 2))
        with nn.parameter_scope("fc"):
            h = F.tanh(PF.affine(h, 1024))
        with nn.parameter_scope("classifier"):
            y = PF.affine(h, 10)
    return y
静的計算グラフ

まず、学習中にニューラルネットワークが変化しない、静的計算グラフの場合を見ましょう。

from nnabla.ext_utils import get_extension_context

# setup cuda extension
ctx_cuda = get_extension_context('cudnn', device_id=GPU)  # replace 'cudnn' by 'cpu' if you want to run the example on the CPU
nn.set_default_context(ctx_cuda)

# create variables for network input and label
x = nn.Variable(img.shape)
t = nn.Variable(label.shape)

# create network
static_y = cnn(x)
static_y.persistent = True

# define loss function for training
static_l = F.mean(F.softmax_cross_entropy(static_y, t))
2017-06-26 23:10:06,350 [nnabla][INFO]: Initializing CUDA extension...
2017-06-26 23:10:06,571 [nnabla][INFO]: Initializing cuDNN extension...

学習のための solver のセットアップ

solver = S.Adam(alpha=1e-3)
solver.set_parameters(nn.get_parameters())

データ反復子の作成

loss = []
def epoch_end_callback(epoch):
    global loss
    print("[{} {} {}]".format(epoch, np.mean(loss), itr))
    loss = []

data = data_iterator_tiny_digits(digits, batch_size=16, shuffle=True)
data.register_epoch_end_callback(epoch_end_callback)
2017-06-26 23:10:07,221 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:10:07,224 [nnabla][INFO]: Using DataSourceWithMemoryCache
2017-06-26 23:10:07,226 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:10:07,228 [nnabla][INFO]: On-memory
2017-06-26 23:10:07,230 [nnabla][INFO]: Using DataIterator

学習の反復の実行と学習ロスの出力。

%%time
for epoch in range(30):
    itr = 0
    while data.epoch == epoch:
        x.d, t.d = data.next()
        static_l.forward(clear_no_need_grad=True)
        solver.zero_grad()
        static_l.backward(clear_buffer=True)
        solver.update()
        loss.append(static_l.d.copy())
        itr += 1
print()
[ 0 0.909297 112 ] [ 1 0.183863 111 ] [ 2 0.0723054 111 ] [ 3 0.0653021 112 ] [ 4 0.0628503 111 ] [ 5 0.0731626 111 ] [ 6 0.0319093 112 ] [ 7 0.0610926 111 ] [ 8 0.0817437 111 ] [ 9 0.0717577 112 ] [ 10 0.0241882 111 ] [ 11 0.0119452 111 ] [ 12 0.00664761 112 ] [ 13 0.00377711 111 ] [ 14 0.000605656 111 ] [ 15 0.000236613 111 ] [ 16 0.000174549 112 ] [ 17 0.000142428 111 ] [ 18 0.000126015 111 ] [ 19 0.000111144 112 ] [ 20 0.000100751 111 ] [ 21 9.03808e-05 111 ] [ 22 8.35904e-05 112 ] [ 23 7.73492e-05 111 ] [ 24 6.91389e-05 111 ] [ 25 6.74929e-05 112 ] [ 26 6.08386e-05 111 ] [ 27 5.62182e-05 111 ] [ 28 5.33428e-05 112 ] [ 29 4.94594e-05 111 ]
CPU times: user 14.3 s, sys: 6.78 s, total: 21.1 s
Wall time: 21.1 s
動的計算グラフ

次に、動的計算グラフを使います。ここでは、ニューラルネットワークを通して順方向 / 逆方向パスをしたい場合、毎回ニューラルネットワークがセットアップされます。これにより、例えば、ランダムに層をドロップアウトしたり、入力データに依存するネットワーク構造を持つことができます。ここでのサンプルでは、簡略化のため、同じニューラルネットワーク構造を使い、動的な生成のみを行います。例えば、 cnn()if np.random.rand() > dropout_probability: を加えると、層をドロップアウトできます。

まず、学習のために solver とデータ反復子をセットアップします。

nn.clear_parameters()
solver = S.Adam(alpha=1e-3)
solver.set_parameters(nn.get_parameters())

loss = []
def epoch_end_callback(epoch):
    global loss
    print("[{} {} {}]".format(epoch, np.mean(loss), itr))
    loss = []
data = data_iterator_tiny_digits(digits, batch_size=16, shuffle=True)
data.register_epoch_end_callback(epoch_end_callback)
2017-06-26 23:10:28,449 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:10:28,450 [nnabla][INFO]: Using DataSourceWithMemoryCache
2017-06-26 23:10:28,450 [nnabla][INFO]: DataSource with shuffle(True)
2017-06-26 23:10:28,451 [nnabla][INFO]: On-memory
2017-06-26 23:10:28,451 [nnabla][INFO]: Using DataIterator
%%time
for epoch in range(30):
    itr = 0
    while data.epoch == epoch:
        x.d, t.d = data.next()
        with nn.auto_forward():
            dynamic_y = cnn(x)
            dynamic_l = F.mean(F.softmax_cross_entropy(dynamic_y, t))
        solver.set_parameters(nn.get_parameters(), reset=False, retain_state=True) # this can be done dynamically
        solver.zero_grad()
        dynamic_l.backward(clear_buffer=True)
        solver.update()
        loss.append(dynamic_l.d.copy())
        itr += 1
print()
[ 0 1.04669 112 ] [ 1 0.151949 111 ] [ 2 0.093581 111 ] [ 3 0.129242 112 ] [ 4 0.0452591 111 ] [ 5 0.0343987 111 ] [ 6 0.0315372 112 ] [ 7 0.0336886 111 ] [ 8 0.0194571 111 ] [ 9 0.00923094 112 ] [ 10 0.00536065 111 ] [ 11 0.000669383 111 ] [ 12 0.000294232 112 ] [ 13 0.000245866 111 ] [ 14 0.000201116 111 ] [ 15 0.000164177 111 ] [ 16 0.00014832 112 ] [ 17 0.000131479 111 ] [ 18 0.000115171 111 ] [ 19 0.000101432 112 ] [ 20 9.06228e-05 111 ] [ 21 8.7103e-05 111 ] [ 22 7.79601e-05 112 ] [ 23 7.59678e-05 111 ] [ 24 6.64341e-05 111 ] [ 25 6.22717e-05 112 ] [ 26 5.8643e-05 111 ] [ 27 5.35373e-05 111 ] [ 28 4.96717e-05 112 ] [ 29 4.65124e-05 111 ]
CPU times: user 23.4 s, sys: 5.35 s, total: 28.7 s
Wall time: 28.7 s

2 つの処理時間を比べると、 ( “ 静的” も “動的” も ) どちらのスキームも同じ実行時間がかかることがわかります。つまり、計算グラフを動的に作成しても、パフォーマンスは下がらないということです。

Graph Converters

As neural networks becomes complex and one of components in a system, we sometimes want to convert a network as we want. Typical usecase is for inference. We want to merge or change some layers in a network as a high-level optimization for the inference speed. Also, there are other usecases: adding new layers to keep track some stats, adding quantize/dequantize layers for a quantized inference, decomposing a layer as combination of a low-rank ones, changing a network architecture for the neural architecture search based on an original network architecture, changing the tensor format from the channel first to channel last and opposite, and so on.

Let's look at the simple cases 1. batch normalization folding 2. channel last conversion

As a reference network, use the follows.

# ResNet-50 for inference
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import numpy as np
from nnabla.utils.inspection import pprint
from nnabla.models.imagenet import ResNet50

model = ResNet50()

batch_size = 1
x = nn.Variable((batch_size,) + model.input_shape)
y = model(x, training=False)
Batch Normalization Folding

See the resnet architecture.

pprint(y)

Now, we can see the batch normalization. For the inference, we do not need to compute the batch normalization explicitly by folding the batch normalization parameters if there is e.g., a convolution before the batch normalization.

To fold the batch normalization, use BatchNormalizationFoldingModifier as the following.

import nnabla.experimental.graph_converters as GC

modifiers = [GC.BatchNormalizationFoldingModifier()]
gc = GC.GraphConverter(modifiers)
yy = gc.convert(y)

Again, see the resnet architecture converted.

pprint(yy)

You can see that the converterd network does not contain the batch normalization any more!

In some cases, we can not fold the batch normalization, but the batch normalization can also be self-folded, i.e., the four parameters: scale, bias, running mean, running variance can be two other scale and bias. For doing this, use BatchNormalizationSelfFoldingModifier.

Channel Last Conversion

In NVIDIA latest GPU architectures since Volta, it supports TensorCore to accelerate the computatoinal performance. To boost the performance as maximum as possible, we need the channel-last tensor format aka NHWC. In NNabla, the default tensor format is the channel first aka NCHW, so as to utilize TensorCore, we need to change the tensor format to NHWC format.

ChannelLastModifier convert a network with NCHW tesnor format to another network with NHWC tensor format.

import nnabla.experimental.graph_converters as GC

modifiers = [GC.ChannelLastModifier([x])]
gc = GC.GraphConverter(modifiers)
yy = gc.convert(y)

Let's see the resnet architecture converted.

pprint(yy)

We can find the channel dimension changed at the last!

If we want to access to the inputs of which tensor format converted,

x_cl = modifiers[0].inputs_cl[0]
print(x_cl)

Note that ChannelLastModifier supports a set of layers: Convolution, Deconvolution, BatchNormalization, MaxPooling, AveragePooling, SumPooling, Unpooling, Concatenate and also supposes NCHW format.

There also exists ChannelFirstModifier in the opposite change.

Mixed Precision を用いた学習

はじめに

従来、ニューラルネットワークの学習の際には重みと活性値として FP32 ( 32bit 浮動小数点数 ) が用いられてきました。しかし、深層学習の成功とニューラルネットワークのサイズ増加に伴い、近年ニューラルネットワークの学習にかかる計算コストが急速に増えています。これは、製品の発売前に多くの試行錯誤を行うにあたり、巨大なサイズのニューラルネットワークの学習のためにより多くの時間が必要になっていることを示しています。この問題に対処するために、深層学習のためのハードウェアを提供する企業 ( 例 NVIDIA ) は計算を高速化するためのアクセラレーターを導入しました。例えば、NVIDIA の Volta 世代以降の GPU は計算を高速化するために Tensor Cores を備えています。

しかし、 FP16 ( 16bit 浮動小数点数 ) を重み、活性値、勾配に使うにあたり、 FP16 の表現力は FP32 と比較して大きく制限されています。つまり、 勾配の値のオーバーフローやアンダーフローが時々 ( あるいは、頻繁に ) 発生し、これによりニューラルネットワークのパフォーマンスに悪影響を及ぼしたり、学習の失敗を引き起こします。

Mixed Precision を用いた学習は、 FP32 ネットワークで得られるものと同じ結果を維持しながら問題を回避する方法の 1 つです。詳しくは、 混合精度学習のユーザーガイド混合精度学習 に記載しています。

このチュートリアルでは、 NNabla における Mixed Precision を用いた学習方法を段階的に説明します。

段階毎の説明

基本的には、 Mixed Precision を用いた学習は 次の 3 つの段階で構成されています。

  1. 計算のためのアクセラレーターの使用 ( ここでは Tensor Cores を仮定しています )

  2. オーバーフローを防ぐためのロススケーリングの使用

  3. オーバーフロー / アンダーフローを防ぐための動的ロススケーリングの使用

NNabla では、次のように対応できます。

1. Tensor Cores の使用
ctx = get_extension_context("cudnn", type_config="half")
2. アンダーフローを防ぐためのロススケーリングの使用
loss_scale = 8
loss.backward(loss_scale)
solver.scale_grad(1. / loss_scale)  # do some gradient clipping, etc. after this
solver.update()
3. オーバーフロー / アンダーフローを防ぐための動的ロススケーリングの使用
loss_scale = 8
scaling_factor = 2
counter = 0
interval = 2000
...
loss.backward(loss_scale, ...)
...
if solver.check_inf_or_nan_grad():
    loss_scale /= scaling_factor
    counter = 0
else:
    solver.scale_grad(1. / loss_scale) # do some gradient clipping, etc. after this
    solver.update()
    if counter > interval:
        loss_scale *= scaling_factor
        counter = 0
    counter += 1

: 手順の 2 番目 ( アンダーフローを防ぐためのロス・スケーリングの使用 ) と 3 番目 ( オーバーフローを防ぐためのロス・スケーリングの使用 ) は、現在実験段階であり、混合精度学習の高速化に尽力しています。そのため、 API 、特に 3 番目は、将来の使用のため変わる可能性があります。

全ての処理を含んだ説明

前述の段階的な説明では、学習ループ内における 3 番目のステップが非常に長くなっています。代わりにここは次のようなラッパークラスを書くことができます。

class DynamicLossScalingUpdater(object):
    '''Dynamic Loss Scaling Updater for the mixed precision training.

    Args:
        solver (:obj:`nnabla.solvers.Solver`): Solver object. E.g., Momentum or Adam.
        loss (:obj:`nnabla.Variable`): Loss variable from which the forward and the backward is called.
        data_feeder (callable :obj:`object`, function, or lambda): Data feeder
        scale (:obj:`float`): Loss scale constant. This is dynamically changing during training.
        scaling_factor (:obj:`float`): Scaling factor for the dynamic loss scaling.
        N (:obj:`int`): Interval, the number of iterations in training for increasing `loss scale` by `scaling_factor`.
        clear_buffer (:obj:`bool`): Clears the no longer referenced variables during backpropagation to save memory.
        accum_grad (:obj:`int`): Number of accumulation of gradients. Update method of the `solver` is called after the `accum_grad` number of the forward and backward is called.
        weight_decay (:obj:`float`): Decay constant. Default is `None`, not applying the weight decay.
        comm (:obj:`nnabla.communicators.Communicator`): Communicator when to do distributed training. Default is :obj:`None`.
        grads (:obj:`list` of :obj:`nnabla._nd_array.NdArray`): The list of gradients to be exchanged when to do distributed training. Default is the empty :obj:`list`.

    Attributes:
        solver (:obj:`nnabla.solvers.Solver`): Solver object. E.g., Momentum or Adam.
        loss (:obj:`nnabla.Variable`): Loss variable from which the forward and the backward is called.
        data_feeder (callable :obj:`object`, function, lambda): Data feeder
        scale (:obj:`float`): Loss scale constant. This is dynamically changing during training.
        scaling_factor (:obj:`float`): Scaling factor for the dynamic loss scaling.
        N (:obj:`int`): Interval, the number of iterations in training for increasing `loss scale` by `scaling_factor`.
        clear_buffer (:obj:`bool`): Clears the no longer referenced variables during backpropagation to save memory.
        accum_grad (:obj:`int`): Number of accumulation of gradients. Update method of the `solver` is called after the `accum_grad` number of the forward and backward is called.
        weight_decay (:obj:`float`): Decay constant. Default is `None`, not applying the weight decay.
        comm (:obj:`nnabla.communicators.Communicator`): Communicator when to do distributed training.
        grads (:obj:`list` of :obj:`nnabla._nd_array.NdArray`): The list of gradients to be exchanged when to do distributed training.

    Example:

        .. code-block:: python
            solver = <Solver>
            loss = <Loss Variable of Network>
            data_feeder = <DataFeeder>

            updater = DynamicLossScalingUpdater(solver, loss, data_feeder)

            # Training iteration
            for itr in range(max_iter):
                # Call solver.zero_grad, data_feeder, loss.forward, loss.backward
                # and solver.update with the dynamic loss scaling.
                updater.update()

    Reference:

        https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html#scalefactor

    '''

    def __init__(self, solver, loss, data_feeder=lambda x: x,
                  scale=8.0, scaling_factor=2.0, N=2000, clear_buffer=True,
                  accum_grad=1, weight_decay=None,
                  comm=None,
                  grads=[]):
        self.solver = solver
        self.loss = loss
        self.data_feeder = data_feeder
        self.scale = scale
        self.scaling_factor = scaling_factor
        self.N = N
        self.clear_buffer = clear_buffer
        self.accum_grad = accum_grad
        self.weight_decay = weight_decay
        self.comm = comm
        self.grads = grads
        self._counter = 0
        self._recursive_count = 0
        self._max_recursive_count = 100

    def update(self):
        """Monolithic update method.

        This method calls the following methods with the dynamic loss scaling.

        1. solver.zerograd
        2. feed data
        3. loss.forward
        4. loss.backward
        5. comm.all_reduce (if it is specified)
        6. solver.update

        """

        # Initialize gradients.
        self.solver.zero_grad()

        # Forward and backward
        for _ in range(self.accum_grad):
            # feed data
            self.data_feeder()

            # forward
            self.loss.forward(clear_no_need_grad=self.clear_buffer)

            # backward with scale
            self.loss.backward(self.scale, clear_buffer=self.clear_buffer)

        # AllReduce
        if self.comm and len(self.grads) != 0:
            self.comm.all_reduce(self.grads, division=False, inplace=False)

        # Check Inf/NaN in grads
        if self.solver.check_inf_or_nan_grad():
            self.scale /= self.scaling_factor
            self._counter = 0

            # Recursively call udpate function until no inf nor nan.
            self._recursive_count += 1
            if self._recursive_count > self._max_recursive_count:
                self._recursive_count = 0
                return  # skip
            return self.update()
        self._recursive_count = 0

        # Rescale grads
        self.solver.scale_grad(1. / self.scale)

        # Do some gradient clipping, etc.
        if self.weight_decay is not None:
            self.solver.weight_decay(self.weight_decay)

        # Update
        self.solver.update()
        if self._counter > self.N:
            self.scale *= self.scaling_factor
            self._counter = 0
        self._counter += 1

その後、学習・ループ内で更新メソッドを呼びます。

from nnabla.experimental.mixed_precision_training import DynamicLossScalingUpdater

solver = <Solver>
loss = <Loss Variable of Network>
data_feeder = <DataFeeder>

updater = DynamicLossScalingUpdater(solver, loss, data_feeder)

# Training iteration
for itr in range(max_iter):
    # Call solver.zero_grad, data_feeder, loss.forward, loss.backward
    # and solver.update with the dynamic loss scaling.
    updater.update()
注意

Mixed Precision を用いた学習では、次のような動作になります。

  1. Solver は FP16 の重みと FP32 の重みのコピーを保持します。 type_config="half" が指定されると、 NNabla における Solver は FP32 の重みと重みの勾配を保持し、それを順方向パスで FP16 の重みへキャストし、逆方向パスで FP16 の重みの勾配へキャストします。

  2. batch-normalization、 Mean、 Sum、 SoftMax、 SoftMaxCrossEntropy などによって計算される統計量 ( 平均や分散 ) の演算には、 FP32 を使用してください ( 混合精度学習のユーザーガイド を参照してください) 。 NNabla では、 type_config="half" を指定した場合もこれらの関数は 自動的に FP32 を使うようにフォールバックされます。

データ並列分散学習

DataParallelCommunicator は、複数のデバイスを使ってニューラルネットワークを学習することができます。 DataParallelCommunicator は通常、データ並列分散学習において勾配交換に使われます。基本的に、ニューラルネットワークには、 データ並列とモデル並列、 2 つのタイプの分散学習があります。ここでは、前者のデータ並列学習のみに焦点を当てます。データ並列分散学習は、 ( ミニバッチ ) 確率的勾配降下法と呼ばれるニューラルネットワークの最適化に使われる非常に簡単な式に基づいています。

最適化プロセスにおいて、最小化を試みる目的関数は以下となります。

\[f(\mathbf{w}; X) = \frac{1}{B \times N} \sum_{i=1}^{B \times N} \ell(\mathbf{w}, \mathbf{x}_i),\]

ここで、 \(f\) はニューラルネットワーク、 \(B \times N\) はバッチサイズ、 \(\ell\) はそれぞれのデータポイント \(\mathbf{x} \in X\) に対する loss 関数、 \(\mathbf{w}\) はニューラルネットワークの学習可能なパラメータを表しています。

この関数を微分すると、以下が得られます。

\[\nabla_{\mathbf{w}} f(\mathbf{w}; X) = \frac{1}{B \times N} \sum_{i=1}^{B \times N} \nabla_{\mathbf{w}} \ell (\mathbf{w}, \mathbf{x}_i).\]

この導関数は線形なので、上記の目的関数を各 \(B\) データポイントにおける導関数の合計の総和に変えることができます。

\[\nabla_{\mathbf{w}} f(\mathbf{w}; X) = \frac{1}{N} \left( \frac{1}{B} \sum_{i=1}^{B} \nabla_{\mathbf{w}} \ell (\mathbf{w}, \mathbf{x}_i) \ + \frac{1}{B} \sum_{i=B+1}^{B \times 2} \nabla_{\mathbf{w}} \ell (\mathbf{w}, \mathbf{x}_i) \ + \ldots \ + \frac{1}{B} \sum_{i=B \times (N-1) + 1}^{B \times N} \nabla_{\mathbf{w}} \ell (\mathbf{w}, \mathbf{x}_i) \right)\]

データ並列分散学習では、上記の式に従って次のステップが実行されます。

  1. 各項ごとに、導関数 ( 勾配 ) の合計をバッチサイズ \(B\) で割る計算を個別のデバイス ( 一般的には GPU ) で行い、

  2. それらのデバイスの結果を総和し、

  3. その結果をデバイスの個数 \(N\) で割ります。

これはデータ並列分散学習の基礎となります。

このチュートリアルでは、とても簡単なサンプルを使って、データ並列分散学習に対する Multi Process Data Parallel Communicator の使い方を示します。

注意

このチュートリアルは IPython Cluster に依拠しているため、次のような Jupyter Notebook のスクリプトの抜粋を実行する場合は、 ここ に従い mpiexec/mpirun モードを有効し、Ipython Clusters タブで対応する Ipython Cluster を起動します。

クライアントの起動

以下のコードは、 Jupyter Notebook を用いるこのチュートリアル のみ で必要となります。

import ipyparallel as ipp
rc = ipp.Client(profile='mpi')
依存関係の準備
%%px
import os
import time

import nnabla as nn
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context
import nnabla.functions as F
from nnabla.initializer import (
    calc_uniform_lim_glorot,
    UniformInitializer)
import nnabla.parametric_functions as PF
import nnabla.solvers as S
import numpy as np
勾配交換のためのコミュニケーターの定義
%%px
extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()
n_devices = comm.size
mpi_rank = comm.rank
device_id = mpi_rank
ctx = get_extension_context(extension_module, device_id=device_id)

異なるランクが異なるデバイスに割り当てられていることを確認します

%%px
print("n_devices={}".format(n_devices))
print("mpi_rank={}".format(mpi_rank))
[stdout:0]
n_devices=2
mpi_rank=1
[stdout:1]
n_devices=2
mpi_rank=0
データポイントととても簡単なニューラルネットワークの作成
%%px
# Data points setting
n_class = 2
b, c, h, w = 4, 1, 32, 32

# Data points
x_data = np.random.rand(b, c, h, w)
y_data = np.random.choice(n_class, b).reshape((b, 1))
x = nn.Variable(x_data.shape)
y = nn.Variable(y_data.shape)
x.d = x_data
y.d = y_data

# Network setting
C = 1
kernel = (3, 3)
pad = (1, 1)
stride = (1, 1)
%%px
rng = np.random.RandomState(0)
w_init = UniformInitializer(
                    calc_uniform_lim_glorot(C, C/2, kernel=(1, 1)),
                    rng=rng)
%%px
# Network
with nn.context_scope(ctx):
    h = PF.convolution(x, C, kernel, pad, stride, w_init=w_init)
    pred = PF.affine(h, n_class, w_init=w_init)
    loss = F.mean(F.softmax_cross_entropy(pred, y))

留意事項 ここでは、最適化プロセスにおいて、各 GPU のネットワークが学習可能なパラメータ同士の同じ値から開始できるように w_init をパラメトリック関数に渡しています。

Solver の作成
%%px
# Solver and add parameters
solver = S.Adam()
solver.set_parameters(nn.get_parameters())
学習

ニューラルネットワークを学習するための nnabla API の基本的な使い方を思い出しましょう。

  1. loss.forward()

  2. solver.zero_grad()

  3. loss.backward()

  4. solver.update()

C.MultiProcessCommunicator を使用する場合、これらのステップは異なる GPU で実行され、これらのステップと 唯一異なる のは comm.all_reduce() です。従って、 C.MultiProcessCommunicator の場合、学習のステップは次のようになります。

  1. loss.forward()

  2. solver.zero_grad()

  3. loss.backward()

  4. comm.all_reduce([x.grad for x in nn.get_parameters().values()])

  5. solver.update()

まず、順方向、 zero_grad 、そして逆方向。

%%px
# Training steps
loss.forward()
solver.zero_grad()
loss.backward()

一度、重みの勾配を確かめます。

%%px
for n, v in nn.get_parameters().items():
    print(n, v.g)
[stdout:0]
('conv/W', array([[[[ 5.0180483,  0.457942 , -2.8701296],
         [ 2.0715926,  3.0698593, -1.6650047],
         [-2.5591214,  6.4248834,  9.881935 ]]]], dtype=float32))
('conv/b', array([8.658947], dtype=float32))
('affine/W', array([[-0.93160367,  0.9316036 ],
       [-1.376812  ,  1.376812  ],
       [-1.8957546 ,  1.8957543 ],
       ...,
       [-0.33000934,  0.33000934],
       [-0.7211893 ,  0.72118926],
       [-0.25237036,  0.25237036]], dtype=float32))
('affine/b', array([-0.48865744,  0.48865741], dtype=float32))
[stdout:1]
('conv/W', array([[[[ -1.2505884 ,  -0.87151337,  -8.685524  ],
         [ 10.738419  ,  14.676786  ,   7.483423  ],
         [  5.612471  , -12.880402  ,  19.141157  ]]]], dtype=float32))
('conv/b', array([13.196114], dtype=float32))
('affine/W', array([[-1.6865108 ,  1.6865108 ],
       [-0.938529  ,  0.938529  ],
       [-1.028422  ,  1.028422  ],
       ...,
       [-0.98217344,  0.98217344],
       [-0.97528917,  0.97528917],
       [-0.413546  ,  0.413546  ]], dtype=float32))
('affine/b', array([-0.7447065,  0.7447065], dtype=float32))

それぞれのデバイスで異なる値を確認できたら、 all_reduce を呼び出します。

%%px
comm.all_reduce([x.grad for x in nn.get_parameters().values()], division=True)

一般に、 all_reduce は合計を意味するだけですが、 comm.all_reduce は合計と加算除算どちらの場合にも対応します。

再度、重みの勾配を確かめます。

%%px
for n, v in nn.get_parameters().items():
    print(n, v.g)
[stdout:0]
('conv/W', array([[[[ 1.8837299 , -0.20678568, -5.777827  ],
         [ 6.4050055 ,  8.8733225 ,  2.9092093 ],
         [ 1.5266749 , -3.2277591 , 14.511546  ]]]], dtype=float32))
('conv/b', array([21.85506], dtype=float32))
('affine/W', array([[-2.6181145,  2.6181145],
       [-2.315341 ,  2.315341 ],
       [-2.9241767,  2.9241762],
       ...,
       [-1.3121828,  1.3121828],
       [-1.6964785,  1.6964784],
       [-0.6659163,  0.6659163]], dtype=float32))
('affine/b', array([-1.233364 ,  1.2333639], dtype=float32))
[stdout:1]
('conv/W', array([[[[ 1.8837299 , -0.20678568, -5.777827  ],
         [ 6.4050055 ,  8.8733225 ,  2.9092093 ],
         [ 1.5266749 , -3.2277591 , 14.511546  ]]]], dtype=float32))
('conv/b', array([21.85506], dtype=float32))
('affine/W', array([[-2.6181145,  2.6181145],
       [-2.315341 ,  2.315341 ],
       [-2.9241767,  2.9241762],
       ...,
       [-1.3121828,  1.3121828],
       [-1.6964785,  1.6964784],
       [-0.6659163,  0.6659163]], dtype=float32))
('affine/b', array([-1.233364 ,  1.2333639], dtype=float32))

all_reduce を使うことで、これらのデバイス上で同じ値を確認できます。

重みを更新します。

%%px
solver.update()

これで、データ並列分散学習に対する C.MultiProcessDataCommunicator の使用については終了です。

さて、 C.MultiProcessCommunicator の使い方について理解できたら、さらに詳細については 以下の cifar10 example を参照してください。

  1. classification.py

​​​

Advanced Topics

When working with multiple nodes with multiple devices (e.g. GPUs), one or a few of them might stop response for some special cases. When your training process originally takes time, it is hard to identify the elapsed time is in training or for dead device.

In current implementation, we introduced the watch dog in all_reduce(). When any node or any device stop response, the watch dog will raise an exception. The typical time for all_reduce() is 60 seconds. It means the process in any node or any device cannot wait at all_reduce() for more than 60 seconds, otherwise, some node or device might highly definitely stop response.

The watch dog is default disabled, if want to enable it, please set environment variable NNABLA_MPI_WATCH_DOG_ENABLE to any none-zero value:

export NNABLA_MPI_WATCH_DOG_ENABLE=1

But in pratice, some task required to be performed on one a few of nodes, and let other nodes wait there. If no explicitly sychronization, the watch dog might be unexpectedly triggered. As the following:

extension_module = "cudnn"
type_config = "float"
ctx = get_extension_context(extension_module, type_config=type_config)
comm = C.MultiProcessDataParalellCommunicator(ctx)
comm.init()

if comm.rank == 0:
   ...  # Here, we do some task on node 0

if comm.rank != 0:
   ...  # here, we do some task on other nodes

 # Till here, multiple nodes has different progress

 for d in data_iterator():
     ...
     comm.all_reduce(...)  # Here, since different nodes has different
                           # start points, all_reduce() might trigger
                           # watch dog timeout exception.

In order to avoid above unexpected exception, we have to explicitly set the synchronization point.

extension_module = "cudnn"
type_config = "float"
ctx = get_extension_context(extension_module, type_config=type_config)
comm = C.MultiProcessDataParalellCommunicator(ctx)
comm.init()

if comm.rank == 0:
   ...  # Here, we do some task on node 0

if comm.rank != 0:
   ...  # here, we do some task on other nodes

 comm.barrier()  # we placed the synchronization point immediate before
                 # comm.all_reduce().

 for d in data_iterator():
     ...
     comm.all_reduce(...) # The wait time at all_reduce() should be strictly
                          # limited in a relative short time.

We placed the synchronization point immediately before comm.all_reduce(), which means that we knew comm.all_reduce() should be perform synchronously after this point. Thus, we may ensure the whole training can be performed stably and not need to wait forever due to a corrupted process.

関数リストとコンバーター

nnabla_cli は nnabla のコマンドラインインターフェイスです。このコマンドラインインターフェイスを使って、ユーザーは現在の NNabla のサポート状況や nnabla のモデル ( 例 *.nnp ) を他のモデルのフォーマット ( 例 *.onnx ) に変換できるかどうか、またはその方法を知ることができます。

サブコマンド function_info は、nnablaですでに実装されている関数のリストを出力してくれます。 この情報により、モデルに合った nnabla-c-runtime ライブラリを構築したり、対象モデルに対してサポートされていない関数をスキップすることができます。

簡単なユースケース

簡単なユースケースをいくつか紹介しましょう。

まず、nnabla が現在サポートしている関数やその数を知りたい場合です。

$ nnabla_cli function_info

次のリストが得られます。

2019-06-14 16:16:13,106 [nnabla][INFO]: Initializing CPU extension...
NNabla command line interface (Version:1.0.18.dev1, Build:190531084842)
LSTM
Sub2
Mul2
GreaterEqual
Sigmoid
NotEqual
Unpooling
Log
CategoricalCrossEntropy
...

これは、現在 nnabla でサポートされているすべての関数のリストです。名前によって関数を探す目的のみのため、詳細はなく、関数名だけが表示されます。各関数の詳細については、オンラインドキュメントで調べる必要があります。

ご存じのように、 nnabla のモデル *.nnp は接尾辞 .nnb を持つコンパクトバージョンに変換することができ 、 nnabla-c-runtime ライブラリによる推論に用いることが可能です。 このフォーマットを簡潔に NNB と名付けました。このフォーマットでサポートされている関数がいくつあるかを知るために、このコマンドを使うことができます。

$ nnabla_cli function_info -f NNB

上記と同様に、関数リストが表示されます。

指定した.nnpモデルで使われている関数を調べることもできます。

$ nnabla_cli function_info my_model.nnp

上記と同様に、このモデルで使われる関数リストが列挙されます。

そして、使用しているモデルを nnabla-c-runtime モデルフォーマットに変換できるかどうかを知ることができます。厳密には、 .nnp における関数セットと nnabla-c-runtime がサポートする関数セットの共通部分を知ることができます。

$ nnabla_cli function_info my_model.nnp -f NNB

この出力は次のようになります。

2019-06-14 17:01:29,393 [nnabla][INFO]: Initializing CPU extension...
NNabla command line interface (Version:1.0.18.dev1, Build:190531084842)
Importing mnist_nnp/lenet_010000.nnp
 Expanding runtime.
nnabla-c-runtime currently support the following functions in model:
Convolution
MulScalar
Affine
MaxPooling
ReLU
...

また、このモデルでサポートされていない関数がある場合は、それらもリストアップされます。

適合する nnabla-c-runtime ライブラリ

nnabla-c-runtime ライブラリを実装するとき、できる限りすべての関数を含んだ状態で実装したいところです。しかし、顧客の観点からはそこまでの必要はない場合もあります。ユーザーが可算モデルに対して nnabla-c-runtime を使いたいだけならば、 nnabla-c-runtime はこのモデルが必要とする演算セットだけを含んでいれば十分です。これはどのように行うのでしょうか?

それは、次のステップで実装できます。

  1. 関数リストの生成

  2. nnabla-c-runtime ライブラリのコンフィグ

  3. nnabla-c-runtime ライブラリの構築

1. 関数リストの生成
$ nnabla_cli function_info my_model.nnp -f NNB -o functions.txt

これは、どのファイルに記述するかを指定する -o パラメータ以外は上記と同じです。 ( もちろんフォーマットは標準出力 へ出力されるバージョンと異なり、よりコンパクトです )

2. nnabla-c-runtime ライブラリのコンフィグ

ユーザーは手動で functions.txt を変更することができます。そして、このファイルは入力として使われ、 nnabla-c-runtime ライブラリのコンフィグファイルを生成するために使われます。

$ nnabla_cli function_info -c functions.txt -o nnabla-c-runtime/build-tools/code-generator/functions.yaml

-c オプションがない場合は、 nnabla で実装されている関数セットすべてを含む形でコンフィグファイルが作成されます。この場合、作成されるライブラリにはすべての関数が含まれることになります ( デフォルトではこのような動作になります ) 。

3. nnabla-c-runtime ライブラリの構築

ビルドプロセスは、次のように比較的直接的です。

#> nnabla-c-runtime>mkdir build
#> nnabla-c-runtime>cd build
#> nnabla-c-runtime>cmake ..
#> nnabla-c-runtime>make

nnabla-c-runtime ライブラリの libnnablart_functions.a には、必要な関数が入っています。

サポートされていない関数のスキップ

*.nnp*.onnx または *.nnb に変換したいとき、対象のフォーマットではサポートされていない関数があります。例えば、ネットワークを nnabla-c-runtime に変換したいとします。ネットワークは以下のようになります。

Affine
Softmax
Tanh
Convolution
MaxPooling
ReLU

nnabla-c-runtime ライブラリの Convolution を使いたくないとします。その際には、 Convolution 演算の箇所でネットワークを 2 つに分割することになります。そのためには、次の 2 ステップが必要です。

  1. functions.txt で関数をコメントアウト

  2. -c パラメータでネットワークを変換

1. functions.txt で関数をコメントアウト
...
;Affine
...
2. -c パラメータでネットワークを変換
$ nnabla_cli convert -c functions.txt a.nnp b.nnb

このように、ネットワークを分割すると、次のように出力されます。

...
LeNet_036_0_5.nnb:
  input:
  - name: Input
    shape: (-1, 1, 28, 28)
  output:
  - name: Tanh_2
    shape: (-1, 30, 4, 4)
LeNet_036_7_7.nnb:
  input:
  - name: Affine
    shape: (-1, 150)
  output:
  - name: ReLU_2
    shape: (-1, 150)
LeNet_036_9_9.nnb:
  input:
  - name: Affine_2
    shape: (-1, 10)
  output:
  - name: Softmax
    shape: (-1, 10)

ネットワークは Affine 関数の箇所で分割されます。ネットワークに 2 つの Affine があるので、 3 つのサブネットワークが生成されます。

ONNX への変換

次のコマンドは、上記と同様の動作を行い、 *.onnx ファイルへと変換を行います。

サポートされているすべての関数を列挙します。

$ nnabla_cli function_info -f ONNX

モデルと ONNX によってサポートされている関数セットの共通部分を列挙します。

$ nnabla_cli function_info LeNet_036.nnp -f ONNX

ネットワークを分割して、いくつかの関数をスキップします。

$ nnabla_cli convert -c functions.txt a.nnp a.onnx

Python コマンドラインインターフェイス

NNabla は、学習したり、推論 ( フォワード ) を実行したり、パラメータやデータセットを変換したり、パフォーマンスを測定したり、ファイルを変換したりすることなどができる、コマンドラインインターフェイスのユーティリティを持っています。

usage: nnabla_cli [-h] [-m]
                  {train,infer,forward,encode_param,decode_param,profile,conv_dataset,compare_with_cpu,create_image_classification_dataset,upload,create_tar,function_info,optimize,dump,nnb_template,convert,plot_series,plot_timer,draw_graph,version}
                  ...

Command line interface for NNabla(Version 1.0.11.dev1, Build 181226024531)

positional arguments:
  {train,infer,forward,encode_param,decode_param,profile,conv_dataset,compare_with_cpu,create_image_classification_dataset,upload,create_tar,function_info,optimize,dump,nnb_template,convert,plot_series,plot_timer,draw_graph,version}
    train               Training with NNP.
    infer               Do inference with NNP and binary data file input.
    forward             Do evaluation with NNP and test dataset.
    encode_param        Encode plain text to parameter format.
    decode_param        Decode parameter to plain text.
    profile             Profiling performance with NNP.
    conv_dataset        Convert CSV dataset to cache.
    compare_with_cpu    Compare performance between two nntxt.
    create_image_classification_dataset
                        Create dataset from image files.
    upload              Upload dataset to Neural Network Console.
    create_tar          Create tar file for Neural Network Console.
    function_info       Output function info.
    optimize            Optimize pb model.
    dump                Dump network with supported format.
    nnb_template        Generate NNB config file template.
    convert             File format converter.
    plot_series         Plot *.series.txt files.
    plot_timer          Plot *.timer.txt files.
    draw_graph          Draw a graph in a NNP or nntxt file with graphviz.
    version             Print version and build number.

optional arguments:
  -h, --help            show this help message and exit
  -m, --mpi             exec with mpi.

NNP での作業

学習
usage: nnabla_cli train [-h] -c CONFIG [-p PARAM] -o OUTDIR

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        path to nntxt
  -p PARAM, --param PARAM
                        path to parameter file
  -o OUTDIR, --outdir OUTDIR
                        output directory
プロファイル
usage: nnabla_cli profile [-h] -c CONFIG -o OUTDIR

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        path to nntxt
  -o OUTDIR, --outdir OUTDIR
                        output directory
CSV データセットを用いた推論
usage: nnabla_cli forward [-h] -c CONFIG [-p PARAM] [-d DATASET] -o OUTDIR [-b BATCH_SIZE]

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        path to nntxt
  -p PARAM, --param PARAM
                        path to parameter file
  -d DATASET, --dataset DATASET
                        path to CSV dataset
  -o OUTDIR, --outdir OUTDIR
                        output directory
  -b BATCH_SIZE, --batch_size BATCH_SIZE
                        Batch size to use batch size in nnp file set -1.
バイナリデータを用いた推論
usage: nnabla_cli infer [-h] -c CONFIG [-o OUTPUT] [-p PARAM] [-b BATCH_SIZE] inputs [inputs ...]

positional arguments:
  inputs

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        path to nntxt
  -o OUTPUT, --output OUTPUT
                        output file prefix
  -p PARAM, --param PARAM
                        path to parameter file
  -b BATCH_SIZE, --batch_size BATCH_SIZE
                        Batch size to use batch size in nnp file set -1.
CPU による比較
usage: nnabla_cli compare_with_cpu [-h] -c CONFIG -c2 CONFIG2 -o OUTDIR

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        path to nntxt
  -c2 CONFIG2, --config2 CONFIG2
                        path to cpu nntxt
  -o OUTDIR, --outdir OUTDIR
                        output directory

データセットの操作

パラメータのエンコード
usage: nnabla_cli encode_param [-h] -i INDIR [-p PARAM]

optional arguments:
  -h, --help            show this help message and exit
  -i INDIR, --indir INDIR
                        input directory
  -p PARAM, --param PARAM
                        path to parameter file
パラメータのデコード
usage: nnabla_cli decode_param [-h] [-p PARAM] -o OUTDIR

optional arguments:
  -h, --help            show this help message and exit
  -p PARAM, --param PARAM
                        path to parameter file
  -o OUTDIR, --outdir OUTDIR
                        output directory
データセットの変換
usage: nnabla_cli conv_dataset [-h] [-F] [-S] [-N] source destination

positional arguments:
  source
  destination

optional arguments:
  -h, --help       show this help message and exit
  -F, --force      force overwrite destination
  -S, --shuffle    shuffle data
  -N, --normalize  normalize data range
画像分類データセットの作成
usage: nnabla_cli create_image_classification_dataset [-h] -i SOURCEDIR -o OUTDIR -c CHANNEL -w WIDTH -g HEIGHT -m MODE -s SHUFFLE -f1 FILE1 [-r1 RATIO1] [-f2 FILE2]
                                                      [-r2 RATIO2]

optional arguments:
  -h, --help            show this help message and exit
  -i SOURCEDIR, --sourcedir SOURCEDIR
                        source directory with directories for each class
  -o OUTDIR, --outdir OUTDIR
                        output directory
  -c CHANNEL, --channel CHANNEL
                        number of output color channels
  -w WIDTH, --width WIDTH
                        width of output image
  -g HEIGHT, --height HEIGHT
                        height of output image
  -m MODE, --mode MODE  shaping mode (trimming or padding)
  -s SHUFFLE, --shuffle SHUFFLE
                        shuffle mode (true or false)
  -f1 FILE1, --file1 FILE1
                        output file name 1
  -r1 RATIO1, --ratio1 RATIO1
                        output file ratio(%) 1
  -f2 FILE2, --file2 FILE2
                        output file name 2
  -r2 RATIO2, --ratio2 RATIO2
                        output file ratio(%) 2
Neural Network Console へデータセットをアップロード
usage: nnabla_cli upload [-h] [-e ENDPOINT] token filename

positional arguments:
  token                 token for upload
  filename              filename to upload

optional arguments:
  -h, --help            show this help message and exit
  -e ENDPOINT, --endpoint ENDPOINT
                        set endpoint uri
Neural Network Console 用のデータセットのアーカイブ作成
usage: nnabla_cli create_tar [-h] source destination

positional arguments:
  source       CSV dataset
  destination  TAR filename

optional arguments:
  -h, --help   show this help message and exit

ファイルのフォーマット変換

詳細は ファイルフォーマットコンバーター を参照してください。

サポートされるフォーマットの内容をダンプする
usage: nnabla_cli dump [-h] [-v] [-F] [-V] [--dump-limit DUMP_LIMIT]
                       [-n DUMP_VARIABLE_NAME] [-I IMPORT_FORMAT]
                       [-E NNP_IMPORT_EXECUTOR_INDEX]
                       [--nnp-exclude-preprocess] [--nnp-no-expand-network]
                       FILE [FILE ...]

positional arguments:
  FILE                  File or directory name(s) to convert.

optional arguments:
  -h, --help            show this help message and exit
  -v, --dump-verbose    [dump] verbose output.
  -F, --dump-functions  [dump] dump function list.
  -V, --dump-variables  [dump] dump variable list.
  --dump-limit DUMP_LIMIT
                        [dump] limit num of items.
  -n DUMP_VARIABLE_NAME, --dump-variable-name DUMP_VARIABLE_NAME
                        [dump] Specific variable name to display.
  -I IMPORT_FORMAT, --import-format IMPORT_FORMAT
                        [import] import format. (one of [NNP,ONNX])
  -E NNP_IMPORT_EXECUTOR_INDEX, --nnp-import-executor-index NNP_IMPORT_EXECUTOR_INDEX
                        [import][NNP] import only specified executor.
  --nnp-exclude-preprocess
                        [import][NNP] EXPERIMENTAL exclude preprocess
                        functions when import.
  --nnp-no-expand-network
                        [import][NNP] expand network with repeat or recurrent.
NNB のコンフィグファイルのテンプレート生成
usage: nnabla_cli nnb_template [-h] [-I IMPORT_FORMAT]
                               [--nnp-no-expand-network] [-b BATCH_SIZE]
                               [-T DEFAULT_VARIABLE_TYPE]
                               FILE [FILE ...]

positional arguments:
  FILE                  File or directory name(s) to convert.

optional arguments:
  -h, --help            show this help message and exit
  -I IMPORT_FORMAT, --import-format IMPORT_FORMAT
                        [import] import format. (one of [NNP,ONNX])
  --nnp-no-expand-network
                        [import][NNP] expand network with repeat or recurrent.
  -b BATCH_SIZE, --batch-size BATCH_SIZE
                        [export] overwrite batch size.
  -T DEFAULT_VARIABLE_TYPE, --default-variable-type DEFAULT_VARIABLE_TYPE
                        Default type of variable
ファイルのフォーマット変換
usage: nnabla_cli convert [-h] [-I IMPORT_FORMAT] [--nnp-no-expand-network]
                          [-O EXPORT_FORMAT] [-f] [-b BATCH_SIZE]
                          [--nnp-parameter-h5] [--nnp-parameter-nntxt]
                          [--nnp-exclude-parameter] [-T DEFAULT_VARIABLE_TYPE]
                          [-s SETTINGS] [-c CONFIG] [-d DEFINE_VERSION] [--api API]
                          [--enable-optimize-pb] [--outputs OUTPUTS]
                          [--inputs INPUTS] FILE [FILE ...]

positional arguments:
  FILE                  File or directory name(s) to convert.
                        (When convert ckpt format of the tensorflow model,
                        If the version of the checkpoint is V1, need to enter the `.ckpt` file,
                        otherwise need to enter the `.meta` file.)

optional arguments:
  -h, --help            show this help message and exit
  -I IMPORT_FORMAT, --import-format IMPORT_FORMAT
                        [import] import format. (one of [NNP,ONNX,TF_CKPT_V1,TF_CKPT_V2,TF_PB,SAVED_MODEL,TFLITE])
  --nnp-no-expand-network
                        [import][NNP] expand network with repeat or recurrent.
  --outputs OUTPUTS
                        [import][tensorflow] The name(s) of the output nodes, comma separated.
                                             Only needed when convert CKPT format.
  --inputs INPUTS
                        [import][tensorflow] The name(s) of the input nodes, comma separated.
                                             Only needed when convert CKPT format.
  -O EXPORT_FORMAT, --export-format EXPORT_FORMAT
                        [export] export format. (one of [NNP,NNB,CSRC,ONNX,SAVED_MODEL,TFLITE,TF_PB],
                                 the export file format is 'CSRC' or 'SAVED_MODEL' that
                                 argument '--export-format' will have to be set!!!)
  -f, --force           [export] overwrite output file.
  -b BATCH_SIZE, --batch-size BATCH_SIZE
                        [export] overwrite batch size.
  --nnp-parameter-h5    [export][NNP] store parameter with h5 format
  --nnp-parameter-nntxt
                        [export][NNP] store parameter into nntxt
  --nnp-exclude-parameter
                        [export][NNP] output without parameter
  -T DEFAULT_VARIABLE_TYPE, --default-variable-type DEFAULT_VARIABLE_TYPE
                        Default type of variable
  -s SETTINGS, --settings SETTINGS
                        Settings in YAML format file.
  -c CONFIG, --config CONFIG
                        [export] config target function list.
  -d DEFINE_VERSION, --define_version
                        [export][ONNX] define onnx opset version. e.g. opset_6
                        [export][ONNX] define convert to onnx for SNPE. e.g. opset_snpe
                        [export][ONNX] define convert to onnx for TensorRT. e.g. opset_tensorrt
                        [export][NNB] define binary format version. e.g. nnb_3
  --api API             [export][NNB] Set API Level to convert to, default is highest API Level.
  --enable-optimize-pb  [export][tensorflow] enable optimization when export to pb.
  --channel_last        [export][TFLite] Specify the data_format of the NNP network,
                                         data_format default is channel_first.
  --quantization        [export][TFLite] export to INT8 quantized tflite model.
  --dataset             [export][TFLite] Specify the path of represent dataset which will be passed to INT8 quantized tflite converter.
pb モデルの最適化
usage: nnabla_cli optimize [-h] input_pb_file output_pb_file

positional arguments:
  input_pb_file       Input pre-optimized pb model.
  output_pb_file      Output optimized pb model.

出力ファイルに Monitor クラスをプロット

:

  • サブコマンドを使用してプロットを行うためには matplotlib パッケージが必要です。

  • 次のコマンドはデフォルトでディスプレイにプロットを表示します。環境によっては、matplotlib のバックエンドレンダリングエンジンを使用します。プロットを画像データやベクトルデータとして保存する場合は、 -o オプションを使用して、プロットを保存したいファイル名を指定してください。

MonitorSeries
usage: nnabla_cli plot_series [-h] [-l LABEL] [-o OUTFILE] [-x XLABEL]
                              [-y YLABEL] [-t TITLE] [-T YLIM_MAX]
                              [-B YLIM_MIN] [-R XLIM_MAX] [-L XLIM_MIN]
                              infile [infile ...]

Plot *.series.txt files produced by nnabla.monitor.MonitorSeries class.

Example:

    nnabla_cli plot_series -x "Epochs" -y "Squared error loss" -T 10 -l "config A" -l "config B" result_a/Training-loss.series.txt result_b/Training-loss.series.txt

positional arguments:
  infile                Path to input file.

optional arguments:
  -h, --help            show this help message and exit
  -l LABEL, --label LABEL
                        Label of each plot.
  -o OUTFILE, --outfile OUTFILE
                        Path to output file.
  -x XLABEL, --xlabel XLABEL
                        X-axis label of plot.
  -y YLABEL, --ylabel YLABEL
                        Y-axis label of plot.
  -t TITLE, --title TITLE
                        Title of plot.
  -T YLIM_MAX, --ylim-max YLIM_MAX
                        Y-axis plot range max.
  -B YLIM_MIN, --ylim-min YLIM_MIN
                        Y-axis plot range min.
  -R XLIM_MAX, --xlim-max XLIM_MAX
                        X-axis plot range max.
  -L XLIM_MIN, --xlim-min XLIM_MIN
                        X-axis plot range min.
MonitorTimeElapsed
usage: nnabla_cli plot_timer [-h] [-l LABEL] [-o OUTFILE] [-x XLABEL]
                             [-y YLABEL] [-t TITLE] [-T YLIM_MAX]
                             [-B YLIM_MIN] [-R XLIM_MAX] [-L XLIM_MIN] [-e]
                             [-u TIME_UNIT]
                             infile [infile ...]

Plot *.timer.txt files produced by nnabla.MonitorTimeElapsed class.

Example:

    nnabla_cli plot_timer -x "Epochs" -l "config A" -l "config B" result_a/Epoch-time.timer.txt result_b/Epoch-time.timer.txt

positional arguments:
  infile                Path to input file.

optional arguments:
  -h, --help            show this help message and exit
  -l LABEL, --label LABEL
                        Label of each plot.
  -o OUTFILE, --outfile OUTFILE
                        Path to output file.
  -x XLABEL, --xlabel XLABEL
                        X-axis label of plot.
  -y YLABEL, --ylabel YLABEL
                        Y-axis label of plot.
  -t TITLE, --title TITLE
                        Title of plot.
  -T YLIM_MAX, --ylim-max YLIM_MAX
                        Y-axis plot range max.
  -B YLIM_MIN, --ylim-min YLIM_MIN
                        Y-axis plot range min.
  -R XLIM_MAX, --xlim-max XLIM_MAX
                        X-axis plot range max.
  -L XLIM_MIN, --xlim-min XLIM_MIN
                        X-axis plot range min.
  -e, --elapsed         Plot total elapsed time. By default, it plots elapsed time per iteration.
  -u TIME_UNIT, --time-unit TIME_UNIT
                        Time unit chosen from {s|m|h|d}.
NNP または .nntxt ファイルからグラフを描く

:

  • この機能を使用するためには Python package としてインストールされた graphviz が必要です。 graphviz Python は graphviz ライブラリ へのインターフェイスですが、 pip コマンドではインストールされません。Ubuntu の apt などを使用してインストールしてください。

usage: nnabla_cli draw_graph [-h] [-o OUTPUT_DIR] [-n NETWORK] [-f FORMAT]
                             input

Draw a graph in a NNP or nntxt file with graphviz.

Example:

    nnabla_cli draw_graph -o output-folder path-to-nnp.nnp

positional arguments:
  input                 Path to input nnp or nntxt.

optional arguments:
  -h, --help            show this help message and exit
  -o OUTPUT_DIR, --output-dir OUTPUT_DIR
                        Output directory.
  -n NETWORK, --network NETWORK
                        Network names to be drawn.
  -f FORMAT, --format FORMAT
                        Graph saving format compatible with graphviz (`pdf`, `png`, ...).

開発

関数情報の生成
usage: nnabla_cli function_info [-h] [-o OUTFILE] [-f FUNC_SET] [-c CONFIG]
                                [-t TARGET] [-q --query] [--nnp-no-expand-network]
                                [--api API] [FILE] [FILE ...]

positional arguments:
  FILE                  Path to nnp file.

optional arguments:
  -h, --help  show this help message and exit
  -o OUTFILE, --output OUTFILE
                      output filename, *.txt or *.yaml, the default is stdout.
  -f FUNC_SET, --all_support FUNC_SET
                      select function set: NNB, ONNX, the default is nnabla.
  -c CONFIG, --config CONFIG
                      user config file for target constraint, *.txt file of the
                      function list or the "opset_" args.
  -t, --target
                      output target function list.
  -q, --query
                      query the detail of a function.
  --nnp-no-expand-network
                      [import][NNP] expand network with repeat or recurrent.
  --api API           List up api levels
バージョンの表示
usage: nnabla_cli version [-h]

optional arguments:
  -h, --help  show this help message and exit

Python API 実装例

NNabla リポジトリではたくさんの例が提供されています。この リンク をたどり、例を参照してください。

Python API リファレンス

共通

コンフィグ

コンフィグファイルを検索して、コンフィグファイルからコンフィグ情報を入手してください。

コンフィグファイルの検索順序については、次の表に記載しています。各コンフィグの値は下記のコンフィグで上書きされます。

Type

Posix

Windows

System wide

/etc/nnabla.conf

c:\ProgramData\NNabla\nnabla.ini

User

~/.nnabla

c:\Users\[USERNAME]\AppData\Roaming\NNabla\nnabla.ini

Default

( ‘config.py’ と同じディレクトリ ) / nnabla.conf

Local

[CURRENT DIRECTORY]/nnabla.conf

以下のようにコンフィグの値を取得することができます。

from utils.config import nnabla_config
value = nnabla_config.get(CATEGORY, VALUE_NAME)

CATEGORY と VALUE_NAME は、 config.py 内で定義されていません。 CATEGORY と VALUE は自由に追加できます。詳細については、 公式ドキュメント を参照してください。

[CATEGORY]
VALUE_NAME = value

これは、 config.py と同じディレクトリにある 'nnabla.conf' 内で定義されているデフォルト値です。

ロガー

ログのためのラッパーモジュール。

次のようなロガーを使うことができます。

from utils.logger import logger

logger.debug('Log message(DEBUG)')
logger.info('Log message(INFO)')
logger.warn('Log message(WARNING)')
logger.error('Log message(ERROR)')
logger.critical('Log message(CRITICAL)')

デフォルトの設定では、以下の出力となります。

$ python scripts/logger_test.py
[nnabla][ERROR]: logger_test.py : <module> : 5 : Log message(ERROR)
[nnabla][CRITICAL]: logger_test.py : <module> : 6 : Log message(CRITICAL)

ログをファイルに出力したい場合は、 nnabla.conf ファイルを生成し、以下のエントリを記載する必要があります。

コンフィグファイルの詳細については、 nnabla.config を参照してください。

[LOG]
log_file_name = /tmp/nbla.log

その後、以下にように出力されます。

$ python scripts/logger_test.py
[nnabla][ERROR]: logger_test.py : <module> : 5 : Log message(ERROR)
[nnabla][CRITICAL]: logger_test.py : <module> : 6 : Log message(CRITICAL)
$ cat /tmp/nbla.log
2017-01-19 14:41:35,132 [nnabla][DEBUG]: scripts/logger_test.py : <module> : 3 : Log message(DEBUG)
2017-01-19 14:41:35,132 [nnabla][INFO]: scripts/logger_test.py : <module> : 4 : Log message(INFO)
2017-01-19 14:41:35,132 [nnabla][ERROR]: scripts/logger_test.py : <module> : 5 : Log message(ERROR)
2017-01-19 14:41:35,132 [nnabla][CRITICAL]: scripts/logger_test.py : <module> : 6 : Log message(CRITICAL)
nnabla.logger.logger

<Logger nnabla (INFO)>の別名です。

Auto-forward モード

NNabla は動的計算グラフの機能を提供し、グラフの構築中に自動フォーワードプロパゲーションを可能にします。これは、 set_auto_forward() 関数を使うことで可能になります。バックプロパゲーションは動的に構築されたグラフにおいて手動で実行されます。

nnabla.auto_forward(auto=True)[ソース]

動的グラフ実行モードのコンテキスト。

パラメータ

auto (bool) -- 計算グラフの構築中に順方向の計算が実行されるかどうか。

戻り値 : bool

nnabla.set_auto_forward(auto)[ソース]

自動フォーワードプロパゲーションに対してデフォルトのモードをセットします。

True をセットした場合、計算グラフが更新されるとすぐにフォワードプロパゲーションが呼び出されます。

パラメータ

auto (bool) -- 計算グラフが更新される時、順方向の計算が実行されるかどうか。

戻り値 : bool

nnabla.get_auto_forward()[ソース]

自動フォワード実行の状態を取得します。

true のとき、計算グラフの定義中にフォワード実行が呼び出されます。

注釈

自動フォワード実行は、通常ユーザーによって呼び出されます。

コンテキスト
class nnabla.Context(backend=None, array_class='', device_id='0')

コンテキストは、関数オペレーターモジュールと最適化モジュールが実行される計算エンジン ( cpu、 cuda、 cudnn など ) を指定するために使われます。コンテキストは、各関数に対してセットすることが可能であり、また、 context-specifier() に列挙されている関数を使って広く全体的にセットすることも可能です。

パラメータ
  • backend (list of str) -- 'cpu' 、 'cuda' 、 'cudnn' など。

  • array_class (str) -- str 、 'CpuArray' 、 'CpuCachedArray' 、 'CudaArray' 、 'CudaCachedArray' など。

  • device_id (str) -- str 、 デフォルト ‘0’

コンテキスト指定子 API
nnabla.context_scope(ctx)[ソース]

Python コンテキストとしてのコンテキスト。

import nnabla as nn
import nnabla.functions as F
x = nn.Variable([2, 3 ,4])
ctx = nnabla_ext.cuda.context('0')
with context_scope(ctx):
    # Inside with scope, the specified context is used.
    with parameter_scope('w1'):
        l1 = F.relu(F.affine(x, 64))
    with parameter_scope('w2'):
        l2 = F.relu(F.affine(x, 64))
nnabla.set_default_context(ctx)[ソース]

デフォルトのコンテキストをセットします。

注釈

context_scope 内で呼び出すことができません。

パラメータ

ctx (Context) -- コンテキスト。

nnabla.get_current_context()[ソース]

現在のコンテキストを取得します。

nnabla.context_scope()nnabla.set_default_context() を使ってセットすることができます。

戻り値

現在のコンテキスト。

戻り値の型

Context

NdArray

class nnabla.NdArray(*args, **kwargs)

nnabla.NdArray is a device-agnostic data container for multi-dimensional arrays (tensors). nnabla.NdArray can also implicitly handle data transfers across different devices (e.g. CPU to CUDA GPU, CUDA GPU to CPU). See Python API Tutorial for more details.

NdArray は、算術演算子 (+, -, *, /, **) をオーバーライドします。オペランドは、スカラー数、 NdArray 、または Variable のいずれかになります。 NdArray を含む算術演算は、すぐに呼び出される計算の出力を保持する NdArray を返します。また、インプレース算術演算 (+=, -=, *=, /=, **=) が実装されます。 = ではインプレース置換は行われずに、単にオブジェクト参照が置換されることに注意してください。代わりに、 copy_from() を使ってインプレース置換を行うことができます。

パラメータ

shape (tuple or int) -- タプルの形状。

bool_fill(self, mask, value)

Return a new but inplaced nnabla.NdArray filled with value where mask is non-zero.

パラメータ
  • mask (nnabla.NdArray) -- Mask with which to fill. Non-zero/zero elements are supposed to be a binary mask as 1/0. No gradients are computed with respect to mask.

  • value (float) -- The value to fill.

cast(self, dtype, ctx=None)

NdArray のデータ型のインプレースキャスト。オプションパラメータの ctx が指定されない場合のみ、 numpy.ndarray として参照値を返します。それ以外の場合は、 None を返します。

パラメータ
戻り値

ctx が None の場合は、 numpy.array 。それ以外の場合はなし。

clear(self)

Clear memories which this NdArray has and return them to allocator.

clear_called

Checking if the array is not modified after cleared. This returns False until clear is called at the first time.

copy_from(self, NdArray arr, use_current_context=True)

他の NdArray オブジェクトから値をコピーします。

呼び出し元のオブジェクト自身を返します。

パラメータ
  • arr (NdArray) -- 呼び出し元のオブジェクトに値をコピーします。 arr の形状は呼び出し元のオブジェクトと同じでないといけません。

  • use_current_context (bool) -- True の場合、デバイスと現在のコンテキスト ( call F.identity(src, output=[self]) と同等 ) において指定されている dtype でコピーが行われています。そうでない場合は、ソース配列のデバイスと dtype が使われます。デフォルトは True です。

戻り値

nnabla.NdArray

data

Returns the values held by this array as a numpy.ndarray. Note that only the references are returned, and the values are not copied. Therefore, modifying the returned nnabla.NdArray will affect the data contained inside the NNabla array. This method can also be called as a setter where an array is created as the same type as rhs. There is an exception where zero() or fill(rhs) is invoked if a scalar with a float or an integer <= 2^53 (as filling value is maintained as float64) is given.

これはデバイス配列から CPU へデータ転送が暗黙的に呼び出される可能性があるということですので注意してください。

パラメータ

value (numpy.ndarray) --

戻り値

numpy.ndarray

data_ptr(self, dtype, ctx=None)

配列のポインターを取得します。

この動作は、 cast メソッド と同じですが、 ctx に基づいたデータポインターを返します。 ctx が指定されない場合は、 nn.get_current_context によって得られるデフォルトのコンテキストが使われます。

パラメータ
戻り値

データポインター。

戻り値の型

int

dtype

dtype を取得します。

戻り値

numpy.dtype

fill(self, value)

すべての要素に指定されたスカラー値を代入します。

注釈

ここでは、内部配列にはすぐに 0 が入りません。この配列を使うとき ( 例えば、順方向または逆方向の計算の際 ) に、要求されたデータ型で配列が生成され、その値が入ります。

パラメータ

value (float) -- 代入する値。

static from_numpy_array(nparr)

Numpy 配列データから NdArray オブジェクトを作成します。

このデータは所定の Numpy 配列で初期化されます。

パラメータ

nparr (ndarray) -- Numpy 多次元配列。

戻り値

nnabla.NdArray

get_data(self, str mode='rw', dtype=None)

指定されたモードで numpy.ndarray としてこの配列が保持する値を返します。

パラメータ
  • mode (str) -- 正しく選択されると、より効率の良い計算が行われます。 * ‘r’ : 読み取り専用アクセス。 * ‘w’ : 書き込み専用アクセス。 * ‘rw’ : 読み書き可。

  • dtype (numpy.dtype, optional) -- 強制的に戻り値の配列の dtype にします。

See :function:`nnabla.NdArray.data` for more details.

masked_fill()

NdArray.bool_fill(self, mask, value) Return a new but inplaced nnabla.NdArray filled with value where mask is non-zero.

Args:

mask (nnabla.NdArray): Mask with which to fill. Non-zero/zero elements are supposed to be a binary mask as 1/0. No gradients are computed with respect to mask. value (float): The value to fill.

modification_count

Returns how many times modified after memory allocation or clearing buffer.

ndim

次元数。

戻り値

int

shape

N-d 配列の形状。

戻り値

tuple of int

size

N-d 配列の合計サイズ。

戻り値

int

size_from_axis(self, axis=- 1)

指定された軸に続いてサイズを返します。

a = nnabla.NdArray([10,9])
a.size_from_axis()
# ==> 90
a.size_from_axis(0)
# ==> 90
a.size_from_axis(1)
# ==> 9
a.size_from_axis(2)
# ==> 1
パラメータ

axis (int, optional) -- デフォルトで -1

戻り値

int

strides

ストライドします。

戻り値

tuple of int

zero(self)

すべての要素に 0 を入れます。

注釈

ここでは、内部配列にすぐには 0 が入りません。この配列を使うとき ( 例えば、順方向または逆方向の計算の際 ) に、要求されたデータ型で配列が生成され、 0 が入ります。

zeroing

zero() を呼び出した後に、配列に変更がないかどうかを確かめます。

Variable

class nnabla.Variable

ベースクラス: object

nnabla.Variable は、 関数パラメトリック関数リスト のリストにある関数とともに ( ニューラルネットワークの ) 計算グラフを作成するために用いられます。また、 nnabla.Variable はネットワークのフォーワード・バックワード計算を実行する機能も提供します。 nnabla.Variable クラスは以下の機能を提供します。

  • 計算グラフにおける親関数への参照。この参照により、計算グラフのすべての接続をたどることができます。

  • Both data and error signal (gradient) containers as nnabla.NdArray s.

  • その他、いくつかの計算グラフのに関する付加的な情報。

Variable は、算術演算子 (+, -, *, /, **) をオーバーライドします。左右のオペランドとしては、スカラー数、 NdArray 、または Variable のいずれかになりますが利用可能です。 NdArray に対して左オペランドまたは右オペランドが指定された場合は、算術演算は、すぐに呼び出された計算の出力を格納する NdArray を返します。それ以外の場合は、グラフの連結を保持する Variable を返します。この演算は、 nnabla.auto_forward がTrue、または nnabla.set_auto_forward(True) が使われると指定されている場合はすぐに呼び出されます。

注釈

2つの Variable の関係演算子 ==!= は、ベースとなる C++ インスタンス ( nbla::Variable ) のアドレスの比較を行います。また、 setdict に対するキーでよく使われる hash() 関数もまた、このアドレスに基づいています。

参考

併せて Python API Tutorial を参照してください。

パラメータ
  • shape (Iterable of int) -- 変数の形状 Shape。

  • need_grad (bool) -- この変数までのバックプロパゲーションが必要か否かのフラグ。

apply(self, **kwargs)

プロパティをセットするための helper です。それ自身を返します。

backward(self, grad=1, bool clear_buffer=False, communicator_callbacks=None, function_pre_hook=None, function_post_hook=None)

この変数から関数グラフのルート変数に到達するまで、バックプロパゲーションを行います。このプロパゲーションは need_grad=False が指定された変数で終了します。

パラメータ
  • grad (scalar, numpy.ndarray, nnabla.NdArray, or None) -- この変数の勾配の値。通常のニューラルネットワークの学習では、デフォルト値に 1 を用います。勾配計算を NNabla の外部で行い、勾配としてその結果を使いたい場合に、このオプションが役に立ちます。このオプションは、この変数の勾配値を変更するのではなく、受け取った値を一時的にその勾配として割り当てることに注意してください。また、 nnabla._variable.Variable.backward を実行したい Variable が他の変数との接続が切れている変数であり、対応する Variable が事前計算された勾配値を保持する場合は、 grad=None を指定する必要があります。 この指定が行われない場合、そのバックワードパス ( 結合されていない Variable からの伝播 ) では、事前計算された勾配値は 無視されます

  • clear_buffer (bool) -- Clears the no longer referenced variables during backpropagation to save memory. Note that all unnecessary intermediate variables will be cleared unless set explicitly as persistent=True.

  • communicator_callbacks (nnabla.CommunicatorBackwardCallback or list of nnabla.CommunicatorBackwardCallback) -- 1) 各関数の方向のバックワード計算が終了したときと、 2) すべてのバックワード計算が終了したときに、コールバック関数を呼び出します。

  • function_pre_hook (callable) -- 各関数の実行直前に、この呼び出し可能なオブジェクトを呼び出します。引数として Function を取る必要があります。デフォルトは None です。

  • function_post_hook (callable) -- 各関数の実行直後に、この呼び出し可能なオブジェクトを呼び出します。引数として Function を取る必要があります。デフォルトは None です。

はじめに、簡単な backward の使用法について説明します。

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import numpy as np
import nnabla.initializer as I

rng = np.random.seed(217)
initializer = I.UniformInitializer((-0.1, 0.1), rng=rng)

x = nn.Variable((8, 3, 32, 32))
x.d = np.random.random(x.shape)  # random input, just for example.

y0 = PF.convolution(x, outmaps=64, kernel=(3, 3), pad=(1, 1), stride=(2, 2), w_init=initializer, name="conv1", with_bias=False)
y1 = F.relu(y0)
y2 = PF.convolution(y1, outmaps=128, kernel=(3, 3), pad=(1, 1), stride=(2, 2), w_init=initializer, name="conv2", with_bias=False)
y3 = F.relu(y2)
y4 = F.average_pooling(y3, kernel=y3.shape[2:])
y5 = PF.affine(y4, 1, w_init=initializer)
loss = F.mean(F.abs(y5 - 1.))
loss.forward()  # Execute forward

# We can check the current gradient of parameter.
print(nn.get_parameters()["conv1/conv/W"].g)

出力 :

[[[[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]
      ...

最初に、すべての勾配をゼロにする必要があります。次に、 backward を呼び出すとどうなるかを見てみましょう。

loss.backward()
print(nn.get_parameters()["conv1/conv/W"].g)

出力 :

[[[[ 0.00539637  0.00770839  0.0090611 ]
   [ 0.0078223   0.00978992  0.00720569]
   [ 0.00879023  0.00578172  0.00790895]]
                     ...

ここで、 backward を呼び出すことによって、勾配が計算され、 g に値が登録されることがわかります。 backward を連続的に呼び出すことで結果が 加算 されていくことに注意してください。つまり、 backward を再度実行すると、結果は 2 倍になります。

loss.backward()  # execute again.
print(nn.get_parameters()["conv1/conv/W"].g)

以下で、累積されていることがわかります。

[[[[ 0.01079273  0.01541678  0.0181222 ]
   [ 0.01564459  0.01957984  0.01441139]
   [ 0.01758046  0.01156345  0.0158179 ]]
                     ...

次は、接続されていない Variable を用いた高度な使用法です ( get_unlinked_variable を参照してください ) 。ここでは同様のネットワークを使用しますが、結合していない Variable により分離されたネットワークとなります。

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import numpy as np
import nnabla.initializer as I

rng = np.random.seed(217)  # use the same random seed.
initializer = I.UniformInitializer((-0.1, 0.1), rng=rng)

x = nn.Variable((8, 3, 32, 32))
x.d = np.random.random(x.shape)  # random input, just for example.

y0 = PF.convolution(x, outmaps=64, kernel=(3, 3), pad=(1, 1), stride=(2, 2), w_init=initializer, name="conv1", with_bias=False)
y1 = F.relu(y0)
y2 = PF.convolution(y1, outmaps=128, kernel=(3, 3), pad=(1, 1), stride=(2, 2), w_init=initializer, name="conv2", with_bias=False)
y3 = F.relu(y2)
y3_unlinked = y3.get_unlinked_variable()  # the computation graph is cut apart here.
y4 = F.average_pooling(y3_unlinked, kernel=y3_unlinked.shape[2:])
y5 = PF.affine(y4, 1, w_init=initializer)
loss = F.mean(F.abs(y5 - 1.))

# Execute forward.
y3.forward()  # you need to execute forward at the unlinked variable first.
loss.forward()  # Then execute forward at the leaf variable.

# Execute backward.
loss.backward()  # works, but backpropagation stops at y3_unlinked.
print(nn.get_parameters()["conv1/conv/W"].g)  # no gradient registered yet.

出力 :

[[[[0. 0. 0.]
   [0. 0. 0.]
   [0. 0. 0.]]
      ...

バックプロパゲーション が y3_unlinked で停止することが確認できます。次に、ルート変数 (x) までのバックプロパゲーションを実行する方法を見てみましょう。これは少々複雑なため、最初によく陥りやすい誤りの一例を示します。 これはあくまで間違った方法での backward の動作を示した例であることにご注意ください。

y3.backward()  # this works, but computed gradient values are not correct.
print(nn.get_parameters()["conv1/conv/W"].g)

出力 :

[[[[ 17.795254    23.960905    25.51168   ]
   [ 20.661646    28.484127    19.406212  ]
   [ 26.91042     22.239697    23.395714  ]]
                     ...

これは間違った結果であることに注意してください。 y3_unlinked が保持するしていた勾配は完全に無視されています。上記のとおり、 backward を呼び出すだけで ( backward の呼び出し元のリーフ変数の) 勾配が 1 と見なされます。

2 つの個別のグラフに対して 正しく バックプロパゲーションを実行するためには、以下のように grad=None を指定する必要があります。次に、変数が保持する現在の勾配を使って計算を行います。( y3.backward(grad=y3_unlinked.g) は同じ動作となります。)

#reset all the gradient values.
for v in nn.get_parameters().values():
    v.g = 0.
for v in [y0, y1, y2, y3, y4, y5]:
    v.g = 0.  # need to reset all the gradient values.

loss.backward()  # backpropagation starts from the leaf variable again.
y3.backward(grad=None)  # By this, it can take over the gradient held by y3_unlinked.
print(nn.get_parameters()["conv1/conv/W"].g)  # correct result.

今回は同じ結果となります。

[[[[ 0.00539637  0.00770839  0.0090611 ]
   [ 0.0078223   0.00978992  0.00720569]
   [ 0.00879023  0.00578172  0.00790895]]
                     ...
bool_fill_(self, mask, value)

Return a new but inplaced nnabla.Variable filled with value where mask is non-zero.

パラメータ
  • mask (nnabla.NdArray) -- Mask with which to fill. Non-zero/zero elements are supposed to be a binary mask as 1/0. No gradients are computed with respect to mask.

  • value (float) -- The value to fill.

戻り値

nnabla.Variable

すべての中間関数や Variable を消去します。

このメソッドは、順方向計算におけるこの Variable までのすべての中間関数と Variable を消去するため、動的グラフにおいて時間によるバックプロパゲーションの打ち切り ( truncated BPTT ) に役立ちます。

d

Returns the values held by this variable, as a numpy.ndarray. Note that the values are referenced (not copied). Therefore, the modification of the returned ndarray will affect the data of the NNabla array. This method can be called as a setter to set the value held by this variable. Refer to the documentation of the setter nnabla.NdArray.data for detailed behaviors of the setter.

パラメータ

value (numpy.ndarray) (optional) --

戻り値

numpy.ndarray

data

Returns the data held by this variable, as a NdArray. This can also be used as a setter.

パラメータ

ndarray (NdArray) -- NdArray オブジェクト。 Variable と同じである必要があります。

戻り値

NdArray

forward(self, bool clear_buffer=False, bool clear_no_need_grad=False, function_pre_hook=None, function_post_hook=None)

Performs a forward propagation from the root node to this variable. The forward propagation is performed on a subset of variables determined by the dependency of this variable. The subset is recursively constructed by tracking variables that the variables in the subset depend on, starting from this variable, until it reaches the root variable(s) in the function graph. See also forward_all, which performs forward computations for all variables within the input graph.

パラメータ
  • clear_buffer (bool) -- Clear the no longer referenced variables during forward propagation to save memory. This is usually set as True in an inference or a validation phase. Default is False. Note that all unnecessary intermediate variables will be cleared unless set explicitly as persistent=True.

  • clear_no_need_grad (bool) -- フォワードプロパゲーション中に need_grad=False で参照されない Variable の data を解放します。学習中にこの関数を呼ぶ場合、通常 True を用います。clear_buffer=True の場合は無視されます。

  • function_pre_hook (callable) -- 各関数の実行直前に、この呼び出し可能なオブジェクトを呼び出します。引数として Function を取る必要があります。デフォルトは None です。

  • function_post_hook (callable) -- 各関数の実行直後に、この呼び出し可能なオブジェクトを呼び出します。引数として Function を取る必要があります。デフォルトは None です。

static from_numpy_array(data, grad=None, need_grad=None)

Numpy Array ( ndarray ) から Variable オブジェクトを作成します。

data は、指定された Numpy 配列で初期化されます。また、 grad も指定された場合は同様です。

Shape も指定された ndarrayによって決まります。

パラメータ
  • data (ndarray) -- 作成された Variable の data にコピーされる値。

  • grad (ndarray) -- 作成された Variable の grad へコピーされる値。

  • need_grad (bool) -- この変数までのバックプロパゲーションが必要か否かのフラグ。

戻り値

Variable

function_references

入力としてこの Variable を取る関数のリストを返します。このメソッドはゲッターとしてのみ呼び出すことができます。

戻り値

nnabla.function.Function のリスト

g

Returns the gradient values held by this variable, as a numpy.ndarray. Note that the values are referenced (not copied). Therefore, the modification of the returned ndarray will affect the data of the NNabla array. This method can be called as a setter to set the gradient held by this variable. Refer to the documentation of the setter nnabla.NdArray.data for detailed behaviors of the setter.

パラメータ

value (numpy.ndarray) --

戻り値

numpy.ndarray

get_unlinked_variable(self, need_grad=None)

Variable のバッファーのインスタンスを共有する、接続の切れた ( 親との接続が切れた ) Variable を取得します。

パラメータ

need_grad (bool, optional) -- デフォルトでは、接続を解除された Variable はこの Variable のインスタンスと同じ need_grad フラグを持ちます。 bool 値を指定することで、連結を解除された変数に新しい need_grad フラグをセットすることができます。意図しない動作を避けるために、このオプションは明示的に指定することを推奨します。

戻り値 : Variable

注釈

接続を解除された Variable は、 need_grad が変更されるかどうかにかかわらず、比較演算子とハッシュ関数において、元の Variable と同等に動作します。 Variable クラスのドキュメントの注意事項を参照してください。また、接続していない Variable を使った backward の実行については、 backward とその例を参照ください。

import numpy as np
import nnabla as nn
import nnabla.parametric_functions as PF

x = nn.Variable.from_numpy_array(np.array([[1, 2], [3, 4]]))
y = PF.affine(x, 4, name="y")

# Create a new variable of which graph connection is unlinked.
# Recommend to specify need_grad option explicitly .
z = y.get_unlinked_variable(need_grad=False)

print(y.parent)
# Affine
print(z.parent)  # z is unlinked from the parent x but shares the buffers of y.
# None
grad

Returns the gradient held by this variable, as a NdArray. This can also be used as a setter.

パラメータ

ndarray (NdArray) -- NdArray オブジェクト。 Variable と同じである必要があります。

戻り値

NdArray

info

object

変数の情報。

Type

info

masked_fill_()

Variable.bool_fill_(self, mask, value)

Return a new but inplaced nnabla.Variable filled with value where mask is non-zero.

パラメータ
  • mask (nnabla.NdArray) -- Mask with which to fill. Non-zero/zero elements are supposed to be a binary mask as 1/0. No gradients are computed with respect to mask.

  • value (float) -- The value to fill.

戻り値

nnabla.Variable

ndim

この Variable の次元数を取得します。

戻り値

int

need_grad

この Variable でバックプロパゲーションが行われるかどうかを示す bool 値を取得、または指定します。

パラメータ

b (bool) -- この変数でバックプロパゲーションが行われるかどうか。

戻り値

この変数が勾配を要求するかどうか。

戻り値の型

bool

no_grad(self)

No gradients for the whole network.

This method is like nnabla.no_grad but can be used for the static network only, and useful for the case where the network is loaded from NNP format.

x = nn.Variable.from_numpy_array([2, 3])
y = <Network>(x).no_grad()
parent

この Variable の親関数を返します。このメソッドはセッターと呼ばれることもあります。

パラメータ

func (nnabla.function.Function) --

戻り値

nnabla.function.Function

persistent

この Variable の永続性を示すフラグを返します。 True の場合、 nnabla._variable.Variable.forward()nnabla._variable.Variable.backward() で消去オプションが有効であっても、 Variable の data 、 grad は解放されません。これは、 Variable の値をデバッグしたり、ログを取る場合に役立ちます。このメソッドはセッターとして呼ぶこともできます。

パラメータ

b (bool) --

戻り値

bool

recompute

Gets or sets a boolean indicating whether its data is cleared during forward propagation and recomputation is performed during backward propagation.

パラメータ

b (bool) -- Whether recomputation is performed during backward propagation.

戻り値

Whether this variable is recomputed during backward propagation.

戻り値の型

bool

reset_shape(self, shape, force=False)

Variable の Shape を指定された Shape へ変更します。

パラメータ
  • shape (Iterable of int) -- ターゲットの Shape 。

  • force (bool) -- 強制的に Shape を変更するためのフラグ。

注釈

このメソッドはターゲットの Shape の形状を破壊的に変更します。安全のためには、代わりに reshape() を使うべきです。

戻り値

None

reshape(self, shape, unlink=False)

指定された Shape に変更された、新しい Variable を返します。

パラメータ
  • shape (Iterable of int) -- ターゲットの Shape 。

  • unlink (bool) -- グラフ結合のリンクを解除するかどうかを指定します ( 指定のない場合、デフォルトではグラフ結合を維持します。つまり、勾配は元の Variable へバックプロパゲーションされます ) 。

戻り値

Variable

rewire_on(self, var)

この Variable の後続のグラフを var の先頭に挿入し、グラフを再構築します。

パラメータ

var (nnabla.Variable) -- 配列の要素と var の親関数が参照として self にコピーされます。 var の親関数は削除されることにご注意ください。

# A. Create a graph A.
xa = nn.Variable((2, 8), need_grad=True)
ya = F.tanh(PF.affine(xa, 10, name='a'))

# B. Create a graph B.
xb = nn.Variable((2, 16), need_grad=True)
yb = F.tanh(PF.affine(
    F.tanh(PF.affine(xb, 8, name='b1')),
    8, name='b2'))

# C. Rewire the graph A on top of B such that
#    `xb->B->(yb->)xa->A->ya`. Note `yb` is gone.
xa.rewire_on(yb)

# D. Execute the rewired graph.
xb.d = 1
ya.forward()
ya.backward()
shape

Variable の Shape を取得します。

戻り値

tuple of int

size

変数のサイズを取得します。

戻り値

int

size_from_axis(self, axis=- 1)

指定された axis のサイズを取得します。

a = nnabla.Variable([10,9])
a.size_from_axis()
# ==> 90
a.size_from_axis(0)
# ==> 90
a.size_from_axis(1)
# ==> 9
a.size_from_axis(2)
# ==> 1
パラメータ

axis (int, optional) -- デフォルトは -1

戻り値

int

unlinked(self, need_grad=None)

この関数の利用は 非推奨 です。代わりに get_unlinked_variable を使用してください。

visit(self, f)

順方向で再帰的に関数にアクセスします。

パラメータ

f (function) -- 引数として nnabla._function.Function オブジェクトを取る Function オブジェクト。

戻り値

None

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF

# Define a simple network-graph
def network_graph(x, maps=16, test=False):
    h = x
    h = PF.convolution(h, maps, kernel=(3, 3), pad=(1, 1), name="first-conv", with_bias=False)
    h = F.average_pooling(h, h.shape[2:])
    pred = PF.affine(h, 10, name="pred")
    return pred

# You can modify this PrintFunc to get the other information like inputs(nnabla_func.inputs), outputs and arguments(nnabla_func.info.args) of nnabla functions.
class PrintFunc(object):
    def __call__(self, nnabla_func):
        print(nnabla_func.info.type_name)

x = nn.Variable([1, 3, 16, 16])
output = network_graph(x)
output.visit(PrintFunc())

出力 :

Convolution
AveragePooling
Affine
visit_check(self, f)

順方向で再帰的に関数にアクセスします。

注釈

関数オブジェクトのいずれかが True を返した場合、順方向のプロパゲーションはすぐに停止し、 True を返します。

パラメータ

f (function) -- 引数として nnabla._function.Function オブジェクトを取る Function オブジェクト。

戻り値

bool Returns True if any of the function object call returns True.

以下のように、 AveragePooling 関数を明示的に加えることができる簡単なネットワークグラフを定義します。

def network_graph(x, add_avg_pool=False, maps=16, test=False):
    h = x
    h = PF.convolution(h, maps, kernel=(3, 3), pad=(1, 1), name="first-conv", with_bias=False)
    if add_avg_pool :
        h = F.average_pooling(h, h.shape[2:])
    else :
        h = F.relu(h)
    pred = PF.affine(h, 10, name="pred")
    return pred

# Define 'PrintFunc()' to check whether "AveragePooling" function exists in the network-graph
class PrintFunc(object):
    def __call__(self, nnabla_func):
        if nnabla_func.info.type_name =="AveragePooling" :
            print("{} exists in the graph".format(nnabla_func.info.type_name))
            return True
        else :
            return False

AveragePooling 関数を持ち、 visit_check() メソッドを呼び出すネットワークグラフを作成します。

x = nn.Variable([1, 3, 16, 16])
output = network_graph(x, add_avg_pool=True)  #Adding AveragePooling function to the graph
print("The return value of visit_check() method is : {}".format(output.visit_check(PrintFunc())))

出力 :

AveragePooling exists in the graph
The return value of visit_check() method is : True

AveragePooling 関数を持たずに、 visit_check() メソッドを呼び出すネットワークグラフを作成します。

nn.clear_parameters()                         # call this in case you want to run the following code again
output = network_graph(x, add_avg_pool=False) # Exclusion of AveragePooling function in the graph
print("The return value of visit_check() method is : {}".format(output.visit_check(PrintFunc())))

出力 :

The return value of visit_check() method is : False

Computation Graph

Computation Graph
nnabla.forward_all(variables, bool clear_buffer=False, bool clear_no_need_grad=False, function_pre_hook=None, function_post_hook=None)

Performs a forward propagation up to variables specified as the 1st argument. See also forward.

パラメータ
  • clear_buffer (bool) --

    Clear the no longer referenced variables during forward propagation to save memory. This is usually set as True in an inference or a validation phase. Default is False. Note that starting variable and destination variable of the input graph will not be cleared, regardless of their persistent flag. All intermediate variables will be cleared unless set explicitly as persistent=True. For example,

    forward_all([h_i, y], clear_buffer=True)
    

    will clear all intermediate variables between h_i and y unless set explicitly as persistent=True, but h_i and y will not be cleared regardless of their persistent flag.

  • clear_no_need_grad (bool) -- Clear the unreferenced variables with need_grad=False during forward propagation. True is usually used when calling this during training. This is ignored when clear_buffer=True.

  • function_pre_hook (callable) -- This callable object is called immediately before each function is executed. It must take Function as an input. The default is None.

  • function_post_hook (callable) -- This callable object is called immediately after each function is executed. It must take Function as an input. The default is None.

サンプル

import numpy as np
import nnabla as nn
import nnabla.parametric_functions as PF

# Create a graph which has two outputs
x = nn.Variable.from_numpy_array(np.array([[1, 2], [3, 4]]))
y = PF.affine(x, 4, name="y")
z = PF.affine(x, 8, name="z")

# Execute a forward propagation recursively up to y and z
nn.forward_all([y, z], clear_buffer)
nnabla.no_grad(no_grad_=True)[ソース]

No gradients for the whole network.

No gradients are required when creating a network, such that when the forward pass is executed, all intermediate buffers except for the leafs in the network are gone at the same time, resulting in memory optimization.

This is useful for example when an output of a pre-trained network is used for an input to another network, where the first pre-trained network does not need to be fine-tuned, but the other network is optimized.

パラメータ

no_grad (bool) -- No gradient flag. Default is True.

Example:

with nn.no_grad():
    output0 = <Network0>(<input0>)

output1 = <Network1>(<input1>, output0)
loss = <Loss>(output1, <ground_truth>)
loss.forward(clear_no_need_grad=True)

This context also works in the dynamic mode.

with nn.auto_forward(), nn.no_grad():
    output0 = <Network0>(<input0>)

注釈

When working with the static network, the need_grad property of the input (e.g., input image) must be False and do not forget to add <root>.forward(clear_no_need_grad=True); otherwise, all intermediate buffers are not gone as expected.

関数

すべての NNabla 関数は nnabla.function.Function クラスから派生しています。

Function
class nnabla.function.Function

Function のインターフェイスクラス。

nnabla.function.Function のインスタンスはユーザによって直接生成されることはありません。 nnabla.functions が提供する関数によって間接的に生成されます。これらの関数は、親プロパティとして生成された関数のインスタンスを保持する nnabla.Variable を返します。

args

Experimental

Get args of the function.

backward(self, inputs, outputs, accum=None)
forward(self, inputs, outputs)
grad_depends_output_data(self, int i, int o)
info

object

info

inplace_data(self, int i)
inplace_data_with(self, int i)
min_outputs(self)
need_setup_recompute(self, int o)
recompute(self, inputs, outputs)
setup(self, inputs, outputs)
setup_recompute(self, inputs, outputs)
tags

Experimental

関数のタグを取得します。

class nnabla.function.PythonFunction(ctx=None)

Creates a user-defined custom function in the subclsass.

To implement the naive multiplicaiton function of two variables using PythonFunction,

import nnabla as nn
import nnabla.functions as F
from nnabla.function import PythonFunction

class Mul2(PythonFunction):

    def __init__(self, ctx):
        super(Mul2, self).__init__(ctx)

    @property
    def name(self):
        return self.__class__.__name__

    def min_outputs(self):
        return 1

    def setup_impl(self, inputs, outputs):
        i0 = inputs[0]
        i1 = inputs[1]
        assert i0.shape == i1.shape, "Shapes of inputs are different."
        o0 = outputs[0]
        o0.reset_shape(i0.shape, True)

    def forward_impl(self, inputs, outputs):
        x0 = inputs[0].data
        x1 = inputs[1].data
        y = outputs[0].data

        # We can also write like, y.copy_from(x0 * x1)
        y.copy_from(F.mul2(x0, x1))

    def backward_impl(self, inputs, outputs, propagate_down, accum):
        # Data of inputs and outputs
        x0 = inputs[0].data
        x1 = inputs[1].data
        y = outputs[0].data
        # Grads of inputs and outputs
        dx0 = inputs[0].grad
        dx1 = inputs[1].grad
        dy = outputs[0].grad

        # backward w.r.t. x0
        if propagate_down[0]:
            if accum[0]:
                dx0 += F.mul2(dy, x1)
            else:
                dx0.copy_from(F.mul2(dy, x1))

        # backward w.r.t. x1
        if propagate_down[1]:
            if accum[1]:
                dx1 += F.mul2(dy, x0)
            else:
                dx1.copy_from(F.mul2(dy, x0))

    def grad_depends_output_data(self, i, o):
        return False

    def grad_depends_input_data(self, i, j):
        return True

def mul2(x, y, ctx=None):
    func = Mul2(ctx)
    return func(x, y)
__init__(self, ctx=None)
パラメータ

ctx (nnabla.Context) -- Context used for the forward and backward pass. If not specified, the current context is used.

backward_impl(self, inputs, outputs, propagate_down, accum)

Backward method.

パラメータ
property ctx

Context Return the context if the context is set in the constructor; otherwise return the global context

forward_impl(self, inputs, outputs)

Forward method.

パラメータ
grad_depends_input_data(self, i, j)

Checking if i-th input' gradient computation requires j-th input's data or not.

パラメータ
grad_depends_output_data(self, i, o)

Checking if i-th input' gradient computation requires o-th output's data or not.

パラメータ
min_outputs(self)

Minimum number of outputs of the function.

property name

Name of the function.

setup_impl(self, inputs, outputs)

Setup method.

パラメータ
関数のリスト

nnabla.functions モジュールは以下に挙げられた様々な型の関数を提供します。これらの関数は、最初の引数として入力 nnabla.Variable を取り、各関数固有のオプションが続きます。

注釈

The functions can also take NdArray (s) as inputs instead of Variable (s). It will execute the function operation immediately, and returns NdArray (s) as output(s) holding output values of the operation. We call this "Imperative Mode" (NdArray + Functions).

ニューラルネットワーク層
nnabla.functions.affine(x, weight, bias=None, base_axis=1, n_outputs=- 1, outputs=None)[ソース]

Affine 層、全結合層とも呼ばれます。Affine 層は次のように計算します。

\[{\mathbf y} = {\mathbf A} {\mathbf x} + {\mathbf b}.\]

ここで、 \({\mathbf x}\) は入力、 \({\mathbf y}\) は出力です。

パラメータ
  • x (Variable) -- (\(M_0 \times ... \times M_{B-1} \times D_B \times ... \times D_N\)) の形状の入力 N-D 配列。 base_axis 前後の次元は行列のように平坦化されます。

  • weight (Variable) -- (\((D_B \times ... \times D_N) \times L_{0} \times \ldots \times L_{I}\)) の形状の重みの行列 [ パラメータ ]

  • bias (Variable) -- バイアスのベクトル (\(L_{0} \times \ldots \times L_{I}\)) [ オプション ][ パラメータ]

  • base_axis (int) -- Base axis of Affine operation. Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

戻り値

\((B + 1)\) -D 配列。 (\(M_0 \times ... \times M_{B-1} \times L_{0} \times \ldots \times L_{I}\))

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.convolution(x, weight, bias=None, base_axis=1, pad=None, stride=None, dilation=None, group=1, channel_last=False, n_outputs=- 1, outputs=None)[ソース]

バイアスを伴う N-D Convolution。

拡張型 Convolution (通称 Atrous Convolution) については以下を参照してください。

参照

注釈

Convolution は計算量が集中する演算であるため、 cudnn バックエンドを使って実行することを推奨します。そして、NNabla は CuDNN ライブラリ関数を使用して指定された convolution パラメータセットによる最速アルゴリズムを決定およびキャッシュするため、結果的にメモリーの追加消費により、GPU のメモリサイズが足りないという問題が発生する可能性があります。そのような場合は、バイト単位で指定する環境変数 NNABLA_CUDNN_WORKSPACE_LIMIT を使って、ワークスペースのメモリ制限に適合するようにアルゴリズムの選択肢を制限できます。また自動検索を確定的な(再現可能な)結果を生成するアルゴリズムに制約した方がよい場合もあります。これは、環境変数 NNABLA_CUDNN_DETERMINISTIC をゼロでない値に設定することで要求できます。

パラメータ
  • x (Variable) -- \((B + 1 + N)\) -D 配列 (\(M_1 \times ... \times M_B \times C \times L_1 \times ... \times L_N\)) 。

  • weight (Variable) -- \((2 + N)\) -D 配列 (\(C' \times C \times K_1 \times ... \times K_N\)) 。 [ パラメータ]

  • bias (Variable) -- バイアスのベクトル (\(C'\)) 。[ オプション ][ パラメータ ]

  • base_axis (int) -- base axis \(B\). [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • group (int) -- Number of groups of channels. This makes the connection across channels sparser, by grouping connections along the mapping direction. [default= 1 ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

戻り値

\((B + 1 + N)\)-D array (\(M_1 \times ... \times M_B \times C' \times L'_1 \times ... \times L'_N\)).

出力の空間サイズは、以下のように計算します。

\[L'_i = \frac{L_i + 2 p_i - d_i (k_i - 1) - 1}{s_i} + 1,\]

ここで、 \(L_i\) は空間サイズ、 \(p_i\) は パディング、 \(d_i\) は拡張、 \(k_i\) はカーネルサイズ、 \(s_i\)\(i\) 空間次元のストライドです。同様の計算は他の空間次元へも適用できます。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.depthwise_convolution(x, weight, bias=None, base_axis=1, pad=None, stride=None, dilation=None, multiplier=1, n_outputs=- 1, outputs=None)[ソース]

バイアスを伴う N-D Depthwise Convolution。

参照

パラメータ
  • x (Variable) -- \((B + 1 + N)\) -D 配列 (\(M_1 \times ... \times M_B \times C \times L_1 \times ... \times L_N\)) 。

  • weight (Variable) -- \((1 + N)\) -D 配列 (\(C \times K_1 \times ... \times K_N\)) 。 [ パラメータ ]

  • bias (Variable) -- バイアスのベクトル (\(C'\)) 。[ オプション ][ パラメータ ]

  • base_axis (int) -- base axis \(B\). [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • multiplier (int) -- Number of output feature maps per input feature map. [default= 1 ]

戻り値

\((B + 1 + N)\)-D array (\(M_1 \times ... \times M_B \times C' \times L'_1 \times ... \times L'_N\)).

出力のマップサイズ \(C'\)\(C\)\(m\) を掛けて

\[C' = m \times C,\]

となります。ここで、 \(m\) は乗数です。

出力の空間サイズは、以下のように計算します。

\[L'_i = \frac{L_i + 2 p_i - d_i (k_i - 1) - 1}{s_i} + 1,\]

ここで、 \(L_i\) は空間サイズ、 \(p_i\) は パディング、 \(d_i\) は拡張、 \(k_i\) はカーネルサイズ、 \(s_i\)\(i\) 空間次元のストライドです。同様の計算は他の空間次元へも適用できます。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.deconvolution(x, weight, bias=None, base_axis=1, pad=None, stride=None, dilation=None, group=1, channel_last=False, output_padding=None, n_outputs=- 1, outputs=None)[ソース]

N-D deconvolution は、transposed convolution としても知られています。逆方向の畳み込み (入力に対する出力の微分) にチャネルごとに学習したバイアス加えて演算を行います。

通常の convolution 関数のように、 convolution() と同じ方法で重みを指定します。そして、 deconvolution() の forward 演算が convolution() の逆方向パスと演算的に同等に行われます。したがって、入力のチャネル数 ( forward convolution の出力として認識できる) を 1 次元目で指定し、グループ数で割った出力のチャネル数を 2 次元目で指定します。

For stride > 1, a parameter-wise identical deconvolution on the output of a convolution may not produce the same output shape as the input to the convolution if, due to striding, the convolution did not fully cover the input spatial dimension. The output_padding parameter can then be used to appropriately increase the calculated output shape. Note that this is used to find the output shape for the deconvolution operation, but not to add zero-padding to the output.

パラメータ
  • x (Variable) -- \((B + 1 + N)\) -D 配列 (\(M_1 \times ... \times M_B \times C \times L_1 \times ... \times L_N\)) 。

  • weight (Variable) -- \((2 + N)\)-D array (\(C \times C' \times K_1 \times ... \times K_N\)). [parameter]

  • bias (Variable) -- バイアスのベクトル (\(C'\)) 。[ オプション ][ パラメータ ]

  • base_axis (int) -- base axis \(B\). [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • group (int) -- Number of groups of channels. This makes the connection across channels sparser, by grouping connections along the mapping direction. [default= 1 ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

  • output_padding (tuple of int) -- Additional size added to the output shape. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

戻り値

\((B + 1 + N)\)-D array (\(M_1 \times ... \times M_B \times C' \times L'_1 \times ... \times L'_N\)).

出力の空間サイズは、以下のように計算します。

\[L'_i =s_i (L_i - 1) - 2 p_i + d_i (k_i - 1) + 1,\]

のように計算します。ここで、 \(s_i\) はストライド、 \(L_i\) は空間サイズ、 \(p_i\) はパディング、 \(d_i\) は拡張、 \(k_i\)\(i\) 空間次元のカーネルサイズです。同様計算は他の空間次元にも適用することができます。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.depthwise_deconvolution(x, weight, bias=None, base_axis=1, pad=None, stride=None, dilation=None, divisor=1, n_outputs=- 1, outputs=None)[ソース]

Depthwise deconvolution は、1 次元および 2 次元入力データに対して、バイアスを伴って transposed depthwise convolution を計算します。

パラメータ
  • x (Variable) -- \((B + 1 + N)\) -D 配列 (\(M_1 \times ... \times M_B \times C \times L_1 \times ... \times L_N\)) 。

  • weight (Variable) -- \((1 + N)\) -D 配列 (\(C \times K_1 \times ... \times K_N\)) 。 [ パラメータ ]

  • bias (Variable) -- バイアスのベクトル (\(C'\)) 。[ オプション ][ パラメータ ]

  • base_axis (int) -- base axis \(B\). [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • divisor (int) -- Number of input feature maps per output feature map. [default= 1 ]

戻り値

\((B + 1 + N)\)-D array (\(M_1 \times ... \times M_B \times C' \times L'_1 \times ... \times L'_N\)).

出力のマップサイズ \(C'\)\(C\)\(m\) を掛けて

\[C' = \frac{C}{d},\]

となります。ここで、 \(d\) は除数です。

出力の空間サイズは、以下のように計算します。

\[L'_i =s_i (L_i - 1) - 2 p_i + d_i (k_i - 1) + 1,\]

のように計算します。ここで、 \(s_i\) はストライド、 \(L_i\) は空間サイズ、 \(p_i\) はパディング、 \(d_i\) は拡張、 \(k_i\)\(i\) 空間次元のカーネルサイズです。同様計算は他の空間次元にも適用することができます。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.deformable_convolution(x, weight, offset, mask=None, bias=None, base_axis=1, pad=None, stride=None, dilation=None, group=1, deformable_group=1, channel_last=False, n_outputs=- 1, outputs=None)[ソース]

2-D Deformable Convolution with bias. Another convolution with fixed output channels must be passed externally to calculate the offsets and mask. Mask should be normalized to \([0,1]\) interval.

\[\begin{eqnarray} y(p) = \sum_{k=1}^{K} w_k \cdot x(p + p_k + \Delta p_k) \cdot \Delta m_k, \end{eqnarray}\]

where \(x\) and \(y\) are input and output, \(w_k\) is the weight, \(p\) is the pixel location of interest, \(p_k\) is the fixed displacement e.g., \(p_k \in \{(-1, -1), (-1, 0), \ldots (1, 1)\}\) for the 2D 3x3 receptive field, \(\Delta p_k\) is the learnable displacement, and \(\Delta m_k\) is the learnable scale normalized in \([0, 1]\) by a function like the sigmoid. Note that \(\Delta p_k\) and \(\Delta m_k\) are sample-dependent, location-dependent, and feature-independent.

参照

パラメータ
  • x (Variable) -- \((B + 1 + N)\) -D 配列 (\(M_1 \times ... \times M_B \times C \times L_1 \times ... \times L_N\)) 。

  • weight (Variable) -- \((2 + N)\) -D 配列 (\(C' \times C \times K_1 \times ... \times K_N\)) 。 [ パラメータ]

  • offset (Variable) -- Offsets for deformable convolutions. Shape is fixed to \((N, deformable{\_}group \times 2 \times Kh \times Kw, H, W)\). Offsets must be calculated externally through a separate convolution layer.

  • mask (Variable) -- Normalized mask for deformable convolutions v2. Shape is fixed to \((N, deformable{\_}group \times Kh \times Kw, H, W)\). Masks must be calculated externally together with the offsets through a separate convolution layer. [optional]

  • bias (Variable) -- バイアスのベクトル (\(C'\)) 。[ オプション ][ パラメータ ]

  • base_axis (int) -- base axis \(B\). [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • group (int) -- Number of groups of channels. This makes the connection across channels sparser, by grouping connections along the mapping direction. [default= 1 ]

  • deformable_group (int) -- Number of deformable groups of channels. [default= 1 ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

戻り値

\((B + 1 + N)\)-D array (\(M_1 \times ... \times M_B \times C' \times L'_1 \times ... \times L'_N\)).

出力の空間サイズは、以下のように計算します。

\[L'_i = \frac{L_i + 2 p_i - d_i (k_i - 1) - 1}{s_i} + 1,\]

ここで、 \(L_i\) は空間サイズ、 \(p_i\) は パディング、 \(d_i\) は拡張、 \(k_i\) はカーネルサイズ、 \(s_i\)\(i\) 空間次元のストライドです。同様の計算は他の空間次元へも適用できます。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.adaptive_separable_convolution(x, vertical_kernel, horizontal_kernel, n_outputs=- 1, outputs=None)[ソース]

NCHW (チャネル優先テンソル) 用の 2-D Adaptive Separable Convolution。サンプルおよびピクセル依存の垂直カーネルと水平カーネルが動的に生成され、この関数において特徴方向に依存しない 2 次元カーネルを近似するために使用されます。したがって、この関数で使用されるカーネルは、サンプルおよびピクセルに依存しますが、特徴方向には依存しません。

パディングが必要な場合は、この関数の前に pad 関数を使って \(x\) を入力してください。

Adaptive separable convolution は次の式で表されます。

\[\tilde{I}(c, h, w) = \sum_{j, i} K_v(j, h, w) \times K_h(i, h, w) \times I(c, h + j, w + i),\]

ここでは、 \(I(c, h, w)\) および \(\tilde{I}(c, h, w)\) は、 \(c\) 番目のチャネル、 \(h\) 番目の高さ、 \(w\) 番目の幅における入力および出力画像であり、 \(K_V(:, h, w)\) および \(K_h(:, h, w)\) は、 \(h\) 番目の高さ、 \(w\) 番目の幅における垂直および水平な 1 次元カーネルとなります。

参照

パラメータ
  • x (Variable) -- \(4-D\) 配列 (\(B \times C \times H \times W\))

  • vertical_kernel (Variable) -- \(4-D\) 配列 (\(B \times K_v \times H \times W\))

  • horizontal_kernel (Variable) -- \(4-D\) 配列 (\(B \times K_h \times H \times W\))

戻り値

\(4-D\) 配列 (\(B \times C \times H - K_v + 1 \times W - K_h + 1\))

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.max_pooling(x, kernel, stride=None, ignore_border=True, pad=None, channel_last=False, n_outputs=- 1, outputs=None)[ソース]

最大プーリング。カーネルによって決定される受容野内の最大値をプールします。

\[y_{i_1, i_2} = \max_{k_1, k_2 \in K} (x_{i_1 + k_1, i_2 + k_2})\]

ここでは、 \(x_{i_1 + k_1, i_2 + k_2}\) は入力、 \(y_{i_1, i_2}\) は出力です。

パラメータ
  • x (Variable) -- 入力変数。

  • kernel (tuple of int) -- 各空間軸に対するカーネルサイズ。

  • stride (tuple of int) -- Subsampling factors for each spatial axis. [default= kernel ]

  • ignore_border (bool) -- If false, kernels covering borders are also considered for the output. [default= True ]

  • pad (tuple of int) -- Border padding values for each spatial axis. Padding will be added both sides of the dimension. [default= (0,) * len(kernel) ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

戻り値

最大値変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.average_pooling(x, kernel, stride=None, ignore_border=True, pad=None, channel_last=False, including_pad=True, n_outputs=- 1, outputs=None)[ソース]

平均プーリング。カーネルによって決定される受容野内の平均値をプールします。

\[y_{i_1, i_2} = \frac{1}{K_1 K_2} \sum_{k1} \sum_{k2} x_{i_1 + k_1, i_2 + k_2}\]

ここでは、 \(x_{i_1 + k_1, i_2 + k_2}\) は入力、 \(y_{i_1, i_2}\) は出力です。

パラメータ
  • x (Variable) -- 入力変数。

  • kernel (tuple of int) -- 各空間軸に対するカーネルサイズ。

  • stride (tuple of int) -- Subsampling factors for each spatial axis. [default= kernel ]

  • ignore_border (bool) -- If false, kernels covering borders are also considered for the output. [default= True ]

  • pad (tuple of int) -- Border padding values for each spatial axis. Padding will be added both sides of the dimension. [default= (0,) * len(kernel) ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

  • including_pad (bool) -- If true, border padding values are considered for the output. [default= True ]

戻り値

平均値変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.global_average_pooling(x, n_outputs=- 1, outputs=None)[ソース]

警告

この関数は実験的なサポートなので、積極的には使用しないでください。

全体平均プーリング。全体のイメージから平均値をプールします。

パラメータ

x (Variable) -- 入力変数。

戻り値

平均値変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sum_pooling(x, kernel, stride=None, ignore_border=True, pad=None, channel_last=False, n_outputs=- 1, outputs=None)[ソース]

合計プーリング。カーネルによって決定される受容野内の合計値をプールします。

\[y_{i_1, i_2} = \sum_{k1} \sum_{k2} x_{i_1 + k_1, i_2 + k_2}\]

ここでは、 \(x_{i_1 + k_1, i_2 + k_2}\) は入力、 \(y_{i_1, i_2}\) は出力です。

パラメータ
  • x (Variable) -- 入力変数。

  • kernel (tuple of int) -- 各空間軸に対するカーネルサイズ。

  • stride (tuple of int) -- Subsampling factors for each spatial axis. [default= kernel ]

  • ignore_border (bool) -- If false, kernels covering borders are also considered for the output. [default= True ]

  • pad (tuple of int) -- Border padding values for each spatial axis. Padding will be added both sides of the dimension. [default= (0,) * len(kernel) ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

戻り値

合計された値の変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.unpooling(x, kernel, channel_last=False, n_outputs=- 1, outputs=None)[ソース]

プーリングの逆演算。入力値をスプレッドします。

\[y_{k_1 i_1 + j_1, k_2 i_2 + j_2} = x_{i_1, i_2}\]

ここでは、 \(_{i_1, i_2}\) は入力、 \(y_{k_1 i_1 + j_1, k_2 i_2 + j_2}\) は出力です。

パラメータ
  • x (Variable) -- 入力変数。

  • kernel (tuple of int) -- 各空間軸に対するカーネルサイズ。

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

戻り値

スプレッドされた値の変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.embed(x0, w, n_outputs=- 1, outputs=None)[ソース]

インデックス配列/テンソルを使った行列 /テンソルのスライス。

パラメータ
  • x0 (Variable) -- \((I_0, ..., I_N)\) の形状のインデックス

  • w (Variable) -- \((W_0, ..., W_M)\) の形状の重み [ パラメータ ]

戻り値

\((I_0, ..., I_N, W_1, ..., W_M)\) の形状の出力

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.rnn(x, h, weight_l0, weight=None, bias=None, num_layers=1, nonlinearity='tanh', dropout=None, bidirectional=False, training=True, n_outputs=- 1, outputs=None)[ソース]

RNN 関数は、入力シーケンスに対して非線形のエルマン RNN を実行します。 RNN 関数は次のように定義します。

\[{\mathbf h_t} = {\mathbf \tanh}( {\mathbf w_{ih}} *{\mathbf x_t} + {\mathbf b_{ih}} + {\mathbf w_{hh}}* {\mathbf h_{(t-1)}} + {\mathbf b_{hh}}).\]

以下の入出力を説明するために、次のような表記を使います。 \(T\): シーケンスの長さ、 \(B\): バッチサイズ、 \(I\): 入力サイズ、 \(L\): 層の数、 \(D\): 方向の数で1か2、 \(H\): 非表示のサイズ。

参照

パラメータ
  • x (Variable) -- \((T, B, I)\) の形状の入力 N-D 配列。

  • h (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • weight_l0 (Variable) -- \((D, H, I + H)\) の形状の入力 N-D 配列。[パラメータ]

  • weight (Variable) -- \((L-1, D, H, D * H + H)\) の形状の入力 N-D 配列。[ オプション ][ パラメータ ]

  • bias (Variable) -- \((L, D, H)\) の N-D 配列。 [ オプション ][ パラメータ ]

  • num_layers (int) -- Number of layers in the network. If set to 1, only the weights for the first layer will be invoked. Default is 1. [default= 1 ]

  • nonlinearity (string) -- Type of nonlinearity applied to input sequcne. Must be either tanh or relu. Default is tanh. [default= 'tanh' ]

  • dropout (float) -- Dropout ratio applied to parameters. Default is 0.0. [default= 0.0 ]

  • bidirectional (bool) -- If True, bidirectional computation will be performed in each layer. Default is False. [default= False ]

  • training (bool) -- Backpropagation will be performed only when it is true. Default is True. [default= True ]

戻り値

\((T, B, D * H)\) の形状の出力 \(y\) ~nnabla.Variable: \((L, D, B, H)\) の形状の出力 \(h_n\)

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.lstm(x, h, c, weight_l0, weight=None, bias=None, num_layers=1, dropout=None, bidirectional=False, training=True, n_outputs=- 1, outputs=None)[ソース]

N-ステップ LSTM 層。

\[\begin{split}{\mathbf f_t} &=& {\mathbf \sigma}( {\mathbf W_f} *{\mathbf x_t} + {\mathbf U_f}* {\mathbf h_{(t-1)}} + {\mathbf b_f})\\ {\mathbf i_t} &=& {\mathbf \sigma}( {\mathbf W_i} *{\mathbf x_t} + {\mathbf U_i}* {\mathbf h_{(t-1)}} + {\mathbf b_i})\\ {\mathbf o_t} &=& {\mathbf \sigma}( {\mathbf W_o} *{\mathbf x_t} + {\mathbf U_o}* {\mathbf h_{(t-1)}} + {\mathbf b_o})\\ {\mathbf c_t} &=& {\mathbf f_t}\odot {\mathbf c_{(t-1)}} + {\mathbf i_t}\odot {\mathbf \tanh}({\mathbf W_c}*{\mathbf x_t} + {\mathbf U_c} *{\mathbf h_{(t-1)}} + {\mathbf b_c})\\ {\mathbf h_t} &=& {\mathbf o_t} \odot {\mathbf \tanh}({\mathbf c_t}).\end{split}\]

以下の入出力を説明するために、次のような表記を使います。 \(T\): シーケンスの長さ、 \(B\): バッチサイズ、 \(I\): 入力サイズ、 \(L\): 層の数、 \(D\): 方向の数で1か2、 \(H\): 非表示のサイズ。

参照

パラメータ
  • x (Variable) -- \((T, B, I)\) の形状の入力 N-D 配列。

  • h (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • c (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • weight_l0 (Variable) -- 第 1 層に対する重みパラメータ。シェイプは \((D, 4, H, I + H)\)。 [ パラメータ ]

  • weight (Variable) -- 第 2 層以上に対する重みパラメータ。形状は \((L-1, D, 4, H, D * H + H)\)。 [ オプション ][ パラメータ ]

  • bias (Variable) -- バイアスのベクトル (\(L\))。形状は \((L, D, 4, H)\)。 [ オプション ][ パラメータ ]

  • num_layers (int) -- Number of layers in the network. If set to 1, only the weights for the first layer will be invoked. Default is 1. [default= 1 ]

  • dropout (float) -- Dropout ratio applied to parameters. Default is 0.0. [default= 0.0 ]

  • bidirectional (bool) -- If True, bidirecitonal computation will be performed in each layer. Default is False. [default= False ]

  • training (bool) -- Backpropagation will be performed only when it is True. Default is True. [default= True ]

戻り値

\((T, B, D * H)\) の形状の出力 \(y\)。メモリレイアウトは \((T, B, D, H)\) として再形成することができます。 ~nnabla.Variable: \((L, D, B, H)\) の形状の出力 \(h_n\) ~nnabla.Variable: \((L, D, B, H)\) の形状の出力 \(c_n\)

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.gru(x, h, weight_l0, weight=None, bias=None, num_layers=1, dropout=None, bidirectional=False, training=True, n_outputs=- 1, outputs=None)[ソース]

N-ステップ GRU 層。

\[\begin{split}{\mathbf r_t} &=& {\mathbf \sigma}( {\mathbf W_r} *{\mathbf x_t} + {\mathbf U_r}* {\mathbf h_{(t-1)}} + {\mathbf b_r})\\ {\mathbf z_t} &=& {\mathbf \sigma}( {\mathbf W_z} *{\mathbf x_t} + {\mathbf U_z}* {\mathbf h_{(t-1)}} + {\mathbf b_z})\\ {\mathbf n_t} &=& {\mathbf \tanh}( {\mathbf W_n}{\mathbf x_t}+ {\mathbf b_{in}}+ {\mathbf r_n}\odot( {\mathbf U_n}{\mathbf h_{t-1}}+ {\mathbf b_{hn}})) \\ {\mathbf h_t} &=& (1- {\mathbf z_t})\odot {\mathbf n_t} + {\mathbf z_t}\odot {\mathbf h_{t-1}}.\end{split}\]

以下の入出力を説明するために、次のような表記を使います。 \(T\): シーケンスの長さ、 \(B\): バッチサイズ、 \(I\): 入力サイズ、 \(L\): 層の数、 \(D\): 方向の数で1か2、 \(H\): 非表示のサイズ。

参照

パラメータ
  • x (Variable) -- \((T, B, I)\) の形状の入力 N-D 配列。

  • h (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • weight_l0 (Variable) -- 第 1 層に対する重みパラメータ。形状は \((D, 3, H, I + H)\) 。 [ パラメータ ]

  • weight (Variable) -- 第 2 層以上に対する重みパラメータ。形状は \((L-1, D, 3, H, D * H + H)\) 。 [ オプション ][ パラメータ ]

  • bias (Variable) -- バイアスのベクトル (\(L\))。形状は \((L, D, 4, H)\)。 [ オプション ][ パラメータ ]

  • num_layers (int) -- Number of layers in the network. If set to 1, only the weights for the first layer will be invoked. Default is 1. [default= 1 ]

  • dropout (float) -- Dropout ratio applied to parameters. Default is 0.0. [default= 0.0 ]

  • bidirectional (bool) -- If True, bidirecitonal computation will be performed in each layer. Default is False. [default= False ]

  • training (bool) -- Backpropagation will be performed only when it is True. Default is True. [default= True ]

戻り値

\((T, B, D * H)\) の形状の出力 \(y\) 。メモリレイアウトは \((T, B, D, H)\) として再形成できます。 ~nnabla.Variable: \((L, D, B, H)\) の形状の出力 \(h_n\)

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.multi_head_attention(query, key, value, num_heads, q_weight, k_weight, v_weight, out_weight, q_bias=None, k_bias=None, v_bias=None, out_bias=None, attn_bias_k=None, attn_bias_v=None, dropout=0.0, additive_mask=None, key_padding_mask=None)[ソース]

MultiHeadAttention。

Computes multi-headed attention with query, key, and value. We use the following notations to describe the inputs and outputs below. \(L_T\): target sequence length, \(L_S\): source sequence length, \(B\): batch size, \(D\): input dimension, \(E\): embedding dimension, \(H\): number of attention heads.

参照

A. Vaswani et al. "Attention is All You Need." NIPS. 2017. <https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf>

パラメータ
  • query (Variable) -- Input N-D array with shape \((L_T, B, D_q)\).

  • key (Variable) -- Input N-D array with shape \((L_S, B, D_k)\).

  • value (Variable) -- Input N-D array with shape \((L_S, B, D_v)\).

  • num_heads (int) -- attention head の数。埋め込みの次元 E はヘッドの数で割り切れなければなりません。通例どおり、デフォルトは 12 です。

  • q_weight (Variable) -- Input N-D array with shape \((D_q, E)\).

  • k_weight (Variable) -- Input N-D array with shape \((D_k, E)\).

  • v_weight (Variable) -- Input N-D array with shape \((D_v, E_v)\).

  • out_weight (Variable) -- Input N-D array with shape \((D_v, E_{out})\).

  • q_bias (Variable, optional) -- \((E, )\) の形状の入力 N-D 配列。

  • k_bias (Variable, optional) -- \((E, )\) の形状の入力 N-D 配列。

  • v_bias (Variable, optional) -- Input N-D array with shape \((E_v, )\).

  • out_bias (Variable, optional) -- Input N-D array with shape \((E_{out}, )\).

  • attn_bias_k (Variable, optional) -- \((E, )\) の形状の入力 N-D 配列。

  • attn_bias_v (Variable, optional) -- Input N-D array with shape \((E_v, )\).

  • dropout (float, optional) -- パラメータに対して適用されたドロップアウトの割合。デフォルトは 0 です。

  • additive_mask (Variable, optional) -- \((L_T, L_S)\) の形状の入力 N-D 配列。特定の位置へのアテンションを防ぐため、値はアテンション層へ追加されます。

  • key_padding_mask (Variable, optional) -- \((B, L_S)\) の形状の入力 N-D 配列。アテンション層は、指定されたパディング要素を無視します。値は 1 または 0 である必要があります。

戻り値

Output \(y\) with shape \((L_T, B, E_{out})\) ~nnabla.Variable: Output \(h_n\) with shape \((B, L_T, L_S)\)

戻り値の型

Variable

nnabla.functions.patch_correlation(x1, x2, patch=(1, 1), shift=(0, 0), patch_step=(1, 1), shift_step=(1, 1), padding=(0, 0, 0, 0), channel_last=False)[ソース]

Multiplicative patch-wise comparison between inputs x1 and x2, which must both be 4-dimensional NCHW (with channel_last=False) or NHWC (with channel_last=True) arrays (where N is the number of samples, H and W are the sample height and width and C is the number of channels). The function returns a 5-D array with shape \((N, C_y, C_x, H_o, W_o)\) where \(H_o, W_o\) are determined by the possible patch locations within the, optionally padded, input image sizeand \(C_y, C_x\) are determined by the optionally shifted patch positions.

Mathematically, the patch correlation is formulated as

\[O(s_y, s_x, h_0, w_0) = \sum_{c} \sum_{k_h} \sum_{k_w} I_1(c, h + k_h, w + k_w) \times I_2(c, h + k_h + s_h, w + k_w + s_w),\]

ここでは、 \(I_1(c, h, w)\) および \(I_2(c, h, w)\)\(c\) 番目のチャネル、 \(h\) 番目の高さ、 \(w\) 番目の幅における入力、 \(k_h, k_w\) はパッチサイズのインデックス、 \(s_h, s_w\) はシフトのインデックスです。

パッチが画像の次元まで拡張され、他のすべてのパラメータがデフォルト値を使用する場合は、(サンプルごとに) 単一の相関値が生成されます。

>>> import numpy as np, nnabla as nn, nnabla.functions as F
>>> N, C, H, W = (1, 2, 3, 4)
>>> x = nn.Variable.from_numpy_array(np.ones([N, C, H, W]))
>>> F.patch_correlation(x, x, patch=(H, W)).d
array([[[[[24.]]]]], dtype=float32)

画像サイズより小さいパッチは、水平方向および垂直方向に移動し、位置ごとの値を生成します。 patch_step 引数は、位置の増分を調整するために使うことができます。

>>> F.patch_correlation(x, x, patch=(H-1, W-1)).d
array([[[[[12., 12.],
          [12., 12.]]]]], dtype=float32)
>>> F.patch_correlation(x, x, patch=(H-1, W-1), patch_step=(2, 1)).d
array([[[[[12., 12.]]]]], dtype=float32)

複数の相関は、 shift_step の増分の shift 値によって指定される最大垂直および水平距離にまたがる相対オフセットで、 x1 からのパッチと x2 からのパッチの間の各位置で実行することができます。シフトされた相関値は、垂直および水平シフトの第 2 および第 3 出力の次元から取得することができます。

>>> F.patch_correlation(x, x, (H, 1), shift=(0, 1)).shape
(1, 1, 3, 1, 4)
>>> F.patch_correlation(x, x, (H, 1), shift=(0, 1)).d
array([[[[[0., 6., 6., 6.]],
         [[6., 6., 6., 6.]],
         [[6., 6., 6., 0.]]]]], dtype=float32)
>>> F.patch_correlation(x, x, (H, 1), shift=(0, 1), shift_step=(1, 2)).d
array([[[[[0., 6., 6., 6.]],
         [[6., 6., 6., 0.]]]]], dtype=float32)

ゼロ値のパディングは、入力画像の上下左右にそれぞれ適用することができます。

>>> F.patch_correlation(x, x, patch=(H, W), padding=(0, 1, W, W)).d
array([[[[[ 0.,  6., 12., 18., 24., 18., 12.,  6.,  0.],
          [ 0.,  4.,  8., 12., 16., 12.,  8.,  4.,  0.]]]]], dtype=float32)

この関数を使って FlowNetC correlation 層を実装することができます。

>>> N, C, H, W = (1, 256, 44, 60)
>>> x1, x2 = nn.Variable((N, C, H, W)), nn.Variable((N, C, H, W))
>>> F.patch_correlation(x1, x2, shift=20, shift_step=2).shape
(1, 21, 21, 44, 60)

参照

パラメータ
  • x1 (Variable) -- \((N, C, H, W)\) または \((N, H, W, C)\) の形状の入力 N-D 配列。

  • x2 (Variable) -- \((N, C, H, W)\) または \((N, H, W, C)\) の形状の入力 N-D 配列。

  • patch -- 相関パッチの高さおよび幅のタプル。単一整数の場合は、高さと幅が同じ値になります。

  • shift -- x1 からの単一パッチと相関関係にある x2 からのパッチの最大垂直および水平変位のタプル。単一整数の場合は、垂直および水平変位が同じ値になります。

  • patch_step -- 入力画像形状内での相関パッチの位置の移動のための垂直および水平増分のタプル。単一整数の場合は、垂直および水平増分が同じ値になります。

  • shift_step -- シフト範囲内での相対オフセット位置の移動のための垂直および水平増分のタプル。単一整数の場合は、垂直および水平増分が同じ値になります。

  • padding -- 上下左右のパディング範囲のタプル。2 つの値からなるタプルは、タプルの 1 番目、2 番目の値がそれぞれ上下の値 (同じ値)、左右の値 (同じ値) となります。単一整数の場合は、すべてのサイドのパディング範囲の値が同じになります。

  • channel_last -- True の場合、最後の次元はチャネル (NHWC 形式) となります。

戻り値

channel_last=True の場合、 \((N, C_y, C_x, H_o, W_o)\) または \((N, H, W, C_y, C_x)\) の形式の N-D 配列。

出力の空間サイズは、以下のように計算します。

\[H_o = \frac{H + (top\_pad + bottom\_pad) - patch_v}{patch\_step_v} + 1.\]

出力のチャネルサイズは次のように計算されます。

\[C_y = \frac{2 \times shift_v}{shift\_step_v} + 1.\]

\(W_o\) および \(C_x\) は異なるコンポーネントでも同じ計算となります。

戻り値の型

Variable

nnabla.functions.roi_align(input, boxes, output_size, spatial_scale=(1.0, 1.0), sampling_ratio=None, channel_last=None, n_outputs=- 1, outputs=None)[ソース]

Map Regions of Interest (RoI) defined by bounding boxes to features of output_size height and width using bilinear interpolation with sampling_ratio points in the interpolation grid.

>>> import numpy as np, nnabla as nn, nnabla.functions as F
>>> nn.set_auto_forward(True)
>>> input = F.pad(F.constant(1, (1, 1, 2, 2)) * 2, (1, 1, 1, 1), "constant", 1)
>>> print(input.d)
[[[[1. 1. 1. 1.]
   [1. 2. 2. 1.]
   [1. 2. 2. 1.]
   [1. 1. 1. 1.]]]]
>>> boxes = nn.Variable.from_numpy_array([[0, 0, 0, 4, 4], [0, 1, 1, 3, 3]])
>>> output = F.roi_align(input, boxes, (2, 2))
>>> print(output.d[0])
[[[[1.25 1.25]
   [1.25 1.25]]]
>>> print(output.d[1])
[[[2.   2.  ]
  [2.   2.  ]]]]

The spatial_scale argument tuple may be used to appropriately scale the box coordinates, for example, to scale normalized box coordinate to the input height and width dimensions.

>>> input = F.reshape(F.arange(1, 13), (1, 1, 3, 4))
>>> print(input.d)
>>> boxes = nn.Variable.from_numpy_array([[0, 1/4, 1/3, 3/4, 2/30]])
>>> output = F.roi_align(input, boxes, (1, 2), spatial_scale=(3, 4))
>>> print(input.d)
[[[[6. 7.]]]]

References:

パラメータ
  • input (Variable) -- N-D array with shape \((N, H, W, C)\) or \((N, C, H, W)\).

  • boxes (Variable) -- N-D array with shape \((K, 5)\) containing box coordinates in (b, x1, y1, x2, y2) format where b is the batch index. Note that an invalid (out-of-range) batch index will generate an error only when running on CPU; when using a GPU context the batch index values are clipped to the range of input samples.

  • output_size (tuple of int) -- the height and width of the output feature maps.

  • spatial_scale (repeated float) -- Scaling factor from box to input coordinates, as (x, y). [default= (1.0, 1.0) ]

  • sampling_ratio (int) -- The number of sampling points used for interpolation. Computed as ceil((y2 - y1) / output_size[0]) for height and likewise for width if sampling_ratio <= 0. [default= -1 ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

戻り値

N-D array with shape \((K, C, output\_size[0], output\_size[1])\) or \((K, output\_size[0], output\_size[1], C)\).

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

ニューラルネットワークの活性化
nnabla.functions.sigmoid(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの sigmoid 関数。

\[f(x) = \frac{1}{1 + \exp(-x)},\]
パラメータ

x (Variable) -- 入力

戻り値

出力

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.swish(x, n_outputs=- 1, outputs=None)[ソース]

Ramachandran 他 (2017) による要素ごとの swish 関数。

\[y_i = \frac{x_i}{1 + \exp(-x_i)},\]

参照

パラメータ

x (Variable) -- 入力

戻り値

出力

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.tanh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの双曲線正接 (tanh) 関数。

\[y_i = \tanh (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.relu(x, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Rectified Linear Unit ( ReLU ) 関数。

\[y_i = \max (0, x_i)\]
パラメータ
  • x (Variable) -- N-D 配列

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.softmax(x, axis=None, n_outputs=- 1, outputs=None)[ソース]

Softmax normalization。 axis によって指定される次元に沿って、以下のとおり計算します。

\[y_i = \frac{\exp(x_i)}{\sum_j \exp(x_j)}\]

ここでは、 \(x_i\) は入力、 \(y_i\) は出力です。

パラメータ
  • x (Variable) -- N-D 配列。通常、スコアを表します。

  • axis (int) -- Axis normalization is taken. [default= len(x.shape) - 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.log_softmax(x, axis=None, n_outputs=- 1, outputs=None)[ソース]

Softmax normalization から log に続く融合演算。次のように定義されます。

\[y_i = \log \frac{\exp(x_i)}{\sum_j \exp(x_j)},\]

ここでは、 \(y_i\) は入力、 \(x_i\) は i 番目のチャネルにおける出力です。この融合の利点は、log アプリケーションによる数値の不安定性を軽減することです。

上記の定義は、次のように再定義することができます。

\[y_i = x_i - \max_j(x_j) - \log\left(\sum_j \exp(x_j - \max_k(x_k))\right).\]

非融合演算においては 0 に対する log の値を求めることができますが、ここでは log が常に \(e\) 以上の値に適用されるため、より安定します。

また、backward 勾配演算は log 勾配により、 x による除算を行わないため、元の勾配演算よりも安定した演算となります。次のように定義されます。

\[dx_i = dy_i - y_i * \sum_j dy_j\]

ここでは、 \(dx_i\) および \(dy_i\) はそれぞれ \(x_i\)\(y_i\) に対する loss 勾配となります。

パラメータ
  • x (Variable) -- N-D 配列。通常、スコアを表します。

  • axis (int) -- Axis normalization is taken. [default= len(x.shape) - 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.elu(x, alpha=1.0, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Exponential Linear Unit ( ELU ) 関数。

\[\begin{split}y_i= \left\{ \begin{array}{ll} x_i & (x > 0)\\ \alpha (\exp(x_i) - 1) & (x \leq 0) \end{array} \right..\end{split}\]

参照

パラメータ
  • x (Variable) -- N-D 配列

  • alpha (float) -- Coefficient for negative outputs. \(\alpha\) in definition [default= 1.0 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.selu(x, scale=1.05070098735548, alpha=1.673263242354377, n_outputs=- 1, outputs=None)[ソース]

Klambauer 他 (2017) による要素ごとの Scaled Exponential Linear Unit ( SELU ) 関数。

\[\begin{split}y_i= \lambda \left\{ \begin{array}{ll} x_i & (x > 0)\\ \alpha (\exp(x_i) - 1) & (x \leq 0) \end{array} \right..\end{split}\]

係数 \(\lambda\)\(\alpha\) は、Klambauer 他 (2017) に記載のとおり、次の値 \(\lambda_{01}\)\(\alpha_{01}\) をそれぞれデフォルトとします。

\[\begin{split}\begin{array}{lll} \lambda_{01} &=& \left( 1 - \operatorname{erfc}\left( \frac{1}{\sqrt{2}} \right) \sqrt{e} \right) \sqrt{2 \pi} \\ && \left( 2 \operatorname{erfc} \left( \sqrt{2} \right) e^2 + \pi \operatorname{erfc}\left( \frac{1}{\sqrt{2}} \right)^2 e \right. \\ && \left. - 2(2 + \pi) \operatorname{erfc} \left( \frac{1}{\sqrt{2}} \right) \sqrt{e} + \pi + 2 \right)^{-1/2} \\ &\approx& 1.0507 \\ \alpha_{01} &=& - \frac {\sqrt {\frac {2}{\pi}}} {\operatorname{erfc} \left( \frac{1}{\sqrt{2}} \right) \exp \left(\frac {1} {2} \right) - 1} \\ &\approx& 1.67326 \end{array}\end{split}\]

参照

パラメータ
  • x (Variable) -- N-D 配列

  • scale (float) -- The coefficient \(\lambda\) in the definition. [default= 1.05070098735548 ]

  • alpha (float) -- The coefficient \(\alpha\) in the definition. [default= 1.673263242354377 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.crelu(x, axis=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Concatenated Rectified Linear Unit ( CReLU ) 関数。この関数は \(x\)\(-x\) の ReLU を計算し、その後、指定された軸における結果を連結し、その結果の配列を返します。

参照

パラメータ
  • x (Variable) -- N-D 配列。

  • axis (int) -- The ReLU activations of positive inputs and negative inputs are concatenated at axis. [default= 1 ]

戻り値

連結によって軸の次元が 2 倍になった N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.celu(x, alpha=1.0, axis=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Concatenated Exponential Linear Unit ( CELU ) 関数。指定された軸におけるプラスおよびマイナス入力の ELU 出力を連結します。

パラメータ
  • x (Variable) -- N-D 配列。

  • alpha (float) -- Coefficient for negative outputs. \(\alpha\) in definition. [default= 1.0 ]

  • axis (int) -- The ELU activations of positive inputs and negative inputs are concatenated at axis. [default= 1 ]

戻り値

連結によって軸の次元が 2 倍になった N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.gelu(x, n_outputs=- 1, outputs=None)[ソース]

Gaussian Error Unit ( GELU ) 関数。

\[GELU(x) = xP(X \leq x) = x \Phi (x)\]

上記は以下によって近似されます。

\[GELU(x) = 0.5x (1 + \tanh ( \sqrt(2/\pi)(x + 0.044715x^3) ))\]

参照

パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.mish(x, n_outputs=- 1, outputs=None)[ソース]

Mish activation function.

\[Mish(x) = x \tanh(\log(1+\exp(x_i)))\]

参照

パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.prelu(x0, x1, base_axis=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Parametrized Rectified Linear 関数。次のように計算します。

\[y_i = \max(0, x_i) + w_i \min(0, x_i)\]

ここでは、マイナス領域の傾き \(w\) は学習され、チャネル ( base_axis で指定される軸) 間で変更されます。

パラメータ
  • x0 (Variable) -- (N-D 配列) 入力

  • x1 (Variable) -- (N-D 配列) 重み

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.leaky_relu(x, alpha=0.1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Leaky Rectified Linear Unit (ReLU) 関数。

次のように定義します。

\[y_i = \alpha * \min(0, x_i) + \max (0, x_i)\]
パラメータ
  • x (Variable) -- N-D 配列

  • alpha (float) -- The slope value multiplied to negative numbers. \(\alpha\) in the definition. [default= 0.1 ]

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.relu6(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの ReLU6 関数。 ReLU 活性化を 6 に制限することは、学習初期段階からスパースな特徴を学習することがあります。

\[ReLU6(x) = \min(\max(0,x,),6)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.hard_sigmoid(x, n_outputs=- 1, outputs=None)[ソース]

セグメントごとの sigmoid の線形の近似。精度より計算速度が重要である場合に適しています。 \(x < -2.5\) の場合は、 \(0\) を返します。 \(x> 2.5\) の場合は、 \(1\) を返します。 \(-2.5 <= x <= 2.5\) の場合は、 \(0.2x + 0.5\) を返します。

パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.hard_tanh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの HardTanh 関数。Tanh 関数より計算量は少ないです。 \(x > 1\) の場合、 \(1\) を返します。 \(x < -1\) の場合、 \(-1\) を返します。それ以外は、 \(x\) を返します。

パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.log_sigmoid(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの LogSigmoid 関数。

\[LogSigmoid(x) = \log(1/(1+\exp(-x_i)))\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.softplus(x, beta=1.0, n_outputs=- 1, outputs=None)[ソース]

要素ごとの SoftPlus 関数。上限と下限のある Sigmoid や Tanh と異なり、SoftPlus は下限のみが 0 に抑えられます。

\[SoftPlus(x) = \frac{1}{\beta} * \log(1+\exp(\beta * x_i))\]
パラメータ
  • x (Variable) -- N-D 配列

  • beta (float) -- the beta value for SoftPlus formulation [default= 1.0 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.softsign(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの SoftSign。Tanh 関数の代わりに使うことができます。Tanh は指数関数を扱いますが、 SoftSign は多項式を扱います。

\[SoftSign(x) = x/(1+|x|)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.tanh_shrink(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの TanhShrink 関数。

\[TanhShrink(x) = x - \tanh(x)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sinc(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Sinc 関数。他の主な活性化関数と異なり、Sinc 関数は上がり下がりがあります。 \(x = 0\) の場合、 \(1\) を返します。それ以外は、 \(\sin(x)/x\) を返します。

パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

Normalization
nnabla.functions.batch_normalization(x, beta, gamma, mean, variance, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None)[ソース]

Batch normalization。

\[\begin{split}\begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\right)^2 \\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\ y_i &=& \hat{x}_i \gamma + \beta. \end{eqnarray}\end{split}\]

テスト中、使用される平均と分散の値は、学習中に変動する平均を使って計算される値となります。

参照

パラメータ
  • x (Variable) -- 入力の N-D 配列。

  • beta (Variable or None) -- 学習される betaの N-D 配列。None の場合、バイアス項を省きます。

  • gamma (Variable or None) -- 学習される gamma の N-D 配列。 None の場合、スケール項を省きます。

  • mean (Variable or None) -- ( forward 実行中に変更される) 実行平均の N-D 配列。 None ならば、ダミー変数が作られ、実行の平均は更新されません。batch_stat=False で、mean=None は禁じられています。

  • variance (Variable or None) -- ( forward 実行中に変更される ) 実行分散の N-D 配列。 None の場合、ダミー変数が生成され、実行分散は更新されません。batch_stat=False の場合、variance=None は禁止されています。

  • axes (list of int or int) -- これらの軸における平均および分散を計算します。

  • decay_rate (float) -- 実行の平均と分散の減衰率。

  • eps (float) -- 標準偏差によるゼロ除算を避けるための小さな値。

  • batch_stat (bool) -- 実行中の統計よりミニバッチの統計を使います。 False の場合、平均と分散は ~nnabla.Variable である必要があります。 (None は禁止されています)

  • output_stat (bool) -- true の場合、平均と分散のバッチの統計を Variable として返します。また、これらは微分可能です。

戻り値

Batch normalization の出力を Variable として返します。 output_stat=True の場合、ミニバンの平均と分散も返します

参考

nnabla.function_bases.batch_normalization.

nnabla.functions.fused_batch_normalization(x, beta, gamma, mean, variance, z=None, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, nonlinearity='relu', output_stat=False, n_outputs=None)[ソース]

追加操作および活性化と融合した Batch normalization。

参照

パラメータ
  • x (Variable) -- 入力の N-D 配列。

  • beta (Variable or None) -- 学習される betaの N-D 配列。None の場合、バイアス項を省きます。

  • gamma (Variable or None) -- 学習される gamma の N-D 配列。 None の場合、スケール項を省きます。

  • mean (Variable or None) -- ( forward 実行中に変更される) 実行平均の N-D 配列。 None ならば、ダミー変数が作られ、実行の平均は更新されません。batch_stat=False で、mean=None は禁じられています。

  • variance (Variable) -- ( forward 実行中に変更される ) 実行分散の N-D 配列。 None の場合、ダミー変数が生成され、実行分散は更新されません。batch_stat=False の場合、variance=None は禁止されています。

  • z (Variable, optional) -- N-D 配列

  • axes (list of int or int) -- これらの軸における平均および分散を計算します。

  • decay_rate (float) -- 実行の平均と分散の減衰率。

  • eps (float) -- 標準偏差によるゼロ除算を避けるための小さな値。

  • batch_stat (bool) -- 実行中の統計よりミニバッチの統計を使います。 False の場合、平均と分散は ~nnabla.Variable である必要があります。 (None は禁止されています)

  • nonlinearity (str) -- relu から選択される非線形。デフォルトは relu です。

  • output_stat (bool) -- true の場合、平均と分散のバッチの統計を Variable として返します。また、これらは微分可能です。

戻り値

Batch normalization の出力を Variable として返します。 output_stat=True の場合、ミニバンの平均と分散も返します

参考

nnabla.function_bases.batch_normalization.

nnabla.functions.sync_batch_normalization(x, beta, gamma, mean, variance, comm, group='world', axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, n_outputs=None)[ソース]

Synchronized batch normalization。

タスクによっては (例えば、意味論的セグメンテーション) 、バッチサイズが小さすぎて、 BatchNormalization 層がうまく動作しない場合があります。SyncBatchNorlization 層は、複数のプロセス間でバッチ統計 (平均と分散) を同期することによって、この問題を解決します。

\[\begin{split}\begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2 \\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon}} \\ y_i &=& \hat{x}_i \gamma + \beta. \end{eqnarray}\end{split}\]

参照

パラメータ
  • x (Variable) -- 入力の N-D 配列。

  • beta (Variable or None) -- 学習される betaの N-D 配列。None の場合、バイアス項を省きます。

  • gamma (Variable or None) -- 学習される gamma の N-D 配列。 None の場合、スケール項を省きます。

  • mean (Variable or None) -- ( forward 実行中に変更される) 実行平均の N-D 配列。 None ならば、ダミー変数が作られ、実行の平均は更新されません。batch_stat=False で、mean=None は禁じられています。

  • variance (Variable or None) -- ( forward 実行中に変更される) 実行分散の N-D 配列。None の場合、ダミー変数が生成され、実行分散は更新されません。 batch_stat=False の場合、variance=None は禁止されています。

  • comm (Communicator) -- communicator

  • group (string) -- communicator グループの名前

  • axes (list of int or int) -- これらの軸における平均および分散を計算します。

  • decay_rate (float) -- 実行の平均と分散の減衰率。

  • eps (float) -- 標準偏差によるゼロ除算を避けるための小さな値。

  • batch_stat (bool) -- 実行中の統計よりミニバッチの統計を使います。 False の場合、平均と分散は ~nnabla.Variable である必要があります。 (None は禁止されています)

  • output_stat (bool) -- true の場合、平均と分散のバッチの統計を Variable として返します。また、これらは微分可能です。

戻り値

Batch normalization の出力を Variable として返します。 output_stat=True の場合、ミニバンの平均と分散も返します

参考

nnabla.function_bases.batch_normalization.

nnabla.functions.mean_subtraction(x, mean, t, base_axis=1, update_running_mean=True)[ソース]

入力配列の要素の平均を減算して、平均を \(0\) に正規化します。この関数を使った配列の前処理は、画像分類のような様々なタスクで精度向上に効果があります。

学習時、この関数は次のように定義されます。

\[\begin{split}\begin{eqnarray} \mu &=& \frac{1}{M} \sum x_i \\ y_i &=& x_i - \mu \end{eqnarray}\end{split}\]

テスト中、使用される平均値は学習時に変動する平均によって計算されたものです。

注釈

backward は、最新のミニバッチのみを考慮した近似微分を実行します。

パラメータ
  • x (Variable) -- 入力の N-D 配列。

  • mean (Variable) -- ( forward 実行中に変更される ) 実行の平均の N-D 配列。

  • t (Variable) -- ( forward 実行中に変更される ) 実行平均のイテレーション回数のスカラ。

  • base_axis (int) -- Base axis of Mean Subtraction operation. Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • update_running_mean (bool) -- Update running mean during forward execution. [default= True ]

戻り値

N-D 配列。

戻り値の型

Variable

参考

nnabla.function_bases.mean_subtraction.

nnabla.functions.norm_normalization(x, p=None, axes=None, eps=1e-12)[ソース]

Norm normalization.

\[y = \frac{x_i}{\|x\|_p}\]
パラメータ
  • x (Variable) -- N-D 配列。

  • p (float) -- Order of the norm. [default= 2 ]

  • axes (repeated int64) -- Axes to be reduced. If empty list is given, all dimensions are reduced. [default= range(x.ndim) ]

  • eps (float) -- Epsilon for the normalization. This eps is added before taking the p-th root in the norm computation. [default= 1e-12 ]

戻り値

N-D 配列

戻り値の型

Variable

nnabla.functions.clip_by_value(x, min, max)[ソース]

値によって入力をクリップします。

\[\begin{split}y = \begin{cases} max & (x > max) \\ x & (otherwise) \\ min & (x < min) \end{cases}.\end{split}\]
パラメータ
  • x (Variable) -- 入力変数。

  • min (Variable or float) -- x がクリップされる最小値。min の形状は x の形状と同じでなければならないことに注意してください。

  • max (Variable or float) -- x がクリップされる最大値。max の形状は x の形状と同じでなければならないことに注意してください

戻り値

N-D 配列。

戻り値の型

Variable

nnabla.functions.clip_grad_by_value(x, min, max, n_outputs=- 1, outputs=None)[ソース]

forward パスでは、この関数は identity として動作します。

以下は、backward パスの場合です。

\[\begin{split}g_x = \begin{cases} max & (g_y > max) \\ g_y & (otherwise) \\ min & (g_y < min) \end{cases}.\end{split}\]

一般的には、計算グラフ全体を通して、勾配の急激な増加を防ぐために使われます。例えば、以下は各特徴マップに対する勾配値をクリップしたい場合です。

x = nn.Variable([16, 3, 32, 32])
min = F.broadcast(nn.Variable.from_numpy_array(np.asarray([-1.0]).reshape((1, 1, 1, 1))), (16, 3, 32, 32))
max = F.broadcast(nn.Variable.from_numpy_array(np.asarray([1.0]).reshape((1, 1, 1, 1))), (16, 3, 32, 32))
c = F.clip_grad_by_value(x, min=min, max=max)
h = PF.convolution(c, 64, (3, 3), pad=(1, 1))
パラメータ
  • x (Variable) -- 入力の N-D 配列。

  • min (Variable) -- y の勾配がクリップされる最小の入力値の N-D 配列。 min の形状は x の形状と同じである必要があり、 min への backward は行われないということに注意してください。

  • max (Variable) -- y の勾配がクリップされる最大の入力値の N-D 配列。 max の形状は x の形状と同じである必要があり、 max への逆方向は行われないということに注意してください。

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.clip_by_norm(x, clip_norm, axis=None)[ソース]

L2 ノルムが ( clip_norm において定義 )閾値より大きい場合は、L2 ノルムにより入力をクリップします。閾値より小さい場合は、入力は変更されません。そのような場合は、演算は次のように表します。

\[y = N \times \frac{x}{\|x\|_2}.\]

ここでは、 \(x\) は入力、 \(y\) は出力、 \(N\)clip_norm です。これは axes が指定されない場合です。 axes が指定される場合は、ノルムは axes 上で計算されます。

パラメータ
  • x (Variable) -- 入力変数。

  • clip_norm (Variable or float) -- 入力スカラ変数または浮動小数点値。正の値である必要があります。

  • axis (None, int or tuple of ints) -- 軸、または削減が行われる軸。 デフォルト値 None を渡すことで、すべての次元を削減します。

戻り値

N-D 配列。

戻り値の型

Variable

nnabla.functions.clip_grad_by_norm(x, clip_norm=None, axes=None, n_outputs=- 1, outputs=None)[ソース]

forward パスでは、この関数は identity として動作します。

以下は、backward パスの場合です。

\[g_x = N \times \frac{g_y}{\|g_y\|_2}.\]

ここでは、 \(g_x\) は入力に対する勾配、 \(g_y\) は出力に対する勾配、 \(N\)\(g_y\) のノルムとなる clip_norm です。これは axes が指定されない場合です。 axes が指定される場合は、ノルムは axes 上で計算されます。

一般的には、計算グラフ全体を通して、勾配の急激な増加を防ぐために使われます。例えば、以下は、特徴軸に対する勾配値を正規化したい場合です。

x = nn.Variable([16, 3, 32, 32])
c = F.clip_grad_by_norm(x, axes=(1, ))
h = PF.convolution(c, 64, (3, 3), pad=(1, 1))
パラメータ
  • x (Variable) -- 入力の N-D 配列。

  • clip_norm (float) -- Clip to the norm of input to clip_norm in the backward pass. [default= 1.0 ]

  • axes (repeated int64) -- Axes to be reduced. If empty list is given, all dimensions are reduced to scalar. This is used in the forward pass. [default= range(x.ndim) ]

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.layer_normalization(x, beta, gamma, batch_axis=0, eps=1e-05, output_stat=False)[ソース]

入力テンソルに Layer Normalization を適用します。また、以下のように定義されます。

\[\begin{split}\begin{eqnarray} \mu^l &=& \frac{1}{H} \sum_{i=1}^{H} x_i^l \\ \sigma^l &=& \sqrt{\frac{1}{H} \sum_{i=1}^{H} \left(x_i^l - \mu^l\right)^2 + \epsilon} \\ y &=& \frac{x - \mu^l}{\sigma^l} \gamma + \beta \end{eqnarray}\end{split}\]

ここでは、 \(x\)\(y\) は入力変数と出力変数で、 \(\mu^l\)\(\sigma^l\) は各層の平均および標準偏差でバッチごとに個別に計算されます。また、 \(\beta\)\(\gamma\) は適用バイアスとゲインです。

入力の形状が [B, C, H, W] (= batch_axis=0) の場合は、計算される平均と標準偏差の形状は [B, 1, 1, 1] です。

参照

パラメータ
  • x (Variable) -- 入力変数。

  • beta (Variable or None) -- 適応バイアス。None の場合、バイアス項は省きます。

  • gamma (Variable or None) -- 適応ゲイン。None の場合、スケール項は省きます。

  • batch_axis (int or repeated int) -- 軸の平均と分散を取ります。

  • eps (float) -- 標準偏差によるゼロ除算を避けるための小さな値。

  • output_stat (bool) -- true の場合、計算される平均および分散も返します。

戻り値

output variable which is normalized its statics and rescaled by alpha and beta. * Variable: Mean (if output_stat=True). * Variable: Std (if output_stat=True)

戻り値の型

nnabla.functions.instance_normalization(x, beta, gamma, channel_axis=1, batch_axis=0, eps=1e-05, output_stat=False)[ソース]

入力テンソルにインスタンスの正規化を適用します。それは次のように定義されます。

\[\begin{split}\begin{eqnarray} \mu^i &=& \frac{1}{H} \sum_{i=1}^{H} x_i^i \\ \sigma^i &=& \sqrt{\frac{1}{H} \sum_{i=1}^{H} \left(x_i^i - \mu^i\right)^2 + \epsilon} \\ y &=& \frac{x - \mu^i}{\sigma^i} \gamma + \beta \end{eqnarray}\end{split}\]

ここでは、 \(x\)\(y\) は入力変数と出力変数で、 \(\mu^i\)\(\sigma^i\) は各層の平均および標準偏差でバッチごとに個別に計算されます。また、 \(\gamma\) と :math:`beta は適用ゲインとバイアスです。

入力の形状が [B, C, H, W] (= channel_axis=1, batch_axis=0) の場合、計算される平均と標準偏差の形状は [B, C, 1, 1] です。

参照

パラメータ
  • x (Variable) -- 入力変数。

  • beta (Variable or None) -- 適応バイアス。None の場合、バイアス項は省きます。

  • gamma (Variable or None) -- 適応ゲイン。None の場合、スケール項は省きます。

  • channel_axis (int) -- チャネル軸。

  • batch_axis (int or repeated int) -- バッチ軸。

  • eps (float) -- 標準偏差によるゼロ除算を避けるための小さな値。

  • output_stat (bool) -- true の場合は、バッチの平均および分散の統計。

戻り値

Normalized output variable. * Variable: Mean (if output_stat=True) * Variable: Std (if output_stat=True)

戻り値の型

nnabla.functions.group_normalization(x, beta, gamma, num_groups, channel_axis=1, batch_axis=0, eps=1e-05, output_stat=False)[ソース]

入力テンソルにグループの正規化を適用します。それは次のように定義されます。

\[\begin{split}\begin{eqnarray} \mu^g &=& \frac{1}{H} \sum_{i=1}^{H} x_i^g \\ \sigma^g &=& \sqrt{\frac{1}{H} \sum_{i=1}^{H} \left(x_i^g - \mu^g\right)^2 + \epsilon} \\ y &=& \frac{x - \mu^g}{\sigma^g} \gamma + \beta \end{eqnarray}\end{split}\]

ここでは、 \(x\)\(y\) は入力変数と出力変数で、 \(\mu^g\)\(\sigma^g\)num_channels / num_groups チャネルを含むグループごとの平均と標準偏差で、 \(\gamma\)\(\beta\) は適応ゲインとバイアスです。

channel_axis によって指定される入力チャネルは num_groups グループに分けられ、平均と標準偏差はグループごとに計算されます。例えば、入力の形状が [B, C, H, W] (= channel_axis=1, batch_axis=0) の場合、入力変数は一度 [B, num_groups, C / num_groups, H, W] に再形成されて、形状が [B, num_groups, 1, 1, 1] である平均と標準偏差によって標準化されます。最後に、出力変数は再び元の入力の形状 ( 上記の場合は = [B, C, H, W] ) に再形成されます。

参照

パラメータ
  • x (Variable) -- 入力変数。

  • beta (Variable or None) -- 適応バイアス。None の場合、バイアス項は省きます。

  • gamma (Variable or None) -- 適応ゲイン。None の場合、スケール項は省きます。

  • num_groups (int) -- グループ数。チャネルの次元 ‘x’ は num_groups の整数倍でなければなりません。

  • channel_axis (int) -- チャネル軸。

  • batch_axis (int or repeated int) -- バッチ軸。

  • eps (float) -- 標準偏差によるゼロ除算を避けるための小さな値。

  • output_stat (bool) -- true の場合は、バッチの平均および分散の統計。

戻り値

Normalized output variable. * Variable: Mean (if output_stat=True) * Variable: Std (if output_stat=True)

戻り値の型

nnabla.functions.weight_standardization(w, channel_axis=0, eps=1e-05, output_stat=False)[ソース]

入力の重みに、Weight Standardization を適用します。それは次のように定義されます。

\[\begin{split}\begin{eqnarray} \mu_{W_i} &=& \frac{1}{I} \sum_{j=1}^{I} W_{ij} \\ \sigma_{W_i} &=& \sqrt{\frac{1}{I} \sum_{i=1}^{I} \left(W_{ij} - \mu_{W_{i}}\right)^2 + \epsilon} \\ \hat{W_{ij}} &=& \frac{W_{ij} - \mu_{W_i}}{\sigma_{W_i}} \\ y &=& \hat{W} \ast x \end{eqnarray}\end{split}\]

サンプル

import numpy as np
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF

rng = np.random.RandomState(313)
x = nn.Variable.from_numpy_array(rng.randn(*(32, 16, 3, 3)))

# For convolution:

def ws_callback_conv(w):
    return F.weight_standardization(w, channel_axis=0)

y = PF.convolution(x, 10, (2, 2), apply_w=ws_callback_conv)

# For affine:

def ws_callback_affine(w):
    return F.weight_standardization(w, channel_axis=1)

y = PF.affine(x, 10, apply_w=ws_callback_affine)

参照

パラメータ
  • w (Variable) -- 重み変数。

  • channel_axis (int) -- 出力チャネルに対する軸。convolution の重みを仮定して、デフォルト値は 0 です。

  • eps (float) -- 標準偏差によるゼロ除算を避けるための小さな値。

  • output_stat (bool) -- true の場合は、バッチの平均および分散の統計。

戻り値

Standardized output weight. * Variable: Mean (if output_stat=True) * Variable: Std (if output_stat=True)

戻り値の型

nnabla.functions.weight_normalization(w, g, dim=0, eps=1e-12, n_outputs=- 1, outputs=None)[ソース]

Weight normalization.

\[\mathbf{w}_{WN} = g \dfrac{\mathbf{w}}{\|\mathbf{w}\|}\]

where \(\mathbf{w}\) is the input weights to be normalized. and \(g\) is learnable multiplication factors each of which is applied to each data at dim.

参照

パラメータ
  • w (Variable) -- N-D array of learnable weights.

  • g (Variable) -- 1-D array of learnable scales.

  • dim (int) -- Output dimension. For the other dimensions, the norms are computed. [default= 0 ]

  • eps (float) -- Epsilon for the normalization. This eps is added before taking the sqrt in the norm computation. [default= 1e-12 ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.spectral_norm(w, u, dim=0, itr=1, eps=1e-12, test=False, output_u=False)[ソース]

Spectral Normalization.

\[W_{sn} = \frac{W}{\sigma(W)}\]

where \(W\) is the input matrix, and the \(\sigma(W)\) is the spectral norm of \(W\). The spectral norm is approximately computed by the power iteration.

参照

Takeru Miyato, Toshiki Kataoka, Masanori Koyama, Yuichi Yoshida, "Spectral Normalization for Generative Adversarial Networks", International Conference on Learning Representations. 2018.

パラメータ
  • w (Variable) -- N-D array of learnable weights. This is normally network parameter.

  • u (Variable) -- 1-D array of singular vector. When test == False, the data region of u will be updated during forward calculation.

  • dim (int) -- Output dimension. Default is 0. If the dimension is not 0, then the specified dimension becomes the most-left dimension by transposing. [default= 0 ]

  • itr (int) -- Number of power iterations. Default is 1. [default= 1 ]

  • eps (float) -- Epsilon for the normalization. This eps is added before taking the sqrt in the norm computation. [default= 1e-12 ]

  • test (bool) -- When in True, u will not be updated. Default is False. [default= False ]

  • output_u (bool) -- Output original u or not. u is updated when test == True but you can get original u as output with this option. Default is False. [default= False ]

戻り値

Spectrally normalized \(W_{sn}\) with the same shape as \(W\).

戻り値の型

Variable

削減
nnabla.functions.sum(x, axis=None, keepdims=False)[ソース]

軸に沿った和を計算する関数。

パラメータ
  • x (Variable) -- 入力変数。

  • axis (None, int or tuple of ints) -- 軸、または合計が計算される対象軸。デフォルト値 None を渡すことで、すべての次元を削減します。

  • keepdims (bool) -- 削減された軸が 1 つの要素をもつ次元として保持されているか否かのフラグ。

戻り値

N-D 配列。

戻り値の型

Variable

nnabla.functions.mean(x, axis=None, keepdims=False)[ソース]

軸に沿った平均を計算する関数。

パラメータ
  • x (Variable) -- 入力変数。

  • axis (None, int or tuple of ints) -- 軸、または平均が計算される対応軸。デフォルト値 None を渡すことで、すべての次元を削減します。

  • keepdims (bool) -- 削減された軸が 1 つの要素をもつ次元として保持されているか否かのフラグ。

戻り値

N-D 配列。

戻り値の型

Variable

nnabla.functions.max(x, axis=None, keepdims=False, with_index=False, only_index=False)[ソース]

最大値演算を使って、指定された axis に従って入力 N-D 配列 x を削減します。 axis の引数は、1 つの軸を削減する場合は単一整数、複数の軸を削減するため場合は整数のタプル、もしくはすべての軸を削減する場合は None になります。 keepdimsTrue の場合、出力はすべての削減次元を 1 とします。 with_index が True の場合、結果はタプル (sorted, indices) 、または only_index が True の場合は単に indices となります。only_index を True に設定すると、 with_index も True になります。

import numpy as np
import nnabla as nn
import nnabla.functions as F

nn.set_auto_forward(True)
x = nn.Variable.from_numpy_array(np.random.rand(2, 3, 4))

maxval = F.max(x, axis=1)
assert np.allclose(maxval.d, np.max(x.d, axis=1))

maxval, indices = F.max(x, axis=1, with_index=True)
assert np.allclose(maxval.d, np.max(x.d, axis=1))
assert np.all(indices.d == np.argmax(x.d, axis=1))

indices = F.max(x, axis=1, only_index=True)
assert np.all(indices.d == np.argmax(x.d, axis=1))
パラメータ
  • x (Variable) -- 入力変数。

  • axis (None, int or tuple of ints) -- 軸、または最大値の計算の対象軸。デフォルト値 None はすべての次元を削減します。

  • keepdims (bool) -- 削減された軸を 1 つの要素をもつ次元とします。

  • with_index (bool) -- 最大値とインデックスのタプルを返します。

  • only_index (bool) -- 最大値のインデックスのみを返します。

戻り値

N-D 配列。

戻り値の型

Variable

nnabla.functions.min(x, axis=None, keepdims=False, with_index=False, only_index=False)[ソース]

最小値演算を使って、指定された axis に従って入力 N-D 配列 x を削減します。 axis の引数は、1 つの軸を削減する場合は単一整数、複数の軸を削減するため場合は整数のタプル、もしくはすべての軸を削減する場合は None になります。 keepdimsTrue の場合、出力はすべての削減次元を 1 とします。 with_index が True の場合、結果はタプル (sorted, indices) 、または only_index が True の場合は単に indices となります。 only_index を True に設定すると、 with_index も True になります。

import numpy as np
import nnabla as nn
import nnabla.functions as F

nn.set_auto_forward(True)
x = nn.Variable.from_numpy_array(np.random.rand(2, 3, 4))

minval = F.min(x, axis=1)
assert np.allclose(minval.d, np.min(x.d, axis=1))

minval, indices = F.min(x, axis=1, with_index=True)
assert np.allclose(minval.d, np.min(x.d, axis=1))
assert np.all(indices.d == np.argmin(x.d, axis=1))

indices = F.min(x, axis=1, only_index=True)
assert np.all(indices.d == np.argmin(x.d, axis=1))
パラメータ
  • x (Variable) -- 入力変数。

  • axis (None, int or tuple of ints) -- 軸、または最小値の計算対象の軸。デフォルト値 None はすべての次元を削減します。

  • keepdims (bool) -- 削減された軸を 1 つの要素をもつ次元とします。

  • with_index (bool) -- 最小値とインデックスのタプルを返します。

  • only_index (bool) -- 最小値のインデックスのみを返します。

戻り値

N-D 配列。

戻り値の型

Variable

nnabla.functions.norm(x, p=None, axis=None, keepdims=False)[ソース]

Reduction along axes with norm operation.

\[y = \|x\|_p = \left( \sum_i |x_i|^p \right)^{\frac{1}{p}}\]
パラメータ
  • x (Variable) -- 入力変数。

  • p (float) -- Order of the norm.

  • axis (None, int or tuple of ints) -- 軸、または最小値の計算対象の軸。デフォルト値 None はすべての次元を削減します。

  • keepdims (bool) -- 削減された軸が 1 つの要素をもつ次元として保持されているか否かのフラグ。

戻り値

N-D 配列。

戻り値の型

Variable

nnabla.functions.prod(x, axis=None, keepdims=False)[ソース]

軸に沿った積を計算する関数。

パラメータ
  • x (Variable) -- 入力変数。

  • axis (None, int or tuple of ints) -- 軸、または最小値の計算対象の軸。デフォルト値 None はすべての次元を削減します。

  • keepdims (bool) -- 削減された軸が 1 つの要素をもつ次元として保持されているか否かのフラグ。

戻り値

N-D 配列。

戻り値の型

Variable

注釈

backward の計算はゼロ値の入力では正確に行われません。

nnabla.functions.reduce_sum(x, n_outputs=- 1, outputs=None)[ソース]

軸に沿った和を計算する関数。

注釈

これは推奨しません。代わりに sum を使用してください。

パラメータ

x (Variable) -- N-D 配列。

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.reduce_mean(x, n_outputs=- 1, outputs=None)[ソース]

軸に沿った平均を計算する関数。

注釈

これは推奨されません。代わりに mean を使用してください。

パラメータ

x (Variable) -- N-D 配列

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

計算
nnabla.functions.add2(x0, x1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとの加算。

\[y_i = x^{(0)}_i + x^{(1)}_i\]
パラメータ
  • x0 (Variable) -- N-D 配列

  • x1 (Variable) -- N-D 配列

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.add_n(*x, **kw)[ソース]

要素ごとの加算。

\[y_i = x^{(0)}_i + . . . + x^{(n-1)}_i\]
パラメータ

*x (Variable) -- N-D 配列。 [variadic]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sub2(x0, x1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとの減算。

\[y_i = x^{(0)}_i - x^{(1)}_i\]
パラメータ
  • x0 (Variable) -- N-D 配列

  • x1 (Variable) -- N-D 配列

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.mul2(x0, x1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとの乗算。

\[y_i = x^{(0)}_i x^{(1)}_i\]
パラメータ
  • x0 (Variable) -- N-D 配列

  • x1 (Variable) -- N-D 配列

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.mul_n(*x, **kw)[ソース]

要素ごとの乗算。

\[y_i = x^{(0)}_i . . . x^{(n-1)}_i\]
パラメータ

*x (Variable) -- N-D 配列。 [variadic]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.div2(x0, x1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとの除算。

\[y_i = \frac{x^{(0)}_i} {x^{(1)}_i}\]
パラメータ
  • x0 (Variable) -- N-D 配列

  • x1 (Variable) -- N-D 配列

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.pow2(x0, x1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとのべき乗関数。

\[y_i = {(x^{(0)}_i)} ^ {x^{(1)}_i}\]
パラメータ
  • x0 (Variable) -- N-D 配列

  • x1 (Variable) -- N-D 配列

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.add_scalar(x, val=1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラ加算。

\[y_i = x_i + v\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.mul_scalar(x, val=1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラ乗算。

\[y_i = v x_i\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.pow_scalar(x, val=1, inplace=False, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラべき乗関数。

\[y_i = (x_i) ^ v\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.r_sub_scalar(x, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラ減算。

\[y_i = v - x_i\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.r_div_scalar(x, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラ除算。

\[y_i = \frac{v}{x_i}\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.r_pow_scalar(x, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラべき乗関数。

\[y_i = v ^ {x_i}\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

論理
nnabla.functions.equal(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの ‘equal’

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 1 & (x^{(0)}_i = x^{(1)}_i) \\ 0 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.equal_scalar(x0, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの ‘equal’

\[\begin{split}f(x_i,v) = \begin{cases} 1 & (x_i = v) \\ 0 & otherwise \end{cases}.\end{split}\]
パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.greater(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 1 & (x^{(0)}_i > x^{(1)}_i) \\ 0 & (x^{(0)}_i \leq x^{(1)}_i) \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.greater_equal(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 1 & (x^{(0)}_i \geq x^{(1)}_i) \\ 0 & (x^{(0)}_i < x^{(1)}_i) \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.greater_equal_scalar(x0, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,v) = \begin{cases} 1 & (x^{(0)}_i \geq v \\ 0 & (x^{(0)}_i < v \end{cases}.\end{split}\]
パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.greater_scalar(x0, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,v) = \begin{cases} 1 & (x^{(0)}_i > v \\ 0 & (x^{(0)}_i \leq v \end{cases}.\end{split}\]
パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.less(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 1 & (x^{(0)}_i < x^{(1)}_i) \\ 0 & (x^{(0)}_i \geq x^{(1)}_i) \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.less_equal(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 1 & (x^{(0)}_i \leq x^{(1)}_i) \\ 0 & (x^{(0)}_i > x^{(1)}_i) \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.less_equal_scalar(x0, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,v) = \begin{cases} 1 & (x^{(0)}_i \leq v) \\ 0 & (x^{(0)}_i > v) \end{cases}.\end{split}\]
パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.less_scalar(x0, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの比較。出力の \(i\) 番目の要素は以下の通りです。

\[\begin{split}f(x^{(0)}_i,v) = \begin{cases} 1 & (x^{(0)}_i < v) \\ 0 & (x^{(0)}_i \geq v) \end{cases}.\end{split}\]
パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.logical_and(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの論理 AND 。

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 1 & (x^{(0)}_i \neq 0 \;\&\; x^{(1)}_i \neq 0) \\ 0 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.logical_and_scalar(x0, val, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの論理 AND 。

\[\begin{split}f(x_i,v) = \begin{cases} 1 & (x_i \neq 0 \;\&\; v \neq 0) \\ 0 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.logical_not(x0, n_outputs=- 1, outputs=None)[ソース]

要素ごとの論理 NOT 演算

\[\begin{split}f(x_i) = \begin{cases} 1 & (x_i = 0) \\ 0 & otherwise \end{cases}.\end{split}\]
パラメータ

x0 (Variable) -- 入力変数

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.logical_or(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの論理 OR 。

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 0 & (x^{(0)}_i = 0 \;\&\; x^{(1)}_i = 0) \\ 1 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.logical_or_scalar(x0, val, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの論理 OR 。

\[\begin{split}f(x_i,v) = \begin{cases} 0 & (x_i = 0 \;\&\; v = 0) \\ 1 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.logical_xor(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの論理 XOR 。

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 1 & (x^{(0)}_i = 0 \;\&\; x^{(1)}_i = 0) \\ 1 & (x^{(0)}_i \neq 0 \;\&\; x^{(1)}_i \neq 0) \\ 0 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.logical_xor_scalar(x0, val, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの論理 XOR 。

\[\begin{split}f(x_i,v) = \begin{cases} 1 & (x_i = 0 \;\&\; v = 0) \\ 1 & (x_i \neq 0 \;\&\; v \neq 0) \\ 0 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.not_equal(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの ‘not equal’

\[\begin{split}f(x^{(0)}_i,x^{(1)}_i) = \begin{cases} 0 & (x^{(0)}_i = x^{(1)}_i) \\ 1 & otherwise \end{cases}.\end{split}\]
パラメータ
戻り値

記述なし

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.not_equal_scalar(x0, val=1, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラの ‘not equal’

\[\begin{split}f(x_i,v) = \begin{cases} 0 & (x_i = v) \\ 1 & otherwise \end{cases}.\end{split}\]
パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sign(x, alpha=1.0, n_outputs=- 1, outputs=None)[ソース]

要素ごとの sign 関数。

forward パスでは、次のように定義されます。

\[\begin{split}f(x) = \begin{cases} 1 & (x > 0) \\ -1 & (x < 0) \\ \alpha & (x = 0) \end{cases}.\end{split}\]

backward パスでは、次のように定義されます。

\[\frac{\partial f(x)}{\partial x} = 1,\]

つまり、backward パスでは勾配に対して identity 関数として動作します。

パラメータ
  • x (Variable) -- 入力

  • alpha (float) -- Value in case of \(x = 0\). [default= 1.0 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.minimum2(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの最小値。

\[y_i = \min(x^{(0)}_i, x^{(1)}_i)\]
パラメータ
戻り値

最小値の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.maximum2(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの最大値。

\[y_i = \max(x^{(0)}_i, x^{(1)}_i)\]
パラメータ
戻り値

最大値の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.minimum_scalar(x, val=1.0, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラ最小値。

\[y_i = \min(x_i, v)\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1.0 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.maximum_scalar(x, val=1.0, n_outputs=- 1, outputs=None)[ソース]

要素ごとのスカラ最大値。

\[y_i = \max (x_i, v)\]
パラメータ
  • x (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 1.0 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.isnan(x0, n_outputs=- 1, outputs=None)[ソース]

要素ごとに NaN のテストを行い、 0/1 配列を返します。

パラメータ

x0 (Variable) -- 入力変数

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.isinf(x0, n_outputs=- 1, outputs=None)[ソース]

要素ごとに inf/-inf のテストを行い、 0/1 配列を返します。

パラメータ

x0 (Variable) -- 入力変数

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.reset_nan(x0, val=0, n_outputs=- 1, outputs=None)[ソース]

NaNs を val で指定されたスカラ値に置換します。

パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 0 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.reset_inf(x0, val=0, n_outputs=- 1, outputs=None)[ソース]

-inf/infval で指定されたスカラ値に置換します。

パラメータ
  • x0 (Variable) -- 入力変数

  • val (float) -- Value of the scalar [default= 0 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.where(condition, x_true, x_false, n_outputs=- 1, outputs=None)[ソース]

condition によって、 x_true または x_false からの要素を返します。

condition のランクが x_true および x_false のランクより高い場合は、 x_true および x_false の最初の次元は condition の次元と一致する必要があります。

例 :

import numpy as np
import nnabla as nn
import nnabla.functions as F

a = nn.Variable.from_numpy_array(np.random.rand(2, 3))
x = nn.Variable.from_numpy_array(np.random.rand(2, 3, 4))
y = nn.Variable.from_numpy_array(np.random.rand(2, 3, 4))
z = F.where(F.greater_scalar(a, 0.5), x, y)
z.forward()

# Numpy equivalent
z_numpy = np.where(a.d > 0.5, x.d, y.d)
assert np.allclose(z_numpy, z.d)
パラメータ
  • condition (Variable) -- N-d 配列。すべての i において、 condition[i] == true の場合は、 x_true[i] となります。それ以外の場合は、 x_false[i] となります。

  • x_true (Variable) -- condition のランク以上の N-d 配列。

  • x_false (Variable) -- condition のランク以上の N-d 配列。

戻り値

condition と同じ形状をもつ N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

数学
nnabla.functions.constant(val=0, shape=[], n_outputs=- 1, outputs=None)[ソース]

定数値配列を生成します。

パラメータ
  • val (float) -- Constant value. [default= 0 ]

  • shape (tuple of int) -- Shape of the output array. [default= [] ]

戻り値

すべての値が指定された定数である N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.arange(start, stop, step=1, n_outputs=- 1, outputs=None)[ソース]

半開区間 [start, stop] (始まりを含み、終わりは含まない区間) 内の値の範囲を step 増分で生成します。

パラメータ
  • start (float) -- 始まりの値。

  • stop (float) -- 終わりの値。

  • step (float) -- Step value. [default= 1 ]

戻り値

生成された値をもつ 1-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.abs(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの絶対値関数。

\[y_i = |x_i|\]
パラメータ

x (Variable) -- 入力変数

戻り値

要素ごとの絶対値

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.exp(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの自然指数関数。

\[y_i = \exp(x_i).\]
パラメータ

x (Variable) -- 入力変数

戻り値

要素ごとの指数変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.log(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの log (自然対数) 関数。

\[y_i = \ln(x_i).\]
パラメータ

x (Variable) -- 入力変数

戻り値

要素ごとのlog (対数) 変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.round(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの round (端数処理) 関数。

forward パスでは、この関数は単に最も近い整数値に round を行う計算を行います。

\[y_i = round(x_i).\]

backward パスでは、以下の通り、単純な Straight-Through Estimator (STE) が適用されます。

\[\frac{\partial y_i}{\partial x_i} = 1.\]
パラメータ

x (Variable) -- 入力変数

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.ceil(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの ceil (切り上げ) 関数。

forward パスでは、この関数は単に入力以上の最小の整数を返します。

\[y_i = ceil(x_i).\]

backward パスでは、以下の通り、単純な Straight-Through Estimator (STE) が適用されます。

\[\frac{\partial y_i}{\partial x_i} = 1.\]
パラメータ

x (Variable) -- 入力変数

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.floor(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの floor (切り捨て) 関数。

forward パスでは、この関数は単に入力以下の最大の整数を返します。

\[y_i = floor(x_i).\]

backward パスでは、以下の通り、単純な Straight-Through Estimator (STE) が適用されます。

\[\frac{\partial y_i}{\partial x_i} = 1.\]
パラメータ

x (Variable) -- 入力変数

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.identity(x, n_outputs=- 1, outputs=None)[ソース]

恒等関数。

\[y = x\]
パラメータ

x (Variable) -- N-D 配列。

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.matrix_diag(x, n_outputs=- 1, outputs=None)[ソース]

最後の2 次元が対角行列になる配列を返します。

パラメータ

x (Variable) -- (\(M_0 \times \ldots \times M_N\)) の形状をもつ N-D 配列。

戻り値

(\(M_0 \times \ldots \times M_N \times M_N\)) の形状をもつ N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.matrix_diag_part(x, n_outputs=- 1, outputs=None)[ソース]

最後の次元の値が入力配列の最後の 2 次元の対角要素からなる配列を返します。

パラメータ

x (Variable) -- (\(M_0 \times \ldots \times M_N \times M_N\)) の形状をもつ N-D 配列。

戻り値

(\(M_0 \times \ldots \times M_N\)) の形状をもつ N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.batch_matmul(a, b, transpose_a=False, transpose_b=False, n_outputs=- 1, outputs=None)[ソース]

バッチの行列乗算。

Two of batchs of matrices are multiplied for each sample in a batch. A batch of matrices is composed as [..., P, Q] where the last two dimensions compose matrix dimensions, and the first dimensions up to the third last dimension are considered as batch samples. These batch dimensions are internally broadcasted when the size of a dimension is 1.

例 :

import nnabla as nn
import nnabla.functions as F
import numpy as np

nn.set_auto_forward(True)

# Same batch size
a = nn.Variable.from_numpy_array(np.random.rand(2, 2, 3, 4))
b = nn.Variable.from_numpy_array(np.random.rand(2, 2, 4, 3))
c = F.batch_matmul(a, b)

# Different batch size with the broadcast
a = nn.Variable.from_numpy_array(np.random.rand(2, 1, 3, 4))
b = nn.Variable.from_numpy_array(np.random.rand(1, 3, 4, 3))
c = F.batch_matmul(a, b)

警告

Since the version 1.13, the behavior of the batch dimensions changed, it supported the internal broadcast when the size of a dimension is 1. Accordingly, this function does not supports different batch dimensions between two inputs even if the total sample size for each input is same.

パラメータ
  • a (Variable) -- 2 次元以上の N-D 配列。最後の 2 次元は行列として扱われます。

  • b (Variable) -- 2 次元以上の N-D 配列。最後の2 次元は行列として扱われます。第 0 次元のサイズから最後から 3 番目までの次元のサイズの積は入力 a の積と同じでなくてはなりません。

  • transpose_a (bool) -- Transpose the last two axes of a in matrix multiplication. [default= False ]

  • transpose_b (bool) -- Transpose the last two axes of b in matrix multiplication. [default= False ]

戻り値

バッチにおけるサンプルごとの行列乗算の出力。 a は [N, P, Q] の形状であり、 b は [N, Q, R] の形状であり、transpose オプションがすべて False の場合は、出力は [N, P, R] の形状になります。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sin(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの sin (正弦) 関数。

\[y_i = \sin (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.cos(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの cos (余弦) 関数。

\[y_i = \cos (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.tan(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの正接 (tan) 関数。

\[y_i = \tan (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sinh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの双曲正弦 (sinh) 関数。

\[y_i = \sinh (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.cosh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの cosh (双曲余弦) 関数。

\[y_i = \cosh (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.tanh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの双曲線正接 (tanh) 関数。

\[y_i = \tanh (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.asin(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの逆正弦 (asin) 関数。

\[y_i = \arcsin (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.acos(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの acos (逆余弦) 関数。

\[y_i = \arccos (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.atan(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの atan (逆正接) 関数。

\[y_i = \arctan (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.atan2(x0, x1, n_outputs=- 1, outputs=None)[ソース]

2 つの入力変数をもつ、要素ごとの atan (逆正接) 関数。

\[y_i = \arctan2 (x_{i1}, x_{i2})\]
パラメータ
戻り値

入力変数と同じ形状をもつ N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.asinh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの asinh (逆双曲線正弦) 関数。

\[y_i = \text{arcsinh} (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.acosh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの逆双曲線余弦 (acosh) 関数。

\[y_i = \text{arccosh} (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.atanh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとの atanh (逆双曲線正接) 関数。

\[y_i = \text{arctanh} (x_i)\]
パラメータ

x (Variable) -- N-D 配列

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.cumsum(x, axis=None, exclusive=False, reverse=False, n_outputs=- 1, outputs=None)[ソース]

Cumulative sum along a given axis.

パラメータ
  • x (Variable) -- N-D 配列。

  • axis (int) -- Axis along which cumulative sum is to be calculated [default= 0 ]

  • exclusive (bool) -- If True, perform exclusive cumsum [default= False ]

  • reverse (bool) -- If True, perform cumsum in reverse direction [default= False ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.cumprod(x, axis=None, exclusive=False, reverse=False, n_outputs=- 1, outputs=None)[ソース]

Cumulative product along a given axis.

注釈

backward の計算はゼロ値の入力では正確に行われません。

パラメータ
  • x (Variable) -- N-D 配列。

  • axis (int) -- Axis along which cumulative product is to be calculated [default= 0 ]

  • exclusive (bool) -- If True, perform exclusive cumprod [default= False ]

  • reverse (bool) -- If True, perform cumprod in reverse direction [default= False ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.batch_inv(x, n_outputs=- 1, outputs=None)[ソース]

入力配列の行列式を返します

パラメータ

x (Variable) -- バッチ化されたN-D配列

戻り値

行列式のバッチN-D配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.batch_det(x, n_outputs=- 1, outputs=None)[ソース]

Batch-wise determinant function.

\[Y_b = \det(X_b),\]

where \(X_b\) and \(Y_b\) are the \(b\)-th input and output, respectively.

パラメータ

x (Variable) -- バッチ化されたN-D配列

戻り値

行列式のバッチN-D配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.batch_logdet(x, n_outputs=- 1, outputs=None)[ソース]

Batch-wise log absolute determinant function.

\[Y_b = \log(|\det(X_b)|),\]

where \(X_b\) and \(Y_b\) are the \(b\)-th input and output, respectively.

パラメータ

x (Variable) -- バッチ化されたN-D配列

戻り値

batched N-D array of log absolute determinant

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

配列操作
nnabla.functions.concatenate(*x, **kw)[ソース]

指定された軸に沿って、可変長個数の入力配列を連結します。

パラメータ
  • *x (Variable) -- N-D 配列。 [variadic]

  • axis (int) -- Axis [default= len(x[0].shape) - 1 ]

戻り値

連結する変数

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.split(x, axis=0)[ソース]

指定された軸における配列を分割します。

Variable の指定された軸 (すなわち x.shape[axis] ) のサイズと一致する数の Variable を返します。

パラメータ

Variabletuple 返します

参考

nnabla.function_bases.split()

nnabla.functions.stack(*x, **kw)[ソース]

新しい軸上に 2 つ、またはそれ以上の配列を結合します。

注釈

既存の軸上に配列を結合する nnabla.functions.concatenate() とは異なり、Stack は新しい軸上に配列を結合します。

パラメータ
  • *x (Variable) -- N-D 配列。スタックされる配列のサイズは同じでなければなりません。[variadic]

  • axis (int) -- The axis on which to concatenate arrays. Axis indices take on values 0, 1, 2, and so on from the left. For example, to stack four (3,28,28) inputs on the second axis, specify 1. In this case, the output size will be (3,4,28,28). [default= 0 ]

戻り値

出力

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.slice(x, start=None, stop=None, step=None, n_outputs=- 1, outputs=None)[ソース]

指定された軸に沿って配列をスライスします。この関数は、Python のスライスに準拠しています。 slice(None, None, -1)slice(-1, None, -1) は特殊なケースであり、入力配列を反転し、対応する次元に沿って入力配列の最後から先頭までを出力配列に結果として出力します。

パラメータ
  • x (Variable) -- N-D 配列

  • start (repeated int64) -- Start indices for each axis [default= (0,) * len(x.shape) ]

  • stop (repeated int64) -- Stop indices for each axis [default= tuple(x.shape) ]

  • step (repeated int64) -- Step indices for each axis [default= (1,) * len(x.shape) ]

戻り値

スライスされた N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.gather(x, Indices, axis=None, batch_dims=None, n_outputs=- 1, outputs=None)[ソース]

Gather from the input data according to the index.

Given the input data \(X\) of \((D_{0}, \ldots, D_{N-1})\) shape and the indices \(IDX\) of \((I_{0}, \ldots, I_{M-1})\) shape, in case of batch_dims = 0, the gather outputs

\[\begin{split}&& Y[d_{0}, \ldots, d_{axis - 1}, i_{0}, \ldots, i_{M-1}, d_{axis + 1}, \ldots, d_{N-1}] = \\ && X[d_{0}, \ldots, d_{axis - 1}, IDX[i_{0}, \ldots, i_{M-1}], d_{axis + 1}, \ldots, d_{N-1}].\end{split}\]

Generally, the gather ouptuts

\[\begin{split}&& Y[d_{0}, \ldots, d_{axis - 1}, i_{B}, \ldots, i_{M-1}, d_{axis + 1}, \ldots, d_{N-1}] = \\ && X[d_{0}, \ldots, d_{axis - 1}, IDX[i_{0}, \ldots, i_{B - 1}, i_{B} \ldots, i_{M-1}], d_{axis + 1}, \ldots d_{N-1}].\end{split}\]

where \(B\) = batch_dims.

x.shape[:batch_dims] must be equal to indices.shape[:batch_dims].

Output shape is x.shape[:axis] + indices.shape[batch_dims:] + x.shape[axis + 1].

パラメータ
  • x (Variable) -- Data from which to gather.

  • Indices (Variable) -- Index with which to gather.

  • axis (int) -- Axis in x to gather from. axis must be greater than or equal to batch_dims. [default= 0 ]

  • batch_dims (int) -- The number of batch dimensions. [default= 0 ]

戻り値

Gathered output.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.gather_nd(data, indices)[ソース]

indices にしたがって data から要素またはスライスを収集します。これは少なくとも2次元で、最初の次元である \(M\) 次元は data\(N\) 次元より低い次元であるか同じでなければなりません。 \((X_0, X_1, ..., X_{N-1})\) 形状の指定された data\((M, Y_0, ..., Y_{K-1})\) 出力の形状をした indices は \((Y_0, ..., Y_{K-1}, X_M, ..., X_{N-1})\) の形状になります。 \(M == N\) の場合は、出力形状は単に \((Y_0, ..., Y_{K-1})\) となります。

gather_nd() の forward は以下と同等です。

def gather_nd(data, index):
    import numpy as np
    tmp_index = index.reshape(index.shape[0], -1)
    tmp_index = (idx + (Ellipsis,) for idx in zip(*new_index))
    out_shape = index.shape[1:] + data.shape[index.shape[0]:]
    return np.vstack(data[idx] for idx in tmp_index).reshape(*out_shape)

例 :

>>> import numpy as np, nnabla as nn, nnabla.functions as F
>>> nn.set_auto_forward(True)
>>> data = F.arange(1, 11).reshape([2, 5])
>>> print(data.d)
[[ 1.  2.  3.  4.  5.]
 [ 6.  7.  8.  9. 10.]]
>>> F.gather_nd(data, [[1, 1, 0]]).shape
(3, 5)
>>> F.gather_nd(data, [[1, 1, 0], [0, 1, 0]]).shape
(3,)
>>> print(F.gather_nd(data, [[1, 1, 0], [0, 1, 0]]).d)
[6. 7. 1.]
>>> print(F.gather_nd(data, [[1, 1, 0]]).d)
[[ 6.  7.  8.  9. 10.]
 [ 6.  7.  8.  9. 10.]
 [ 1.  2.  3.  4.  5.]]

indicesVariable として提供された場合、関数作成後、実際のインデックス値を変更することが可能となります。CPU上で実行する場合は範囲外の indices はエラーとなりますが、高速演算コンテキストを使用する場合はエラーとならずに無視されますので留意してください。

>>> indices = nn.Variable((2, 1))
>>> indices.d = [[0], [0]]
>>> y = F.gather_nd(data, indices)
>>> print(y.d)
[1.]
>>> indices.d = [[1], [4]]
>>> y.forward()
>>> print(y.d)
[10.]
パラメータ

戻り値:収集された要素の ~nnabla.Variable または ~nnabla.NdArray。

nnabla.functions.scatter_nd(data, indices, shape=None, out=None, add=False)[ソース]

indices にしたがって data を、指定された shape の新しい配列または out として提供される既存の配列に散布します。 shape または out 引数の内のどちらか 1 つを指定する必要があります。出力の shape または out 配列の形状が \((X_0,X_1,\ldots,X_{N-1})\) と、 indices の形状 \((M,Y_0,\ldots,Y_{K-1})\) が指定された場合、入力 data の形状は \((Y_0,\ldots,Y_{K-1},X_M,\ldots,X_{N-1})\) となります。 \(M==N\) の場合、data の形状は単純に \((Y_0,\ldots,Y_{K-1})\) となります。 indices は整数として扱われ、変換される可能性があることに留意してください。

scatter_nd() の forward は以下と同等になります。

def scatter_nd(data, indices, shape=None, out=None):
    assert (shape and not out) or (out and not shape)
    if isinstance(indices, numpy.ndarray)
        indices = indices.tolist()
    result = out if out else numpy.zeros(shape)
    result[indices] = data
    return result

例 :

>>> import numpy as np, nnabla as nn, nnabla.functions as F
>>> nn.set_auto_forward(True)
>>> data = nn.Variable.from_numpy_array(np.array([9, 10, 11, 12]))
>>> indices = nn.Variable.from_numpy_array(np.array([[4, 3, 1, 7]]))
>>> scattered = F.scatter_nd(data, indices, shape=(8,))
>>> print(scatterd.d)
[ 0. 11.  0. 10.  9.  0.  0. 12.]
>>> print(F.gather_nd(scattered, indices).d)
[ 9. 10. 11. 12.]
パラメータ

戻り値:指定された shape の ~nnabla.Variable または ~nnabla.NdArray。

nnabla.functions.scatter_add(x0, indices, x1, axis=None)[ソース]

Add all values from x1 into the x0 according to index specified by indices. This function adds x1 into the copy of x0 and outputs the copy. The original x0 will not be changed. x0, indices and x1 must have same number of dimensions.

The forward of scatter_add() is equivalent to:

def scatter_add(x0, indices, x1, axis):
    # Assuming each input is 3 dimensional
    import numpy as np
    output = np.copy(x0)
    for i in range(indices.shape[0]):
        for j in range(indices.shape[1]):
            for k in range(indices.shape[2]):
                if axis == 0:
                    output[indices[i][j][k]][j][k] += x1[i][j][k]
                elif axis == 1:
                    output[i][indices[i][j][k]][k] += x1[i][j][k]
                elif axis == 2:
                    output[i][j][indices[i][j][k]] += x1[i][j][k]
    return output
パラメータ
  • x0 (Variable) -- N-D array which the data is added to its copy.

  • indices (Variable) -- N-D array scatter indices. The size of each dimension must be equal or smaller than that of x0 except for the specified axis. The value of indices must be smaller than the size of specified axis' dimension of x0. The size of each dimension must be equal or smaller than that of x1. Indices must not be negative.

  • x1 (Variable) -- N-D array which is scattered and added to x0.

  • axis (int) -- Axis along which to index. The axis must not exceed the inputs' dimension. [default= 0 ]

戻り値

N-D array which contains the result of scatter addition. The shape is same as x0.

戻り値の型

Variable

nnabla.functions.pad(x, pad_width, mode='constant', constant_value=0, n_outputs=- 1, outputs=None)[ソース]

入力 N-D 配列 x を、イテレーション可能な pad_width の半分の要素数とする次元数に対してパディングします。ある軸の前後のパディングサイズは pad_width の各 2 つの値によって決まります。イテレーション可能な pad_width は、入力変数 x のすべての次元または少ない次元数となる正の値の偶数を保持する必要があります。 pad_width がより少ない次元数である場合は、 x の最も深い次元に適用されます。

x = nn.Variable.from_numpy_array(np.ones((2, 3, 4)))
assert F.pad(x, (1, 1, 2, 2)).shape == (2, 5, 8)

パディングは、要求された mode にしたがって実行されます。

constant

キーワード引数である constant_value で指定された値でパディングします。

x = nn.Variable.from_numpy_array(np.array([1, 2, 3, 4], dtype=np.int))
y = F.pad(x, (3, 3), 'constant', constant_value = -1)
y.forward()
assert np.all(y.d == np.array([-1, -1, -1, 1, 2, 3, 4, -1, -1, -1]))
reflect

各軸に沿ったベクトルの最初と最後の値でミラー化されたベクトルを反転してパディングします。

x = nn.Variable.from_numpy_array(np.array([1, 2, 3, 4], dtype=np.int))
y = F.pad(x, (3, 3), 'reflect')
y.forward()
assert np.all(y.d == np.array([4, 3, 2, 1, 2, 3, 4, 3, 2, 1]))
repeat

Pads with the edge value of the vector along each axis.

x = nn.Variable.from_numpy_array(np.array([1, 2, 3, 4], dtype=np.int))
y = F.pad(x, (3, 3), 'repeat')
y.forward()
assert np.all(y.d == np.array([1, 1, 1, 1, 2, 3, 4, 4, 4, 4]))
パラメータ
  • x (Variable) -- N-D 配列

  • pad_width (repeated int64) -- 前後 のイテレーション可能なパディング値。

  • mode (string) -- Padding mode string. [default= 'constant' ]

  • constant_value (float) -- Fill value if mode is constant. [default= 0 ]

戻り値

入力と同じ次元数をもつパディングされた N-D 配列。

x = nn.Variable((3, 3, 4, 2))  # a shape like (B, C, H, W)
# 1-D padding: last dim by 1 left and 2 on the right side
assert F.pad(x, (1, 2)).shape == (3, 3, 4, 5)
# 2-D padding: last dim by (1, 1) and 2nd to last by (2, 2)
assert F.pad(x, (2, 2, 1, 1)).shape == (3, 3, 8, 4)
# 3-D padding: dims C by (0, 1), H by (2, 1), and W by (3, 3)
assert F.pad(x, (0, 1, 2, 1, 3, 3)).shape == (3, 4, 7, 8)

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.transpose(x, axes, n_outputs=- 1, outputs=None)[ソース]

テンソル次元を転置します。

パラメータ
  • x (Variable) -- N-D 配列

  • axes (repeated int64) -- 各軸のソース軸インデックス。

戻り値

転置された N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.broadcast(x, shape, n_outputs=- 1, outputs=None)[ソース]

指定された形状に ND 配列をブロードキャストします。

パラメータ
  • x (Variable) -- N-D 配列

  • shape (tuple of int) -- ブロードキャストされる形状。サイズは x の形状が1ではない軸において、同じでなければなりません。

戻り値

ブロードキャストされた N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.broadcast_to(x, y, axis=None, n_outputs=- 1, outputs=None)[ソース]

警告

この関数は実験的なサポートなので、積極的には使用しないでください。

指定されたバッファに ND 配列をブロードキャストします。

パラメータ
  • x (Variable) -- N-D 配列

  • y (Variable) -- N-D 配列

  • axis (int) -- Target axis to start broadcasting. If this is not set, broadcast will try to fit y to x starting from the last dimension [default= -1 ]

戻り値

ブロードキャストされた N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.tile(x, reps)[ソース]

xreps で与えられた回数分、繰り返し送られます。もし reps がシーケンスである場合、出力は d = max(len(reps), x.ndim) の次元を有し、且つ x はいくつかの新しい軸を前方に付け加えられたことで d 次元に生成されるか、 reps が x.ndim と同じ長さになるように、1 を前方に付け加えられることで x.ndim 次元になります。

パラメータ
  • x (Variable) -- 入力 N-D 配列。

  • reps (int or sequence of int) -- 各軸に沿った x の繰り返し。

戻り値

N-D 配列。

戻り値の型

Variable

>>> import numpy as np, nnabla as nn, nnabla.functions as F
>>> F.tile(nn.Variable([2, 3]), 3).shape    # reps is promoted to [1, 3]
(2, 9)
>>> F.tile(nn.Variable([3]), [2, 3]).shape  # x is promoted to shape (1, 3)
(2, 9)
>>> nn.set_auto_forward(True)
>>> x = nn.Variable.from_numpy_array(np.array([1, 2, 3]))
>>> print(F.tile(x, 3).d)
[1. 2. 3. 1. 2. 3. 1. 2. 3.]
>>> print(F.tile(x, [2, 3]).d)
[[1. 2. 3. 1. 2. 3. 1. 2. 3.]
 [1. 2. 3. 1. 2. 3. 1. 2. 3.]]
>>> x = nn.Variable.from_numpy_array(np.array([[1, 3], [2, 4]]))
>>> print(F.tile(x, 3).d)
[[1. 3. 1. 3. 1. 3.]
 [2. 4. 2. 4. 2. 4.]]
>>> print(F.tile(x, [2, 3]).d)
[[1. 3. 1. 3. 1. 3.]
 [2. 4. 2. 4. 2. 4.]
 [1. 3. 1. 3. 1. 3.]
 [2. 4. 2. 4. 2. 4.]]
nnabla.functions.meshgrid(*x, ij_indexing=False)[ソース]
nnabla.functions.flip(x, axes=None, n_outputs=- 1, outputs=None)[ソース]

配列の指定された次元の要素の順序を逆にします。

パラメータ
  • x (Variable) -- N-D 配列

  • axes (repeated int64) -- The index of the dimension to reverse the order of the elements. Axis indices take on values 0, 1, 2, and so on from the left. For example, to flip a 32 (W) by 24 (H) 100 RGB image (100,3,24,32) vertically and horizontally, specify (2,3). [default= [len(x.shape) - 1] ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.shift(x, shifts=None, border_mode='nearest', n_outputs=- 1, outputs=None)[ソース]

指定された量だけ配列要素をずらします。

パラメータ
  • x (Variable) -- N-D 配列。

  • shifts (repeated int64) -- The amount to shift elements. For example, to shift image data to the right by 2 pixels and up 3 pixels, specify (-3,2). [default= (0,) * len(x.shape) ]

  • border_mode (string) -- Specify how to process the ends of arrays whose values will be undetermined as a result of shifting. nearest: The data at the ends of the original array is copied and used. reflect: Original data reflected at the ends of the original array is used. [default= 'nearest' ]

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sort(x, axis=- 1, reverse=False, with_index=False, only_index=False)[ソース]

x の要素を、特定の axis における値の昇順で並べ替えます。負の axisx の最後の次元からカウントされるため、デフォルトの -1 は最後の次元に沿ってソートされます。 もし、 reverse が True の場合、要素は降順で並べ替えられます。

もし with_index が True の場合、結果はタプル (sorted, indices) 、または only_index が True の場合は indices のみです。 only_index を True に設定すると、 with_index も True になります。

import numpy as np
import nnabla as nn
import nnabla.functions as F

nn.set_auto_forward(True)
x = nn.Variable.from_numpy_array(np.random.rand(2, 3, 4))

sorted = F.sort(x)
assert np.allclose(sorted.d, np.sort(x.d))

sorted, indices = F.sort(x, with_index=True)
assert np.allclose(sorted.d, np.sort(x.d))
assert np.all(indices.d == np.argsort(x.d))

indices = F.sort(x, only_index=True)
assert np.all(indices.d == np.argsort(x.d))
パラメータ
  • x (Variable) -- N-D 配列

  • axis (int) -- 並べ替える軸。

  • reverse (bool) -- 降順でソートします。

  • with_index (bool) -- ソートされた値とインデックスを返します。

  • only_index (bool) -- ソートされたインデックスのみを返します。

戻り値 : ~nnabla.Variable sorted または ~nnabla.Variable indices または (~nnabla.Variable sorted , ~nnabla.Variable indices )

nnabla.functions.reshape(x, shape, inplace=True, n_outputs=- 1, outputs=None)[ソース]

入力変数を in-place で変形します。変数のコピーは作成されません。出力変数(y)は新しい形状を持ちますが、入力変数(x)と同じデータを指します。これは、もし出力変数(y)のデータが変更されると、整形が in-place で行われるため、入力変数(x)のデータも変更されることを意味します。

注釈

この関数は、 nnabla.Variable.reshape() メソッドと同じ動作をします。

パラメータ
  • x (Variable) -- N-D 配列。

  • shape (tuple of int) -- 各軸の次元。 -1 は、1つの形状次元でのみ指定できます。値は、配列のサイズと残りの次元から計算されます。

  • inplace (bool) -- The output array is shared with the input array if True. [default= True ]

戻り値

整形された N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.one_hot(x, shape, n_outputs=- 1, outputs=None)[ソース]

この関数は、入力インデックスに基づいて one-hot ベクトルを作成します。

例 :

import nnabla as nn
import nnabla.functions as F
import numpy as np

labels = nn.Variable.from_numpy_array(np.array([[9], [4], [5], [1], [0]]))
print(labels.shape)  # (5, 1)

num_class = 10

y_train = F.one_hot(labels, shape=(num_class, ))
y_train.forward()

print(y_train.shape)  # (5, 10)
print(y_train.d)

# [[0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
#  [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
#  [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
#  [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
#  [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]

# Can also be used for ndarray.

labels = nn.Variable.from_numpy_array(np.array([[1, 7], [4, 7], [8, 6], [5, 0], [2, 6]]))
print(labels.shape)  # (5, 2)

num_class_1, num_class_2  = 10, 8

y_train = F.one_hot(labels, shape=(num_class_1, num_class_2))
y_train.forward()

print(y_train.shape)  # (5, 10, 8)
print(y_train.d)

# [[[0. 0. 0. 0. 0. 0. 0. 0.]          [[0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 1.]           [0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]           [0. 0. 0. 0. 0. 0. 1. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]           [0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]           [0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]    ...    [0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]           [0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]           [0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]           [0. 0. 0. 0. 0. 0. 0. 0.]
#   [0. 0. 0. 0. 0. 0. 0. 0.]],         [0. 0. 0. 0. 0. 0. 0. 0.]]]
パラメータ
  • x (Variable) -- ラベルのインデックスを表す N-D 配列。

  • shape (tuple of int) -- クラスの数。ラベルデータに含まれるクラスの数と正確に同じでなければならないことに注意してください。間違った数値を渡すと、予期しないエラーが発生する可能性があり、現在この関数は入力が有効かどうかをチェックしていません。また、 nd-labels が指定されている場合、次元数が一致する必要があります。上記の例を参照してください。

戻り値

ベクトル / テンソルの N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.assign(dst, src, n_outputs=- 1, outputs=None)[ソース]

tf.assign と同じように、ソース配列を宛先配列に割り当てます。これは、パラメータを同期、または手動で更新するのに役立ちます。

dst = nn.Variable((2, 3, 4))
src = nn.Variable((2, 3, 4))
assign = F.assign(dst, src)

assign.forward()
assert np.allclose(dst.d, src.d) # dst and src have identical values.
assert np.allclose(assign.d dst.d) # returned Variable is also identical to dst.

TensorFlow とは異なり、返される変数には dst への backward パスがあります。

\[g_{dst} = g_{y}\]
パラメータ
戻り値

代入された配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.top_k_data(x, k, abs=False, reduce=True, base_axis=1, n_outputs=- 1, outputs=None)[ソース]

x の各サンプルから k 個の最大値を選択します。 k 個の値は変更されず、それ以外の値は 0 になります。 abs が True の場合、 k 個の最大値が大きさによって選択されます。 reduce が True(デフォルト)の場合、すべての特徴次元は、 k 個の最大値のみを伝達するサイズ k の単一次元に縮小されます。それ以外の場合、 reduce が False の場合、入力と出力の次元は同じです。 base_axis の前の次元はサンプルの次元数として扱われ、形状に関係なくサンプルのすべての要素( base_axis からの次元)から k 値が選択されます。

>>> import nnabla as nn, nnabla.functions as F
>>> x = nn.Variable((4, 5, 6))
>>> F.top_k_data(x, 3, reduce=False).shape
(4, 5, 6)
>>> F.top_k_data(x, 3, reduce=True).shape
(4, 3)
>>> F.top_k_data(x, 3, reduce=True, base_axis=2).shape
(4, 5, 3)
パラメータ
  • x (Variable) -- N-D 配列

  • k (int) -- 伝達する最大データ値の数。

  • abs (bool) -- Determine largest data values by magnitude. [default= False ]

  • reduce (bool) -- Reduce feature size to one dimension of size k. [default= True ]

  • base_axis (int) -- First dimension of the sample shape. [default= 1 ]

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.top_k_grad(x, k, abs=False, base_axis=1, n_outputs=- 1, outputs=None)[ソース]

x の各サンプルに対して k 個の最大勾配を選択します。 k 個の値は変更されず、それ以外の値は0になります。 abs が True の場合、 k 個の最大勾配が大きさによって選択されます。 base_axis の前の次元はサンプル次元の数として扱われ、形状に関係なくサンプルのすべての勾配( base_axis からの次元)から k 個の勾配が選択されます。

パラメータ
  • x (Variable) -- N-D 配列

  • k (int) -- 伝達する最大勾配の数。

  • abs (bool) -- Determine largest gradients by magnitude. [default= False ]

  • base_axis (int) -- First dimension of the sample shape. [default= 1 ]

戻り値

x と同じ形状とデータを持つ N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.pack_padded_sequence(padded_sequence, lengths, batch_first=False, n_outputs=- 1, outputs=None)[ソース]

Pack a padded variable-length sequences.

This method packs a padded variable-length sequences.

\(T_i\) is the length of the \(i\)-th Variable in the sequences. \(B\) is the batch size equal to the length of the sequences. \(T\) is the max of \(T_i\) for all \(i\). \(*\) is the remaining dimensions including none.

注釈

This function assumes the length-sorted padded sequence in the decreasing order and must be used by pack_padded_sequence() in the dynamic computation mode. See :

パラメータ
  • padded_sequence (Variable) -- Padded sequence of (\(T \times B \times *\)) or (\(B \times T \times *\)) shape.

  • lengths (Variable) -- Sequence length for each batch and always resides in CPU.

  • batch_first (bool) --

    padded_sequence is of (\(T\), \(B\), \(*\)) shape if False, otherwise (\(B\), \(T\), \(*\)).

    [default= False ]

戻り値

Packed sequence of (\(N\), \(*\)) shape. ~nnabla.Variable: Batch size for each time and always resides in CPU.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.pad_packed_sequence(packed_sequence, batch_sizes, batch_first=False, padding_value=None, total_length=None, n_outputs=- 1, outputs=None)[ソース]

Pad packed sequence.

This method unpacks the packed sequqnce and pad it, the inverse operation of pack_padded_sequence().

\(T_i\) is the length of the \(i\)-th Variable in the sequences. \(B\) is the batch size equal to the length of the sequences. \(T\) is the max of \(T_i\) for all \(i\). \(*\) is the remaining dimensions including none.

注釈

This function assumes the output of the length-sorted padded sequence in the decreasing order and must be used by pad_packed_sequence() in the dynamic computation mode.

パラメータ
  • packed_sequence (Variable) -- Packed sequence of (\(N\), \(*\)) shape.

  • batch_sizes (Variable) -- Batch size for each time and always resides in CPU.

  • batch_first (bool) --

    padded_sequence is of (\(T\), \(B\), \(*\)) shape if False, otherwise (\(B\), \(T\), \(*\)).

    [default= False ]

  • padding_value (float) -- Padding value. [default= 0.0 ]

  • total_length (int) --

    If not None, the outputs are padded up to the total_length. If the total_length is less than the max length in the sequences, the error is thrown.

    [default= -1 ]

戻り値

Padded sequence of (\(T \times B \times *\)) or (\(B \times T \times *\)) shape. ~nnabla.Variable: Sequence length for each batch and always resides in CPU.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.searchsorted(sorted_sequence, values, right=None, n_outputs=- 1, outputs=None)[ソース]

Finds indices in the innermost dimension of a sorted sequance where values must be inserted in order to maintain value

パラメータ
  • sorted_sequence (Variable) -- N-D array of sorted sequence where search is to be performed. Note that this must be a sorted array

  • values (Variable) -- N-D array of Search values

  • right (bool) -- :If True, given a value v, the function returns index i such that sorted_sequence[i-1] <= v < sorted_sequence[i] (index of closest upper bound of v). By default, this is false so the function returns index i such that a[i-1] < v <= a[i] (index of closest lower bound of v) [default= False ]

戻り値

N-D array containing the required indices

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.bool_gather(input, mask, n_outputs=- 1, outputs=None)[ソース]

Gather from the input data according to the mask.

Given an input of \((B_1, \ldots, B_N, D_1, \ldots, D_M)\) shape and mask of \((B_1, \ldots, B_N)\) shape, the function returns an output of \((nnz, D_1, \ldots, D_M)\) shape and \(nnz\) is the number of non-zero elements in mask.

import numpy as np
import nnabla as nn
import nnabla.functions as F

nn.set_auto_forward(True)

input = nn.Variable.from_numpy_array([[1, 2], [3, 4], [5, 6]])
mask = nn.Variable.from_numpy_array([1, 0, 1])
output = F.bool_gather(input, mask)

print(output.d) # [[1, 2], [5, 6]]

Note that this function is normally used with the dynamic graph since this function outputs a variable-length output. If used with the static graph, a network has to be constructed all time in iteration.

パラメータ
  • input (Variable) -- Data from which to gather.

  • mask (Variable) -- Mask with which to gather. Non-zero/zero elements are supposed to be a binary mask as 1/0. No gradients are computed with respect to mask.

戻り値

Gathered output.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.bool_scatter(input, mask, output=None, n_outputs=- 1, outputs=None)[ソース]

Scatter the input according to the mask.

Given an input of \((nnz, D_1, \ldots, D_M)\) shape and mask of \((B_1, \ldots, B_N)\) shape, the function returns an output \((B_1, \ldots, B_N, D_1, \ldots, D_M)\) and \(nnz\) is the number of non-zero elements in the mask.

import numpy as np
import nnabla as nn
import nnabla.functions as F

nn.set_auto_forward(True)

input0 = nn.Variable.from_numpy_array([[1, 2], [3, 4], [5, 6]])
mask = nn.Variable.from_numpy_array([1, 0, 1])
output0 = F.bool_gather(input0, mask)

input1 = output0 + 10
output1 = F.bool_scatter(input1, mask)

print(output1.d)  # [[11, 12], [0, 0], [15, 16]]

Note that the higher-order gradients of this function relies on F.gather, thus the higher-order gradients of this function is normally used with the dynamic graph.

パラメータ
  • input (Variable) -- Data to be scattered.

  • mask (Variable) -- Mask with which to scatter. Non-zero/zero elements are supposed to be a binary mask as 1/0. No gradients are computed with respect to mask.

  • output (Variable) -- Destination of output. If specified, data are inplaced. [optional]

戻り値

Scattered output.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.bool_fill(data, mask, value=0, n_outputs=- 1, outputs=None)[ソース]

Fill the data with the value to according to the mask.

import numpy as np
import nnabla as nn
import nnabla.functions as F

nn.set_auto_forward(True)

input = nn.Variable.from_numpy_array([[np.inf, 2], [3, np.nan]])
mask = nn.Variable.from_numpy_array([[1, 0], [0, 1]])
output = F.bool_fill(input, mask, -1)

print(output.d)  # [[-1, 2], [3, -1]]
パラメータ
  • data (Variable) -- Data to be filled.

  • mask (Variable) -- Mask with which to fill. Non-zero/zero elements are supposed to be a binary mask as 1/0. No gradients are computed with respect to mask.

  • value (float) -- Value to fill. [default= 0 ]

戻り値

Filled output.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.dot(a, b, out=None)[ソース]

A compatible operation with numpy.dot.

注釈

Any operation between nnabla's Variable/NdArray and numpy array is not supported.

If both arguments are 1-D, it is inner product of vectors. If both arguments are 2-D, it is matrix multiplication. If either a or b is 0-D(scalar), it is equivalent to multiply. If b is a 1-D array, it is a sum product over the last axis of a and b. If b is an M-D array (M>=2), it is a sum product over the last axis of a and the second-to-last axis of b.

パラメータ
  • a (Variable, NdArray or scalar) -- Left input array.

  • b (Variable, NdArray or scalar) -- Right input array.

  • out -- Output argument. This must have the same shape, dtype, and type as the result that would be returned for F.dot(a,b).

戻り値

~nnabla.Variable or ~nnabla.NdArray

例 :

import numpy as np
import nnabla as nn
import nnabla.functions as F

# 2-D matrix * 2-D matrix
arr1 = np.arange(5*6).reshape(5, 6)
arr2 = np.arange(6*8).reshape(6, 8)
nd1 = nn.NdArray.from_numpy_array(arr1)
nd2 = nn.NdArray.from_numpy_array(arr2)
ans1 = F.dot(nd1, nd2)
print(ans1.shape)
#(5, 8)

var1 = nn.Variable.from_numpy_array(arr1)
var2 = nn.Variable.from_numpy_array(arr2)
ans2 = F.dot(var1, var2)
ans2.forward()
print(ans2.shape)
#(5, 8)

out1 = nn.NdArray((5, 8))
out1.cast(np.float32)
F.dot(nd1, nd2, out1)
print(out1.shape)
#(5, 8)

out2 = nn.Variable((5, 8))
out2.data.cast(np.float32)
F.dot(var1, var2, out2)
out2.forward()
print(out2.shape)
#(5, 8)

# N-D matrix * M-D matrix (M>=2)
arr1 = np.arange(5*6*7*8).reshape(5, 6, 7, 8)
arr2 = np.arange(2*3*8*6).reshape(2, 3, 8, 6)
nd1 = nn.NdArray.from_numpy_array(arr1)
nd2 = nn.NdArray.from_numpy_array(arr2)
ans1 = F.dot(nd1, nd2)
print(ans1.shape)
#(5, 6, 7, 2, 3, 6)

var1 = nn.Variable.from_numpy_array(arr1)
var2 = nn.Variable.from_numpy_array(arr2)
ans2 = F.dot(var1, var2)
ans2.forward()
print(ans2.shape)
#(5, 6, 7, 2, 3, 6)

out1 = nn.NdArray((5, 6, 7, 2, 3, 6))
out1.cast(np.float32)
F.dot(nd1, nd2, out1)
print(out1.shape)
#(5, 6, 7, 2, 3, 6)

out2 = nn.Variable((5, 6, 7, 2, 3, 6))
out2.data.cast(np.float32)
F.dot(var1, var2, out2)
out2.forward()
print(out2.shape)
#(5, 6, 7, 2, 3, 6)
確率論
nnabla.functions.rand(low=0, high=1, shape=[], seed=- 1, n_outputs=- 1, outputs=None)[ソース]

下限の \(low\) 、 上限の \(high\) 、返される変数の形状によって定められる \(x \sim U(low, high)\) の一様分布から数を抽出します。

パラメータ
  • low (float) -- \(low\) in definition. [default= 0 ]

  • high (float) -- \(high\) in definition. [default= 1 ]

  • shape (tuple of int) -- Shape of returned variable. [default= [] ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

引数で定められた形状の変数。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.randint(low=0, high=1, shape=[], seed=- 1, n_outputs=- 1, outputs=None)[ソース]

Samples integer numbers from a uniform distribution \(x \sim U(low, high)\) given lowest value \(low\), upper bound \(high\), and the shape of the returned Variable. The lowest value \(low\) is included in the range, while the upper bound \(high\) is excluded, corresponding to the half-open interval \([low, high)\).

パラメータ
  • low (int) -- \(low\) in definition. [default= 0 ]

  • high (int) -- \(high\) in definition. [default= 1 ]

  • shape (tuple of int) -- Shape of returned variable. [default= [] ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

引数で定められた形状の変数。 dtype は int32 です。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.randn(mu=0, sigma=1, shape=[], seed=- 1, n_outputs=- 1, outputs=None)[ソース]

平均 \(\mu\) 、 標準偏差 \(\sigma\) 、返される変数の形状によって定められた \(x \sim N(\mu, \sigma)\) の正規分布から数を抽出します。

パラメータ
  • mu (float) -- \(\mu\) in definition. [default= 0 ]

  • sigma (float) -- \(\sigma\) in definition. [default= 1 ]

  • shape (tuple of int) -- Shape of returned variable. [default= [] ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

引数で定められた形状の変数。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.rand_binomial(n=1, p=0.5, shape=[], seed=- 1, n_outputs=- 1, outputs=None)[ソース]

Samples numbers from a binomial distribution \(x \sim B(n, p)\) given the numbers of trials \(n\), probability \(p\), and shape of the returned Variable. When \(n = 1\), this behaves like the Bernoulli distriburion.

パラメータ
  • n (int) -- \(n\) in definition, the number of trials. [default= 1 ]

  • p (float) -- \(p\) in definition, probability of success. [default= 0.5 ]

  • shape (tuple of int) -- Shape of returned variable. [default= [] ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

引数で定められた形状の変数。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.rand_beta(alpha=0.5, beta=0.5, shape=[], seed=- 1, n_outputs=- 1, outputs=None)[ソース]

Samples numbers from a beta distribution \(x \sim \beta(\alpha, \beta)\).

パラメータ
  • alpha (float) -- \(\alpha\), scale parameter. [default= 0.5 ]

  • beta (float) -- \(\beta\), scale parameter. [default= 0.5 ]

  • shape (tuple of int) -- Shape of returned variable. [default= [] ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

引数で定められた形状の変数。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.rand_gamma(k=0.5, theta=1, shape=[], seed=- 1, n_outputs=- 1, outputs=None)[ソース]

Samples numbers from a gamma distribution \(x \sim \frac {\gamma(k, \frac {x}{\theta})}{\Gamma(k)}\).

パラメータ
  • k (float) -- k, scale parameter. [default= 0.5 ]

  • theta (float) -- \(\theta\), scale parameter. [default= 1 ]

  • shape (tuple of int) -- Shape of returned variable. [default= [] ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

引数で定められた形状の変数。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.dropout(x, p=0.5, seed=- 1, n_outputs=- 1, outputs=None)[ソース]

ドロップアウト。サンプル数 \(u\)\([0, 1]\) の一様分布から抽出します。 \(u \leq p\) の場合は入力を無視します。

\[\begin{split}y = \left\{ \begin{array}{ll} \frac{x}{1 - p} & (u > p) \\ 0 & ({\rm otherwise}) \end{array} \right.\end{split}\]

注釈

Usually dropout only applied during training as below (except MC dropout). If you want to use dropout as an MC dropout, remove 'if train:'.

h = PF.affine(x, num_hidden)
if train:
    h = F.dropout(h, 0.5)
パラメータ
  • x (Variable) -- N-D 配列

  • p (float) -- \(p\) in definition. [default= 0.5 ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.random_choice(x, w, shape=[], replace=True, seed=- 1, n_outputs=- 1, outputs=None)[ソース]

Generate random samples from population x with selection probabilities determined by the relative weights w. The number of samples to draw is given by the product of shapes dimensions, and the samples are returned with the given shape. By default, samples are drawn with replacement, i.e. selection of a specific population member is solely determined by its associated weight. Sampling without replacement, where any population member may be drawn only once, is used if replace is set to False.

xw の両方について、最後の次元は、個々の母集団とその重みに対応し、要求された shape 分のサンプルが生成されます。それ以外の次元は shape の前に付きます。

import nnabla as nn
import nnabla.functions as F
import numpy as np
nn.set_auto_forward(True)

# x holds two populations
x = nn.Variable.from_numpy_array(np.array([[11, 22, 33], [110, 220, 330]]))
# w holds the weights for each population
w = nn.Variable.from_numpy_array(np.array([[10, 20, 70], [70, 20, 10]]))

# draw one sample from each population
y = F.random_choice(x, w)  # y.shape => (2, 1)

# draw 12 samples with shape (3, 4) from each population
y = F.random_choice(x, w, shape=(3, 4))  # y.shape => (2, 3, 4)

重みはゼロより小さくてはいけません。母集団ごとに重みの合計はゼロより大きくなければならないことに留意してください。さらに、重複なしのサンプリングでは、ゼロ以外の重みの数が、生成されるサンプルの数以上でなければなりません。これらの条件は “cpu” 計算コンテキストで検証されますが、 “cuda” または “cudnn” アクセラレーションを使用する場合は検証されません(パフォーマンスに悪影響を与える追加のデバイス同期ステップが必要になるからです)。

(カテゴリ別または多項のような)インデックス値の暗黙的な配列からのランダムサンプリングは、インデックスとして構築された入力 x を使用して実現できます。

w = nn.Variable.from_numpy_array(np.array([1, 2, 3, 2, 1]))
y = F.random_choice(F.arange(0, 5), w)
パラメータ
  • x (Variable) -- ランダムサンプルの生成元の N-D 配列。

  • w (Variable) -- x の要素の関連する重みのN-D配列。

  • shape (tuple of int) -- Number and shape of generated samples. [default= [] ]

  • replace (bool) -- Whether sampling is with or without replacement. [default= True ]

  • seed (int) -- Random seed. [default= -1 ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.random_crop(x, shape=None, base_axis=1, seed=- 1, n_outputs=- 1, outputs=None)[ソース]

RandomCropは、配列の一部をランダムに切り抜きます。

パラメータ
  • x (Variable) -- N-D 配列

  • shape (tuple of int) -- The data size to extract. For example, to randomly extract a portion of the image (3,48,48) from a 3,64,64 image, specify (3,48,48). [default= x.shape ]

  • base_axis (int) -- No Description [default= 1 ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.random_erase(x, prob=0.5, area_ratios=(0.02, 0.4), aspect_ratios=(0.3, 3.3333), replacements=(0.0, 255.0), n=None, share=True, inplace=False, base_axis=1, seed=- 1, channel_last=False, ste_fine_grained=True, n_outputs=- 1, outputs=None)[ソース]

入力のパッチをランダムに消去し、ランダムな値で置き換えます。

shareTrue の場合、指定された確率、ランダムに選択された面積比およびアスペクト比で各サンプルおよび各 n に対して消去を行います。それ以外の場合 ( share = False ) は、さらに各特徴マップに対して消去を行います。

ランダムパッチは以下のようにランダム座標によって選択されます。

\[\begin{split}S_e &&= Uniform(s_l, s_h) \times S \\ r_e &&= Uniform(r_l, r_h) \\ H_e &&= \sqrt{S_e \times r_e} \\ W_e &&= \sqrt{S_e / r_e} \\ y_e &&= Uniform(0, H - H_e) \\ x_e &&= Uniform(0, W - W_e),\end{split}\]

ここでは、 \(S\) は面積、 \(s_l\) および \(s_h\) は面積比の範囲の低値および高値、 \(r_l\) および \(r_h\) はアスペクト比の範囲の低値および高値、 \(H_e\) および \(W_e\) はパッチの高さおよび幅、 \(y_e\) および \(x_e\) はパッチの開始座標です。入力のピクセルがこのパッチに該当する場合は、そのピクセル値は replacements 範囲のランダムな値に置き換えられます。

ste_fine_grained が False の場合、backward は勾配を渡すように実装されます。それ以外の場合は、backward は消去されていない領域のみで実行されます。

参照

パラメータ
  • x (Variable) -- N-D 配列。

  • prob (float) -- Probability to erase. [default= 0.5 ]

  • area_ratios (repeated float) -- Low and high of the area ratio range. [default= (0.02, 0.4) ]

  • aspect_ratios (repeated float) -- Low and high of the aspect ratios range. [default= (0.3, 3.3333) ]

  • replacements (repeated float) -- Low and high of the replacement value range. [default= (0.0, 255.0) ]

  • n (int) -- Max number of patches to be erased. [default= 1 ]

  • share (bool) -- Use a same bounding box randomly picked over the feature dimension when being True. Default is True. [default= True ]

  • inplace (bool) -- This option is obsolete and ignored. Output is never in-placed with input. [default= False ]

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

  • ste_fine_grained (bool) -- Straight Through Estimator is fine-grained or not. Default is True. [default= True ]

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.random_flip(x, axes=None, base_axis=1, seed=- 1, n_outputs=- 1, outputs=None)[ソース]

配列の指定された次元の要素の順序を 50% の確率で逆にします。

パラメータ
  • x (Variable) -- N-D 配列

  • axes (repeated int64) -- The index of the axis to reverse the order of the elements. Axis indices take on values 0, 1, 2, and so on from the left. For example, to flip a 32 (W) by 24 (H) 100 RGB images (100, 3,24,32) vertically and horizontally at random, specify (2,3). [default= [len(x.shape) - 1] ]

  • base_axis (int) -- No Description [default= 1 ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.random_shift(x, shifts=None, border_mode='nearest', constant_value=0, base_axis=1, seed=- 1, n_outputs=- 1, outputs=None)[ソース]

指定された範囲内で配列要素をランダムにずらします。

パラメータ
  • x (Variable) -- N-D 配列。

  • shifts (repeated int64) -- Max absolute amount to shift elements. For example, to shift image data horizontally by \(\pm 2\) pixels and vertically by \(\pm 3\) pixels, specify (3,2). [default= (0,) * len(x.shape) ]

  • border_mode (string) -- Specify how to process the ends of arrays whose values will be undetermined as a result of shifting. nearest: The data at the ends of the original array is copied and used. reflect: Original data reflected at the ends of the original array is used. constant: Constant value is used. [default= 'nearest' ]

  • constant_value (float) -- Value used for outside of the original array if border_mode='constant'. [default= 0 ]

  • base_axis (int) -- No Description [default= 1 ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.image_augmentation(x, shape=None, pad=(0, 0), min_scale=1.0, max_scale=1.0, angle=0.0, aspect_ratio=1.0, distortion=0.0, flip_lr=False, flip_ud=False, brightness=0.0, brightness_each=False, contrast=1.0, contrast_center=0.0, contrast_each=False, noise=0.0, seed=- 1, n_outputs=- 1, outputs=None)[ソース]

ImageAugmentation は、入力画像をランダムに変更します。

パラメータ
  • x (Variable) -- N-D 配列。

  • shape (tuple of int) -- The output image data size. [default= x.shape ]

  • pad (tuple of int) -- Border padding values for each spatial axis. Padding will be added both sides of the dimension. [default= (0, 0) ]

  • min_scale (float) -- The minimum scale ratio when randomly scaling the image. For example, to scale down to 0.8 times the size of the original image, specify "0.8". To not apply random scaling, set both min_scale and max_scale to "1.0". [default= 1.0 ]

  • max_scale (float) -- The maximum scale ratio when randomly scaling the image. For example, to scale down to 2 times the size of the original image, specify "2.0". [default= 1.0 ]

  • angle (float) -- The rotation angle range in radians when randomly rotating the image. The image is randomly rotated in the -Angle to +Angle range. For example, to rotate in a +-15 degree range, specify "0.26" (15 degrees/360 degrees * 2PI). To not apply random rotation, specify "0.0". [default= 0.0 ]

  • aspect_ratio (float) -- The aspect ratio range when randomly deforming the image. For example, to deform aspect ratio of image from 1:1.3 to 1.3:1, specify "1.3". To not apply random deforming, specify "1.0". [default= 1.0 ]

  • distortion (float) -- The distortion range when randomly distorting the image. To not apply distortion, specify "0.0". [default= 0.0 ]

  • flip_lr (bool) -- Whether to randomly flip the image horizontally at 50% probability. [default= False ]

  • flip_ud (bool) -- Whether to randomly flip the image vertically at 50% probability. [default= False ]

  • brightness (float) -- The absolute range of values to randomly add to the brightness. A random value in the -Brightness to +Brightness range is added to the brightness. For example, to vary the brightness in the -0.05 to +0.05 range, specify "0.05". To not apply random addition to brightness, specify "0.0". [default= 0.0 ]

  • brightness_each (bool) -- Whether to apply the random addition to brightness (as specified by brightness) to each color channel. True: brightness is added based on a different random number for each channel. False: brightness is added based on a random number common to all channels. [default= False ]

  • contrast (float) -- The range in which to randomly vary the image contrast. The contrast is varied in the 1/Contrast times to Contrast times range. The output brightness is equal to (input - contrast_center) * contrast + contrast_center. For example, to vary the contrast in the 0.91 times to 1.1 times range, specify "1.1". To not apply random contrast variation, specify "1.0". [default= 1.0 ]

  • contrast_center (float) -- Intensity center used for applying contrast. [default= 0.0 ]

  • contrast_each (bool) -- Whether to apply the random contrast variation (as specified by contrast) to each color channel. True: contrast is varied based on a different random number for each channel. False: contrast is varied based on a random number common to all channels. [default= False ]

  • noise (float) -- Sigma of normal random number to be added. [default= 0.0 ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

Loss 関数
nnabla.functions.sigmoid_cross_entropy(x, target, n_outputs=- 1, outputs=None)[ソース]

sigmoid 関数に渡される、 x とターゲット変数間の要素ごとのクロスエントロピー。

\[y_i = - \left(x^{(1)}_i \ln \left(\sigma \left(x^{(0)}_i \right)\right) + \ \left(1 - x^{(1)}_i\right) \ln \left(1 - \sigma \left(x^{(0)}_i \ \right)\right)\right)\]

ここで、 \(\sigma(s)=\frac{1}{1+\exp(-s)}\) とします。

注釈

SigmoidCrossEntropy は Sigmoid + BinaryCrossEntropy と同等ですが、一度に計算すると計算エラーを減らす効果があります。

パラメータ
  • x (Variable) -- N-D 配列。 通常はスコアを示します。値は \([-\infty, \infty]\) [パラメータ] にあります。

  • target (Variable) -- ラベルの N-D 配列。許可される値は 0 または 1 のみです。 [パラメータ]

戻り値

要素ごとの損失の N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.binary_cross_entropy(x, target, n_outputs=- 1, outputs=None)[ソース]

x とターゲット変数間の要素ごとのクロスエントロピー。

\[y_i = - \left(x^{(1)}_i * \ln \left(x^{(0)}_i\right) + \left(1 - \ x^{(1)}_i\right) * \ln \left(1 - x^{(0)}_i\right)\right).\]
パラメータ
  • x (Variable) -- N-D 配列の確率。 \(-\infty\) から \(\infty\)

  • target (Variable) -- ラベルの N-D 配列。通常は 0 または 1 に設定されますが、SigmoidCrossEntropy とは異なり、入力と逆伝播を行うことができるため、確率(0〜1)が可能です。

戻り値

要素ごとの損失の N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.softmax_cross_entropy(x, target, axis=None, n_outputs=- 1, outputs=None)[ソース]

Softmax normalization を使用したカテゴリインデックスによって与えられる変数と、ラベルの変数間の要素単位のクロスエントロピー。

\[y_{j} = -\ln \left(\frac{\exp(x_{j,t_j})}{\sum_{i'} \exp(x_{j,i'})}\right)\]

軸で指定された次元に沿って (\(i\) は正規化が実行される軸です ) 。

注釈

SoftmaxCrossEntropy は Softmax + CategoricalCrossEntropy と同等ですが、一度に計算すると計算エラーを減らす効果があります。

パラメータ
  • x (Variable) -- N-D 配列。 通常はスコアを示します。 \((D_1 \times ... \times D_i \times ... \times D_N)\) [パラメータ]

  • target (Variable) -- N-D array of labels. \((D_1 \times ... \times 1 \times ... \times D_N)\) , each label should be the index from 0 to n-class, -1 if not belongs any class. [parameter]

  • axis (int) -- Axis normalization is taken. [default= len(x.shape) - 1 ]

戻り値

要素ごとの損失の N-D 配列。 \((D_1 \times ... \times 1 \times ... \times D_N)\)

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.categorical_cross_entropy(x, target, axis=None, n_outputs=- 1, outputs=None)[ソース]

x とターゲット t の要素ごとのクロスエントロピー。ターゲットはカテゴリインデックスによって指定されます。

\[y_{j} = -\ln \left( x_{j, t_j} \right)\]

軸で指定された次元に沿って (\(i\) は正規化が実行される軸です ) 。

パラメータ
  • x (Variable) -- N-D 配列。 通常はスコアを示します。 \((D_1 \times ... \times D_i \times ... \times D_N)\) [パラメータ]

  • target (Variable) -- N-D array of labels. \((D_1 \times ... \times 1 \times ... \times D_N)\), each label should be the index from 0 to n-class, -1 if not belongs any class. [parameter]

  • axis (int) -- Axis normalization is taken. [default= len(x.shape) - 1 ]

戻り値

要素ごとの損失の N-D 配列。 \((D_1 \times ... \times 1 \times ... \times D_N)\)

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.squared_error(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの二乗誤差

\[y_i = \left(x^{(0)}_i - x^{(1)}_i\right)^2.\]
パラメータ
戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.absolute_error(x0, x1, n_outputs=- 1, outputs=None)[ソース]

要素ごとの絶対誤差

\[y_i = | x^{(0)}_i - x^{(1)}_i |.\]
パラメータ
戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.huber_loss(x0, x1, delta=1.0, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Huber loss

\[\begin{split}y_i= \left\{ \begin{array}{ll} d^2 & (|d| < \delta)\\ \delta (2 |d| - \delta) & ({\rm otherwise}) \end{array} \right.\end{split}\]

\(d = x^{(0)}_i - x^{(1)}_i\) の箇所

パラメータ
戻り値

要素ごとの損失の N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.epsilon_insensitive_loss(x0, x1, epsilon, n_outputs=- 1, outputs=None)[ソース]

要素ごとの Epsilon Insensitive loss

\[\begin{split}y_i= \left\{ \begin{array}{ll} | x^{(0)}_i - x^{(1)}_i | - \epsilon & if \ \ | x^{(0)}_i - x^{(1)}_i | > \epsilon \\ 0 & otherwise \end{array} \right.\end{split}\]
パラメータ
  • x0 (Variable) -- N-D 配列。

  • x1 (Variable) -- N-D 配列。

  • epsilon (float) -- 影響を受けないパラメータ。

戻り値

要素ごとの損失の N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.kl_multinomial(p, q, base_axis=1, n_outputs=- 1, outputs=None)[ソース]

多項分布の Kullback Leibler Divergence。

\[D = \sum_i p_i \log \left( \frac{p_i}{q_i} \right)\]
パラメータ
  • p (Variable) -- ソース・カテゴリカル確率の N-D 配列

  • q (Variable) -- ターゲット・カテゴリカル確率の N-D 配列

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

戻り値

Kullback Leibler divergence \(KL(p \parallel q)\)

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

信号処理
nnabla.functions.interpolate(x, scale=None, output_size=None, mode='linear', align_corners=False, half_pixel=False, half_pixel_for_nn=False, channel_last=False)[ソース]

補間で ND 配列のサイズを変更します。

空間次元のスケーリング係数は、 scale または output_size のいずれかによって決定されます。

nd = len(scale)nd = len(output_size) が空間次元を決定します。 入力 x の最後の数 nd 次元が空間次元とされます。

If scale is given, the output_size is calculated by

output_size[i] = floor(scale[i] * x.shape[i - len(scale)]).

Calculation of the coordinate transformation are as follows.

The input coordinate i_input is computed by the output coordinate i_output, the input size size_input, and the output size size_output as

align_corners

half_pixel

i_input

True

True

Not supported.

True

False

i_output * (size_input - 1) / (size_output - 1)

False

True

(i_output + 0.5) * size_input / size_output - 0.5

False

False

i_output * size_input / size_output

In the case of the nearest mode and half_pixel_for_nn is True, the input coordinate i_input is computed by the output coordinate i_output as

i_input = (i_output + 0.5) * size_input / size_output.

例 :

import numpy as np
import nnabla as nn
import nnabla.functions as F

x_data = np.random.rand(64, 3, 224, 224)
x = nn.Variable.from_numpy_array(x_data)

# Resize by scales
y = F.interpolate(x, scale=(2, 2), mode='linear')
print(y.shape)  # (64, 3, 448, 448)
y.forward()
print(y.d)  # Print output

# Resize to a size
y2 = F.interpolate(x, output_size=(320, 257), mode='linear')
print(y2.shape)  # (64, 3, 320, 257)
y2.forward()
print(y2.d)  # Print output
パラメータ
  • x (Variable) -- 任意の次元数の N-D 次元配列。

  • scale (tuple of ints) -- 軸に沿った倍率。 デフォルトは None です。これを省略する場合は、 output_size を指定する必要があります。

  • output_size (tuple of ints) -- 軸の出力サイズ。 これが与えられている場合、スケール係数は出力サイズと入力サイズによって決定されます。 デフォルトは None です。これを省略する場合は、 scale を指定する必要があります。

  • mode (str) -- (‘linear’|’nearest’) から選択された補間モード。デフォルトは linear です。

  • align_corners (bool) -- If true, the corner pixels of input and output arrays are aligned, such that the output corner pixels have the same values with the input corner pixels. Default is False.

  • half_pixel -- If true, in the coordinate transformation, 0.5 is added to the output coordinate and 0.5 is subtracted from the input coordinate after scaling. Default is False.

  • half_pixel_for_nn -- This is a special argument to support the backward-compatibility of the nearest neighbor interpolation. Default is False. When in True, the implementation of nearest neighbor interpolation is the old one.

  • channel_last -- True の場合、最後の次元はチャネル (NHWC 形式) となります。

戻り値

N-D 配列。

戻り値の型

Variable

警告

Up to the version 1.8.0, the default of align_corners was None, and it becomes True if mode is linear, otherwise False.

警告

Up to the version 1.8.0, the nearest mode interpolation corresponds to the nearest mode and half_pixel_for_nn = True after the version 1.8.0.

nnabla.functions.fft(x, signal_ndim, normalized=False, n_outputs=- 1, outputs=None)[ソース]

Complex-to-complex 離散フーリエ変換。

\[X_{k_1, \ldots, k_d} = \sum_{n_1=0}^{N_1-1} \dots \sum_{n_d=0}^{N_d-1} x_{n_1, \ldots, n_d} \exp\left(-2 \pi j \left( \sum_{i=0}^{d} \frac{k_i n_i}{N_i} \right) \right),\]

ここでは、

\[k_i = 0, \ldots, N_i - 1 となります。\]

この関数は、現在、主要なバッチ次元の有無にかかわらず、 1-D、 2-D、および 3-D DFT をサポートしています。

入力は、少なくとも signal_ndim + 1 次元の複素数値であることが期待されています。 最後の次元は2つの形状をしており、 x […、0] は実数部であり、 x […、1] は虚数部です。

例 :

import numpy as np
import nnabla as nn
import nnabla.functions as F
from nnabla.ext_utils import get_extension_context

ctx = get_extension_context("cudnn")
nn.set_default_context(ctx)

# Example for a batched 2D-FFT and 2D-IFFT (batch-size: 2, data-size: 4x3)
x_data = np.random.rand(2, 4, 3) + 1j * np.random.rand(2, 4, 3)
x = nn.Variable.from_numpy_array(np.stack([np.real(x_data), np.imag(x_data)], axis=3))
y = F.fft(x, signal_ndim=2, normalized=True)
z = F.ifft(y, signal_ndim=2, normalized=True)
z.forward()

np.allclose(z.d[..., 0] + 1j*z.d[...,1], x_data)
パラメータ
  • x (Variable) -- 入力。

  • signal_ndim (int) -- 各信号の次元数。 1、2、または3でなければなりません。

  • normalized (bool) -- Use unitary normalization. If True, the normalization constant \(\sqrt{\frac{1}{\prod_{i=1}^{d} N_i}}\) is multiplied. [default= False ]

戻り値

FFT変換された信号。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.ifft(x, signal_ndim, normalized=False, n_outputs=- 1, outputs=None)[ソース]

Complex-to-complex 逆離散フーリエ変換、

\[X_{k_1, \ldots, k_d} = \frac{1}{\prod_{i=1}^{d} N_i} \sum_{n_1=0}^{N_1-1} \dots \sum_{n_d=0}^{N_d-1} x_{n_1, \ldots, n_d} \exp\left(2 \pi j \left( \sum_{i=0}^{d} \frac{k_i n_i}{N_i} \right) \right),\]

ここでは、

\[k_i = 0, \ldots, N_i - 1 となります。\]

この関数は、現在、主要なバッチ次元の有無にかかわらず、 1-D、 2-D、および 3-D DFT をサポートしています。

入力は、少なくとも signal_ndim + 1 次元の複素数値であることが期待されています。 最後の次元は2つの形状をしており、 x […、0] は実数部であり、 x […、1] は虚数部です。

パラメータ
  • x (Variable) -- 入力。

  • signal_ndim (int) -- 各信号の次元数。 1、2、または3でなければなりません。

  • normalized (bool) -- Use unitary normalization. If True, the normalization constant \(\frac{1}{\prod_{i=1}^{d} N_i}\) becomes \(\sqrt{\frac{1}{\prod_{i=1}^{d} N_i}}\). [default= False ]

戻り値

IFFT 変換された信号。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.stft(x, window_size, stride, fft_size, window_type='hanning', center=True, pad_mode='reflect', as_istft_backward=False)[ソース]

短時間フーリエ変換を計算します

パラメータ
  • x (Variable) -- batch_size x sample_size サイズの時間領域列。

  • window_size (int) -- STFT 分析ウィンドウのサイズ。

  • stride (int) -- hop size とも呼ばれる、ウィンドウをシフトするサンプルの数。

  • fft_size (int) -- FFT のサイズ。出力には fft_size // 2+ 1 の周波数ビンがあります。

  • window_type (str) -- 分析ウィンドウは、 hanninghamming 、または rectangular のいずれかになります。便宜上、 window_type='rectangular' と同等の window_type=None もサポートされています。

  • center (bool) -- True の場合、信号 x は、反射パディングを使用して FFT サイズの半分でパディングされます。

  • pad_mode (str) -- 'constant' または 'reflect' のパディングモード。 0'constant' パッド。

  • as_istft_backward -- If True, then forward execution behaves as backward execution of ISTFT, treating input x as output gradient of ISTFT and outputs y_r and y_i as inputs gradient of ISTFT. This option is only used in nn.grad operator.

戻り値

STFT 結果の実数部と虚数部を戻します。

  • Variable: batch_size x fft_size//2 + 1 x frame_size サイズの STFT の実部。

  • Variable: batch x fft_size//2 + 1 x frame_size サイズの STFT の架空の部分。

nnabla.functions.istft(y_r, y_i, window_size, stride, fft_size, window_type='hanning', center=True, pad_mode='reflect', as_stft_backward=False)[ソース]

逆短時間フーリエ変換を計算します

注意: 時間領域信号の再構成には、定数二乗逆ウィンドウを使用するため、最初と最後の window_size - stride は完全には再構成されません。

パラメータ
  • y_r (Variable) -- batch_size x fft_size//2 + 1 x frame_size サイズのSTFT の実部。

  • y_i (Variable) -- batch_size x fft_size//2 + 1 x frame_size サイズの STFT の架空の部分。

  • window_size (int) -- STFT 分析ウィンドウのサイズ。

  • stride (int) -- hop size とも呼ばれる、ウィンドウをシフトするサンプルの数。

  • fft_size (int) -- FFT のサイズ、 (STFT は fft_size // 2 + 1 周波数ビンがあります)。

  • window_type (str) -- 分析ウィンドウは、 hanninghamming 、または rectangular のいずれかになります。便宜上、 window_type='rectangular' と同等の window_type=None もサポートされています。

  • center (bool) -- True の場合、時間領域信号が中心にあるフレームであると想定されます。

  • pad_mode (str) -- Padding mode corresponding to STFT pad_mode, which can be 'constant' or 'reflect'. 'constant' pads with 0. This option is ignored for the normal use of ISTFT. You need to set the same pad_mode only when as_stft_backward == True.

  • as_stft_backward (bool) -- If True, then forward execution behaves as backward execution of STFT, treating inputs y_r and y_i as outputs gradient of STFT and output x as input gradient of STFT. This option is only used in nn.grad operator.

戻り値

batch_size x sample_size サイズの時間領域列。

戻り値の型

Variable

Geometric Neural Network Layers
nnabla.functions.affine_grid(theta, size, align_corners=False, n_outputs=- 1, outputs=None)[ソース]

Generate the source grid based on the normalized target grid with size. The target grid is first normalized in [-1, 1], then tranformed by the affine transformation \(\theta\) to generate the source grid. 2D and 3D grid are supported now.

This function is normally used with the warp_by_grid function for constructing the spatial transformer.

パラメータ
  • theta (Variable) -- N-D array with the shape (\(B \times 2 \times 3\)), the sample-wise affine transformation matrix.

  • size (repeated int64) -- The grid size of (\(H \times W\)) for 2D and (\(D \times H \times W\)) for 3D.

  • align_corners (bool) -- If True, the top-left and bottom-right pixels correspond to (-1, -1) and (1, 1) respectively since a pixel is located on the corner of a grid, and the target grid is normalized in [-1, 1]. If False, the normalized target grid in [-1, 1] is scaled by size - 1 / size according to the respective spatial size (e.g., \(H\) and \(W\)) before the transformation since a pixel is located on a center of a cell in a grid. [default= False ]

戻り値

N-D array with the shape (\(B \times H \times W \times 2\)) for 2D and (\(B \times D \times H \times W \times 3\)) for 3D. The last dimension of 2 is for (x, y) and of 3 for (x, y, z). The gird is used as the source grid for the warping.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.warp_by_grid(x, grid, mode='linear', padding_mode='zero', align_corners=False, channel_last=False, n_outputs=- 1, outputs=None)[ソース]

Warp the input data by the grid. This function is normally used with the generated normalized grid by the affine_grid function for constructing the spatial transformer.

パラメータ
  • x (Variable) -- Input data to be warped with the shape (\(B \times C \times H_{in} \times W_{in}\)) for 2D and (\(B \times C \times D_{in} \times H_{in} \times W_{in}\)) for 3D.

  • grid (Variable) -- Grid warping the input data with the shape (\(B \times H_{out} \times W_{out} \times 2\)) for 2D and (\(B \times D_{out} \times H_{out} \times W_{out} \times 3\)) for 3D. The last dimension of 2 is for (x, y) or 3 for (x, y, z).

  • mode (string) -- Interpolation mode, linear or nearest. [default= 'linear' ]

  • padding_mode (string) -- Padding mode when the grid value is outside [-1, 1]. If this is "zero", 0 is used for padding. "reflect" uses the values reflected at the ends of the original input data like the mirror. "repeat" used the values at the ends of the original input data. [default= 'zero' ]

  • align_corners (bool) -- The target grid normalized in [-1, 1] is scaled by size - 1 / size according to the respective spatial size (e.g., \(H\) and \(W\)) before the transformation if this is False. If this is True, the top-left and bottom-right pixels correspond to (-1, -1) and (1, 1) respectively. [default= False ]

  • channel_last (bool) -- If True, the last dimension is considered as channel dimension, a.k.a NHWC order. [default= False ]

戻り値

Output data warped by the grid.

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.warp_by_flow(data, flow, n_outputs=- 1, outputs=None)[ソース]

Transform the image(s) data by flow field(s) of offset vectors such that each output pixel corresponds to the input image pixel at the relative offset location given by horizontal and vertical flow values (in other words, the flow field describes the coordinate displacements for each output pixel to the corresponding input pixel). Both data and flow are 4-D variables (in "NCHW" layout) with identical shape except the flow channel dimension (which is always 2).

\[output_{n,c,y,x} = data_{n,c,y',x'},\]

ここでは、

\[\begin{split}y' &=& y + flow_{n,1,y,x}, \\ x' &=& x + flow_{n,0,y,x}.\end{split}\]

入力画像の最も近い 4 つのピクセル間をバイリニア補完することによって、 \(y'\) および \(x'\) における出力ピクセル値を取得します。入力画像外のピクセル値には、暗黙的に最も近い境界ピクセルが埋め込まれます。

パラメータ
  • data (Variable) -- (N, Channels, Height, Width) の形式の入力画像データ。

  • flow (Variable) -- (N, 2, Height, Width) の形式の flow フィールドベクトル。

戻り値

(N, Channels, Height, Width) の形式の変換画像データ。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

量子化ニューラルネットワーク層
nnabla.functions.binary_sigmoid(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとのバイナリ sigmoid 関数。forward パスでは

\[\begin{split}f(x) = \begin{cases} 1 & (x > 0) \\ 0 & ({\rm otherwise})\end{cases},\end{split}\]

を計算しますが、backward パスでは勾配の直線近似が使用され、すなわち、以下のようになります。

\[\begin{split}\frac{\partial f(x)}{\partial x} = \begin{cases} 0 & (|x| \geq 1) \\ \frac{1}{2} & ({\rm otherwise}) \end{cases}.\end{split}\]

参照

パラメータ

x (Variable) -- 入力。

戻り値

出力。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.binary_tanh(x, n_outputs=- 1, outputs=None)[ソース]

要素ごとのバイナリ tanh 関数。forward パスでは、以下の計算をします。

\[\begin{split}f(x) = \begin{cases} 1 & (x > 0) \\ -1 & ({\rm otherwise}) \end{cases},\end{split}\]

を計算しますが、backward パスでは勾配の直線近似が使用され、すなわち、以下のようになります。

\[\begin{split}\frac{\partial f(x)}{\partial x} = \begin{cases} 0 & (|x| \geq 1) \\ 1 & ({\rm otherwise}) \end{cases}.\end{split}\]

参照

パラメータ

x (Variable) -- 入力。

戻り値

出力。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.binary_connect_affine(x, weight, binary_weight, bias=None, base_axis=1, quantize_zero_to=1.0, n_outputs=- 1, outputs=None)[ソース]

この関数は BinaryConnect affine 層を提供します。forward パスでは以下の計算します。

\[y_j = \sum_{i} sign(w_{j,i}) x_i,\]

つまり、重み \(w_{j,i}\)\(sign(w_{j,i})\) に 2 値化されるため、各重みは \(\{-1,\,1\}\) になります。この重みの 2 値化により、内積の計算は、加算/減算になるため、乗算を必要としません。

この関数は、 batch_normalization() と併せて使用される必要があります。

注釈

1) If you would like to share the binary weights between other layers, please use the standard, floating value weights (weight) and not the binary weights (binary_weight).

2) The weights and the binary weights become in sync only after a call to forward(), and not after a call to backward(). If you wish to store the parameters of the network, remember to call forward(), once before doing so, otherwise the weights and the binary weights will not be in sync.

3) CPU and GPU implementations now use floating values for binary_weight, since this function is for simulation purposes.

参照

パラメータ
  • x (Variable) -- 入力。

  • weight (Variable) -- 重み。 [パラメータ]

  • binary_weight (Variable) -- 2 値化された重み。 [パラメータ]

  • bias (Variable) -- バイアス。[オプション][パラメータ]

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • quantize_zero_to (float) -- Input value at zero is quantized to this value. [default= 1.0 ]

戻り値

出力。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.binary_connect_convolution(x, weight, binary_weight, bias=None, base_axis=1, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, n_outputs=- 1, outputs=None)[ソース]

この関数は BinaryConnect convolution 層を提供します。forward パスでは以下の計算します。

\[y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} sign(w_{n, m, i, j}) x_{m, a + i, b + j},\]

つまり、重み \(w_{n, m, i, j}\)\(sign(w_{n, m, i, j})\) に2 値化されるため、各重みは \(\{-1,\,1\}\) になります。この重みの 2 値化により、内積の計算は、加算/減算になるため、乗算を必要としません。

この関数は、 batch_normalization() と併せて使用される必要があります。

参照

注釈

1) If you would like to share the binary weights between other layers, please use the standard, floating value weights (weight) and not the binary weights (binary_weight).

2) The weights and the binary weights become in sync only after a call to forward(), and not after a call to backward(). If you wish to store the parameters of the network, remember to call forward(), once before doing so, otherwise the weights and the binary weights will not be in sync.

3) CPU and GPU implementations now use floating values for binary_weight, since this function is for simulation purposes.

パラメータ
  • x (Variable) -- 入力。

  • weight (Variable) -- 重み。[パラメータ]

  • binary_weight (Variable) -- 2値化された重み。[パラメータ]

  • bias (Variable) -- バイアス。[オプション][パラメータ]

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • group (int) -- Number of groups of channels. This makes the connection across channels sparser, by grouping connections along the mapping direction. [default= 1 ]

  • quantize_zero_to (float) -- Input value at zero is quantized to this value. [default= 1.0 ]

戻り値

出力

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.binary_weight_affine(x, weight, binary_weight, alpha, bias=None, base_axis=1, quantize_zero_to=1.0, n_outputs=- 1, outputs=None)[ソース]

この関数は Binary Weight Network affine 層を提供します。forward パスでは以下の計算します。

\[y_j = \frac{1}{\|\mathbf{w}_j\|_{\ell_1}} \sum_{i} sign(w_{j,i}) x_i\]

つまり、重み \(w_{j,i}\)\(sign(w_{j,i})\) に 2 値化されるため、各重みは \(\{-1,\,1\}\) になります。この重みの 2 値化により、内積の計算は加算/減算になり、スケーリング係数 \(\alpha_j = \frac{1}{\|\mathbf{w}_j\|_{\ell_1}}\) との乗算が続きます。

参照

注釈

1) If you would like to share the binary weights with other layers, please use the standard, floating value weights (weight) and not the binary weights (binary_weight).

2) The weights and the binary weights become in sync only after a call to forward(), and not after a call to backward(). If you wish to store the parameters of the network, remember to call forward(), once before doing so, otherwise the weights and the binary weights will not be in sync.

3) CPU and GPU implementations now use floating values for binary_weight, since this function is for simulation purposes.

パラメータ
  • x (Variable) -- 入力。

  • weight (Variable) -- 重み。[パラメータ]

  • binary_weight (Variable) -- 2値化された重み。[パラメータ]

  • alpha (Variable) -- アルファ。[パラメータ]

  • bias (Variable) -- バイアス。[オプション][パラメータ]

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • quantize_zero_to (float) -- Input value at zero is quantized to this value. [default= 1.0 ]

戻り値

出力。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.binary_weight_convolution(x, weight, binary_weight, alpha, bias=None, base_axis=1, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, n_outputs=- 1, outputs=None)[ソース]

この関数は Binary Weight Network convolution 層を提供します。foward パスでは以下の計算をします。

\[y_{n, a, b} = \frac{1}{\|\mathbf{w}_n\|_{\ell_1}} \sum_{m} \sum_{i} \sum_{j} sign(w_{n, m, i, j}) x_{m, a + i, b + j}.\]

つまり、重み \(w_{n, m, i, j}\)\(sign(w_{n, m, i, j})\) に 2 値化されるため、各重みは \(\{-1,\,1\}\) になります。この重みの 2 値化により、内積の計算は加算/減算になり、スケーリング係数 \(\alpha_n = \frac{1}{\|\mathbf{w}_n\|_{\ell_1}}\) との乗算が続きます。

参照

注釈

1) If you would like to share the binary weights between other standard layers, please use the standard, floating value weights (weight) and not the binary weights (binary_weight).

2) The weights and the binary weights become in sync only after a call to forward(), and not after a call to backward(). If you wish to store the parameters of the network, remember to call forward(), once before doing so, otherwise the weights and the binary weights will not be in sync.

3) CPU and GPU implementations now use floating values for binary_weight, since this function is for simulation purposes.

パラメータ
  • x (Variable) -- 入力。

  • weight (Variable) -- 重み。[パラメータ]

  • binary_weight (Variable) -- 2値化された重み。[パラメータ]

  • alpha (Variable) -- アルファ。[パラメータ]

  • bias (Variable) -- バイアス。[オプション][パラメータ]

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • group (int) -- Number of groups of channels. This makes the connection across channels sparser, by grouping connections along the mapping direction. [default= 1 ]

  • quantize_zero_to (float) -- Input value at zero is quantized to this value. [default= 1.0 ]

戻り値

出力

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.fixed_point_quantize(x, sign=True, n=8, delta=0.0625, quantize=True, ste_fine_grained=True, outputs=None)[ソース]

Fixed Point Quantize.

This function simulates to uniformly quantize values in fixed-point number representation.

パラメータ
  • x (Variable) -- 入力変数。

  • sign (bool) -- 符号あり、または、符号なしを示します。デフォルトは true です。

  • n (int) -- 使用されるビット幅。 sign は 1 ビットを消費することに注意してください。 \(n-1\)signed の場合の数値表現に使用されます。

  • delta (float) -- ステップサイズ。

  • quantize (bool) -- true の場合、入力を量子化、そうでなければしない。

  • ste_fine_grained (bool) -- true の場合、 STE は1ではありません。

戻り値

N-D 配列。

戻り値の型

Variable

参考

nnabla.function_bases.fixed_point_quantize.

forward パスでは、

\[\begin{split}\begin{equation} q_i= \left\{ \begin{array}{ll} max & if \ \ \ x_i > max \\ sign(x_i) \times floor(|x_i| \delta^{-1} + 2^{-1}) \times \delta & if \ \ min \le x_i \le max \\ min & if \ \ x_i < min \\ \end{array} \right., \end{equation}\end{split}\]

ここで、\(\delta\) はステップサイズで、 \((min, max) :=(- (2^{n-1} - 1)\delta, (2^{n-1} - 1)\delta)\) \(sign\) が true である場合、 \((min, max) := (0, (2^n - 1) \delta)\) 、そうでなければ、 \(n\) は合計ビット幅が使用されます。

ste_fine_grained を false として backward パスで使用する場合、

\[\begin{equation} \frac{\partial q_i}{\partial x_i} = 1. \end{equation}\]

ste_fine_grained を true として backward パスで使用する場合、

\[\begin{split}\begin{equation} \frac{\partial q_i}{\partial x_i}= \left\{ \begin{array}{ll} 0 & if \ \ \ x_i > max \\ 1 & if \ \ min \le x_i \le max \\ 0 & if \ \ x_i < min \\ \end{array} \right.. \end{equation}\end{split}\]

注釈

この関数はシミュレーション用であるため、量子化された値は浮動小数点数として保存されます。

nnabla.functions.min_max_quantize(x, qr_min, qr_max, ql_min, ql_max, decay=0.999, x_min_max=False, ema=False, ste_fine_grained=True, eps=0.01, quantize=True, outputs=None)[ソース]

最小最大量子化。

This function simulates to uniformly quantize values in fixed-point number representation.

最小最大量子化は、次の式として定義されます。

\[y = round \left(\frac{\min(\max(x, m), M) - m}{scale} \right) \times scale + m,\]

ここで、 \(scale\)

\[scale = \frac{M - m}{M_q - m_q},\]

および

\[\begin{split}m_q = ql_{min}, \\ M_q = ql_{max}, \\ m = qr_{min}, \\ M = qr_{max}.\end{split}\]

ste_fine_grained を false として backward パスで使用する場合、

\[\frac{\partial q_i}{\partial x_i} = 1.\]

ste_fine_grained を true として backward パスで使用する場合、

\[\begin{split} \frac{\partial q_i}{\partial x_i}= \left\{ \begin{array}{ll} 0 & if \ \ \ x_i > M \\ 1 & if \ \ m \le x_i \le M \\ 0 & if \ \ x_i < m \\ \end{array} \right..\end{split}\]

\(qr_{min}\)\(qr_{max}\) は次のように処理されます。

  • x_min_maxTrueemaTrue : \(min(x)\)\(max(x)\) ごとに指数移動平均が計算され、 \(qr_{min}\)\(qr_{max}\) に保存されます。

  • x_min_maxTrueemaFalse : \(min(x)\)\(max(x)\) が計算され、 \(qr_{min}\)\(qr_{max}\) に保存されます。

  • x_min_maxFalseemaTrue : \(qr_{min}\)\(qr_{max}\) に保存されている指数移動平均が使用されます。

  • x_min_maxFalseemaFalse : \(qr_{min}\)\(qr_{max}\) の勾配は、backward パスで計算されます。

より正確には、最小最大量子化の推論では、実際の値 0 に対応する ゼロ点 ( zp ) を考慮する必要があり、そのデータ型は整数です。 zero-point は以下の様に定義されます。

\[\begin{split} && zp_f = ql_{min} -\frac{qr_{min}}{scale}, \\ && zp = \left\{ \begin{array}{ll} ql_{max} & if \ \ \ zp_f >= ql_{max} \\ round(zp_f) & if \ \ otherwise \\ ql_{min} & if \ \ zp_f <= ql_{min} \\ \end{array} \right..\end{split}\]

従って、 ゼロ点 の量子化効果をシミュレートするために、forward パスと backward パスの両方で、 \(qr_{min}\)\(qr_{max}\) は次のように調整されます。

\[\begin{split}qr_{min}^{adj} = ql_{min} - zp * scale, \\ qr_{max}^{adj} = ql_{max} - zp * scale.\end{split}\]

これらの操作は、通常 ナッジ と呼ばれます。

最後に、最小最大量子化の式では、 \(m\)\(M\) はそれぞれ \(qr_{min}^{adj}\)\(qr_{max}^{adj}\) に置き換えられます。

パラメータ
  • x (Variable) -- 入力 N-D 配列。

  • qr_min (Variable) -- 最小量子化範囲 ( forward パス実行中に変更)。

  • qr_max (Variable) -- 最大量子化範囲 (forward パス実行中に変更)。

  • ql_min (Variable) -- 最小量子化レベル、通常は 0 。

  • ql_max (Variable) -- 最大量子化レベル、通常は 255。

  • decay (float) -- 指数移動平均の減衰率。

  • x_min_max (bool) -- x の最小値と最大値を使用して、量子化範囲を計算します。デフォルトは False です。

  • ema (bool) -- 最小および最大量子化範囲の指数移動平均を使用します。デフォルトは False です。

  • ste_fine_grained (bool) -- True の場合、STE は1ではなく、min-max から計算された { 0, 1 }-maskは、backward の勾配に適用されます。そうでなければ、STE は1です。

  • eps (float) -- イプシロン、すなわち \(qr_{max} - qr_{min}\) がイプシロンより大きいことを確認するための小さな値。

  • quantize (bool) -- 量子化を適用するかどうか。

参照

Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, Matthew Tang, Andrew Howard, Hartwig Adam, and Dmitry Kalenichenko, "Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference", https://arxiv.org/abs/1712.05877

nnabla.functions.pow2_quantize(x, sign=True, with_zero=True, n=8, m=1, quantize=True, ste_fine_grained=True, outputs=None)[ソース]

Pow2 Quantize.

This function simulates to uniformly quantize values in fixed-point number representation.

パラメータ
  • x (Variable) -- 入力変数。

  • sign (bool) -- 符号あり、または、符号なしを示します。デフォルトは true です。

  • with_zero (bool) -- 量子化値としてゼロを使用することを示します。デフォルトは true です。 zero は 1 ビットを消費することに注意してください。

  • n (int) -- 使用されるビット幅。 sign は 1 ビットを消費することに注意してください。 \(n-1\) は、 signed の場合の数値表現に使用されます。 デフォルトは 8 です。

  • m (int) -- \(2^m\) はダイナミックレンジの上限で、 \(-2^m\) は下限 \(m \in \mathcal{Z}\) です。デフォルトは 1 です。

  • quantize (bool) -- true の場合、入力を量子化、そうでなければしない。

  • ste_fine_grained (bool) -- true の場合、 STE は1ではありません。

戻り値

N-D 配列。

戻り値の型

Variable

参考

nnabla.function_bases.pow2_quantize.

signed のケースの forward パスでは、

\[\begin{split}q_i= \left\{ \begin{array}{ll} max_{+} & if \ \ \overline{q_i} > max_{+} \\ \overline{q_i} & if \ \ min_{+} \le \overline{q_i} \le max_{+} \\ min_{+} & if \ \ 0 \le \overline{q_i} < min_{+} \\ min_{-} & if \ \ min_{-} < \overline{q_i} < 0 \\ \overline{q_i} & if \ \ max_{-} \le \overline{q_i} \le min_{-}\\ max_{-} & if \ \ \overline{q_i} < max_{-} \\ \end{array} \right.,\end{split}\]

ここでは、

\[\begin{split}&& max_{+} = 2^{m}, min_{+} = 2^{m - (2^{n-1} - 1)},\\ && max_{-} = -2^{m}, min_{-} = -2^{m - (2^{n-1} - 1)},\\ && \overline{q_i} = sign(x_i) \times 2^{round(\log_2 |x_i|)}.\end{split}\]

この量子化では、2 つの 2 のべき乗数の間の幾何平均を量子化し閾値として使用します。

unsigned のケースの forward パスでは、

\[\begin{split}q_i= \left\{ \begin{array}{ll} max & if \ \ \overline{q_i} > max \\ \overline{q_i} & if \ \ min \le \overline{q_i} \le max \\ min & if \ \ 0 < \overline{q_i} < min \\ \end{array} \right.,\end{split}\]

ここでは、

\[\begin{split}&& max = 2^{m}, min = 2^{m - (2^{n} - 1)},\\ && \overline{q_i} = 2^{int(\log_2 |x_i|)}.\end{split}\]

with_zero を true として使用する場合、プルーニング閾値を使用して、入力を0または \(min\) に丸めます。プルーニング閾値は、この関数で次のように定義されています。

\[pruning\ threshold = min \times 2^{-\frac{1}{2}}.\]

入力の絶対値がこの値よりも小さい場合、入力は 0 に丸められ、それ以外の場合は \(min\) になります。

ste_fine_grained を false として backward パスで使用する場合、

\[\frac{\partial q_i}{\partial x_i} = 1.\]

ste_fine_grained を true として backward パスで使用する場合、

\[\begin{split}\frac{\partial q_i}{\partial x_i}= \left\{ \begin{array}{ll} 0 & if \ \ \overline{q_i} > max_{+} \\ 1 & if \ \ otherwise \\ 0 & if \ \ \overline{q_i} < max_{-} \\ \end{array} \right..\end{split}\]
nnabla.functions.prune(x, rate=0.9, n_outputs=- 1, outputs=None)[ソース]

次の式のように、入力をプルーニングします。

\[\begin{split}q_i = \left \{ \begin{array}{ll} 0 & abs(x_i) < threshold \\ x_i & otherwise \end{array} \right.\end{split}\]

ここで、\(threshold\) は閾値 threshold = np.sort(np.abs(x))[int((x.size - 1) * rate)] によって定義されます。

パラメータ
  • x (Variable) -- N-D 配列

  • rate (float) -- Sparse rate, or pruning rate. [default= 0.9 ]

戻り値

x と同じ形状の N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.inq_affine(x, weight, indicator_fixedweights, bias=None, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='largest_abs', seed=- 1, n_outputs=- 1, outputs=None)[ソース]

この関数は INQ affine 層を提供します。forward パスにおいて以下のように計算されます。

\[y_j = \sum_{i} w_{j,i} x_i,\]

ここでは、重み \(w_{j,i}\) は学習中に順に 2 のべき乗の数に量子化されます。backward パスでは、固定値でない (つまり、学習可能な) 重みのみが更新されます。

参照

パラメータ
  • x (Variable) -- 入力。

  • weight (Variable) -- 重み。 [パラメータ]

  • indicator_fixedweights (Variable) -- すでに重みが固定されているインデックス (0 = 固定値でない, 1 = 固定値). [パラメータ]

  • bias (Variable) -- バイアス。[オプション][パラメータ]

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • num_bits (int) -- Number of bits per weight. Needs to be >= 2 as two bits are used to code zero and sign of weight. [default= 4 ]

  • inq_iterations (repeated int64) -- List which specifies after how many forward passes we fix 50% of the learnable weights. If we have done as many iterations as specified in the last element of inq_iterations, then all weights are fixed. [default= () ]

  • selection_algorithm (string) -- Chooses algorithm that we use for selecting the weights to fix ("largest_abs" ... fix weights with largest absolute value, "random" ... fix weights randomly) [default= 'largest_abs' ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

出力。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.inq_convolution(x, weight, indicator_fixedweights, bias=None, base_axis=1, pad=None, stride=None, dilation=None, group=1, num_bits=4, inq_iterations=(), selection_algorithm='largest_abs', seed=- 1, n_outputs=- 1, outputs=None)[ソース]

この関数は、INQ convolution 層を提供します。 forward パスにおいて以下のように計算されます。

\[y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} w_{n, m, i, j} x_{m, a + i, b + j},\]

ここでは、重み \(w_{j,i}\) は学習中に順に 2 のべき乗の数に量子化されます。backward パスでは、固定値でない (つまり、学習可能な) 重みのみが更新されます。

参照

パラメータ
  • x (Variable) -- 入力。

  • weight (Variable) -- 重み。[パラメータ]

  • indicator_fixedweights (Variable) -- すでに重みが固定されているインデックス (0 = 固定値でない, 1 = 固定値). [パラメータ]

  • bias (Variable) -- バイアス。[オプション][パラメータ]

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • pad (tuple of int) -- Padding sizes for dimensions. [default= (0,) * (len(x.shape) - (base_axis+1)) ]

  • stride (tuple of int) -- Stride sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • dilation (tuple of int) -- Dilation sizes for dimensions. [default= (1,) * (len(x.shape) - (base_axis+1)) ]

  • group (int) -- Number of groups of channels. This makes the connection across channels sparser, by grouping connections along the mapping direction. [default= 1 ]

  • num_bits (int) -- Number of bits per weight. Needs to be >= 2 as two bits are used to code zero and sign of weight. [default= 4 ]

  • inq_iterations (repeated int64) -- List which specifies after how many forward passes we fix 50% of the learnable weights. If we have done as many iterations as specified in the last element of inq_iterations, then all weights are fixed. [default= () ]

  • selection_algorithm (string) -- Chooses algorithm that we use for selecting the weights to fix ("largest_abs" ... fix weights with largest absolute value, "random" ... fix weights randomly) [default= 'largest_abs' ]

  • seed (int) -- Random seed. When -1, seed is sampled from global random number generator. [default= -1 ]

戻り値

出力

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

サポートされていない、特別な使用
nnabla.functions.vat_noise(x, w, base_axis=1, eps=1.0, n_outputs=- 1, outputs=None)[ソース]

仮想敵対訓練のためのノイズ。

この層は、仮想敵対訓練のノイズを取得するために特化された、GUI ネットワーク設計のための特別な層です。

backward プロセスでは、重みパラメータが勾配に置き換えられます。

forward

\[y_i = \frac{\epsilon x_i}{\sqrt{\sum_k x_k^2 + c}}\]

backward

\[\delta x_i = 0\]
\[w_i = \epsilon \delta y_i\]

注釈

この層は、GUI ネットワーク設計のための特別な層です。

参照

パラメータ
  • x (Variable) -- ノイズ入力の N-D 配列。ノイズは、最初は標準のガウスノイズですが、次のステップでは、勾配変数がフィードバックされます。

  • w (Variable) -- 勾配値を保持するための N-D 勾配。

  • base_axis (int) -- Dimensions up to base_axis is treated as sample dimension. [default= 1 ]

  • eps (float) -- Noise norm (l2) factor. [default= 1.0 ]

戻り値

N-D 配列

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

この関数は、forward パスで恒等関数として動作し、backward パスの勾配を削除します。

この層は、GUI ネットワーク設計のための特別な層であり、この層を追加することにより、後方向操作をゼロにするために使用されます。

forward

\[y_i = x_i\]

backward

\[\delta x_i = 0\]

注釈

この層は、GUI ネットワーク設計のための特別な層です。

パラメータ

x (Variable) -- N-D 配列。

戻り値

N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.sink(*x, **kw)[ソース]

複数の変数の forward または backward 関数を1か所で呼び出すために使用されるダミー変数を作成します。

これは、任意の形状の任意の数の入力変数を取り、単一の 0 形状の出力を作成します。forward パスは何もしません。 one_input_grad が true に設定されている場合、backward パスは入力 grads に1を設定します。

注釈

sink はグラフの最後でのみ呼び出すことができ、入力変数の grad がクリアされます

y.backward(clear_buffer=True) が呼ばれます。

パラメータ
  • *x (Variable) -- 任意の形状の任意の数の入力。 [variadic]

  • one_input_grad (bool) -- Set grads of inputs as one during backward. It is useful to set false if you want to set external gradients to the input variables. [default= True ]

戻り値

ダミー変数。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.confusion_matrix(x, target, axis=None, n_outputs=- 1, outputs=None)[ソース]

Confusion matrix。戻り値は、要素に対応するサンプル数で合計されています。

パラメータ
  • x (Variable) -- Probabilities N-D array. (\(D_1 \times ... \times D_i \times ... \times D_N\))

  • target (Variable) -- Labels N-D array. (\(D_1 \times ... \times 1 \times ... \times D_N\))

  • axis (int) -- Axis on which the confusion matrix is calculated. [default= len(x.shape) - 1 ]

戻り値

Confusion matrix 2 次元配列。 Col インデックスはestimated クラス。 Row インデックスは label クラス。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

画像オブジェクト検出
nnabla.functions.nms_detection2d(x, thresh=None, nms=None, nms_per_class=None, n_outputs=- 1, outputs=None)[ソース]

Non-Maximum Suppression (NMS) to 2D Object detector output. The input is a 3-dimensional tensor with shape of (B, N, 5 + C) where B denotes batch size, N denotes the number of detection box candidates, and C denotes the number of classes of object detection. 5 + C consists of the box coordinates x, y, w, h in normalized coordinates (size of each x and y are 1.0), objectness (learned to predict IoU value to ground truth box), and the class probabilities of C classes. It outputs a tensor with the same dimensions as the input, where all values are copied from the input to the output, except the class probabilities are multiplied by objectness, and possibly suppressed to 0 by NMS. During NMS, all of combination of pairs of bounding boxes is compared. For each pair, the bounding box with a lower detection score (described below) is suppressed if the overlap ratio (the IoU) is greater than the value of nms.

NMS には2つの抑制モードがあります。

1.クラス確率による抑制 ( nms_per_classTrue ) : 各境界ボックスの検出スコアは、各クラスの objectness \* probability[class_id] によって計算されます。抑制はクラスごとに独立して行われます。

2.オブジェクトネスによる抑制 ( nms_per_classFalse ) : 抑制は、 objectness を検出スコアとして使用して、各境界ボックスに対して行われます。すべてのクラス確率は、抑制されたボックスごとに 0 になります。

参照

パラメータ
  • x (Variable) -- A 3- 次元配列。

  • thresh (float) -- Detection score threshold. [default= 0.5 ]

  • nms (float) -- IoU threshold for Non-maximum suppression (NMS). [default= 0.45 ]

  • nms_per_class (bool) -- If true, NMS is applied for each class. [default= True ]

戻り値

入力と同じ次元の3次元配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

検証
nnabla.functions.top_n_error(x, target, axis=None, n=1, n_outputs=- 1, outputs=None)[ソース]

軸で指定された次元に沿った上位 N エラー、出力の要素は以下となります。

\[\begin{split}y_i = \left \{ \begin{array}{l} 1 \ (x_i \ is \ not \ within \ N-th \ place) \\ 0 \ (x_i \ is \ within \ N-th \ place) \end{array} \right.\end{split}\]
パラメータ
  • x (Variable) -- N-D 配列確率。 \(D_1 \times ... \times D_i \times ... \times D_N\)

  • target (Variable) -- ラベルの N-D 配列。 \(D_1 \times ... \times 1 \times ... \times D_N\)

  • axis (int) -- Axis on which the top N error is calculated. [default= len(x.shape) - 1 ]

  • n (int) -- top N [default= 1 ]

戻り値

要素単位でのエラーの N-D 配列。 (\(D_1 \times ... \times 1 \times ... \times D_N\))

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.binary_error(x, target, n_outputs=- 1, outputs=None)[ソース]

要素ごとのバイナリエラー。

\[\begin{split}y_i = \left \{ \begin{array}{l} 0 ((x^{(0)} \geq 0.5) = (x^{(1)} \geq 0.5)) \\ 1 ((x^{(0)} \geq 0.5) \neq (x^{(1)} \geq 0.5)) \end{array} \right.\end{split}\]
パラメータ
  • x (Variable) -- N-D 配列の確率。 \(-\infty\) から \(\infty\)

  • target (Variable) -- N-D ラベル配列。通常は0または1として設定されますが、入力として確率(0〜1)を許可します。

戻り値

要素ごとのバイナリエラー N-D 配列。

戻り値の型

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

パラメトリック関数

NNabla では、最適化可能なパラメータを持つ複数の関数を組み合わせることでで学習可能なモデルを作成します。このような関数をパラメトリック関数といいます。パラメトリック関数は、 nnabla.parametric_functions にて提供されています。

また、

Python API Tutorial も併せてご参照ください。

パラメータを管理するためのAPI

全ての パラメトリック関数リスト によって登録されるパラメータは、このセクションにリストアップされているAPI を使って管理することができます。

nnabla.parameter.parameter_scope(name, scope=None)[ソース]

nnabla.parametric_functions にリストされたパラメトリック関数によって登録されるパラメータをグループ化します。

パラメータ
  • name (str) -- パラメータスコープ名。

  • scope (OrderedDict, optional) -- 現在のパラメータスコープをローカルディクショナリとして指定する。デフォルト値は None です。この場合、グローバルに保持されている現在のパラメータスコープが使用されます。

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.functions as F

with nn.parameter_scope('conv1'):
    conv_out1 = PF.convolution(x, 32, (5, 5))
    bn_out1 = PF.batch_normalization(conv_out1)
    act_out1 = F.relu(bn_out1)
with nn.parameter_scope('conv2'):
    conv_out2 = PF.convolution(act_out1, 64, (3, 3))
    bn_out2 = PF.batch_normalization(conv_out2)
    act_out2 = F.relu(bn_out2)

The with statement 文のブロックを入れ子に(ネスト)することで、パラメータスコープを入れ子に(ネスト)することができます。また、これはパラメータ名に “/” を使うことでも可能となります。

例:

with nn.parameter_scope('network1'):
    with nn.parameter_scope('conv1'):
        conv_out1 = PF.convolution(x, 32, (5, 5))
        bn_out1 = PF.batch_normalization(conv_out1)
        act_out1 = F.relu(bn_out1)
    with nn.parameter_scope('conv2'):
        conv_out2 = PF.convolution(act_out1, 64, (3, 3))
        bn_out2 = PF.batch_normalization(conv_out2)
        act_out2 = F.relu(bn_out2)

以下と同等です。

with nn.parameter_scope('network1/conv1'):
    conv_out1 = PF.convolution(x, 32, (5, 5))
    bn_out1 = PF.batch_normalization(conv_out1)
    act_out1 = F.relu(bn_out1)
with nn.parameter_scope('network1/conv2'):
    conv_out2 = PF.convolution(act_out1, 64, (3, 3))
    bn_out2 = PF.batch_normalization(conv_out2)
    act_out2 = F.relu(bn_out2)
nnabla.parameter.get_current_parameter_scope()[ソース]

現在のパラメータスコープを返します。

nnabla.parameter.get_parameters(params=None, path='', grad_only=True)[ソース]

現在のパラメータスコープにおけるパラメータ変数を取得します。

パラメータ
  • params (dict) -- 内部使用。ユーザーが手動で設定することはありません。

  • path (str) -- 内部使用。ユーザーが手動で設定することはありません。

  • grad_only (bool) -- False の場合は現在のスコープ内にあるすべてのパラメータを取得し、True の場合は need_grad = True のパラメータのみを取得します。

戻り値

{str : Variable}

戻り値の型

dict

nnabla.parameter.clear_parameters()[ソース]

現在のスコープにおけるすべてのパラメータを消去します。

nnabla.parameter.save_parameters(path, params=None, extension=None)[ソース]

すべてのパラメータを特定のフォーマットでファイルに保存します。

現在、hdf5 と protobuf のフォーマットがサポートされています。

パラメータ
  • path -- パスまたはファイルオブジェクト

  • params (dict, optional) -- 保存されるパラメータ。辞書は Variable へのパラメータ名 (str) です。

nnabla.parameter.load_parameters(path, proto=None, needs_proto=False, extension='.nntxt')[ソース]

特定のフォーマットのファイルからパラメータを読み込みます。

パラメータ

path -- パスまたはファイルオブジェクト

nnabla.parameter.get_parameter_or_create(name, shape=None, initializer=None, need_grad=True, as_need_grad=None)[ソース]

現在のパラメータスコープに存在する、指定された名前のパラメータ変数を返します。

指定された名前の変数が存在しない場合には、新しい変数を作成し、現在のパラメータスコープにその名前で登録してから、パラメータ変数を返します。

パラメータ
  • name (str) -- 現在のスコープにおける名前。すでに存在する場合、名前はパラメータマネージャーから照会されます。

  • shape (tuple of int) -- 作成されるパラメータの形状。指定されたパラメータの形状は、この形状と一致する必要があります。デフォルトは None で、イニシャライザーが numpy.ndarray として指定されている場合にのみ有効です。

  • initializer (nnabla.initializer.BaseInitializer or numpy.ndarray) -- パラメータに適用される初期化関数。 numpy.ndarray を指定して、numpy 配列データからパラメータを初期化することもできます。

  • need_grad (bool) -- 指定された need_grad フラグでパラメータを登録します。デフォルトは True です。フラグが以前に指定されたものと異なる場合、フラグは上書きされますが、パラメータの値は保持されます。

  • as_need_grad (bool) -- 指定された need_grad フラグでパラメータ変数を取得します。これは、指定された名前を持つ、登録済みのパラメータ変数のフラグを上書きしないことに注意してください。代わりに、指定されたフラグが以前に登録された need_grad フラグと一致しない場合、同じ配列の内容を参照する新しい変数を返しますが、その際 need_grad=as_need_grad を使用します。

注釈

このメソッドは、現在のパラメータスコープにおいて登録されているものとは繋がりのない Variable を返します( nnabla.Variable.get_unlinked_variable() を使用)。つまり、 need_grad 属性の変更は、現在のパラメータスコープに存在する変数に影響しません。

パラメトリック関数リスト

以下にリストアップされているパラメトリック関数は、 nnabla.parametric_functions にて提供されています。 関数 にリストされている関数と同様に、最初の引数には Variable 、次にそれぞれのパラメトリック関数固有のオプションを取ります。さらに、パラメータ変数 ( Variable ) をパラメータスコープに登録します。

パラメータ変数は、それぞれのパラメトリック関数ごとに指定された need_grad プロパティを使ってパラメトリック関数に登録されます。 need_grad=False フラグが設定された変数は、勾配降下による更新は行われません。したがって、これらの変数に対して backward 計算が行われることはありません。forward パスや backward パスの間、パラメータを更新する場合(例えば、batch normalizationなど)、通常 False が指定されます。

すべてのパラメトリック関数は、オプション引数 fix_parameters=False を取ります。 True を渡すと、関連したパラメータ変数は登録されている変数のプロパティに関係なく、プロパティ need_grad=False で計算グラフ (computation graph) に繋がり、それらの変数に対して backward 勾配計算は行われません。これは、評価目的で計算グラフを構築したり、グラフ中の一部のパラメータを固定したりする際に便利です。

以下にリストアップされているパラメトリック関数はすべて、下記のデコレータを使ってデコレートされています。

nnabla.parametric_functions.parametric_function_api(scope_name=None, param_desc=None)[ソース]

パラメトリック関数のデコレータ

デコレートされた関数は、常にパラメータスコープ scope_name のもとで呼ばれます。また、最後の引数として name (str, デフォルトは None) が追加されます。name が指定されると、スコープ scope_name はスコープ name の下にネストされます。この機能に利用することで、ソースコードの行数を削減することができます。どのパラメトリック関数でもこのデコレータでデコレートする必要があります。

パラメータ
  • scope_name (str, optional) -- 元の関数は、 scope_name で指定されたパラメータスコープ内で呼び出されます。

  • param_desc (list, optional) -- パラメータの説明は自動的に docstring に含まれます。これは、( name ( str )、description ( str )、shape info ( str )、need_grad ( bool ) )で構成される 4 つの要素を持つタプルのリストである必要があります。

戻り値

デコレートされたパラメトリック関数

戻り値の型

function

登録されている変数を照会および操作する方法については、 パラメータを管理するためのAPI を参照してください。

以下は、パラメトリック関数のリストです。

nnabla.parametric_functions.affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None, name=None)[ソース]

全結合層ともいわれる、affine 層。以下の計算を行います。

\[{\mathbf y} = {\mathbf A} {\mathbf x} + {\mathbf b}.\]

ここでは、 \({\mathbf x}, {\mathbf y}\) はそれぞれ入力、出力、 \({\mathbf A}, {\mathbf b}\) は定数です。

パラメータ
  • inp (Variable) -- (\(M_0 \times \ldots \times M_{B-1} \times D_B \times \ldots \times D_N\)) の形状の入力 N-D 配列。base_axis 前後の次元は、行列となるように平坦化されます。

  • n_outmaps (int or tuple of int) -- データごとの出力ニューロンの数。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • apply_w (function) -- 重みに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

  • apply_b (function) -- バイアスに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "affine" に登録されます。

  • W (need_grad=True) : 重み行列 (形状: (inmaps, outmaps))

  • b (need_grad=True) : バイアスベクター (形状: (outputs,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = affine(<args>)
nnabla.parametric_functions.convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, channel_last=False, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None, name=None)[ソース]

バイアス項を含んだ N-D Convolution

Dilated Convolution (別名 Atrous Convolution) については、以下をご参照ください。

注釈

Convolution は、計算負荷の大きい演算となるため、 cudnn バックエンドで実行することを推奨します。その際、NNabla は CuDNN library の関数を使って、 与えられたconvolution パラメータセットに対して最速のアルゴリズムを決定し、キャッシュします。それにより、メモリをさらに消費し、GPU のメモリサイズが足りなくなる問題を引き起こす可能性があります。そのような場合は、環境変数 NNABLA_CUDNN_WORKSPACE_LIMIT にバイト数を指定することで、所定のワークスペースのメモリ制限に収まるように、アルゴリズムの選択を制限することができます。場合によっては、自動検索を決定的な(再現性のある)結果を生成するアルゴリズムに制限した方がよいケースがあります。その場合には、環境変数 NNABLA_CUDNN_DETERMINISTIC をゼロ以外の値に設定してください。

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • channel_last (bool) -- True の場合、最後の次元はチャネル次元になり、いわゆるNHWC 順になります。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • apply_w (function) -- 重みに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

  • apply_b (function) -- バイアスに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

戻り値

N-D 配列。出力形状については、 convolution を参照してください。

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "conv" に登録されます。

  • W (need_grad=True) : フィルターの重み (形状: (outmaps, inmaps // group, *kernel))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = convolution(<args>)
nnabla.parametric_functions.depthwise_convolution(inp, kernel, pad=None, stride=None, dilation=None, multiplier=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

バイアス項を使った N-D Depthwise Convolution

参照 :

パラメータ
  • inp (Variable) -- N-D 配列

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • multiplier (int) -- 入力特徴マップごとの出力特徴マップの数。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

N-D 配列。出力形状については、 depthwise_convolution を参照してください。

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "depthwise_conv" に登録されます。

  • W (need_grad=True) : フィルターの重み (形状: (inmaps * multiplier, *kernel))

  • b (need_grad=True) : バイアスベクター (形状: (inmaps * multiplier,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = depthwise_convolution(<args>)
nnabla.parametric_functions.deconvolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, channel_last=False, output_padding=None, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None, name=None)[ソース]

Deconvolution 層

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- deconvolution カーネルの数(出力チャネル数と同じ)。例えば、入力に対して、16 種類のフィルターによるdeconvolution を適用するには、16 を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の2次元カーネルによる deconvolution を適用するには、( 3, 5 )を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • apply_w (function) -- 重みに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

  • apply_b (function) -- バイアスに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

戻り値

N-D 配列。出力形状については、 deconvolution を参照してください。

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "deconv" に登録されます。

  • W (need_grad=True) : フィルターの重み (形状: (inmaps, outmaps // group, *kernel))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = deconvolution(<args>)
nnabla.parametric_functions.depthwise_deconvolution(inp, kernel, pad=None, stride=None, dilation=None, divisor=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

Depthwise deconvolution は、1 次元および 2 次元の入力データに対して depthwise convolusion の転置を計算します。

パラメータ
  • inp (Variable) -- N-D 配列

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • divisor (int) -- 出力フィーチャマップごとの入力フィーチャマップの数。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

N-D 配列。出力形状については、 depthwise_deconvolution を参照してください。

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "depthwise_deconv" に登録されます。

  • W (need_grad=True) : フィルターの重み (形状: (inmaps,) + kernel)

  • b (need_grad=True) : バイアスベクター (形状: (inmaps / divisor,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = depthwise_deconvolution(<args>)
nnabla.parametric_functions.deformable_convolution(inp, outmaps, kernel, offset, mask=None, pad=None, stride=None, dilation=None, group=1, deformable_group=1, channel_last=False, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, apply_w=None, apply_b=None, name=None)[ソース]

2D Deformable Convolution with a bias term. If use mask, this function is Deformable Convolution v2.

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • offset (Variable) -- Offsets for deformable convolutions. Shape is fixed to \((N, deformable{\_}group \times 2 \times Kh \times Kw, H, W)\). Offsets must be calculated externally through a separate convolution layer.

  • mask (Variable) -- Normalized mask for deformable convolutions v2. Shape is fixed to \((N, deformable{\_}group \times Kh \times Kw, H, W)\). Masks must be calculated externally together with the offsets through a separate convolution layer.

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • deformable_group (int) -- Number of deformable groups of channels. This makes connections across channels more sparse by grouping connections along map direction.

  • channel_last (bool) -- True の場合、最後の次元はチャネル次元になり、いわゆるNHWC 順になります。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • apply_w (function) -- 重みに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

  • apply_b (function) -- バイアスに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

戻り値

N-D 配列。出力形状については、 convolution を参照してください。

戻り値の型

Variable

登録されるパラメータ

The following variables are registered in a parameter scope "deformable_conv";

  • W (need_grad=True) : フィルターの重み (形状: (outmaps, inmaps // group, *kernel))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = deformable_convolution(<args>)
nnabla.parametric_functions.batch_normalization(inp, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None, no_scale=False, no_bias=False, name=None)[ソース]

Batch normalization 層

\[\begin{split}\begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \sum \left(x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon }}\\ y_i &= & \hat{x}_i \gamma + \beta. \end{array}\end{split}\]

ここでは、 \(x_i, y_i\) は入力とします。テスト時には、学習中に計算された移動平均を使って算出された平均 (mean) と分散 (variance) が使われます。

パラメータ
  • inp (Variable) -- 入力の N-D 配列。

  • axes (tuple of int) -- axes の各要素の平均と分散は、残りの axes の要素を使用して計算されます。例えば、入力が 4 次元で、 axes[1] の場合、バッチ平均は np.mean(inp.d, axis=(0, 2, 3), keepdims=True) として計算されます ( numpy 式を例として使用 )。

  • decay_rate (float) -- 移動平均と分散の減衰率。

  • eps (float) -- std によるゼロ除算を回避する小さな値。

  • batch_stat (bool) -- 移動統計量ではなく、ミニバッチ統計量を使用します。

  • output_stat (bool) -- バッチ平均と分散を出力します。

  • fix_parameters (bool) -- True に設定すると、beta と gamma は更新されません。

  • param_init (dict) -- パラメータイニシャライザーは dict で設定できます。dict のキーは 'beta''gamma''mean' または 'var' である必要があります。dict の値は、 Initializer または numpy.ndarray numpy.ndarray である必要があります。例 {'beta': ConstantInitializer(0), 'gamma': np.ones(gamma_shape) * 2}

  • no_scale (bool) -- True の場合、スケール項は省略されます。

  • no_bias (bool) -- True の場合、バイアス項は省略されます。

戻り値

N-D 配列

戻り値の型

Variable

参照

パラメータの形状は入力データと同じ次元数で、各軸のサイズは、 axes に指定された軸については入力と同じ大きさであり、残りは 1 となります。例えば、入力が 4 次元で、 axes=[1] である場合、パラメータ形状は、 param_shape = np.mean(inp.d, axis=(0, 2, 3), keepdims=True).shape (例として、numpy 表記を使用) となります。

登録されるパラメータ

以下の変数は、パラメータスコープ "bn" に登録されます。

  • beta (need_grad=True) : 学習可能な \(\beta\). (形状: <上記参照>)

  • gamma (need_grad=True) : 学習可能なスケーリングファクター \(\gamma\). (形状: <上記参照>)

  • mean (need_grad=False) : バッチ平均の移動平均 (形状: <上記参照>)

  • var (need_grad=False) : バッチ分散の移動平均 (形状: <上記参照>)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = batch_normalization(<args>)
nnabla.parametric_functions.fused_batch_normalization(inp, z=None, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, nonlinearity='relu', output_stat=False, fix_parameters=False, param_init=None, no_scale=False, no_bias=False, name=None)[ソース]

Batch Normalizationの直後に続く残差入力とのadd2演算と非線形活性化演算の実行を含んだ Batch normalization 層。

パラメータ
  • inp (Variable) -- 入力の N-D 配列。

  • z (Variable, optional) -- 残差の入力。 None を指定すると、BN 操作の直後に activation 関数が実行されます。

  • axes (tuple of int) -- axes の各要素の平均と分散は、残りの axes の要素を使用して計算されます。例えば、入力が 4 次元で、 axes[1] の場合、バッチ平均は np.mean(inp.d, axis=(0, 2, 3), keepdims=True) として計算されます ( numpy 式を例として使用 )。

  • decay_rate (float) -- 移動平均と分散の減衰率。

  • eps (float) -- std によるゼロ除算を回避する小さな値。

  • batch_stat (bool) -- 移動統計量ではなく、ミニバッチ統計量を使用します。

  • nonlinearity (string) -- activation 関数。デフォルトは 'relu' です。

  • output_stat (bool) -- バッチ平均と分散を出力します。

  • fix_parameters (bool) -- True に設定すると、beta と gamma は更新されません。

  • no_scale (bool) -- True の場合、スケール項は省略されます。

  • no_bias (bool) -- True の場合、バイアス項は省略されます。

戻り値

N-D 配列

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "bn" に登録されます。

  • beta (need_grad=True) : 学習可能な \(\beta\). (形状: <上記参照>)

  • gamma (need_grad=True) : 学習可能なスケーリングファクター \(\gamma\). (形状: <上記参照>)

  • mean (need_grad=False) : バッチ平均の移動平均 (形状: <上記参照>)

  • var (need_grad=False) : バッチ分散の移動平均 (形状: <上記参照>)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = fused_batch_normalization(<args>)
nnabla.parametric_functions.sync_batch_normalization(inp, comm, group='world', axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None, no_scale=False, no_bias=False, name=None)[ソース]

Synchronized batch normalization 層

タスク (例: semantic segmentation ) によっては、バッチサイズが小さすぎて、BatchNormalization 層がうまく動かない場合があります。SyncBatchNorlization 層は、バッチ統計情報(平均と分散)を複数のプロセス間で同期することでこのような問題を解決します。

\[\begin{split}\begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon }}\\ y_i &= & \hat{x}_i \gamma + \beta. \end{array}\end{split}\]

ここでは、 \(x_i, y_i\) は入力とします。

パラメータ
  • inp (Variable) -- 入力の N-D 配列。

  • comm (Communicator) -- communicator

  • group (string) -- communicator グループの名前

  • axes (tuple of int) -- axes の各要素の平均と分散は、残りの axes の要素を使用して計算されます。例えば、入力が 4 次元で、 axes[1] の場合、バッチ平均は np.mean(inp.d, axis=(0, 2, 3), keepdims=True) として計算されます ( numpy 式を例として使用 )。

  • decay_rate (float) -- 移動平均と分散の減衰率。

  • eps (float) -- std によるゼロ除算を回避する小さな値。

  • batch_stat (bool) -- 移動統計量ではなく、ミニバッチ統計量を使用します。

  • output_stat (bool) -- バッチ平均と分散を出力します。

  • fix_parameters (bool) -- True に設定すると、beta と gamma は更新されません。

  • param_init (dict) -- パラメータイニシャライザーは dict で設定できます。dict のキーは 'beta''gamma''mean' または 'var' である必要があります。dict の値は、 Initializer または numpy.ndarray numpy.ndarray である必要があります。例 {'beta': ConstantInitializer(0), 'gamma': np.ones(gamma_shape) * 2}

  • no_scale (bool) -- True の場合、スケール項は省略されます。

  • no_bias (bool) -- True の場合、バイアス項は省略されます。

戻り値

N-D 配列

戻り値の型

Variable

参照

パラメータの形状は入力データと同じ次元数で、各軸のサイズは、 axes に指定された軸については入力と同じ大きさであり、残りは 1 となります。例えば、入力が 4 次元で、 axes=[1] である場合、パラメータ形状は、 param_shape = np.mean(inp.d, axis=(0, 2, 3), keepdims=True).shape (例として、numpy 表記を使用) となります。

登録されるパラメータ

以下の変数は、パラメータスコープ "bn" に登録されます。

  • beta (need_grad=True) : 学習可能な \(\beta\). (形状: <上記参照>)

  • gamma (need_grad=True) : 学習可能なスケーリングファクター \(\gamma\). (形状: <上記参照>)

  • mean (need_grad=False) : バッチ平均の移動平均 (形状: <上記参照>)

  • var (need_grad=False) : バッチ分散の移動平均 (形状: <上記参照>)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = sync_batch_normalization(<args>)
nnabla.parametric_functions.mean_subtraction(inp, base_axis=1, update_running_mean=True, fix_parameters=False, name=None)[ソース]

Mean subtraction 層

入力配列の要素の平均値を減算し、平均を \(0\) に正規化します。この関数を使った配列の前処理は、画像分類などの様々なタスクにおいて精度を向上させる効果があります。

学習時は、この関数は以下のように定義されます。

\[\begin{split}\begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i \\ y_i &=& x_i - \mu \end{array}\end{split}\]

テスト時には、学習中に計算した移動平均の値を上式の平均として利用します。

注釈

backward は、最新のミニバッチのみを考慮した近似微分を行います。

パラメータ
  • inp (Variable) -- 入力の N-D 配列。

  • base_axis (int) -- Mean Subtraction 演算のベース軸。base_axis までの次元はサンプル次元として扱われます。

  • update_running_mean (bool) -- True に設定すると、移動平均は更新されません。

  • fix_parameters (bool) -- ダミーパラメータ。この引数は何にも影響しません。

戻り値

N-D 配列

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "mean_subtraction" に登録されます。

  • mean (need_grad=False) : 移動平均 (形状: inp.shape[base_axis:])

  • t (need_grad=False) : forward パスを使ったミニバッチカウンター (形状: (1,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = mean_subtraction(<args>)
nnabla.parametric_functions.layer_normalization(inp, batch_axis=0, eps=1e-05, output_stat=False, fix_parameters=False, param_init=None, no_scale=False, no_bias=False, name=None)[ソース]

入力変数に Layer Normalization を適用します。Layer Normalizationは以下のように定義されます。

\[\begin{split}\begin{eqnarray} \mu^l &=& \frac{1}{H} \sum_{i=1}^{H} x_i^l \\ \sigma^l &=& \sqrt{\frac{1}{H} \sum_{i=1}^{H} \left(x_i^l - \mu^l\right)^2} \\ y &=& \frac{x - \mu^l}{\sigma^l + \epsilon} \gamma + \beta \end{eqnarray}\end{split}\]

ここでは、 \(x\)\(y\) は入力と出力変数、 \(\mu^l\)\(\sigma^l\) はバッチ軸に沿った層ごとの平均値と標準値、 \(\alpha\)\(\beta\) は学習可能なパラメータです。

注釈

全てのチャンネルにスカラースケールやバイアスを適用する他の normalization とは異なり、Layer Normalization は要素ごとにスケールやバイアスを適用します。

参照

パラメータ
  • inp (Variable) -- 入力変数。

  • batch_axis (int or repeated int) -- 平均と分散を計算する軸。

  • eps (float) -- std によるゼロ除算を回避する小さな値。

  • output_stat (bool) -- True の場合、計算された平均と分散も返します。

  • fix_parameters (bool) -- True に設定すると、beta と gamma は更新されません。

  • param_init (dict) -- パラメータイニシャライザーは dict で設定できます。 dictのキーは 'gamma''beta' である必要があります。dict の値は、 Initializer または numpy.ndarray である必要があります。例 {'gamma': np.ones(...) * 2, 'beta': ConstantInitializer(0)}

  • no_scale (bool) -- True の場合、スケール項は省略されます。

  • no_bias (bool) -- True の場合、バイアス項は省略されます。

戻り値

Normalized output variable. * Variable: Mean (if output_stat=True). * Variable: Std (if output_stat=True)

戻り値の型

登録されるパラメータ

以下の変数は、パラメータスコープ "layer_normalization" に登録されます。

  • beta (need_grad=True) : 学習可能な \(\beta\). (形状: <上記参照>)

  • gamma (need_grad=True) : 学習可能なスケーリングファクター \(\gamma\). (形状: <上記参照>)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = layer_normalization(<args>)
nnabla.parametric_functions.instance_normalization(inp, channel_axis=1, batch_axis=0, eps=1e-05, output_stat=False, fix_parameters=False, param_init=None, no_scale=False, no_bias=False, name=None)[ソース]

入力変数に Instance Normalization を適用します。Instance Normalizaionは以下のように定義されます。

\[\begin{split}\begin{eqnarray} \mu^i &=& \frac{1}{H} \sum_{i=1}^{H} x_i^i \\ \sigma^i &=& \sqrt{\frac{1}{H} \sum_{i=1}^{H} \left(x_i^i - \mu^i\right)^2} \\ y &=& \frac{x - \mu^i}{\sigma^ + \epsilon} \gamma + \beta \end{eqnarray}\end{split}\]

ここでは、 \(x\)\(y\) は入力と出力変数、 \(\mu^i\)\(\sigma^i\) はバッチとチャネルごとに個別に計算される平均値と標準偏差、 \(\gamma\)\(\beta\) は適用ゲインとバイアスとします。

例えば、入力の形状が [ B, C, H, W ] ( = channel_axis=1, batch_axis=0 ) の場合、 計算される平均値と標準値の形状は [ B, C, 1, 1 ] です。

参照

パラメータ
  • inp (Variable) -- 入力変数。

  • channel_axis (int or repeated int) -- チャンネル軸。

  • batch_axis (int or repeated int) -- バッチ軸。

  • eps (float) -- std によるゼロ除算を回避する小さな値。

  • output_stat (bool) -- True の場合、バッチの平均と分散を出力します。

  • fix_parameters (bool) -- True の場合、beta と gamma は更新されません。

  • param_init (dict) -- パラメータイニシャライザーは dict で設定できます。 dictのキーは 'gamma''beta' である必要があります。dict の値は、 Initializer または numpy.ndarray である必要があります。例 {'gamma': np.ones(...) * 2, 'beta': ConstantInitializer(0)}

  • no_scale (bool) -- True の場合、スケール項は省略されます。

  • no_bias (bool) -- True の場合、バイアス項は省略されます。

  • Returns --

登録されるパラメータ

以下の変数は、パラメータスコープ "instance_normalization" に登録されます。

  • beta (need_grad=True) : 学習可能な \(\beta\). (形状: <上記参照>)

  • gamma (need_grad=True) : 学習可能なスケーリングファクター \(\gamma\). (形状: <上記参照>)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = instance_normalization(<args>)
nnabla.parametric_functions.group_normalization(inp, num_groups, channel_axis=1, batch_axis=0, eps=1e-05, output_stat=False, fix_parameters=False, param_init=None, no_scale=False, no_bias=False, name=None)[ソース]

入力変数に Group Normalization を適用します。Group Normalizationは以下のように定義されます。

\[\begin{split}\begin{eqnarray} \mu^g &=& \frac{1}{H} \sum_{i=1}^{H} x_i^g \\ \sigma^g &=& \sqrt{\frac{1}{H} \sum_{i=1}^{H} \left(x_i^g - \mu^g\right)^2} \\ y &=& \frac{x - \mu^g}{\sigma^g + \epsilon} \gamma + \beta \end{eqnarray}\end{split}\]

ここでは、 \(x\)\(y\) は入力と出力変数、 \(\mu^g\)\(\sigma^g\) は グループごとの平均と標準偏差で、各グループのチェンネル数は num_channels / num_groups です。 \(\gamma\)\(\beta\) は適応ゲインとバイアスです。

channel_axis によって指定された入力チャネルは、 num_groups グループに分けられ、グループごとに平均と標準偏差が計算されます。例えば、入力の形状が [ B, C, H, W ] (= channel_axis=1, batch_axis=0) の場合、入力変数は、まず [ B, num_groups, C / num_groups, H, W ] に変形され、形状が [ B, num_groups, C / num_groups, 1, 1 ] の平均値と標準値によって標準化されます。出力変数は元々の入力の形状 ( 上述の例の場合は [ B, C, H, W ])に再度変形されてから出力されます。

参照

パラメータ
  • inp (Variable) -- 入力変数。

  • num_groups (int) -- グループ数。 'x' のチャンネル dim は num_groups の整数倍である必要があります。

  • channel_axis (int) -- チャンネル軸。

  • batch_axis (int or repeated int) -- 平均と分散を計算する軸。

  • eps (float) -- std によるゼロ除算を回避する小さな値。

  • output_stat (bool) -- True の場合、平均と分散のバッチの統計。

  • fix_parameters (bool) -- True に設定すると、beta と gamma は更新されません。

  • param_init (dict) -- パラメータイニシャライザーは dict で設定できます。 dictのキーは 'gamma''beta' である必要があります。dict の値は、 Initializer または numpy.ndarray である必要があります。例 {'gamma': np.ones(...) * 2, 'beta': ConstantInitializer(0)}

  • no_scale (bool) -- True の場合、スケール項は省略されます。

  • no_bias (bool) -- True の場合、バイアス項は省略されます。

戻り値

Normalized output variable. * Variable: Mean (if output_stat=True) * Variable: Std (if output_stat=True)

戻り値の型

登録されるパラメータ

以下の変数は、パラメータスコープ "group_normalization" に登録されます。

  • beta (need_grad=True) : 学習可能な \(\beta\). (形状: <上記参照>)

  • gamma (need_grad=True) : 学習可能なスケーリングファクター \(\gamma\). (形状: <上記参照>)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = group_normalization(<args>)
nnabla.parametric_functions.rnn(x, h, w0_init=None, w_init=None, b_init=None, num_layers=1, nonlinearity='tanh', dropout=0.0, bidirectional=False, training=True, rng=None, with_bias=True, fix_parameters=False, name=None)[ソース]

N-Step RNN (回帰型ニューラルネットワーク)。

N-Step RNN 関数は、入力シーケンスに対して非線形層を含んだElman RNN を実装したものです。N-Step RNN 関数は以下のように定義されます。

\[h_t = \tanh(w_{ih}x_t+b_{ih}+w_{hh}h_{(t-1)}).\]

これ以降の入力や出力の説明には、以下の表記を利用します。 \(T\): シーケンスの長さ、 \(B\): バッチサイズ、 \(I\): 入力サイズ、 \(L\): 層数、 \(D\): 方向数(1もしくは2)、 \(H\): 隠れサイズ。

参照

Jeffrey L. Elman. "Finding Structure in Time." Cognitive Science. 1990.

パラメータ
  • x (Variable) -- \((T, B, I)\) の形状の入力 N-D 配列。

  • h (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • w0_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- 最初の層での重みのイニシャライザー。 形状は \((D, H, I + H)\)

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- 二番目、それ以上の層での重みのイニシャライザー。 形状は \((L-1, D, H, D*H + H)\)

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- バイアスのイニシャライザー。形状は \((L, D, H)\)

  • num_layers (int, optional) -- ネットワーク内のレイヤー数。 1 に設定すると、最初のレイヤーの重みのみが呼び出されます。デフォルトは 1 です。

  • nonlinearity (str, optional) -- 入力シーケンスに適用される非線形演算の種類。 tanh または relu である必要があります。デフォルトは tanh です。

  • dropout (float, optional) -- パラメータに適用されるドロップアウトの割合。デフォルトは 0.0 です。

  • bidirectional (bool, optional) -- Trueの場合、各層で双方向計算が実行されます。デフォルトは False です。

  • training (bool, optional) -- True の場合のみ、Backpropagation が実行されます。デフォルトは True です。

  • with_bias (bool, optional) -- バイアス項を含めるか否かを指定します。

戻り値

Output \(y\) with shape \((T, B, D * H)\) ~nnabla.Variable: Output \(h_n\) with shape \((L, D, B, H)\)

戻り値の型

Variable

サンプル

x = nn.Variable((seq_len, batch_size, input_size))
h = nn.Variable((num_layers, num_directions, batch_size, hidden_size))
y, hn = PF.rnn(x, h)
登録されるパラメータ

以下の変数は、パラメータスコープ "rnn" に登録されます。

  • weight_l0 (need_grad=True) : 第0層でのフィルターの重み (形状: (D, H, I + H))

  • weight (need_grad=True) : 第1層以上でのフィルターの重み (形状: (L-1, D, H, DH + H))

  • bias (need_grad=True) : バイアス。 (形状: (L, D, H))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = rnn(<args>)
nnabla.parametric_functions.lstm(x, h, c, w0_init=None, w_init=None, b_init=None, num_layers=1, dropout=0.0, bidirectional=False, training=True, rng=None, with_bias=True, fix_parameters=False, name=None)[ソース]

LSTM (long short-term memory).

Long Short-Term Memory (LSTM) は、回帰型ニューラルネットワーク (RNN) 層を構成するための要素の一つです。LSTM ユニットは、セルと入力、出力、忘却ゲートで構成され、その関数は以下のように定義されます。

\[\begin{split}f_t&&=\sigma(W_fx_t+U_fh_{t-1}+b_f) \\ i_t&&=\sigma(W_ix_t+U_ih_{t-1}+b_i) \\ o_t&&=\sigma(W_ox_t+U_oh_{t-1}+b_o) \\ c_t&&=f_t\odot c_{t-1}+i_t\odot\tanh(W_cx_t+U_ch_{t-1}+b_c) \\ h_t&&=o_t\odot\tanh(c_t).\end{split}\]

これ以降の入力や出力の説明には、以下の表記を利用します。 \(T\): シーケンスの長さ、 \(B\): バッチサイズ、 \(I\): 入力サイズ、 \(L\): 層数、 \(D\): 方向数(1もしくは2)、 \(H\): 隠れサイズ。

参照

S. Hochreiter, and J. Schmidhuber. "Long Short-Term Memory." Neural Computation. 1997.

パラメータ
  • x (Variable) -- \((T, B, I)\) の形状の入力 N-D 配列。

  • h (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • c (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • w0_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- 最初の層での重みのイニシャライザー。 形状は \((D, 4, H, I + H)\) です。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- オプション) – 二番目、それ以上の層での重みのイニシャライザー。 形状は \((L-1, D, 4, H, D * H + H)\) です。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- バイアスのイニシャライザー。形状は \((L, D, 4, H)\) です。

  • num_layers (int, optional) -- ネットワーク内のレイヤー数。 1 に設定すると、最初のレイヤーの重みのみが呼び出されます。デフォルトは 1 です。

  • dropout (float, optional) -- パラメータに適用されるドロップアウトの割合。デフォルトは 0.0 です。

  • bidirectional (bool, optional) -- Trueの場合、各層で双方向計算が実行されます。デフォルトは False です。

  • training (bool, optional) -- True の場合のみ、Backpropagation が実行されます。デフォルトは True です。

  • with_bias (bool, optional) -- バイアス項を含めるか否かを指定します。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

戻り値

\((T, B, D * H)\) の形状の出力 \(y\) ~nnabla.Variable: \((L, D, B, H)\) の形状の出力 \(h_n\) ~nnabla.Variable: \((L, D, B, H)\) の形状の出力 \(c_n\)

戻り値の型

Variable

サンプル

x = nn.Variable((seq_len, batch_size, input_size))
h = nn.Variable((num_layers, num_directions, batch_size, hidden_size))
c = nn.Variable((num_layers, num_directions, batch_size, hidden_size))
y, hn, cn = PF.lstm(x, h, c)
登録されるパラメータ

以下の変数は、パラメータスコープ "lstm" に登録されます。

  • weight_l0 (need_grad=True) : 第 0 層でのフィルターの重み (形状: (D, 4, H, I + H))

  • weight (need_grad=True) : 第 1 層以上でのフィルターの重み (形状: (L-1, D, 4, H, DH + H))

  • bias (need_grad=True) : バイアス (形状: (L, D, 4, H))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = lstm(<args>)
nnabla.parametric_functions.gru(x, h, w0_init=None, w_init=None, b_init=None, num_layers=1, dropout=0.0, bidirectional=False, training=True, rng=None, with_bias=True, fix_parameters=False, name=None)[ソース]

GRU (gated recurrent units)

GRU は、以下の通り定義されます。

\[\begin{split}r_t&&=\sigma(W_rx_t+U_rh_{t-1}+b_r) \\ z_t&&=\sigma(W_zx_t+U_zh_{t-1}+b_z) \\ n_t&&=\tanh(W_nx_t+b_{in}+r_n \odot (U_nh_{t-1}+b_{hn})) \\ h_t&&=(1-z_t) \odot n_t+z_t \odot h_{t-1}.\end{split}\]

これ以降の入力や出力の説明には、以下の表記を利用します。 \(T\): シーケンスの長さ、 \(B\): バッチサイズ、 \(I\): 入力サイズ、 \(L\): 層数、 \(D\): 方向数(1もしくは2)、 \(H\): 隠れサイズ。

参照

K. Cho et al. "Learning Phrase Representations using RNN Encoder--Decoder for Statistical Machine Translation." Empirical Methods in Natural Language Processing. 2014.

パラメータ
  • x (Variable) -- \((T, B, I)\) の形状の入力 N-D 配列。

  • h (Variable) -- \((L, D, B, H)\) の形状の入力 N-D 配列。

  • w0_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- 最初の層での重みのイニシャライザー。 形状は \((D, 3, H, I + H)\) です。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- オプション) – 二番目、それ以上の層での重みのイニシャライザー。 形状は \((L-1, D, 3, H, D * H + H)\) です。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray, optional) -- バイアスのイニシャライザー。形状は \((L, D, 4, H)\) です。

  • num_layers (int, optional) -- ネットワーク内のレイヤー数。 1 に設定すると、最初のレイヤーの重みのみが呼び出されます。デフォルトは 1 です。

  • dropout (float, optional) -- パラメータに適用されるドロップアウトの割合。デフォルトは 0.0 です。

  • bidirectional (bool, optional) -- Trueの場合、各層で双方向計算が実行されます。デフォルトは False です。

  • training (bool, optional) -- True の場合のみ、Backpropagation が実行されます。デフォルトは True です。

  • with_bias (bool, optional) -- バイアス項を含めるか否かを指定します。

戻り値

Output \(y\) with shape \((T, B, D * H)\) ~nnabla.Variable: Output \(h_n\) with shape \((L, D, B, H)\)

戻り値の型

Variable

サンプル

x = nn.Variable((seq_len, batch_size, input_size))
h = nn.Variable((num_layers, num_directions, batch_size, hidden_size))
y, hn = PF.gru(x, h)
登録されるパラメータ

以下の変数は、パラメータスコープ "gru" に登録されます。

  • weight_l0 (need_grad=True) : 第0層でのフィルターの重み (形状: (D, 3, H, I + H))

  • weight (need_grad=True) : 第1層以上でのフィルターの重み (形状: (L-1, D, 3, H, DH + H))

  • bias (need_grad=True) : バイアス (形状: (L, D, 4, H))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = gru(<args>)
nnabla.parametric_functions.embed(inp, n_inputs, n_features, initializer=None, fix_parameters=False, apply_w=None, name=None)[ソース]

Embed (埋め込み)。

Embed は、インデックス配列/テンソルを使って、配列/テンソルをスライスします。重みは、 nnabla.initializer.UniformInitializer を使って \(-\sqrt{3}\) から \(\sqrt{3}\) の範囲内に初期化されます。

パラメータ
  • x (Variable) -- \((I_0, ..., I_N)\) の形状の [整数] インデックス

  • n_inputs -- データに出現し得る入力、単語、語彙の数

  • n_features -- 埋め込む機能の数

  • fix_parameters (bool) -- True に設定すると、埋め込み重み行列は更新されません。

  • apply_w (function) -- 重みに適用されるラムダ、関数、または呼び出し可能なオブジェクト。

戻り値

\((I_0, ..., I_N, W_1, ..., W_M)\) の形状の出力

戻り値の型

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "embed" に登録されます。

  • W (need_grad=True) : 埋め込み行列 (形状: (n_inputs, n_features))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = embed(<args>)
nnabla.parametric_functions.prelu(inp, base_axis=1, shared=True, fix_parameters=False, slope_init=None, name=None)[ソース]

次のように定義されたパラメータ化された正規化線形ユニット関数。

\[y_i = \max(0, x_i) + w_i \min(0, x_i)\]

ここでは、負の傾き \(w\) が学習され、チャネル ( base_axis で指定された軸) 間で変化します。重みは \(-1\) で初期化されます。

パラメータ
  • x (Variable) -- 入力 N-D 配列

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • shared (bool) -- 共有の重み値を使用するか否か

  • fix_parameters (bool) -- True の場合、負の勾配値は更新されません。

  • slope_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 負の傾きのイニシャライザー。デフォルトでは、 0.25 で初期化されます。

戻り値

N-D 配列

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "prelu" に登録されます。

  • slope (need_grad=True) : 負の傾き(形状: 共有されている場合は tuple() それ以外は (inp.shape[base_axis],))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = prelu(<args>)
nnabla.parametric_functions.svd_affine(inp, n_outmaps, r, base_axis=1, uv_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

SVD Affine (特異値分解 Affine) は、Affine 層の低ランク近似です。ボトルネックのある 2 つの連続した Affine 層と見なすことができます。次のように計算します。

\[{\mathbf y} = {\mathbf U} {\mathbf V} {\mathbf x} + {\mathbf b}.\]

ここで、 \({\mathbf x}, {\mathbf y}\) はそれぞれ入力と出力で、 \({\mathbf U}, {\mathbf V}, {\mathbf b}\) は定数です。

重み \({\mathbf U}\)\({\mathbf V}\) は、元の重み行列 \({\mathbf W}\) の特異値分解 ( SVD ) を使って、 \({R}\) 個の支配的な特異値と対応する特異ベクトルを選択することによって近似します。したがって、低ランク \({R}\) はボトルネックのサイズとなります。

uv_init が numpy 配列の場合、 \({\mathbf U}\)\({\mathbf V}\) は、 uv_init\({\mathbf{UV}}\) で近似されるように計算されます。 uv_initNone またはイニシャライザーの場合、 \({\mathbf U}\)\({\mathbf V}\) の積はランダムな初期値を近似します。

\({\mathbf U}\)\({\mathbf V}\) がコンテキストに存在する場合、それらは uv_init よりも優先されます。

Affine の重みが \({I \times O}\) で、指定する圧縮率が \({CR}\) とすると、 \({R}\) を次のように設定できます。

\[R = \left\lfloor \frac{(1 - CR)OI}{O + I} \right\rfloor.\]
パラメータ
  • inp (Variable) -- (\(M_0 \times \ldots \times M_{B-1} \times D_B \times \ldots \times D_N\)) の形状の入力 N-D 配列。base_axis 前後の次元は、行列となるように平坦化されます。

  • n_outmaps (int or tuple) -- データごとの出力ニューロンの数。

  • r (int) -- 分解された層のランク (ボトルネックのサイズ)

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • uv_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

以下の変数がパラメータスコープ "svd_affine" に登録されます。

  • U (need_grad=True) : \({\mathbf U}\). (形状: (inmaps, r))

  • V (need_grad=True) : \({\mathbf V}\). (形状: (r, outmaps))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = svd_affine(<args>)
nnabla.parametric_functions.svd_convolution(inp, outmaps, kernel, r, pad=None, stride=None, dilation=None, uv_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

SVD convolution (特異値分解 convolution) は、convolution 層を低ランク近似します。これは、depth wise convolution に続く 1 x 1 convolution と見なすことができます。

i 番目の入力マップの平坦化されたカーネルは、それらの低ランクの近似で表されます。 i 番目のインプット \({\mathbf W_i}\) のカーネルは、特異値分解 ( SVD )を利用して、 \({R}\) 個の支配的な特異値と対応する特異ベクトルを選択することで近似されます。

\[{\mathbf W_{:,i,:}} ~ {\mathbf U_i} {\mathbf V_i}.\]

\({\mathbf U}\) は、乗数 \({R}\) を使った depthwise convolution の重さを含み、 \({\mathbf V}\) は 1 x 1 convolution の重みを含みます。

uv_init が numpy 配列の場合、 \({\mathbf U}\)\({\mathbf V}\) は、 uv_init\({\mathbf{UV}}\) で近似されるように計算されます。 uv_initNone またはイニシャライザーの場合、 \({\mathbf U}\)\({\mathbf V}\) の積はランダムな初期値を近似します。

\({\mathbf U}\)\({\mathbf V}\) がコンテキストに存在する場合、それらは uv_init よりも優先されます。

convolution のカーネルテンソルが \({O \times I \times K \times K}\) であり、指定する圧縮率が \({CR}\) であるとすると、 \({R}\) は次のように設定できます。

\[R = \left\lfloor \frac{(1 - CR)OIK^2}{I(O + K^2)} \right\rfloor.\]
パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple) -- カーネルサイズ。例えば、入力に対して3 (高さ) x 5 (幅) の 2 次元カーネルによる convlution を適用するには、( 3, 5 ) を指定します。

  • r (int) -- 分解された層のランク。

  • pad (tuple) -- 各次元に対するパディングサイズ (int) 。

  • stride (tuple) -- 各次元に対するストライドサイズ (int) 。

  • dilation (tuple) -- 各次元に対する膨張サイズ (int) 。

  • uv_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "svd_conv" に登録されます;

  • U (need_grad=True) : 分解フィルターの重み \({\mathbf U}\). (形状: (inmaps * r, *kernel))

  • V (need_grad=True) : 分解フィルターの重み \({\mathbf V}\). (形状: (outmaps, inmaps * r, 1, ...))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = svd_convolution(<args>)
nnabla.parametric_functions.cpd3_convolution(inp, outmaps, kernel, r, pad=None, stride=None, dilation=None, oik_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, max_iter=500, stopping_criterion=1e-05, lambda_reg=0.0, name=None)[ソース]

CP convolution は、convolution 層の低ランク近似です。パラメータを含む 3D テンソルは、 N-D カーネルを 1 D に折り畳むことによって構築され、そのテンソルは 3 つの行列に分解されます。分解されたレイヤーは、特徴マップ \({R}\) に対する入力特徴マップの線形結合と見なされ、その後、depthwise convolution が続き、その後に出力マップを計算するための特徴マップの線形結合が続きます。

CP 分解では、次の形式のランク 1 テンソル \({R}\) により、カーネルテンソルに近似させることができます。

\[\sum_{r=1}^{R} \lambda_r {\mathbf{o}^{(r)} \otimes \mathbf{i}^{(r)} \otimes \mathbf{k}^{(r)}},\]

ここで、 \({\lambda}_r\) は正規化係数、 \({\otimes}\) は外積です。

oik_init が numpy 配列の場合、U と V は uv_init が UV から近似できるように計算されます。 oik_init が None またはイニシャライザーの場合、 U と V の積はランダムに初期化された配列を近似します。

OI 、および K がコンテキスト内に存在する場合、それらは層の初期化に使用され、oik_init は使用されません。

Affine のカーネルテンソルが \({I \times O}\) で、指定する圧縮率が \({CR}\) であるとすると、 \({R}\) は次のように設定することができます。

\[R = \left\lfloor \frac{(1 - CR)OIK^2}{O + I + K^2} \right\rfloor.\]

参照

  • Lebedev, Vadim, Yaroslav Ganin, Maksim Rakhuba, Ivan Oseledets, and Victor Lempitsky, "Speeding-up convolutional neural networks using fine-tuned cp-decomposition.", arXiv preprint arXiv:1412.6553 (2014).

  • Marcella Astrid, Seung-Ik Lee, "CP-decomposition with Tensor Power Method for Convolutional Neural Networks Compression", BigComp 2017.

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • r (int) -- 因数分解された層のランク。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • oik_init (numpy array or nnabla.initializer.BaseInitializer) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • max_iter (int) -- ALSの最大イテレーション。

  • stopping_criterion (float) -- ALS を停止するための閾値。値が負の場合、収束チェックは無視されます。つまり、計算時間を短縮することができます。

  • lambda_reg (float) -- ALS の正則化パラメータ。 lambda_reg が大きいほど、正則化が大きくなります。

戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "cpd3_conv" に登録されます。

  • I (need_grad=True) : 分解フィルターの重み \({\mathbf I}\). (形状: (r, inmaps, 1, ...))

  • K (need_grad=True) : 分割フィルターの重み \({\mathbf K}\). (形状: (r, *kernel))

  • O (need_grad=True) : 分解フィルターの重み \({\mathbf O}\). (形状: (outmaps, r, 1, ...))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = cpd3_convolution(<args>)
nnabla.parametric_functions.binary_connect_affine(inp, n_outmaps, base_axis=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

Binary Connect Affine は、乗算なしの内積です。

Binary Connect Affine は Affine 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_i = \sum_{i} sign(w_i) x_i.\]

したがって、 \(sign(w_i)\)\(1\) または \(-1\) であり、内積は加算に単純化されます。

この関数は、Batch Normalization と併せて使用する必要があります。

参照

M. Courbariaux, Y. Bengio, and J.-P. David. "BinaryConnect: Training Deep Neural Networks with binary weights during propagations." Advances in Neural Information Processing Systems. 2015.

注釈

1 ) 複数の層で重みを共有したい場合は、バイナリ化された重み (binary_weight) ではなく、通常の浮動小数点表現での重み (weight) を共有してください。

2 ) 重みとバイナリの重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点表現の重みとバイナリの重みが同期されません。

3 ) この関数はシミュレーション専用であるため、量子化された値は binary_weight の浮動小数点数として格納されます。

パラメータ
戻り値

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "bicon_affine" に登録されます。

  • W (need_grad=True) : 浮動小数点表現での重み行列。 (形状: (inmaps, outmaps))

  • Wb (need_grad=False) : バイナリ化された重み。 (形状: (inmaps, outmaps))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = binary_connect_affine(<args>)
nnabla.parametric_functions.binary_connect_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

Binary Connect Convolution は、乗算なしの内積です。

Binary Connect Convolution は convolution 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} sign(w_{n, m, i, j}) x_{m, a + i, b + j}.\]

したがって、 \(sign(w_i)\)\(1\) または \(-1\) であり、内積は加算に単純化されます。

この関数は、BatchNormalization と共に使用する必要があります。

参照

M. Courbariaux, Y. Bengio, and J.-P. David. "BinaryConnect: Training Deep Neural Networks with binary weights during propagations." Advances in Neural Information Processing Systems. 2015.

注釈

1 ) 複数の層で重みを共有したい場合は、バイナリ化された重み (binary_weight) ではなく、通常の浮動小数点表現での重み (weight) を共有してください。

2 ) 重みとバイナリの重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点表現の重みとバイナリの重みが同期されません。

3 ) この関数はシミュレーション専用であるため、量子化された値は binary_weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • quantize_zero_to (float) -- ゼロでの入力値は、この値に量子化されます。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • wb_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイナリの重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "bicon_conv" に登録されます。

  • W (need_grad=True) : 浮動小数点表現におけるフィルターの重み。(形状: (outmaps, inmaps, *kernel))

  • Wb (need_grad=False) : バイナリ化されたフィルターの重み。(形状: (outmaps, inmaps, *kernel))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = binary_connect_convolution(<args>)
nnabla.parametric_functions.binary_weight_affine(inp, n_outmaps, base_axis=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

Binary Weight Affine は、スケールファクターを伴う乗算なしの内積です。

Binary Weight Affine は Affine 関数ですが、この関数の内積は次のとおりです。

\[y_j = \frac{1}{\|\mathbf{w}_j\|_{\ell_1}} \sum_{i} sign(w_{ji}) x_i\]

したがって、 \(sign(w_{ji})\)\(1\) または \(-1\) であり、内積計算は加算とスケールファクター \(\alpha = \frac{1}{\|\mathbf{w}_j\|_{\ell_1}}\) による乗算に単純化されます。 \(\alpha\) の数が Affine 関数の outmaps となります。

参照

Rastegari, Mohammad, et al. "XNOR-Net: ImageNet Classification Using Binary Convolutional Neural Networks." arXiv preprint arXiv:1603.05279 (2016).

注釈

1 ) 複数の層で重みを共有したい場合は、バイナリ化された重み (binary_weight) ではなく、通常の浮動小数点表現での重み (weight) を共有してください。

2 ) 重みとバイナリの重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点表現の重みとバイナリの重みが同期されません。

3 ) この関数はシミュレーション専用であるため、量子化された値は binary_weight の浮動小数点数として格納されます。

パラメータ
戻り値

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "bwn_affine" に登録されます。

  • W (need_grad=True) : 浮動小数点表現での重み行列。 (形状: (inmaps, outmaps))

  • Wb (need_grad=False) : バイナリ化された重み。 (形状: (inmaps, outmaps))

  • alpha (need_grad=False) : スケールファクター \(\alpha\) (形状: (outmaps,))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = binary_weight_affine(<args>)
nnabla.parametric_functions.binary_weight_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, quantize_zero_to=1.0, w_init=None, wb_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

Binary Weight Convolution は、スケールファクターを伴う乗算なしの内積です。

Binary Weight Convolution は、convolution 関数ですが、この関数の内積は次のとおりです。

\[y_{n, a, b} = \frac{1}{\|\mathbf{w}_n\|_{\ell_1}} \sum_{m} \sum_{i} \sum_{j} sign(w_{n, m, i, j}) x_{m, a + i, b + j}.\]

したがって、 \(sign(w_{n, m, i, j})\)\(1\) または \(-1\) であり、内積は加算とスケールファクター \(\alpha = \frac{1}{\|\mathbf{w}_n\|_{\ell_1}}\) による乗算に単純化されます。 \(n\) の数は、convolution 関数の outmaps の数です。

参照

Rastegari, Mohammad, et al. "XNOR-Net: ImageNet Classification Using Binary Convolutional Neural Networks." arXiv preprint arXiv:1603.05279 (2016).

注釈

1 ) 複数の層で重みを共有したい場合は、バイナリ化された重み (binary_weight) ではなく、通常の浮動小数点表現での重み (weight) を共有してください。

2 ) 重みとバイナリの重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点表現の重みとバイナリの重みが同期されません。

3 ) この関数はシミュレーション専用であるため、量子化された値は binary_weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • quantize_zero_to (float) -- ゼロでの入力値は、この値に量子化されます。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • wb_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイナリの重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "bwn_conv" に登録されます。

  • W (need_grad=True) : 浮動小数点表現におけるフィルターの重み。(形状: (outmaps, inmaps, *kernel))

  • Wb (need_grad=False) : バイナリ化されたフィルターの重み。(形状: (outmaps, inmaps, *kernel))

  • alpha (need_grad=False) : スケールファクター \(\alpha\) (形状: (outmaps,))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = binary_weight_convolution(<args>)
nnabla.parametric_functions.inq_affine(inp, n_outmaps, base_axis=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=- 1, w_init=None, i_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

Incremental Network Quantization Affine (増分ネットワーク量子化 Affine) 層。

学習中、重みは順次 2 の累乗の値に量子化されます。これにより、乗算のないネットワークの学習が可能になります。

inq_iterations を使用すると、学習可能な重みの半分が固定され、2 の累乗に量子化されるまでに forward パスを行う回数を指定することができます。 inq_iterations の最後の値に到達すると、すべての重みが固定されます。

詳しくは以下をご参照ください。

参照: Zhou A, Yao A, Guo Y, Xu L, Chen Y. Incremental network quantization: Towards lossless CNNs with low-precision weights. <https://arxiv.org/abs/1702.03044>

パラメータ
  • inp (Variable) -- (\(M_0 \times \ldots \times M_{B-1} \times D_B \times \ldots \times D_N\)) の形状の入力 N-D 配列。base_axis 前後の次元は、行列のように平坦化されます。

  • n_outmaps (int or tuple of int) -- データごとの出力ニューロンの数。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • quantize_zero_to (float) -- ゼロでの入力値は、この値に量子化されます。

  • num_bits (int) -- 重みごとのビット数。1 ビットは値 "0" のコーディングにすでに使用されているため、値は 1 より大きくする必要があります。

  • inq_iterations (tuple of int) -- 重みの半分を固定するイテレーション数のタプル。

  • selection_algorithm (str) -- 固定する重みを決定するために使用されるアルゴリズムを選択します。(“largest_abs” … 最大絶対値で重みを固定します。 “random” …重みをランダムに固定します。)

  • seed (int) -- Random seed for INQ algorithm

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • i_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- インジケーターのイニシャライザー (0 … 学習可能, 1 … 固定)。デフォルトでは、ゼロで初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "inq_affine" に登録されます。

  • W (need_grad=True) : 浮動小数点表現での重み行列。 (形状: (inmaps, outmaps))

  • I (need_grad=False) : 固定の重みのバイナリインジケーター行列 (形状: (inmaps, outmaps))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = inq_affine(<args>)
nnabla.parametric_functions.inq_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, num_bits=4, inq_iterations=(), selection_algorithm='random', seed=- 1, w_init=None, i_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, name=None)[ソース]

Incremental Network Quantization Convolution (増分ネットワーク量子化 Convolution) 層

学習中、重みは順次 2 の累乗の値に量子化されます。これにより、乗算のないネットワークの学習が可能になります。

inq_iterations を使用すると、学習可能な重みの半分が固定され、2 の累乗に量子化されるまでに forward パスを行う回数を指定することができます。 inq_iterations の最後の値に到達すると、すべての重みが固定されます。

詳しくは以下をご参照ください。

参照: Zhou A, Yao A, Guo Y, Xu L, Chen Y. Incremental network quantization: Towards lossless CNNs with low-precision weights. <https://arxiv.org/abs/1702.03044>

パラメータ
  • inp (Variable) -- (\(M_0 \times \ldots \times M_{B-1} \times D_B \times \ldots \times D_N\)) の形状の入力 N-D 配列。base_axis 前後の次元は、行列のように平坦化されます。

  • n_outmaps (int or tuple of int) -- データごとの出力ニューロンの数。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • num_bits (int) -- 重みごとのビット数。1 ビットは値 "0" のコーディングにすでに使用されているため、値は 1 より大きくする必要があります。

  • inq_iterations (tuple of int) -- 重みの半分を固定するイテレーション数のタプル。

  • selection_algorithm (str) -- 固定する重みを決定するために使用されるアルゴリズムを選択します。(“largest_abs” … 最大絶対値で重みを固定します。 “random” …重みをランダムに固定します。)

  • seed (int) -- Random seed for INQ algorithm

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • i_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- インジケーターのイニシャライザー (0 … 学習可能, 1 … 固定)。デフォルトでは、ゼロで初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

戻り値

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "inq_conv" に登録されます。

  • W (need_grad=True) : 浮動小数点表現におけるフィルターの重み。(形状: (outmaps, inmaps, *kernel))

  • I (need_grad=False) : 固定の重みのバイナリインジケーター行列 (形状: (outmaps, inmaps, *kernel))

  • b (need_grad=True) : バイアスベクター (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = inq_convolution(<args>)
nnabla.parametric_functions.fixed_point_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, n_w=8, delta_w=0.0625, ste_fine_grained_w=True, quantize_b=True, sign_b=True, n_b=8, delta_b=0.0625, ste_fine_grained_b=True, name=None)[ソース]

Fixed-Point Quantized Affine (固定小数点量子化 Affine)

Fixed-Point Quantized Affine は Affine 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_j = \sum_{i} Q(w_{ji}) x_i,\]

ここで \(Q(w_{ji})\) は fixed-point quantization 関数です。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- (\(M_0 \times \ldots \times M_{B-1} \times D_B \times \ldots \times D_N\)) の形状の入力 N-D 配列。base_axis 前後の次元は、行列となるように平坦化されます。

  • n_outmaps (int or tuple of int) -- データごとの出力ニューロンの数。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • quantize_w (bool) -- True の場合、重みを量子化します。

  • sign_w (bool) -- True の場合、符号付き量子化を使用します。

  • n_w (int) -- 重みに使われるビット幅。

  • delta_w (float) -- 重みの間隔サイズ。

  • ste_fine_grained_w (bool) -- True の場合、STE はfine-grainedです。

  • quantize_b (bool) -- True の場合、バイアスを量子化します。

  • n_b (int) -- バイアスに使われるビット幅

  • delta_w -- バイアスの間隔サイズ。

  • ste_fine_grained_b (bool) -- True の場合、STE はfine-grainedです。

戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "fp_quantized_affine" に登録されます。

  • W (need_grad=True) : 浮動小数点による重みの行列 (形状: (inmaps, outmaps))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み (形状: (inmaps, outmaps))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = fixed_point_quantized_affine(<args>)
nnabla.parametric_functions.fixed_point_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, channel_last=False, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, n_w=8, delta_w=0.0625, ste_fine_grained_w=True, quantize_b=True, sign_b=True, n_b=8, delta_b=0.0625, ste_fine_grained_b=True, name=None)[ソース]

Fixed-Point Quantized Convolution (固定小数点量子化 Convolution)

Fixed-Point Quantized Convolution は、convolution 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i, b + j},\]

ここで \(Q(w_{n, m, i, j})\) は fixed-point quantization 関数です。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • quantize_w (bool) -- True の場合、重みを量子化します。

  • quantize_bias (bool) -- True の場合、バイアスを量子化します。

  • sign_w (bool) -- True の場合、符号付き量子化を使用します。

  • n_w (int) -- 重みに使われるビット幅。

  • delta_w (float) -- 重みの間隔サイズ。

  • ste_fine_grained_w (bool) -- True の場合、STE はfine-grainedです。

  • quantize_b (bool) -- True の場合、バイアスを量子化します。

  • n_b (int) -- バイアスに使われるビット幅

  • delta_w -- バイアスの間隔サイズ。

  • ste_fine_grained_b (bool) -- True の場合、STE はfine-grainedです。

戻り値

N-D 配列

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "fp_quantized_conv" に登録されます。

  • W (need_grad=True) : 浮動小数点によるフィルターの重み (形状: (outmaps, inmaps // group, *kernel))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み(形状: (outmaps, inmaps // group, *kernel))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = fixed_point_quantized_convolution(<args>)
nnabla.parametric_functions.min_max_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, ql_min_w=0, ql_max_w=255, w_min_max=False, qr_min_w_init=None, qr_max_w_init=None, ste_fine_grained_w=True, quantize_b=True, ql_min_b=0, ql_max_b=255, b_min_max=False, qr_min_b_init=None, qr_max_b_init=None, ste_fine_grained_b=True, eps=0.01, name=None)[ソース]

Min-max Quantized Affine (最小最大量子化 Affine)

Min-max Quantized Affine は、Affine 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_j = \sum_{i} Q(w_{ji}) x_i,\]

ここで \(Q(w_{ji})\) は min-max quantization 関数です。

Min-max Quantized Affine では、指数移動平均は使用されません。量子化範囲の最小値と最大値は、重みとバイアスの最小値と最大値であるか、学習によって決定されます。

入力の最小値と最大値は、常に指数移動平均の代わりに使用されることに注意してください。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "min_max_quantized_affine" に登録されます。

  • W (need_grad=True) : 浮動小数点による重みの行列 (形状: (inmaps, outmaps))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み (形状: (inmaps, outmaps))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

  • qr_min (need_grad=False) : 最小量子化範囲。入力または学習可能な範囲の最小値 (形状: ql_min.shape)

  • qr_max (need_grad=False) : 最大量子化範囲。入力または学習可能な範囲の最大値 (形状: ql_max.shape)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = min_max_quantized_affine(<args>)
nnabla.parametric_functions.min_max_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, channel_last=False, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, ql_min_w=0, ql_max_w=255, w_min_max=False, qr_min_w_init=None, qr_max_w_init=None, ste_fine_grained_w=True, quantize_b=True, ql_min_b=0, ql_max_b=255, b_min_max=False, qr_min_b_init=None, qr_max_b_init=None, ste_fine_grained_b=True, eps=0.01, name=None)[ソース]

Min-max Quantized Convolution (最小最大量子化 Convolution)

Min-max Quantized Convolution は、convolution 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i, b + j},\]

ここでの \(Q(w_{n, m, i, j})\) は min-max quantization 関数です。

min_max_quantized convolution では、指数移動平均は使用されません。量子化範囲の最小値と最大値は、重みとバイアスの最小値と最大値であるか、学習によって決定されます。

入力の最小値と最大値は、常に指数移動平均の代わりに使用されることに注意してください。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • channel_last (bool) -- True の場合、最後の次元はチャネル次元になり、いわゆるNHWC 順になります。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • quantize_w (bool) -- True の場合、重みを量子化します。

  • ql_min_w (int, float, or Variable) -- 重みの最小量子化レベル。デフォルトは 0 です。

  • ql_max_w (int, float, or Variable) -- 重みの最大量子化レベル。デフォルトは 255 です。

  • w_min_max (bool) -- 量子化範囲を計算するために重みの最小値と最大値を使用します。デフォルトは False です。

  • qr_min_w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 最小量子化範囲のイニシャライザー、 qr_min 。デフォルトは、 nnabla.initializer.ConstantInitializer (-2.0)。

  • qr_max_w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for the maximum quantization range, qr_max Default is nnabla.initializer.ConstantInitializer (2.0).

  • ste_fine_grained_w (bool) -- True の場合、STE は 1 ではなく、min-max から計算された {0、1} -マスクが backward の勾配に適用されます。それ以外の場合、STE は 1 です。

  • quantize_b (bool) -- True の場合、バイアスを量子化します。

  • ql_min_b (int, float, or Variable) -- バイアスの最小量子化レベル。デフォルトは 0 です。

  • ql_max_b (int, float, or Variable) -- バイアスの最大量子化レベル。デフォルトは 255 です。

  • b_min_max (bool) -- 量子化範囲を計算するためにバイアスの最小値と最大値を使用します。デフォルトは False です。

  • qr_min_b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 最小量子化範囲のイニシャライザー、 qr_min 。 デフォルトは、 nnabla.initializer.ConstantInitializer (-6.0)。

  • qr_max_b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for the maximum quantization range, qr_max Default is nnabla.initializer.ConstantInitializer (6.0).

  • ste_fine_grained_b (bool) -- True の場合、STE は 1 ではなく、min-max から計算された {0、1} -マスクが backward の勾配に適用されます。それ以外の場合、STE は 1 です。

  • eps (float) -- イプシロン、 \(qr_{max} - qr_{min}\) が確実に重みとバイアスの両方のイプシロンより大きくなるような小さな値。

戻り値

N-D 配列

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "min_max_quantized_conv" に登録されます。

  • W (need_grad=True) : 浮動小数点によるフィルターの重み (形状: (outmaps, inmaps // group, *kernel))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み(形状: (outmaps, inmaps // group, *kernel))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

  • qr_min (need_grad=False) : 最小量子化範囲。入力または学習可能な範囲の最小値 (形状: ql_min.shape)

  • qr_max (need_grad=False) : 最大量子化範囲。入力または学習可能な範囲の最大値 (形状: ql_max.shape)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = min_max_quantized_convolution(<args>)
nnabla.parametric_functions.pow2_quantized_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, sign_w=True, with_zero_w=False, n_w=8, m_w=2, ste_fine_grained_w=True, quantize_b=True, sign_b=True, with_zero_b=False, n_b=8, m_b=2, ste_fine_grained_b=True, name=None)[ソース]

Pow2 Quantized Affine ( 2 のべき乗量子化 Affine)

Pow2 Quantized Affine は、Affine 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_j = \sum_{i} Q(w_{ji}) x_i,\]

ここで \(Q(w_{ji})\) は 2のべき乗量子化関数です。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- (\(M_0 \times \ldots \times M_{B-1} \times D_B \times \ldots \times D_N\)) の形状の入力 N-D 配列。base_axis 前後の次元は、行列となるように平坦化されます。

  • n_outmaps (int or tuple of int) -- データごとの出力ニューロンの数。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • quantize_w (bool) -- True の場合、重みを量子化します。

  • sign_w (bool) -- True の場合、符号付き量子化を使用します。

  • with_zero_w (bool) -- 量子化値としてゼロを使用することを示します。デフォルトは false です。

  • n_w (int) -- 重みに使われるビット幅。

  • m_w (int) -- 重みにおいて \(2^m\) は上限、 \(-2^m\) は下限となります。デフォルトは2です。

  • ste_fine_grained_w (bool) -- True の場合、STE はfine-grainedです。

  • quantize_b (bool) -- True の場合、バイアスを量子化します。

  • with_zero_b (bool) -- 量子化値としてゼロを使用することを示します。デフォルトは false です。

  • n_b (int) -- バイアスに使われるビット幅

  • m_b (int) -- バイアスにおいて \(2^m\) は上限、 \(-2^m\) は下限となります。デフォルトは2です。

  • ste_fine_grained_b (bool) -- True の場合、STE はfine-grainedです。

戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "pow2_quantized_affine" に登録されます。

  • W (need_grad=True) : 浮動小数点による重みの行列 (形状: (inmaps, outmaps))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み (形状: (inmaps, outmaps))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = pow2_quantized_affine(<args>)
nnabla.parametric_functions.pow2_quantized_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, quantize_w=True, with_zero_w=False, sign_w=True, n_w=8, m_w=2, ste_fine_grained_w=True, quantize_b=True, with_zero_b=False, sign_b=True, n_b=8, m_b=2, ste_fine_grained_b=True, name=None)[ソース]

Pow2 Quantized Convolution ( 2 のべき乗量子化 Convolution)

Pow2 Quantized Convolution は、convolution 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i, b + j},\]

ここで \(Q(w_{n, m, i, j})\) は2のべき乗量子化関数です。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。デフォルトでは、 nnabla.initializer.calc_uniform_lim_glorot によって決定される範囲内で nnabla.initializer.UniformInitializer で初期化されます。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。 with_biasTrue の場合、デフォルトではゼロで初期化されます。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • quantize_w (bool) -- True の場合、重みを量子化します。

  • sign_w (bool) -- True の場合、符号付き量子化を使用します。

  • n_w (int) -- 重みに使われるビット幅。

  • m_w (int) -- 重みにおいて \(2^m\) は上限、 \(-2^m\) は下限となります。デフォルトは2です。

  • ste_fine_grained_w (bool) -- True の場合、STE はfine-grainedです。

  • quantize_b (bool) -- True の場合、バイアスを量子化します。

  • sign_b (bool) -- True の場合、符号付き量子化を使用します。

  • n_b (int) -- バイアスに使われるビット幅

  • m_b (int) -- バイアスにおいて \(2^m\) は上限、 \(-2^m\) は下限となります。デフォルトは2です。

  • ste_fine_grained_b (bool) -- True の場合、STE はfine-grainedです。

戻り値

N-D 配列

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "pow2_quantized_conv" に登録されます。

  • W (need_grad=True) : 浮動小数点によるフィルターの重み (形状: (outmaps, inmaps // group, *kernel))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み(形状: (outmaps, inmaps // group, *kernel))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = pow2_quantized_convolution(<args>)
nnabla.parametric_functions.pruned_affine(inp, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True, prune_w=True, rate_w=0.9, prune_b=True, rate_b=0.9, name=None)[ソース]

Pruned Affine (枝刈りされた Affine)

Pruned Affine は、Affine 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_j = \sum_{i} Q(w_{ji}) x_i,\]

ここで \(Q(w_{ji})\) は pruning 関数、すなわち F.prune です。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- (\(M_0 \times \ldots \times M_{B-1} \times D_B \times \ldots \times D_N\)) の形状の入力 N-D 配列。base_axis 前後の次元は、行列となるように平坦化されます。

  • n_outmaps (int or tuple of int) -- データごとの出力ニューロンの数。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • prune_w (bool) -- True の場合、重みを量子化します。

  • rate_w (float) -- 重みの pruning (枝刈りする) 割合

  • prune_b (bool) -- True の場合、バイアスを量子化します。

  • rate_b (float) -- バイアスの pruning (枝刈りする) 割合

戻り値

\((B + 1)\)-D 配列。 (\(M_0 \times \ldots \times M_{B-1} \times L\))

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "pruned_affine" に登録されます。

  • W (need_grad=True) : 浮動小数点による重みの行列 (形状: (inmaps, outmaps))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み (形状: (inmaps, outmaps))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = pruned_affine(<args>)
nnabla.parametric_functions.pruned_convolution(inp, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, channel_last=False, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True, prune_w=True, rate_w=0.9, prune_b=True, rate_b=0.9, name=None)[ソース]

Pruned Convolution (枝刈りされた Convolution)

Pruned Convolution は、convolution 関数ですが、内積の定義が変更されています。この関数の入出力関係は次のとおりです。

\[y_{n, a, b} = \sum_{m} \sum_{i} \sum_{j} Q(w_{n, m, i, j}) x_{m, a + i, b + j},\]

ここで \(Q(w_{ji})\) は pruning 関数、すなわち F.prune です。

注釈

1 ) 複数の層で重みを共有する場合は、量子化された重み (quantized weight) ではなく、標準の浮動小数点の重み (weight) を共有してください。

2 ) 重みと量子化された重みは、 forward() が呼び出された後にのみ同期され、 backward() への呼び出し後では同期されません。ネットワークのパラメータにアクセスする前には、必ず forward() を 1 回呼び出してください。これを行わないと、浮動小数点の重みとバイナリの重みが同期しなくなります。

3 ) この関数はシミュレーション専用であるため、量子化された値は quantized weight の浮動小数点数として格納されます。

パラメータ
  • inp (Variable) -- N-D 配列

  • outmaps (int) -- convolution カーネルの数(出力チャネルの数)。例えば、入力に対して、16 種類のフィルターによるconvolution を適用するには、16を指定します。

  • kernel (tuple of int) -- convolution カーネルのサイズ。例えば、画像に対して、3(高さ)x 5(幅)の 2 次元カーネルによる convolution を適用するには、( 3, 5 ) を指定します。

  • pad (tuple of int) -- 各次元に対するパディングサイズ。

  • stride (tuple of int) -- 各次元に対するストライドサイズ。

  • dilation (tuple of int) -- 各次元に対する膨張サイズ。

  • group (int) -- チャネルのグループ数。これにより、マップ方向に沿って接続をグループ化することにより、チャネル間の接続がよりスパースになります。

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 重みのイニシャライザー。

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- バイアスのイニシャライザー。

  • base_axis (int) -- base_axis までの次元は、サンプル次元として扱われます。

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

  • rng (numpy.random.RandomState) -- イニシャライザーのためのランダムジェネレーター。

  • with_bias (bool) -- バイアス項を含めるか否かを指定します。

  • prune_w (bool) -- True の場合、重みを量子化します。

  • rate_w (float) -- 重みの pruning (枝刈りする) 割合

  • prune_b (bool) -- True の場合、バイアスを量子化します。

  • rate_b (float) -- バイアスの pruning (枝刈りする) 割合

戻り値

N-D 配列

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "pruned_conv" に登録されます。

  • W (need_grad=True) : 浮動小数点によるフィルターの重み (形状: (outmaps, inmaps // group, *kernel))

  • b (need_grad=True) : 浮動小数点によるバイアスベクトル (形状: (outmaps,))

  • W_q (need_grad=False) : 量子化された重み(形状: (outmaps, inmaps // group, *kernel))

  • b_q (need_grad=False) : 量子化されたバイアス (形状: (outmaps,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = pruned_convolution(<args>)
nnabla.parametric_functions.min_max_quantize(x, ql_min=0, ql_max=255, decay=0.999, x_min_max=False, ema=False, ste_fine_grained=True, eps=0.01, qr_min_init=None, qr_max_init=None, fix_parameters=False, outputs=None, name=None)[ソース]

Min-max quantization (最小最大量子化)

この関数は、最小および最大量子化レベルの範囲の値を均一に量子化します。

最小最大量子化は、次の方程式として定義されます。

\[y = round \left(\frac{\min(\max(x, m), M) - m}{scale} \right) \times scale + m,\]

ここで、 \(scale\) は次のように定義されます。

\[scale = \frac{M - m}{M_q - m_q},\]

そして

\[\begin{split}m_q = ql_{min}, \\ M_q = ql_{max}, \\ m = qr_{min}, \\ M = qr_{max}.\end{split}\]

backward パスにおいて ste_fine_grained が false として使われる時、

\[\frac{\partial q_i}{\partial x_i} = 1.\]

backward パスにおいて ste_fine_grained が True として使われる時、

\[\begin{split} \frac{\partial q_i}{\partial x_i}= \left\{ \begin{array}{ll} 0 & if \ \ \ x_i > M \\ 1 & if \ \ m \le x_i \le M \\ 0 & if \ \ x_i < m \\ \end{array} \right..\end{split}\]

\(qr_{min}\)\(qr_{max}\) は以下のように扱われます。

  • x_min_maxTrue で、 emaTrue の場合: \(min(x)\) および \(max(x)\) ごとに指数移動平均が計算され、 \(qr_{min}\) および \(qr_{max}\) に格納されます。

  • x_min_maxTrue で、 emaFalse の場合: \(min(x)\)\(max(x)\) が計算され、 \(qr_{min}\)\(qr_{max}\) に格納されます。

  • x_min_maxFalse で、 emaTrue の場合: \(qr_{min}\)\(qr_{max}\) に格納されている指数移動平均が使用されます。

  • x_min_maxFalse で、 emaFalse の場合: \(qr_{min}\)\(qr_{max}\) の勾配は、backward パスで計算されます。

より正確には、min-max quantization の推論では、実際の値 0 に対応する ゼロ点 ( zp ) を考慮する必要があり、そのデータ型は整数です。 ゼロポイント は次のように定義されます

\[\begin{split} && zp_f = ql_{min} -\frac{qr_{min}}{scale}, \\ && zp = \left\{ \begin{array}{ll} ql_{max} & if \ \ \ zp_f >= ql_{max} \\ round(zp_f) & if \ \ otherwise \\ ql_{min} & if \ \ zp_f <= ql_{min} \\ \end{array} \right..\end{split}\]

したがって、 ゼロ点 の量子化効果をシミュレートするために、forward パスと backward パスの両方で、 \(qr_{min}\)\(qr_{max}\) は次のように調整されます。

\[\begin{split}qr_{min}^{adj} = ql_{min} - zp * scale, \\ qr_{max}^{adj} = ql_{max} - zp * scale.\end{split}\]

これらの操作は nudge と呼ばれます。

最後に、min-max quantization の式では、 \(m\)\(M\) はそれぞれ \(qr_{min}^{adj}\)\(qr_{max}^{adj}\) に置き換えられます。

パラメータ
  • x (Variable) -- 入力 N-D 配列。

  • ql_min (int, float, or Variable) -- 最小量子化レベル。デフォルトは 0 です。

  • ql_max (int, float, or Variable) -- 最大量子化レベル。デフォルトは 255 です。

  • decay (float) -- 指数移動平均の減衰率。

  • x_min_max (bool) -- 量子化範囲を計算するために、 x の最小値と最大値を使用します。デフォルトは False です。

  • ema (bool) -- 最小および最大量子化範囲に指数移動平均を使用します。デフォルトは False です。

  • ste_fine_grained (bool) -- True の場合、STE は 1 ではなく、min-max から計算された {0、1} -マスクが backward の勾配に適用されます。それ以外の場合、STE は 1 です。

  • eps (float) -- イプシロン、 \(qr_{max} - qr_{min}\) が確実に重みとバイアスの両方のイプシロンより大きくなるような小さな値。

  • qr_min_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- 最小量子化範囲のイニシャライザー、 qr_min 。 デフォルトは、 nnabla.initializer.ConstantInitializer (-6.0)。

  • qr_max_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for the maximum quantization range, qr_max Default is nnabla.initializer.ConstantInitializer (6.0).

  • fix_parameters (bool) -- True の場合, 重みとバイアスは更新されません。

参照

Benoit Jacob, Skirmantas Kligys, Bo Chen, Menglong Zhu, Matthew Tang, Andrew Howard, Hartwig Adam, and Dmitry Kalenichenko, "Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference", https://arxiv.org/abs/1712.05877

登録されるパラメータ

次の変数は、パラメータスコープ "min_max_quantize" に登録されます。

  • qr_min (need_grad=False) : 最小量子化範囲、 ema が True の場合、-6.0 で初期化された入力の最小値の指数移動平均 (形状: ql_min.shape)

  • qr_max (need_grad=False) : 最大量子化範囲、 ema が True の場合に 6.0 で初期化された入力の最大値の指数移動平均。(形状: ql_max.shape)

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = min_max_quantize(<args>)
nnabla.parametric_functions.lstm_cell(x, h, c, state_size, w_init=None, b_init=None, fix_parameters=False, name=None)[ソース]

Long Short-Term Memory (長・短期記憶)

Long Short-Term Memory (LSTM) は、回帰型ニューラルネットワーク (RNN) 層を構成するための要素の一つです。LSTM ユニットは、セルと入力、出力、忘却ゲートで構成され、その関数は以下のように定義されます。

\[\begin{split}f_t&&=\sigma(W_fx_t+U_fh_{t-1}+b_f) \\ i_t&&=\sigma(W_ix_t+U_ih_{t-1}+b_i) \\ o_t&&=\sigma(W_ox_t+U_oh_{t-1}+b_o) \\ c_t&&=f_t\odot c_{t-1}+i_t\odot\tanh(W_cx_t+U_ch_{t-1}+b_c) \\ h_t&&=o_t\odot\tanh(c_t).\end{split}\]

参照

S. Hochreiter, and J. Schmidhuber. "Long Short-Term Memory." Neural Computation. 1997.

パラメータ
戻り値

Variable

登録されるパラメータ

以下の変数は、パラメータスコープ "lstm" に登録されます。

  • affine/W (need_grad=True) : LSTM ブロックの重み行列(形状: (inmaps, 4, state_size))

  • affine/b (need_grad=True) : LSTM ブロックのバイアスベクトル(形状: (4, state_size,))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = lstm_cell(<args>)
class nnabla.parametric_functions.LSTMCell(batch_size, state_size, h=None, c=None, name=None)[ソース]
__call__(x, w_init, b_init, fix_parameters)[ソース]

lstm 関数を呼び出して h と c を更新します。

パラメータ
nnabla.parametric_functions.spectral_norm(w, dim=0, itr=1, eps=1e-12, test=False, u_init=None, fix_parameters=True, name=None)[ソース]

Spectral Normalization (スペクトル正規化)

\[W_{sn} = \frac{W}{\sigma(W)}.\]

ここで、 \(W\) は入力の行列であり、 \(\sigma(W)\)\(W\) のスペクトルノルムです。スペクトルノルムは、パワーイテレーションによって近似的に計算されます。

参照

Takeru Miyato, Toshiki Kataoka, Masanori Koyama, Yuichi Yoshida, "Spectral Normalization for Generative Adversarial Networks", International Conference on Learning Representations. 2018.

パラメータ
  • W (Variable) -- 形状の入力 N-D 配列。これは通常ネットワークのパラメータです。

  • dim (int) -- 出力次元。デフォルトは 0 です。次元が 0 でない場合、指定された次元は転置によって左端の次元になります。

  • itr (int) -- イテレーション回数。デフォルトは 1 です。

  • eps (float) -- 正規化の際に用いられるイプシロン。デフォルトは 1e-12 です。

  • test (bool) -- テストモードを使用します。デフォルトは False です。

戻り値

\(W\) と同じ形状のスペクトル正規化された \(W_{sn}\)

戻り値の型

Variable

サンプル

import nnabla as nn
import nnabla.parametric_functions as PF

b, c, h, w = 4, 64, 32, 32

# Spectrally normalized convolution
apply_w = lambda w: PF.spectral_norm(w, dim=0)
h = nn.Variable.from_numpy_array(np.random.randn(b, c, h, w))
h = PF.convolution(h, with_bias=False, apply_w=apply_w)

# Spectrally normalized affine
apply_w = lambda w: PF.spectral_norm(w, dim=1)
h = nn.Variable.from_numpy_array(np.random.randn(b, c))
h = PF.affine(h, with_bias=False, apply_w=apply_w)

# Spectrally normalized embed
apply_w = lambda w: PF.spectral_norm(w, dim=1)
h = nn.Variable.from_numpy_array(np.random.randn(b, c))
h = PF.embed(h, c, apply_w=apply_w)
登録されるパラメータ

次の変数は、パラメータスコープ "spectral-norm" に登録されています。

  • u (need_grad=False) : 特異ベクトル (形状: (w.shape[dim], ))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = spectral_norm(<args>)
nnabla.parametric_functions.weight_normalization(w, dim=0, eps=1e-12, g_init=None, fix_parameters=False, name=None)[ソース]

Weight Normalization

\[\mathbf{w}_{WN} = g \dfrac{\mathbf{w}}{\|\mathbf{w}\|}\]

where \(\mathbf{w}\) is the input weights to be normalized, and \(g\) is learnable multiplication factors each of which is applied to each input weights at dim. This function is in general used as callback passed to apply_w for PF.convolution, PF.affine and so on. According to the author`s original implementation, \(v\) should be initialized by \(N(0, 0.05)\). To meet this condition, initializer should be passed to convolution which Weight Normalization is applied, like an example below.

参照

パラメータ
  • W (Variable) -- 形状の入力 N-D 配列。これは通常ネットワークのパラメータです。

  • dim (int) -- 出力次元。デフォルトは 0 です。次元が 0 でない場合、指定された次元は転置によって左端の次元になります。

  • eps (float) -- 正規化の際に用いられるイプシロン。デフォルトは 1e-12 です。

  • g_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for the scale. By default, L2-norm of weights corresponding to dim are used.

戻り値

\(W\) with the same shape as \(v\).

戻り値の型

Variable

サンプル

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

# h is nn.Variable.

# convolution
# according to the original implementation, w should be initialized by N(0, 0.05).
h = PF.convolution(h, ..., apply_w=PF.weight_normalization, w_init=I.NormalInitializer(0.05))

# affine
h = PF.affine(h, ..., apply_w=lambda w: PF.weight_normalization(w, dim=1), w_init=I.NormalInitializer(0.05))

警告

Up to the version 1.10.0, this had been implemented as the composite functions.

登録されるパラメータ

次の変数は、パラメータスコープ "wn" に登録されます。

  • g (need_grad=True) : Weight Normalization 適応スケールスカラー。 (形状: w.shape[dim])

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = weight_normalization(<args>)
nnabla.parametric_functions.multi_head_attention(query, key, value, num_heads=12, dropout=0.0, k_embed_dim=None, v_embed_dim=None, out_dim=None, rng=None, with_bias=True, add_attn_bias=False, additive_mask=None, key_padding_mask=None, fix_parameters=False, param_init=None, name=None)[ソース]

MultiHeadAttention

Computes multi-headed attention with query, key, and value. We use the following notations to describe the inputs and outputs below. \(L_T\): target sequence length, \(L_S\): source sequence length, \(B\): batch size, \(D\): input dimension, \(E\): embedding dimension.

参照

A. Vaswani et al. "Attention is All You Need." NIPS. 2017. <https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf>

例:

q = nn.Variable((tgt_len, batch_size, q_input_dim))
k = nn.Variable((src_len, batch_size, k_input_dim))
v = nn.Variable((src_len, batch_size, v_input_dim))

out, w = PF.multi_head_attention(q, k, v)
out.forward()
パラメータ
  • query (Variable) -- Input N-D array with shape \((L_T, B, D_q)\).

  • key (Variable) -- Input N-D array with shape \((L_S, B, D_k)\).

  • value (Variable) -- Input N-D array with shape \((L_S, B, D_v)\).

  • num_heads (int, optional) -- attention head の数。次元 E の埋め込みは、head の数で割り切れる必要があることに注意してください。デフォルトはよく用いられる12です。

  • dropout (float, optional) -- パラメータに適用されるドロップアウト比。デフォルトは 0 です。

  • k_embed_dim (int, optional) -- Embedding dimension for key. If specified, embedding dimensions for both query and key are set as that value. Otherwise, k_embed_dim is set as the same alue as embedding dimension for query.

  • v_embed_dim (int, optional) -- Embedding dimension for value. If not specified, it is defaulted as the same value as embedding dimension for query.

  • out_dim (int, optional) -- Embedding dimension for output weight. If not spefied, it is defaulted as the same value as embedding dimension for value.

  • rng (numpy.random.RandomState, optional) -- イニシャライザーのランダムジェネレーター。デフォルトは None です。

  • with_bias (bool, optional) -- バイアス項を含めるか否かを指定します。 デフォルトは True です。

  • add_attn_bias (bool, optional) -- キーと値に attention バイアスパラメータを追加するか否かを指定します。デフォルトは False です。

  • additive_mask (Variable, optional) -- \((L_T, L_S)\) の形状の入力 N-D 配列。 特定の位置への attention を防ぐために、attention 層に値が追加されます。

  • key_padding_mask (Variable, optional) -- \((B, L_S)\) の形状の入力 N-D 配列。指定されたパディング要素は attention 層によって無視されます。値は 1 または 0 である必要があります。

  • fix_parameters (bool, optional) -- True に設定すると、重みとバイアスは更新されません。デフォルトは False です。

  • param_init (dict, optional) -- パラメータイニシャライザーは dict で設定できます。dict の設定可能なキーには、q_weight、k_weight、v_weight、q_bias、k_bias、v_bias、out_weight、out_bias、attn_bias_k、attn_bias_v があります。dict の値は、 Initializer または numpy.ndarray である必要がります。例 {'q_bias': ConstantInitializer(0)}

戻り値

\((L_T, B, E)\) の形状をもつ出力 \(y\) ~nnabla.Variable: \((B, L_T, L_S)\) の形状をもつ出力 \(h_n\)

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "multi_head_attention" に登録されます。

  • q_weight (need_grad=True) : クエリの重み (形状: (E, E))

  • k_weight (need_grad=True) : キーの重み (形状: (E_k, E))

  • v_weight (need_grad=True) : 値の重み (形状: (E_v, E))

  • out_weight (need_grad=True) : 射影の重み (形状: (E, E))

  • q_bias (need_grad=True) : クエリのバイアス (形状: (E, ))

  • k_bias (need_grad=True) : キーのバイアス (形状: (E, ))

  • v_bias (need_grad=True) : 値のバイアス (形状: (E, ))

  • out_bias (need_grad=True) : 射影のバイアス (形状: (E, ))

  • attn_bias_k (need_grad=True) : k のattention バイアス (形状: (E, 1))

  • attn_bias_v (need_grad=True) : v の attention バイアス (形状: (E, 1))

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = multi_head_attention(<args>)
nnabla.parametric_functions.transformer(src, tgt, embed_dim=512, num_heads=8, num_encoder_layers=6, num_decoder_layers=6, dim_feedforward=2048, dropout=0.1, activation=None, src_additive_mask=None, tgt_additive_mask=None, memory_additive_mask=None, src_key_padding_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None, rng=None, add_attn_bias=False, fix_parameters=False, name=None)[ソース]

Transformer (トランスフォーマー)

以下では入力と出力を説明するために、次の表記を使用します。 \(L_T\) :ターゲットシーケンスの長さ、 \(L_S\) :ソースシーケンスの長さ、 \(B\) :バッチサイズ、 \(E\) :埋め込み次元。

参照

A. Vaswani et al. "Attention is All You Need." NIPS. 2017. <https://papers.nips.cc/paper/7181-attention-is-all-you-need.pdf>

例:

src = nn.Variable((src_len, batch_size, embed_dim),need_grad=True)
tgt = nn.Variable((tgt_len, batch_size, embed_dim),need_grad=True)
out = PF.transformer(src, tgt, num_heads=16, num_encoder_layers=12)
out.forward()
パラメータ
  • src (Variable) -- \((L_S, B, E)\) の形状のエンコーダーへの入力ソースシーケンス。

  • tgt (Variable) -- \((L_T, B, E)\) の形状のデコーダーへの入力ターゲットシーケンス。

  • embed_dim (int, optional) -- 使用する埋め込み次元。デフォルトは 512 です。

  • num_heads (int, optional) -- attention head の数。デフォルトは 12 です。

  • num_encoder_layers (int, optional) -- 使用するエンコーダー層数。デフォルトは 6 です。

  • num_decoder_layers (int, optional) -- 使用するデコーダー層数。デフォルトは 6 です。

  • dim_feedforward (int, optional) -- feedforward ネットワークモデルの次元。デフォルトは 2048 です。

  • dropout (float, optional) -- 適用されるドロップアウト率。デフォルトは 0.1 です。

  • activation (function, optional) -- 使用する非線形活性化関数。デフォルトは None で、その場合F.relu が使用されます。

  • src_additive_mask (Variable, optional) -- src シーケンスの追加マスク (オプション). \((L_S, L_S)\)

  • tgt_additive_mask (Variable, optional) -- Additive mask for the tgt sequence (optional). \((L_T, L_T)\).

  • memory_additive_mask (Variable, optional) -- エンコーダー出力の追加マスク (オプション). \((L_T, L_S)\)

  • src_key_padding_mask (Variable, optional) -- Key padding mask for src keys per batch (optional). \((B, L_S)\). Specified padding elements will be ignored by the attention layer. Values must be either 1 or 0.

  • tgt_key_padding_mask (Variable, optional) -- Key padding mask for tgt keys per batch (optional). \((B, L_T)\). Specified padding elements will be ignored by the attention layer. Values must be either 1 or 0.

  • memory_key_padding_mask (Variable, optional) -- Key padding mask for memory keys per batch (optional). \((B, L_S)\). Specified padding elements will be ignored by the attention layer. Values must be either 1 or 0.

  • rng (numpy.random.RandomState, optional) -- イニシャライザーのランダムジェネレーター。デフォルトは None です。

  • add_attn_bias (bool, optional) -- キーと値に attention バイアスパラメータを追加するか否かを指定します。デフォルトは False です。

  • fix_parameters (bool, optional) -- True に設定すると、重みとバイアスは更新されません。デフォルトは False です。

戻り値

形状 \((L_T, B, E)\) の出力 \(y\)

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "transformer" に登録されます。

  • encoder{layer#} (need_grad=True) : n 番目のエンコーダー層のパラメータ (形状: Refer to transformer_encode for details)

  • decoder{layer#} (need_grad=True) : n 番目のデコーダー層のパラメータ (形状: 詳細については transformer_decodeを参照してください )

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = transformer(<args>)
nnabla.parametric_functions.transformer_encode(src, embed_dim, num_heads, dim_feedforward=2048, dropout=0.1, activation=None, src_additive_mask=None, src_key_padding_mask=None, rng=None, add_attn_bias=False, fix_parameters=False, name=None)[ソース]

Transformer Encoder (トランスフォーマーエンコーダー)

パラメータ
  • src (Variable) -- \((L_S, B, E)\) の形状のエンコーダー層への入力シーケンス。

  • embed_dim (int) -- 埋め込み次元の数。

  • num_heads (int) -- attention head の数。

  • dim_feedforward (int, optional) -- feedforward ネットワークモデルの次元。デフォルトは 2048 です。

  • dropout (float, optional) -- ドロップアウト率。デフォルトは 0.1 です。

  • activation (function, optional) -- 使用する非線形活性化関数。デフォルトは None で、その場合F.relu が使用されます。

  • src_additive_mask (Variable, optional) -- 形状 \((L_S, L_S)\) のソースシーケンスの追加マスク

  • src_key_padding_mask (Variable, optional) -- \((B, L_S)\) の形状のソースシーケンスのパディングマスク 。指定されたパディング要素は attention 層によって無視されます。値は 1 または 0 である必要があります。

  • rng (numpy.random.RandomState, optional) -- イニシャライザーのランダムジェネレーター。デフォルトは None です。

  • add_attn_bias (bool, optional) -- キーと値に attention バイアスパラメータを追加するか否かを指定します。デフォルトは False です。

  • fix_parameters (bool, optional) -- True に設定すると、重みとバイアスは更新されません。デフォルトは False です。

戻り値

形状 \((L_S, B, E)\) の出力 \(y\)

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "transformer_encode" に登録されます。

  • src_self_attn (need_grad=True) : ソースシーケンスの self-attention パラメータ(形状: 詳細については multi_head_attention を参照してください )

  • enc_affine1 (need_grad=True) : エンコーダーで使用される最初の Affine (形状: 詳細については affine を参照してください )

  • enc_affine2 (need_grad=True) : エンコーダーで使用される 2 番目の Affine (形状: 詳細については affine を参照してください )

  • enc_layer_norm1 (need_grad=True) : エンコーダーで使用される最初の layer normalization (形状: 詳細については layer_normalization を参照してください )

  • enc_layer_norm2 (need_grad=True) : エンコーダーで使用される 2 番目の layer normalization (形状: 詳細については layer_normalization を参照してください )

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = transformer_encode(<args>)
nnabla.parametric_functions.transformer_decode(tgt, memory, embed_dim, num_heads, dim_feedforward=2048, dropout=0.1, activation=None, tgt_additive_mask=None, memory_additive_mask=None, tgt_key_padding_mask=None, memory_key_padding_mask=None, rng=None, add_attn_bias=False, fix_parameters=False, name=None)[ソース]

Transformer Decoder (トランスフォーマーデコーダー)

パラメータ
  • tgt (Variable) -- \((L_T, B, E)\) の形状のデコーダー層への入力シーケンス。

  • memory (Variable) -- \((L_T, B, E)\) の形状のエンコーダーの最後の層からの出力シーケンス。

  • embed_dim (int) -- 埋め込み次元の数。

  • num_heads (int) -- attention head の数。

  • dim_feedforward (int, optional) -- feedforward ネットワークモデルの次元。デフォルトは 2048 です。

  • dropout (float, optional) -- ドロップアウト率。デフォルトは 0.1 です。

  • activation (function, optional) -- 使用する非線形活性化関数。デフォルトは None で、その場合F.relu が使用されます。

  • tgt_additive_mask (Variable, optional) -- \((L_T, L_T)\) の形状のターゲットシーケンスの追加マスク。

  • memory_additive_mask (Variable, optional) -- \((L_T, L_S)\) の形状のメモリシーケンスの追加マスク。

  • tgt_key_padding_mask (Variable, optional) -- \((B, L_T)\) の形状のターゲットシーケンスのパディングマスク。指定されたパディング要素は、attention 層によって無視されます。値は 1 または 0 である必要があります。

  • memory_key_padding_mask (Variable, optional) -- \((B, L_S)\) の形状のマスクシーケンスのパディングマスク。指定されたパディング要素は、attention 層によって無視されます。値は 1 または 0 である必要があります。

  • rng (numpy.random.RandomState) -- イニシャライザーのランダムジェネレーター。デフォルトは None です。

  • add_attn_bias (bool, optional) -- キーと値に attention バイアスパラメータを追加するか否かを指定します。デフォルトは False です。

  • fix_parameters (bool) -- True に設定すると、重みとバイアスは更新されません。デフォルトは False です。

戻り値

形状 \((L_T, B, E)\) の出力 \(y\)

戻り値の型

Variable

登録されるパラメータ

次の変数は、パラメータスコープ "transformer_decode" に登録されます。

  • tgt_self_attn (need_grad=True) : ターゲットシーケンスの self-attention パラメータ(形状: 詳細については  multi_head_attention を参照してください )

  • tgt_memory_attn (need_grad=True) : エンコーダーからの出力をキーとするターゲットシーケンスの attention パラメータ (形状: 詳細については multi_head_attention for details を参照してください)

  • dec_affine1 (need_grad=True) : デコーダーで使用される最初の Affine (形状: 詳細については affine を参照してください )

  • dec_affine2 (need_grad=True) : デコーダーで使用される 2 番目の Affine (形状: 詳細については affine を参照してください )

  • dec_layer_norm1 (need_grad=True) : デコーダーで使用される最初の layer normalization (形状: 詳細については layer_normalization を参照してください )

  • dec_layer_norm2 (need_grad=True) : デコーダーで使用される 2 番目の layer normalization (形状: 詳細については layer_normalization を参照してください )

  • dec_layer_norm3 (need_grad=True) : デコーダーで使用される 3 番目の layer normalization (形状: 詳細については layer_normalization を参照してください )

注釈

name オプションが渡された場合、パラメータは特定の名前でパラメータスコープ内にラップされ、以下のコードと同じ結果となります。これは、コードの簡素化に利用できます。

with parameter_scope(name):
    output = transformer_decode(<args>)
パラメータイニシャライザー

一部のパラメトリック関数は、オプションで以下のパラメータイニシャライザーを使用することができます。

class nnabla.initializer.BaseInitializer[ソース]

パラメータイニシャライザーのベースクラス

__call__(shape)[ソース]

イニシャライザーで配列を生成します。

パラメータ

shape (tuple of int) -- 生成された形状の numpy.ndarray

戻り値

配列

戻り値の型

numpy.ndarray

注釈

BaseInitializer のサブクラスはこのメソッドをオーバーライドする必要があります。

class nnabla.initializer.ConstantInitializer(value=0)[ソース]

ベースクラス: nnabla.initializer.BaseInitializer

定数値で構成される配列を生成します。

パラメータ

value (float) -- 定数値。

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
w = I.ConstantInitializer(0.1)
b = I.ConstantInitializer() # this generates constant valued array of default value 0
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv'
class nnabla.initializer.NormalInitializer(sigma=1.0, rng=None)[ソース]

ベースクラス: nnabla.initializer.BaseInitializer

指定された正規分布からランダム配列を生成します。

\[\mathbf x \sim {\cal N} (\mathbf 0 | \sigma^2 \mathbf I)\]
パラメータ

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
w = I.NormalInitializer(5e-5)
b = I.NormalInitializer(0.0)
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')
class nnabla.initializer.UniformInitializer(lim=(- 1, 1), rng=None)[ソース]

ベースクラス: nnabla.initializer.BaseInitializer

指定された均一分布からランダム配列を生成します。

\[\mathbf x \sim {\cal U} (a, b)\]
パラメータ

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
w = I.UniformInitializer() # this generates uniform distribution within the default range of (-1,1)
b = I.UniformInitializer((-0.5,0.5))
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')
class nnabla.initializer.UniformIntInitializer(lim=(0, 10), rng=None)[ソース]

ベースクラス: nnabla.initializer.BaseInitializer

指定された整数均一分布からランダム配列を生成します。

\[\mathbf x \sim {\cal U} ([a, b))\]
パラメータ

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
w = I.UniformIntInitializer() # this generates uniform integer distribution within the default range of (0,10)
b = I.UniformIntInitializer((-1,1))
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')
class nnabla.initializer.RangeInitializer(start=0, step=1)[ソース]

ベースクラス: nnabla.initializer.BaseInitializer

数値のシーケンスをもつ配列を生成します。

\[\mathbf x[i] = start + step * i\]
パラメータ
  • start (int) -- 最初の値。

  • step (int) -- 間隔の値。

例:

import nnabla as nn
import nnabla.initializer as I

x = nn.Variable([100])
x.d = I.RangeInitializer(0, 1)(x.shape)
class nnabla.initializer.OrthogonalInitializer(gain=1.0, rng=None)[ソース]

ベースクラス: nnabla.initializer.BaseInitializer

Saxe らによって提案された直交行列の重みを生成します。

パラメータ
  • gain (float) -- 単位タイプに応じて決定する必要があるスケーリングファクター。

  • rng (numpy.random.RandomState) -- 乱数ジェネレーター。

例:

import numpy as np
import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
w = I.OrthogonalInitializer(np.sqrt(2.0))
b = I.ConstantInitializer(0.0)
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')

参照

class nnabla.initializer.WeightNormalizationScaleInitializer(w, dim=0, eps=1e-12)[ソース]

ベースクラス: nnabla.initializer.BaseInitializer

Compute the L2-norm for each weight kernel.

This initializer is specific to the weight normalization scale to keep the same magnitude of the originally initialized weights even after the applicaiton of the weight normalization at only initialization.

パラメータ
  • w (Variable) -- Weight the weight normalization is applied.

  • dim (int) -- Output dimension of the weight normalization.

  • eps (float) -- Eplision of the weight normalization.

nnabla.initializer.calc_normal_std_he_forward(inmaps, outmaps, kernel=(1, 1))[ソース]

He らによって提案された標準偏差を計算します。

\[\sigma = \sqrt{\frac{2}{NK}}\]
パラメータ
  • inmaps (int) -- 入力Variableのマップサイズ、 \(N\) .

  • outmaps (int) -- 入力Variableのマップサイズ, \(M\) .

  • kernel (tuple of int) -- convolution カーネルの空間形状。上記の定義では、 \(K\) は形状次元の積です。Affine では、デフォルト値を使用する必要があります。

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
s = I.calc_normal_std_he_forward(x.shape[1],64)
w = I.NormalInitializer(s)
b = I.ConstantInitializer(0)
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')

参照

nnabla.initializer.calc_normal_std_he_backward(inmaps, outmaps, kernel=(1, 1))[ソース]

He らにより提案された標準偏差を計算します (backward の場合)。

\[\sigma = \sqrt{\frac{2}{MK}}\]
パラメータ
  • inmaps (int) -- 入力Variableのマップサイズ、 \(N\) .

  • outmaps (int) -- 入力Variableのマップサイズ, \(M\) .

  • kernel (tuple of int) -- convolution カーネルの空間形状。上記の定義では、 \(K\) は形状次元の積です。Affine では、デフォルト値を使用する必要があります。

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
s = I.calc_normal_std_he_backward(x.shape[1],64)
w = I.NormalInitializer(s)
b = I.ConstantInitializer(0)
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')

参照

nnabla.initializer.calc_normal_std_glorot(inmaps, outmaps, kernel=(1, 1))[ソース]

Glorot らによって提案された標準偏差を計算します。

注釈

v.1.2 から以下のように定義を更新しました。デフォルトの初期化を用いている既存のスクリプトの動作に影響を与える可能性があります。

\[\sigma = \sqrt{\frac{2}{K(N + M)}}\]
パラメータ
  • inmaps (int) -- 入力Variableのマップサイズ、 \(N\) .

  • outmaps (int) -- 入力Variableのマップサイズ, \(M\) .

  • kernel (tuple of int) -- convolution カーネルの空間形状。上記の定義では、 \(K\) は形状次元の積です。Affine では、デフォルト値を使用する必要があります。

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
s = I.calc_normal_std_glorot(x.shape[1],64)
w = I.NormalInitializer(s)
b = I.ConstantInitializer(0)
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')

参照

nnabla.initializer.calc_uniform_lim_glorot(inmaps, outmaps, kernel=(1, 1))[ソース]

Glorot らによって提案された均一分布の下限と上限を計算します。

注釈

v.1.3 から以下のように定義を更新しました。デフォルトの初期化を用いている既存のスクリプトの動作に影響を与える可能性があります。

\[\begin{split}b &= \sqrt{\frac{6}{K(N + M)}}\\ a &= -b\end{split}\]
パラメータ
  • inmaps (int) -- 入力Variableのマップサイズ、 \(N\) .

  • outmaps (int) -- 入力Variableのマップサイズ, \(M\) .

  • kernel (tuple of int) -- convolution カーネルの空間形状。上記の定義では、 \(K\) は形状次元の積です。Affine では、デフォルト値を使用する必要があります。

例:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.initializer as I

x = nn.Variable([60,1,28,28])
lb,ub= I.calc_uniform_lim_glorot(x.shape[1],64)
w = I.UniformInitializer((lb,ub))
b = I.ConstantInitializer(0)
h = PF.convolution(x, 64, [3, 3], w_init=w, b_init=b, pad=[1, 1], name='conv')

参照

Grad

nnabla.grad.grad(outputs, inputs, grad_outputs=None, persistent_outputs=[], bind_grad_output=False)[ソース]

入力に対する出力の勾配関数。

grad 関数は入力に対する出力の勾配の和を計算します。

\[g_i = \sum_{j} {\frac{\partial y_j}{\partial x_i}},\]

\(y_j\) は各出力、 \(x_i\) は各入力、 \(g_i\)\(j\) 全体の \(x_i\) に対する \(y_j\) の勾配の和です。

パラメータ
  • outputs (list of Variable or Variable) -- 微分可能な関数の出力。

  • inputs (list of Variable or Variable) -- 計算される出力の勾配に対応する入力。

  • grad_outputs (None, scalar, numpy.ndarray, nnabla.NdArray, or list of scalar, numpy.ndarray, or nnabla.NdArray,) -- Gradient outputs corresponding to outputs. This is same as the grad argument of backward(). Default is None, so 1 is used as the in-coming gradient at the very beginning of the Variable in the gradient graph.

  • persistent_outputs (list of bool) -- 出力の persistent フラグを指定します。指定がない場合は、すべての出力は persistent になります。

  • bind_grad_output (bool) -- Bind data to grad of input variable. This is useful for the case where one wants to use the gradient graph for training a neural network using the first-order gradients only. Default is False.

戻り値

Variable のリスト。

If the backpropagation does not reach input(s), the corresponding returned value(s) are zero (i.e., the gradients w.r.t. inputs are zero) and not connected as a part of the gradient graph.

Example (Gradient Penalty):

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import numpy as np
from nnabla.ext_utils import get_extension_context

# Context
extension_module = "cudnn"
ctx = get_extension_context(extension_module)
nn.set_default_context(ctx)

# Input and label
x = nn.Variable.from_numpy_array(np.random.randn(4, 3, 32, 32))
y = nn.Variable.from_numpy_array(np.random.randint(0, 10, 4).reshape(4, 1))

# Network
h = PF.convolution(x, 8, (3, 3), (1, 1), name="conv1")
h = F.relu(h)
h = F.max_pooling(h, (2, 2))
h = PF.convolution(h, 16, (3, 3), (1, 1), name="conv2")
h = F.relu(h)
h = F.max_pooling(h, (2, 2))
p = PF.affine(h, 10, name="pred")
loss = F.mean(F.softmax_cross_entropy(p, y))

# Grad
outputs = [loss]
inputs = nn.get_parameters().values()
grads = nn.grad(outputs, inputs)  # gradients of the parameters

# Backward of the outputs w.r.t. the parameters by constraining the gradient norms.
t = 0 # or 1
gp = sum([(F.sum(g ** 2) ** 0.5 - t) ** 2 for g in grads])
loss += gp
loss.forward()
loss.backward()

Example (Higer-order Gradients):

import nnabla as nn
import nnabla.functions as F
import numpy as np

x = nn.Variable.from_numpy_array(np.random.randn(2, 2)).apply(need_grad=True)
x.grad.zero()
y = F.sin(x)
def grad(y, x, n=1):
    dx = [y]
    for _ in range(n):
        dx = nn.grad([dx[0]], [x])
    return dx[0]
dnx = grad(y, x, n=10)
dnx.forward()
print(np.allclose(-np.sin(x.d), dnx.d))
dnx.backward()
print(np.allclose(-np.cos(x.d), x.g))

# Show the supported status for each function
from nnabla.backward_functions import show_registry
show_registry()
nnabla.backward_functions.register(func_name, func)[ソース]

Register the backward function to a function.

パラメータ
  • func_name (str) -- The function class name, for example, Affine.

  • func (function) -- The function to be called as the backward function to the function func_name.. Arguments of the func must be (ctx: nn.Context, inputs: list of nn.Variable, **kwargs).. The inputs are the ones to the function of the func_name. The kwargs are the arguments of the function. For example, if the func_name is Affine, func is affine_backward, the inputs are data, weights, and bias if necessary, and kwargs = dict(base_axis=base_axis).

nnabla.backward_functions.show_registry()[ソース]

Show all backward fuctions registry

Solvers

nnabla.solvers.Solver クラスは、計算グラフのパラメータを最適化するための確率的勾配降下法ベースのオプティマイザーを表します。NNabla は、以下にリストされた様々な solver を提供します。

Solver
class nnabla.solvers.Solver

Solver インターフェイスクラス。

このクラスに提供される同じ API を使用して、様々な種類の solver を実装できます。

例:

# Network building comes above
import nnabla.solvers as S
solver = S.Sgd(lr=1e-3)
solver.set_parameters(nn.get_parameters())

for itr in range(num_itr):
    x.d = ... # set data
    t.d = ... # set label
    loss.forward()
    solver.zero_grad()  # All gradient buffer being 0
    loss.backward()
    solver.weight_decay(decay_rate)  # Apply weight decay
    solver.clip_grad_by_norm(clip_norm)  # Apply clip grad by norm
    solver.update()  # updating parameters

注釈

NNable で提供される全ての solver は、 Solver の継承クラスに属します。solver は、このクラス自体からインスタンス化されることはありません。

check_inf_grad(self, pre_hook=None, post_hook=None)

設定された勾配に inf があるかを確認します。

check_inf_or_nan_grad(self, pre_hook=None, post_hook=None)

設定された勾配に inf または nan があるかを確認します。

check_nan_grad(self, pre_hook=None, post_hook=None)

設定された勾配に nan があるかを確認します。

clear_parameters(self)

登録されているすべてのパラメータと状態をクリアします。

clip_grad_by_norm(self, float clip_norm, pre_hook=None, post_hook=None)

ノルムにより勾配をクリッピングします。この関数が呼び出されると、指定されたノルムで勾配をクリッピングします。

パラメータ

clip_norm (float) -- クリッピングノルムの値。

get_parameters(self)

登録されている全てのパラメータを取得します。

get_states(self)

全ての状態を取得します。

info

オブジェクト

info

learning_rate(self)

学習率を取得します。

load_states(self, path)

solver の状態を読み込みます。

パラメータ

path -- 読み込む state ファイルへのパス。

name

solver の名前を取得します。

remove_parameters(self, vector[string] keys)

keys の vector で指定された、登録済みのパラメータを削除します。

save_states(self, path)

solver の状態を保存します。

パラメータ

path -- パスまたはファイルオブジェクト。

scale_grad(self, scale, pre_hook=None, post_hook=None)

勾配のスケールを定数倍にします。

set_learning_rate(self, learning_rate)

学習率を設定します。

set_parameters(self, param_dict, bool reset=True, bool retain_state=False)

辞書で指定されたキーとパラメータ Variable でパラメータを設定します。

パラメータ
  • param_dict (dict) -- キー: 文字列, 値: Variable。

  • reset (bool) -- true の場合、パラメータを設定する前に、全てのパラメータをクリアします。false の場合、パラメータは上書きされるか、(新しい場合は) 追加されます 。

  • retain_state (bool) -- この値は、reset が false の場合のみ考慮されます。 この値が true 、かつキーが既に存在する場合 ( 上書き ) 、キーに関連付けられた状態 ( モメンタムなど ) は、パラメータの形状と新しいパラメータの形状が一致する場合に保持されます。

set_states(self, states)

状態を設定します。 set_parameters を呼び出し、最初に solver の状態を初期化してください。それを行わずにこのメソッドを呼び出すと、値エラーが発生します。

set_states_from_protobuf(self, optimizer_proto)

protobuf ファイルから solver に状態を設定します。

内部的に使用される helper メソッド。

set_states_to_protobuf(self, optimizer)

Optimizer から protobuf ファイルに状態を保存します。

内部的に使用される helper メソッド。

setup(self, params)

非推奨です。 param_dictset_parameters を呼び出してください。

update(self, update_pre_hook=None, update_post_hook=None)

この関数を呼び出すと、パラメータ値は、パラメータ Variablegrad に保存されている backpropagation で蓄積された勾配を使用して更新されます。更新ルールは、Solver の派生クラスにおいて C++ コアで実装されています。更新されたパラメータ値は、パラメータ Variable の data フィールドに保存されます。

パラメータ
  • update_pre_hook (callable) -- This callable object is called immediately before each update of parameters. The default is None.

  • update_post_hook (callable) -- This callable object is called immediately after each update of parameters. The default is None.

weight_decay(self, float decay_rate, pre_hook=None, post_hook=None)

勾配に、weight decay を適用します。これが呼ばれると、現在のパラメータ値の一定割合の分だけ勾配が減衰します。

パラメータ

decay_rate (float) -- weight decay の係数。

zero_grad(self)

登録されている全てのパラメータの勾配をゼロで初期化します。

Solver のリスト
nnabla.solvers.Sgd(lr=0.001)

確率的勾配降下法(SGD)オプティマイザー。

\[w_{t+1} \leftarrow w_t - \eta \Delta w_t\]
パラメータ

lr (float) -- 学習率 (\(\eta\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

nnabla.solvers.Momentum(lr=0.001, momentum=0.9)

モメンタムを使った SGD。

\[\begin{split}v_t &\leftarrow \gamma v_{t-1} + \eta \Delta w_t\\ w_{t+1} &\leftarrow w_t - v_t\end{split}\]
パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • momentum (float) -- モメンタムの減衰率。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.Lars(lr=0.001, momentum=0.9, coefficient=0.001, eps=1e-06)

モメンタムを使った LARS。

\[\begin{split}\lambda &\leftarrow \eta \frac{\| w_t \|}{\| \Delta w_t + \beta w_t \|} \\ v_{t+1} &\leftarrow m v_t + \gamma \lambda (\Delta w_t + \beta w_t) \\ w_{t+1} &\leftarrow w_t - v_{t+1}\end{split}\]
パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • momentum (float) -- モメンタムの減衰率。

  • coefficient (float) -- Trust 係数。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.Nesterov(lr=0.001, momentum=0.9)

Nesterov 加速勾配オプティマイザー。

\[\begin{split}v_t &\leftarrow \gamma v_{t-1} - \eta \Delta w_t\\ w_{t+1} &\leftarrow w_t - \gamma v_{t-1} + \left(1 + \gamma \right) v_t\end{split}\]
パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • momentum (float) -- モメンタムの減衰率。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

  • Yurii Nesterov. A method for unconstrained convex minimization problem with the rate of convergence \(o(1/k2)\).

nnabla.solvers.Adadelta(lr=1.0, decay=0.95, eps=1e-06)

AdaDelta オプティマイザー。

\[\begin{split}g_t &\leftarrow \Delta w_t\\ v_t &\leftarrow - \frac{RMS \left[ v_t \right]_{t-1}} {RMS \left[ g \right]_t}g_t\\ w_{t+1} &\leftarrow w_t + \eta v_t\end{split}\]
パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • decay (float) -- 減衰率 (\(\gamma\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.Adagrad(lr=0.01, eps=1e-08)

ADAGrad オプティマイザー。

\[\begin{split}g_t &\leftarrow \Delta w_t\\ G_t &\leftarrow G_{t-1} + g_t^2\\ w_{t+1} &\leftarrow w_t - \frac{\eta}{\sqrt{G_t} + \epsilon} g_t\end{split}\]
パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.AdaBelief(alpha=0.001, beta1=0.9, beta2=0.999, eps=1e-08, wd=0.0, amsgrad=False, weight_decouple=False, fixed_decay=False, rectify=False)

AdaBelief optimizer.

\[\begin{split}m_t &\leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t\\ s_t &\leftarrow \beta_2 s_{t-1} + (1 - \beta_2) (g_t - m_t)^2\\ w_{t+1} &\leftarrow w_t - \alpha \frac{\sqrt{1 - \beta_2^t}}{1 - \beta_1^t} \frac{m_t}{\sqrt{s_t + \epsilon} + \epsilon}\end{split}\]
パラメータ
  • alpha (float) -- ステップサイズ (\(\alpha\))。

  • beta1 (float) -- 一次モメンタムの減衰率 (\(\beta_1\))。

  • beta2 (float) -- 二次モメンタムの減衰率 (\(\beta_2\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

  • wd (float) -- Weight decay rate. This option only takes effect when weight_decouple option is enabled.

  • amsgrad (bool) -- Perform AMSGrad variant of AdaBelief.

  • weight_decouple (bool) -- Perform decoupled weight decay as in AdamW.

  • fixed_decay (bool) -- If True, the weight decay ratio will be kept fixed. Note that this option only takes effect when weight_decouple option is enabled.

  • rectify (bool) -- Perform RAdam variant of AdaBelief.

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.RMSprop(lr=0.001, decay=0.9, eps=1e-08)

RMSprop オプティマイザー (Geoffery Hinton) 。

\[\begin{split}g_t &\leftarrow \Delta w_t\\ v_t &\leftarrow \gamma v_{t-1} + \left(1 - \gamma \right) g_t^2\\ w_{t+1} &\leftarrow w_t - \eta \frac{g_t}{\sqrt{v_t} + \epsilon}\end{split}\]
パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • decay (float) -- 減衰率 (\(\gamma\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.RMSpropGraves(lr=0.0001, decay=0.95, momentum=0.9, eps=0.0001)

RMSpropGraves optimizer (Alex Graves).

\[\begin{split}n_t &\leftarrow \rho n_{t-1} + \left(1 - \rho \right) {e_t}^2\\ g_t &\leftarrow \rho g_{t-1} + \left(1 - \rho \right) e_t\\ d_t &\leftarrow \beta d_{t-1} - \eta \frac{e_t}{\sqrt{n_t - {g_t}^2 + \epsilon}}\\ w_{t+1} &\leftarrow w_t + d_t\end{split}\]

where \(e_t\) denotes the gradient.

パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • decay (float) -- Decay rate (\(\rho\)).

  • momentum (float) -- Momentum (\(\beta\))

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.Adam(alpha=0.001, beta1=0.9, beta2=0.999, eps=1e-08)

ADAM オプティマイザー。

\[\begin{split}m_t &\leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t\\ v_t &\leftarrow \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\ w_{t+1} &\leftarrow w_t - \alpha \frac{\sqrt{1 - \beta_2^t}}{1 - \beta_1^t} \frac{m_t}{\sqrt{v_t} + \epsilon}\end{split}\]

\(g_t\) は勾配を示し、 \(m_0 \leftarrow 0\) および \(v_0 \leftarrow 0\) とする。

パラメータ
  • alpha (float) -- ステップサイズ (\(\alpha\))。

  • beta1 (float) -- 一次モメンタムの減衰率 (\(\beta_1\))。

  • beta2 (float) -- 二次モメンタムの減衰率 (\(\beta_2\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.AdaBound(alpha=0.001, beta1=0.9, beta2=0.999, eps=1e-08, final_lr=0.1, gamma=0.001)

AdaBound オプティマイザーは、Adam に学習率の上限と下限を動的を適用します。

\[\begin{split}w_{t+1} &\leftarrow w_t - \eta_t*m_t\\ \eta_t &= clip( \alpha\frac{\sqrt{1 - \beta_2^t}}{(1 - \beta_1^t)(\sqrt{v_t} + \epsilon)}, \eta_l(t), \eta_u(t))\\ \eta_l(t) &= (1 - (1/((1-\gamma)t+1)))\alpha^*\\ \eta_u(t) &= (1 + (1/((1-\gamma)t)))\alpha^*\end{split}\]

学習率のスケジューリングが \(\alpha\) と \(\alpha^*\) の両方に適切に適用されるように、 \(\alpha\) の現在の値 ( set_learning_rate(lr) により設定) を \(\alpha\) の初期値で割った値を用いて \(\alpha^*\) (final_lr) がスケーリングされます。

パラメータ
  • alpha (float) -- ステップサイズ (\(\alpha\))。

  • beta1 (float) -- 一次モメンタムの減衰率 (\(\beta_1\))。

  • beta2 (float) -- 二次モメンタムの減衰率 (\(\beta_2\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

  • final_lr (float) -- 最終的な (SGD) 学習率。

  • gamma (float) -- bound 関数の収束速度。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.Adamax(alpha=0.002, beta1=0.9, beta2=0.999, eps=1e-08)

ADAMAX オプティマイザー。

\[\begin{split}m_t &\leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t\\ v_t &\leftarrow \max\left(\beta_2 v_{t-1}, |g_t|\right)\\ w_{t+1} &\leftarrow w_t - \alpha \frac{\sqrt{1 - \beta_2^t}}{1 - \beta_1^t} \frac{m_t}{v_t + \epsilon}\end{split}\]

\(g_t\) が勾配を示し、 \(m_0 \leftarrow 0\) および \(v_0 \leftarrow 0\) とすると、 \(v_t\) は一連の勾配 \(t=0,...,t\) の指数関数的に重み付けされた無限大ノルムになります。

パラメータ
  • alpha (float) -- ステップサイズ (\(\alpha\))。

  • beta1 (float) -- 一次モメンタムの減衰率 (\(\beta_1\))。

  • beta2 (float) -- 二次モメンタムの減衰率 (\(\beta_2\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.AMSGRAD(alpha=0.001, beta1=0.9, beta2=0.999, eps=1e-08, bias_correction=False)

AMSGRAD オプティマイザー。

\[\begin{split}m_t &\leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t\\ v_t &\leftarrow \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\ \hat{v_t} &= \max(\hat{v_{t-1}}, v_t)\\ w_{t+1} &\leftarrow w_t - \alpha \frac{m_t}{\sqrt{\hat{v_t}} + \epsilon}\end{split}\]

\(g_t\) は勾配を示し、 \(m_0 \leftarrow 0\) および \(v_0 \leftarrow 0\) とする。

パラメータ
  • alpha (float) -- ステップサイズ (\(\alpha\))。

  • beta1 (float) -- 一次モメンタムの減衰率 (\(\beta_1\))。

  • beta2 (float) -- 二次モメンタムの減衰率 (\(\beta_2\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\)) 。 注意 こちらは論文には記載されていません。

  • bias_correction (bool) -- ADAM で定義された移動平均にバイアス補正を適用します。注意 こちらは論文には記載されていません。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.AMSBound(alpha=0.001, beta1=0.9, beta2=0.999, eps=1e-08, final_lr=0.1, gamma=0.001, bias_correction=False)

AMSBound オプティマイザーは AMSGrad に対して学習率の上限と下限を動的に適用します。

\[\begin{split}w_{t+1} &\leftarrow w_t - \eta_t*m_t\\ \eta_t &= clip( \alpha\frac{\sqrt{1 - \beta_2^t}}{(1 - \beta_1^t)(\sqrt{\hat{v_t}} + \epsilon)}, \eta_l(t), \eta_u(t))\\ \hat{v_t} &= \max(\hat{v_{t-1}}, v_t)\\ \eta_l(t) &= (1 - (1/((1-\gamma)t+1)))\alpha^*\\ \eta_u(t) &= (1 + (1/((1-\gamma)t)))\alpha^*\end{split}\]

学習率のスケジューリングが \(\alpha\) と \(\alpha^*\) の両方に適切に適用されるように、 \(\alpha\) の現在の値 ( set_learning_rate(lr) により設定) を \(\alpha\) の初期値で割った値を用いて \(\alpha^*\) (final_lr) がスケーリングされます。

パラメータ
  • alpha (float) -- ステップサイズ (\(\alpha\))。

  • beta1 (float) -- 一次モメンタムの減衰率 (\(\beta_1\))。

  • beta2 (float) -- 二次モメンタムの減衰率 (\(\beta_2\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\)) 。 注意 こちらは論文には記載されていません。

  • final_lr (float) -- 最終的な (SGD) 学習率。

  • gamma (float) -- bound 関数の収束速度。

  • bias_correction (bool) -- ADAM で定義された移動平均にバイアス補正を適用します。注意 こちらは論文には記載されていません。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.AdamW(alpha=0.001, beta1=0.9, beta2=0.999, eps=1e-08, wd=0.0001)

減結合 weight decay を使ったADAM オプティマイザー。

\[\begin{split}m_t &\leftarrow \beta_1 m_{t-1} + (1 - \beta_1) g_t\\ v_t &\leftarrow \beta_2 v_{t-1} + (1 - \beta_2) g_t^2\\ w_{t+1} &\leftarrow w_t - \alpha \frac{\sqrt{1 - \beta_2^t}}{1 - \beta_1^t} \frac{m_t}{\sqrt{v_t} + \epsilon} - \eta_t\lambda w_t\end{split}\]

ここでは、 \(g_t\) は勾配を示し、 \(\lambda\) は減結合 weight decay 率、 \(m_0 \leftarrow 0\) および \(v_0 \leftarrow 0\) です。

パラメータ
  • alpha (float) -- ステップサイズ (\(\alpha\))。

  • beta1 (float) -- 一次モメンタムの減衰率 (\(\beta_1\))。

  • beta2 (float) -- 二次モメンタムの減衰率 (\(\beta_2\))。

  • eps (float) -- ゼロ除算を回避するための小さな値 (\(\epsilon\))。

  • wd (float) -- Weight decay 率。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

nnabla.solvers.SgdW(lr=0.001, momentum=0.9, wd=0.0001)

減結合 weight decay を使ったStochastic gradient descent (SGD) オプティマイザー。

\[\begin{split}v_t &\leftarrow \gamma v_{t-1} + \eta g_t - (\eta / \eta_0)\lambda v_{t-1}\\ w_{t+1} &\leftarrow w_t - v_t\end{split}\]

ここでは、 \(\lambda\) は減結合 weight decay 率です。

パラメータ
  • lr (float) -- 学習率 (\(\eta\))。

  • momentum (float) -- モメンタムの減衰率。

  • wd (float) -- Weight decay 率。

戻り値

Solver クラスのインスタンス。 詳しくは Solver API ガイドを参照してください。

戻り値の型

Solver

注釈

コンテキスト を指定して、指定されたタイプの Solver の優先ターゲット実装(CUDA など)をインスタンス化できます。 コンテキスト は nnabla.set_default_context(ctx) または nnabla.context_scope(ctx) で設定できます。API ドキュメントを参照してください。

参照

Communicator

Communicator は、計算グラフに含まれているパラメータを転送するAPIです。

このドキュメントは、communicator.py のエイリアスです。

Communicator のインターフェイス
class nnabla.communicators.Communicator

Communicator のインターフェイスクラスです。

Communicator は、MPI のようにグループ通信を利用して、データ(例:勾配など)をやり取りします。このクラスは、分散学習を行う際に使用されます。

abort(self)

MPI 実行環境を終了します。

add_context_and_parameters(self, ctx_param_dict)

コンテキストとパラメータを追加します。

パラメータ

ctx_param_dict (tuple of Context, dict) -- キーが string 、値が Variable の辞書です。

all_gather(self, ndarray, ndarray_list, string group='world')

異なるデバイスのデータに対して、All gether を実行します。

パラメータ
  • ndarray (NdArray) -- 収集するデータ。

  • ndarray_list (NdArray) -- 保存するデータ 。

  • group (string) -- グループの名前です。このグループは、集合が呼び出されるときに使用されます。

例:

# Run like `mpirun -n 2 python <code_snippet.py>`
# note: the order of the output to stdout are stochastic because of multiprocesses.

# Communicator and Context
import numpy as np
import nnabla as nn
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context

extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()

# Data
x = nn.Variable([2, 2])
x.d = np.random.rand(*x.shape)
y_list = [nn.Variable([2, 2]), nn.Variable([2, 2])]
print("Before the collective ({}-th)".format(comm.rank))
print(x.d)

# AllGather
comm.all_gather(x.data, [y.data for y in y_list])

# Check
print("After the collective ({}-th)".format(comm.rank))
for y in y_list:
    print(y.d)
all_reduce(self, data, bool division=False, bool inplace=False, string group='world')

異なるデバイスのデータに対して、 All reduce を実行します。

パラメータ
  • data (NdArray or list of NdArray) --

  • division (bool) -- all_reduce した値を 与えられた contexts 数、または通信を行うデバイス数で割るかどうかを決定するフラグです。

  • inplace (bool) -- パック配列を使用するためのフラグです。デフォルトは false です。true の場合、メモリ効率は良いですが、処理が遅くなります。false の場合、メモリ効率は良くありませんが高速です。どちらの場合も、最終的な処理結果は同じメモリ領域に得られます。

  • group (string) -- グループの名前です。このグループは、集合が呼び出されるときに使用されます。

例:

# Run like `mpirun -n 2 python <code_snippet.py>`
# note: the order of the output to stdout are stochastic because of multiprocesses.

# Communicator and Context
import numpy as np
import nnabla as nn
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context

extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()

# Data
x_list = [nn.Variable([2, 2]), nn.Variable([2, 2])]
print("Before the collective ({}-th)".format(comm.rank))
for x in x_list:
    x.d = np.random.rand(*x.shape)
    print(x.d)

# AllReduce
comm.all_reduce([x.data for x in x_list], inplace=True)

# Check
print("After the collective ({}-th)".format(comm.rank))
for x in x_list:
    print(x.d)
all_reduce_callback(self, data, size_t pack_size, bool division=False, string group='world')

異なるデバイスのデータに対して、 All reduce を実行します。

注釈

この関数は現在、共有パラメータ ( RNN など) をサポートしていません。

パラメータ
  • data (NdArray or list of NdArray) --

  • pack_size (int) -- パックデータに含まれる値の数。

  • division (bool) -- all_reduce した値を 与えられた contexts 数、または通信を行うデバイス数で割るかどうかを決定するフラグです。

  • group (string) -- グループの名前です。このグループは、集合が呼び出されるときに使用されます。

例:

マルチプロセスデータ並列分散学習を行う例を以下に示します。

# Run like `mpirun -n 2 python <code_snippet.py>`

# Communicator and Context
import numpy as np
import nnabla as nn
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context

extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()

n_class = 2
b, c, h, w = 4, 1, 32, 32

# Data
x = nn.Variable([b, c, h, w])
y = nn.Variable([b, 1])

# Network setting
h = PF.convolution(x, 1, (3, 3), (1, 1), (1, 1))
pred = PF.affine(h, 2)
loss = F.mean(F.softmax_cross_entropy(pred, y))

loss.forward()
# AllReduce during backward
loss.backward(communicator_callbacks = comm.all_reduce_callback([v.grad for v in nn.get_parameters().values()], 1024 * 1024 * 2))
allreduce(self, bool division=False, bool inplace=False)

この関数の利用は非推奨です。代わりに all_reduce を参照してください。

与えられたパラメータに対して、 All reduce を実行します。現在、allreduce は勾配領域に適用されます。

パラメータ
  • division (bool) -- all_reduce した値を 与えられた contexts 数、または通信を行うデバイス数で割るかどうかを決定するフラグです。

  • inplace (bool) -- パック配列を使用するためのフラグです。デフォルトは false です。true の場合、メモリ効率は良いですが、処理が遅くなります。false の場合、メモリ効率は良くありませんが高速です。どちらの場合も、最終的な処理結果は同じメモリ領域に得られます。

barrier(self)

Communicator のすべてのプロセスがこのルーチンに到達するまで、それぞれのプロセスをブロックします。

bcast(self, data, int src, bool inplace=False, string group='world')

異なるデバイスにデータをブロードキャストします。

パラメータ
  • data (NdArray or list of NdArray) --

  • src (int) -- データがブロードキャストされるソースランク。

  • inplace (bool) -- パック配列を使用するためのフラグです。デフォルトは false です。true の場合、メモリ効率は良いですが、処理が遅くなります。false の場合、メモリ効率は良くありませんが高速です。どちらの場合も、最終的な処理結果は同じメモリ領域に得られます。

  • group (string) -- グループの名前です。このグループは、集合が呼び出されるときに使用されます。

例:

# Run like `mpirun -n 2 python <code_snippet.py>`
# note: the order of the output to stdout are stochastic because of multiprocesses.

# Communicator and Context
import numpy as np
import nnabla as nn
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context

extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()

# Data
x_list = [nn.Variable([2, 2]), nn.Variable([2, 2])]
print("Before the collective ({}-th)".format(comm.rank))
for x in x_list:
    x.d = np.random.rand(*x.shape)
    print(x.d)

# Bcast
comm.bcast([x.data for x in x_list], src=0, inplace=True)

# Check
print("After the collective ({}-th)".format(comm.rank))
for x in x_list:
    print(x.d)
clear_context_parameters(self)

登録されているすべてのコンテキストとパラメータを消去します。

find_group(self, group)

グループ内のランクのリストを返します。グループが存在しない場合は、空のリストが返されます。

パラメータ

group (str) -- グループの名前です。

戻り値

ランクのリストです (int) 。

戻り値の型

ranks (list)

init(self)

Communicator を初期化します。

マルチスレッドまたはマルチプロセスにより、 Initall または initrank となります。必ず 先にadd_context_and_parameters によって通信を行う全てのパラメータを追加してから、この関数を実行してください。

list_groups(self)
戻り値

グループ (str) のランク (list)。

戻り値の型

groups (dict)

local_rank

Communicator のローカルランクを取得します。

name

Communicator の名前を取得します。

new_group(self, name_ranks)
パラメータ

name_ranks (tuple) -- 名前のタプル (str) とランク (list)。

戻り値

グループ名 (str)。

例:

# Communicator and Context
extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()

# New group
group = comm.new_group("node0", [0, 1, 2, 3])
rank

Communicator のランクを取得します。

reduce(self, data, int dst, bool division=False, bool inplace=False, string group='world')

異なるデバイスのデータに対して、 reduce を実行します。

パラメータ
  • data (NdArray or list of NdArray) --

  • dst (int) -- 結果が保存される送り先のランク。

  • division (bool) -- all_reduce した値を 与えられた contexts 数、または通信を行うデバイス数で割るかどうかを決定するフラグです。

  • inplace (bool) -- パック配列を使用するためのフラグです。デフォルトは false です。true の場合、メモリ効率は良いですが、処理が遅くなります。false の場合、メモリ効率は良くありませんが高速です。どちらの場合も、最終的な処理結果は同じメモリ領域に得られます。

  • group (string) -- グループの名前です。このグループは、集合が呼び出されるときに使用されます。

例:

# Run like `mpirun -n 2 python <code_snippet.py>`
# note: the order of the output to stdout are stochastic because of multiprocesses.

# Communicator and Context
import numpy as np
import nnabla as nn
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context

extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()

# Data
x_list = [nn.Variable([2, 2]), nn.Variable([2, 2])]
print("Before the collective ({}-th)".format(comm.rank))
for x in x_list:
    x.d = np.random.rand(*x.shape)
    print(x.d)

# Reduce
comm.reduce([x.data for x in x_list], dst=0, inplace=True)

# Check
print("After the collective ({}-th)".format(comm.rank))
for x in x_list:
    print(x.d)
reduce_scatter(self, ndarray_list, ndarray, bool division=False, string group='world')

異なるデバイスのデータに対して、 Reduce scatter を実行します。

パラメータ
  • ndarray_list (NdArray) -- さまざまなデバイスで削減されるデータのリスト。

  • ndarray (NdArray) -- 保存するデータ 。

  • group (string) -- グループの名前です。このグループは、集合が呼び出されるときに使用されます。

例:

# Run like `mpirun -n 2 python <code_snippet.py>`
# note: the order of the output to stdout are stochastic because of multiprocesses.

# Communicator and Context
import numpy as np
import nnabla as nn
import nnabla.communicators as C
from nnabla.ext_utils import get_extension_context

extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()

# Data
x_list = [nn.Variable([2, 2]), nn.Variable([2, 2])]
y = nn.Variable([2, 2])
print("Before the collective ({}-th)".format(comm.rank))
for x in x_list:
    x.d = np.random.rand(*x.shape)
    print(x.d)

# ReduceScatter
comm.reduce_scatter([x.data for x in x_list], y.data)

# Check
print("After the collective ({}-th)".format(comm.rank))
print(y.d)
size

Communicator のサイズを取得します。

Communicator の一覧
nnabla.communicators.MultiProcessDataParalellCommunicator()

MultiProcessDataParallelCommunicator(CContext ctx)

分散学習のためのマルチプロセスデータ並列 Communicator。

パラメータ

context (Context) -- この Communicator で使用されるコンテキスト。

例:

マルチプロセスデータ並列分散学習を行う例を以下に示します。

# Communicator and Context
extension_module = "cudnn"
ctx = get_extension_context(extension_module)
comm = C.MultiProcessCommunicator(ctx)
comm.init()
n_devices = comm.size
mpi_rank = comm.rank
device_id = comm.local_rank
ctx.device_id = str(device_id)
nn.set_default_context(ctx)

# Network and Solver created here

...


# Training loop
for itr in range(num_itr):
    # Forward, zerograd, backward
    loss.forward()
    solver.zero_grad()
    loss.backward()

    # Allreduce
    comm.all_reduce([v.grad for v in nn.get_parameters().values()])

    # Update
    solver.update()

Monitor

Monitor API は、ニューラルネットワークの学習の進行状況を記録するための helper を提供します。

class nnabla.monitor.Monitor(save_path)[ソース]

このクラスは、ログの出力ディレクトリを設定するために作成されます。作成された nnabla.monitor.Monitor インスタンスは、以下の Monitor のクラスに渡されます。

Monitor のリスト
class nnabla.monitor.MonitorSeries(name, monitor=None, interval=1, verbose=True)[ソース]

学習中の様々な値を記録します。

値は画面に表示されるほか、ファイル <name>-series.txt に出力されます。

例 :

mons = MonitorSeries('mon', interval=2)
for i in range(10):
    mons.add(i, i * 2)
パラメータ
  • name (str) -- monitor の名前。画面に表示されるログの中で使用される他、出力される .txt ファイルの名前の一部としても使われます。

  • monitor (Monitor) -- Monitor クラスのインスタンス。

  • interval (int) -- 出力を表示する間隔。 .add() によって追加された値は、その間隔内で平均されます。

  • verbose (bool) -- 画面へ出力を表示するか選択できます。

add(index, value)[ソース]

モニタに値を追加し、ログとして記録します。

パラメータ
  • index (int) -- 値のインデックス。通常は現在のイテレーションなど。

  • value (float) -- 記録する値。

class nnabla.monitor.MonitorTimeElapsed(name, monitor=None, interval=100, verbose=True)[ソース]

経過時間を記録します。

値は画面に表示されるほか、ファイル <name>-timer.txt に出力されます。

例 :

import time
mont = MonitorTimeElapsed("time", interval=2)
for i in range(10):
    time.sleep(1)
    mont.add(i)
パラメータ
  • name (str) -- monitor の名前。画面に表示されるログの中で使用される他、出力される .txt ファイルの名前の一部としても使われます。

  • monitor (Monitor) -- Monitor クラスのインスタンス。

  • interval (int) -- 出力を表示する間隔。経過時間はその間隔内で計算されます。

  • verbose (bool) -- 画面へ出力を表示するか選択できます。

add(index)[ソース]

以前にこのメソッドが呼び出された時点もしくはこのオブジェクトが作成された時点から、次にこのメソッドが呼び出されるまでの経過時間を計算します。

パラメータ

index (int) -- 表示、そしてインターバルを取得するために使用されるインデックス。

class nnabla.monitor.MonitorImage(name, monitor, interval=1000, verbose=True, num_images=16, normalize_method=None)[ソース]

画像を保存します。

この .add() メソッドは (N,..., C, H, W) 配列を入力として取り、 [H, W, :min(3, C)] の形式で num_images 枚の画像に変換したのち、 monitor で指定したフォルダへ保存します。

値は画面に表示されるほか、ファイル <name>/{iter}-{image index}.png に出力されます 。

例 :

import numpy as np
m = Monitor('tmp.monitor')
mi = MonitorImage('noise', m, interval=2, num_images=2)
x = np.random.randn(10, 3, 8, 8)
for i in range(10):
    mi.add(i, x)
パラメータ
  • name (str) -- monitor の名前。画面に表示されるログの中で使用される他、出力される .txt ファイルの名前の一部としても使われます。

  • monitor (Monitor) -- Monitor クラスのインスタンス。

  • interval (int) -- 出力を表示する間隔。

  • num_images (int) -- 各イテレーションで保存される画像の数。

  • normalize_method (function) -- 出力する画像に適用する正規化関数を指定します。この関数はNCHW形式の画像のミニバッチを numpy.ndarray として受け取り、入力を [0、1] の範囲にマッピングするものである必要があります。デフォルトでは、画像に対して min-max 正規化を行う関数が用いられます。

add(index, var)[ソース]

画像のミニバッチを monitor に追加します。

パラメータ
  • index (int) -- 値のインデックス。通常は現在のイテレーションなど。

  • var (Variable, NdArray, or ndarray) -- (N, ..., C, H, W) 形式の画像のミニバッチ 。C == 2 の場合、ブルーチャネルが追加されます。C > 3 の場合、配列がスライスされ、C > 3 部分は無視されます。

class nnabla.monitor.MonitorImageTile(name, monitor, interval=1000, verbose=True, num_images=16, normalize_method=None)[ソース]

複数枚の画像をタイルしてまとめた画像を保存します。

この .add() メソッドは (N,..., C, H, W) 配列を入力として受け取り、(H, W, :min(3, C)) の形式で num_images 枚の画像をタイルしたうえで、 monitorで指定したフォルダへ保存します。

値は画面に表示されるほか、ファイル <name>/{iter}-{image index}.png に出力されます 。

例 :

import numpy as np
m = Monitor('tmp.monitor')
mi = MonitorImageTile('noise_noise', m, interval=2, num_images=4)
x = np.random.randn(10, 3, 8, 8)
for i in range(10):
    mi.add(i, x)
パラメータ
  • name (str) -- monitor の名前。画面に表示されるログの中で使用される他、出力される .txt ファイルの名前の一部としても使われます。

  • monitor (Monitor) -- Monitor クラスのインスタンス。

  • interval (int) -- 出力を表示する間隔。

  • num_images (int) -- 各イテレーションで単一の画像に保存するためにタイル化された画像の数。

  • normalize_method (function) -- 出力する画像に適用する正規化関数を指定します。この関数はNCHW形式の画像のミニバッチを numpy.ndarray として受け取り、入力を [0、1] の範囲にマッピングするものである必要があります。デフォルトでは、画像に対して min-max 正規化を行う関数が用いられます。

add(index, var)[ソース]

画像のミニバッチを monitor に追加します。

パラメータ
  • index (int) -- 値のインデックス。通常は現在のイテレーションなど。

  • var (Variable, NdArray, or ndarray) -- (N, ..., C, H, W) 形式の画像のミニバッチ 。C == 2 の場合、ブルーチャネルが追加されます。C > 3 の場合、配列がスライスされ、C > 3 部分は無視されます。

ユーティリティ関数
nnabla.monitor.tile_images(data, padsize=1, padval=0)[ソース]

( B, C, H, W ) の形状の配列をタイル化された画像に変換します。

パラメータ
  • data (ndarray) -- ( B, C, H, W ) の形状の配列。

  • padsize (int) -- 各タイルのパティングをこのサイズにします。

  • padval (float) -- パディングピクセルをこの値で埋めます。

戻り値

タイル画像。

戻り値の型

tile_image (ndarray)

nnabla.monitor.plot_series(filename, plot_kwargs=None)[ソース]

MonitorSeries の出力テキストファイルから系列データをプロットします。

パラメータ
  • filename (str) -- MonitorSeries クラスによって生成された *.series.txt ファイルへのパス。

  • plot_kwags (dict, optional) -- :function:`matplotlib.pyplot.plot` に渡されるキーワード引数。

注釈

matplotlib パッケージが必要です。

nnabla.monitor.plot_time_elapsed(filename, elapsed=False, unit='s', plot_kwargs=None)[ソース]

MonitorTimeElapsed の出力テキストファイルから系列データをプロットします。

パラメータ
  • filename (str) -- MonitorSeries クラスによって生成された *.series.txt ファイルへのパス。

  • elapsed (bool) -- True の場合、合計経過時間をプロットします。

  • unit (str) -- 's' , 'm' , 'h' , 'd' のいずれかから選択される時間単位。

  • plot_kwags (dict, optional) -- :function:`matplotlib.pyplot.plot` に渡されるキーワード引数。

注釈

matplotlib パッケージが必要です。

ユーティリティ

NNP の保存やロードのユーティリティ

重要なお知らせ: Neural Network Console で NPP ファイルを扱うには、保存する / 読み込むネットワークが LoopControl 関数である RepeatStart, RepeatEnd, RecurrentInput, RecurrentOutput または Delay を含む場合、 ファイルフォーマットコンバーター を使ってネットワークを拡張する必要があります。

nnabla.utils.save.save(filename, contents, include_params=False, variable_batch_size=True, extension='.nnp', parameters=None)[ソース]

ネットワーク定義の保存、推論/学習実行の設定等。

パラメータ
  • filename (str or file object) -- 情報を保存するためのファイル名。ファイルの拡張子は、保存するファイルフォーマットを決定します。.nnp: (推奨) nntxt (ネットワーク定義等) と h5 (パラメータ) で ZIP圧縮ファイルを生成します。.nntxt: テキスト形式の Protobuf 。 .protobuf: バイナリ形式の Protobuf (下位互換性の点で安全でありません)

  • contents (dict) -- 保存する情報。

  • include_params (bool) -- 単一ファイルにパラメータを含めます。ファイル名の拡張子が nnp の場合、無視されます。

  • variable_batch_size (bool) -- True の場合、すべての変数の最初の次元は batch size、残りは placeholder (より具体的には -1) とみなされます。 placeholder の次元は読み込み中、あるいは読み込み後に埋められます。

  • extension -- if files is file-like object, extension is one of ".nntxt", ".prototxt", ".protobuf", ".h5", ".nnp".

サンプル

次の例では、2 つの入力と 2 つの出力 MLP を作成し、ネットワーク構造と初期化されたパラメータを保存します。

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
from nnabla.utils.save import save

batch_size = 16
x0 = nn.Variable([batch_size, 100])
x1 = nn.Variable([batch_size, 100])
h1_0 = PF.affine(x0, 100, name='affine1_0')
h1_1 = PF.affine(x1, 100, name='affine1_0')
h1 = F.tanh(h1_0 + h1_1)
h2 = F.tanh(PF.affine(h1, 50, name='affine2'))
y0 = PF.affine(h2, 10, name='affiney_0')
y1 = PF.affine(h2, 10, name='affiney_1')

contents = {
    'networks': [
        {'name': 'net1',
         'batch_size': batch_size,
         'outputs': {'y0': y0, 'y1': y1},
         'names': {'x0': x0, 'x1': x1}}],
    'executors': [
        {'name': 'runtime',
         'network': 'net1',
         'data': ['x0', 'x1'],
         'output': ['y0', 'y1']}]}
save('net.nnp', contents)

学習可能なモデルを取得するには、以下のコードを代わりにお使いください。

contents = {
'global_config': {'default_context': ctx},
'training_config':
    {'max_epoch': args.max_epoch,
     'iter_per_epoch': args_added.iter_per_epoch,
     'save_best': True},
'networks': [
    {'name': 'training',
     'batch_size': args.batch_size,
     'outputs': {'loss': loss_t},
     'names': {'x': x, 'y': t, 'loss': loss_t}},
    {'name': 'validation',
     'batch_size': args.batch_size,
     'outputs': {'loss': loss_v},
     'names': {'x': x, 'y': t, 'loss': loss_v}}],
'optimizers': [
    {'name': 'optimizer',
     'solver': solver,
     'network': 'training',
     'dataset': 'mnist_training',
     'weight_decay': 0,
     'lr_decay': 1,
     'lr_decay_interval': 1,
     'update_interval': 1}],
'datasets': [
    {'name': 'mnist_training',
     'uri': 'MNIST_TRAINING',
     'cache_dir': args.cache_dir + '/mnist_training.cache/',
     'variables': {'x': x, 'y': t},
     'shuffle': True,
     'batch_size': args.batch_size,
     'no_image_normalization': True},
    {'name': 'mnist_validation',
     'uri': 'MNIST_VALIDATION',
     'cache_dir': args.cache_dir + '/mnist_test.cache/',
     'variables': {'x': x, 'y': t},
     'shuffle': False,
     'batch_size': args.batch_size,
     'no_image_normalization': True
     }],
'monitors': [
    {'name': 'training_loss',
     'network': 'validation',
     'dataset': 'mnist_training'},
    {'name': 'validation_loss',
     'network': 'validation',
     'dataset': 'mnist_validation'}],
}
class nnabla.utils.nnp_graph.NnpLoader(filepath, scope=None, extension='.nntxt')[ソース]

NNP ファイルローダー。

パラメータ
  • filepath -- file-like object or filepath.

  • extension -- if filepath is file-like object, extension is one of ".nnp", ".nntxt", ".prototxt".

サンプル

from nnabla.utils.nnp_graph import NnpLoader

# Read a .nnp file.
nnp = NnpLoader('/path/to/nnp.nnp')
# Assume a graph `graph_a` is in the nnp file.
net = nnp.get_network(network_name, batch_size=1)
# `x` is an input of the graph.
x = net.inputs['x']
# 'y' is an outputs of the graph.
y = net.outputs['y']
# Set random data as input and perform forward prop.
x.d = np.random.randn(*x.shape)
y.forward(clear_buffer=True)
print('output:', y.d)
get_network(name, batch_size=None, callback=None)[ソース]

name で指定されたネットワークの variable graph を作成します。

戻り値: NnpNetwork

get_network_names()[ソース]

利用可能なネットワーク名を返します。

class nnabla.utils.nnp_graph.NnpNetwork(proto_network, batch_size, callback)[ソース]

nnp ファイルから読み込んだ graph object。

NnpNetwork のインスタンスは通常 NnpLoader インスタンスにより作成されます。詳しくは、NnpLoader にある使用例をご覧ください。

variables

変数名をキーとして、nnabla.Variable を値として作成した graph にある全ての変数の辞書。

dict

inputs

すべての入力変数。

dict

outputs

すべての出力変数。

dict

画像ユーティリティ

このモジュールは画像に対する読み込み、書き込み、サイズ変更を行う関数を提供します。これらの関数のバックエンドはユーザー環境により自動的に変更されます。バックエンドの優先度は以下の通りです (上位ほど優先度高):

  • OpenCV (cv2)

  • scikit-image (skimage)

  • pillow (PIL) (インストールが必要)

このモジュールを使うには、これらのうち少なくとも 1 つのモジュールをインストールする必要があります。

nnabla.utils.image_utils.imread(path, grayscale=False, size=None, interpolate='bilinear', channel_first=False, as_uint16=False, num_channels=- 1, **kwargs)[ソース]

path から画像を読み込みます。 size を指定した場合、出力配列がサイズ変更されます。デフォルトの出力形状は、RGB 画像では (高さ, 幅, チャネル)、グレースケール画像では (高さ, 幅) となります。

パラメータ
  • path (String or File Object) -- 入力画像のパス。

  • grayscale (bool) -- True の場合、画像はグレースケールに再スケーリングされます。デフォルトは False です。

  • size (tuple of int) -- 出力形状。順番は (幅, 高さ)。 None の場合、画像はサイズ変更されません。デフォルトは None です。

  • interpolate (str) --

    補間法。この引数はバックエンドに依存します。この引数を指定したい場合、現在使用しているバックエンドに注意を払う必要があります。 以下を選択できます:

    • pil backend: ["nearest", "box", "bilinear", "hamming", "bicubic", "lanczos"].

    • cv2 backend: ["nearest", "bilinear", "bicubic", "lanczos"].

    両方のバックエンドのデフォルトは "bilinear" です。

  • channel_first (bool) -- True の場合、出力配列の形状は RGB 画像で (チャネル, 高さ, 幅) となります。デフォルトは False です。

  • as_uint16 (bool) -- True の場合、この関数は画像を np.uint16 として読み取ろうとします。デフォルトは False です。

  • num_channels (int) -- 出力配列のチャネルサイズ。デフォルトは -1 で、raw 画像形状を保持します。

  • return_palette_indices (bool) -- この引数は、pil バックエンドでのみ使うことができます。このフラグが True であり、PIL.Image のモードが "P" の場合、この関数はインデックスを含む 2 次元配列をパレットに返します。それ以外の場合は、(画像情報によって) “RGB” もしくは “RGBA” の 3 次元配列を返します。デフォルト値は False です。

戻り値

as_uint16=True の場合、出力 dtype は np.uint16 となり、その他は np.uint8 (デフォルト) となります。

戻り値の型

numpy.ndarray

nnabla.utils.image_utils.imsave(path, img, channel_first=False, as_uint16=False, auto_scale=True, **kwargs)[ソース]

path で指定されたファイルに img を保存します。デフォルトで、 img の形状は (高さ, 幅, チャネル) であることが必要です。

パラメータ
  • path (str) -- 出力パス。

  • img (numpy.ndarray) -- 入力画像。すべてのピクセル値は正の値であり、uint8 では int の [0, 255]、uint16 では int の [0, 65535]、float では [0, 1] の範囲内にある必要があります。float 画像を渡すとき、 auto_scale を True に設定する必要があります (そうでなければ例外が発生します)。負の値を持つ画像が入力に渡された場合、例外が発生します。

  • channel_first (bool) -- True の場合、形状が (チャネル, 高さ, 幅) となる画像を入力することが出来ます。デフォルトは False です。

  • as_uint16 (bool) -- True の場合、保存する前に画像を uint16 にキャストします。デフォルトは False です。

  • auto_scale (bool) -- ピクセル値の範囲がスケールアップされているか否かを表します。スケールアップされたピクセル値の範囲は uint8 で [0, 255]、uint16 で [0, 65535] となる出力 dtype に依存します。

nnabla.utils.image_utils.imresize(img, size, interpolate='bilinear', channel_first=False, **kwargs)[ソース]

imgsize にサイズ変更します。デフォルトでは、入力画像の形状は (高さ, 幅, チャネル) である必要があります。

パラメータ
  • img (numpy.ndarray) -- 入力画像。

  • size (tuple of int) -- 出力形状。順番は (幅, 高さ)。

  • interpolate (str) --

    補間法。この引数はバックエンドに依存します。この引数を指定したい場合、現在使用しているバックエンドに注意を払う必要があります。 以下を選択できます:

    • pil backend: ["nearest", "box", "bilinear", "hamming", "bicubic", "lanczos"].

    • cv2 backend: ["nearest", "bilinear", "bicubic", "lanczos"].

    両方のバックエンドのデフォルトは "bilinear" です。

  • channel_first (bool) -- True の場合、出力配列の形状は RGB 画像で (チャネル, 高さ, 幅) となります。デフォルトは False です。

戻り値

numpy.ndarray

データのイテレーター

NNabla では学習のためのデータ使用に関する様々なユーティリティを提供しています。

DataSource
class nnabla.utils.data_source.DataSource(shuffle=False, rng=None)[ソース]

ベースクラス: object

本クラスはデータソース用の様々なプロパティとメソッドを含んでおり、 DataIterator で利用されます。

パラメータ
  • shuffle (bool) -- データセットがシャッフルされるか否かを示します。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

property position

現在のエポックでのデータの位置。

戻り値

データの位置

戻り値の型

int

property shuffle

データセットがシャッフルされたか否か。

戻り値

データセットがシャッフルされた否か。

戻り値の型

bool

property variables

データの変数名。

戻り値

変数名のタプル

戻り値の型

tuple

class nnabla.utils.data_source.DataSourceWithFileCache(data_source, cache_dir=None, cache_file_name_prefix='cache', shuffle=False, rng=None)[ソース]

ベースクラス: nnabla.utils.data_source.DataSource

本クラスはキャッシュファイルから読み取ることができるデータソース用の様々なプロパティとメソッドを含んでおり、データのイテレーターで利用されます。

パラメータ
  • data_source (DataSource) -- データを提供する DataSource クラスのインスタンスです。

  • cache_dir (str) -- file_cache の場所。この値が None の場合、 data_source.DataSourceWithFileCache がファイルキャッシュを暗黙的に一時ディレクトリに作成し、data_iterator 終了時にすべて消去します。 そうでない場合は、 data_source.DataSourceWithFileCache がキャッシュファイルを生成し続けます。デフォルトは None です。

  • cache_file_name_prefix (str) -- キャッシュファイルのファイル名の先頭文字列です。デフォルトは 'cache' です。

  • shuffle (bool) -- データセットがシャッフルされるか否かを示します。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

property position

現在のエポックでのデータの位置。

戻り値

データの位置

戻り値の型

int

property shuffle

データセットがシャッフルされたか否か。

戻り値

データセットがシャッフルされた否か。

戻り値の型

bool

property variables

データの変数名。

戻り値

変数名のタプル

戻り値の型

tuple

class nnabla.utils.data_source.DataSourceWithMemoryCache(data_source, shuffle=False, rng=None)[ソース]

ベースクラス: nnabla.utils.data_source.DataSource

本クラスはメモリキャッシュから読み取ることができるデータソース用の様々なプロパティとメソッドを含んでおり、データのイテレーターで利用されます。

パラメータ
  • data_source (DataSource) -- データを提供する DataSource クラスのインスタンスです。

  • shuffle (bool) -- データセットがシャッフルされるか否かを示します。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

property position

現在のエポックでのデータの位置。

戻り値

データの位置

戻り値の型

int

property shuffle

データセットがシャッフルされたか否か。

戻り値

データセットがシャッフルされた否か。

戻り値の型

bool

property variables

データの変数名。

戻り値

変数名のタプル

戻り値の型

tuple

DataIterator
class nnabla.utils.data_iterator.DataIterator(data_source, batch_size, rng=None, use_thread=True, epoch_begin_callbacks=[], epoch_end_callbacks=[], stop_exhausted=False)[ソース]

ベースクラス: object

data_source からデータを収集し、大量のデータを生成します。

パラメータ
  • data_source (DataSource) -- 本クラスにデータを提供する DataSource クラスのインスタンスです。

  • batch_size (int) -- データユニットのサイズ。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

  • use_thread (bool) -- If use_thread is set to True, iterator will use another thread to fetch data. If use_thread is set to False, iterator will use current thread to fetch data.

  • epoch_begin_callbacks (list of functions) -- 1 つの項目が 1 つの関数であり、エポックインデックスを引数として取ります。これらはエポックの開始時に呼び出されます。

  • epoch_end_callbacks (list of functions) -- 1 つの項目が 1 つの関数であり、エポックインデックスを引数として取ります。これらはエポックの終了時に呼び出されます。

  • stop_exhausted (bool) -- If stop_exhausted is set to False, iterator will be reset so that iteration can be continued. If stop_exhausted is set to True, iterator will raise StopIteration to stop the loop.

property batch_size

next() が返す学習のサンプル数。

戻り値

学習のサンプル数

戻り値の型

int

property epoch

The number of times position() returns to zero.

戻り値

epoch

戻り値の型

int

next()[ソース]

データのタプルを生成します。

例えば、もし self._variables == ('x', 'y')() である場合、このメソッドは :py:meth:` ( [[X] * batch_size], [[Y] * batch_size] )` を返します。

戻り値

numpy.ndarray にあるミニバッチ用のデータのタプル

戻り値の型

tuple

property position

現在のエポックでのデータの位置。

戻り値

データの位置

戻り値の型

int

register_epoch_begin_callback(callback)[ソース]

エポック開始時のコールバックを登録します。

パラメータ

callback (function) -- 関数はエポックインデックスを引数として取ります。

register_epoch_end_callback(callback)[ソース]

エポック終了時のコールバックを登録します。

パラメータ

callback (function) -- 関数はエポックインデックスを引数として取ります。

property size

DataIterator が生成するデータサイズ。 self._data_source.size() を超えない batch_size の整数倍の最大値を表します。

戻り値

データサイズ

戻り値の型

int

slice(rng, num_of_slices=None, slice_pos=None, slice_start=None, slice_end=None, cache_dir=None, use_cache=False)[ソース]

データのイテレーターをスライスすることで、新しく生成されたデータのイテレーターが元データの限定部分へアクセスできるようになります。

パラメータ
  • rng (numpy.random.RandomState) -- Initializer の乱数ジェネレーター。

  • num_of_slices (int) -- 生成するスライスの合計数。slice_pos と共に使う必要があります。

  • slice_pos (int) -- 新しいデータのイテレーターに割り当てられたスライスの位置。 num_of_slices と共に使う必要があります。

  • slice_start (int) -- 新しいデータのイテレーターにスライスされる範囲の開始位置。 slice_end と共に使う必要があります。

  • slice_end (int) -- 新しいデータのイテレーターにスライスされる範囲の終了位置。 slice_start と共に使う必要があります。

  • cache_dir (str) -- Directory to save cache files. if cache_dir is None and use_cache is True, will used memory cache.

  • use_cache (bool) -- Whether use cache for data_source.

例:

from nnabla.utils.data_iterator import data_iterator_simple
import numpy as np

def load_func1(index):
    d = np.ones((2, 2)) * index
    return d

di = data_iterator_simple(load_func1, 1000, batch_size=3)

di_s1 = di.slice(None, num_of_slices=10, slice_pos=0)
di_s2 = di.slice(None, num_of_slices=10, slice_pos=1)

di_s3 = di.slice(None, slice_start=100, slice_end=200)
di_s4 = di.slice(None, slice_start=300, slice_end=400)
property variables

データの変数名。

戻り値

変数名のタプル

戻り値の型

tuple

ユーティリティ
nnabla.utils.data_iterator.data_iterator(data_source, batch_size, rng=None, use_thread=True, with_memory_cache=True, with_file_cache=False, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[], stop_exhausted=False)[ソース]

DataSource を使うための Helper メソッド。

データソースの簡単な実装のため、独自の DataSource と共に DataIterator を使うことができます。

例えば、

ds = YourOwnImplementationOfDataSource()
batch = data_iterator(ds, batch_size)
パラメータ
  • data_source (DataSource) -- データを提供する DataSource クラスのインスタンスです。

  • batch_size (int) -- バッチサイズ。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

  • use_thread (bool) -- If use_thread is set to True, iterator will use another thread to fetch data. If use_thread is set to False, iterator will use current thread to fetch data.

  • with_memory_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithMemoryCache を使用します。data_source がオンメモリデータを提供しない限り、この値を True に設定することを推奨します。 デフォルトは True です。

  • with_file_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithFileCache を使用します。data_source が遅い場合、このオプションを有効にすることをおすすめします。デフォルトは False です。

  • cache_dir (str) -- file_cache の場所。この値が None の場合、 data_source.DataSourceWithFileCache がファイルキャッシュを暗黙的に一時ディレクトリに作成し、data_iterator 終了時にすべて消去します。 そうでない場合は、 data_source.DataSourceWithFileCache がキャッシュファイルを生成し続けます。デフォルトは None です。

  • epoch_begin_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として取ります。これらはエポックの開始時に呼び出されます。

  • epoch_end_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として受取ります。これらはエポックの終了時に呼び出されます。

  • stop_exhausted (bool) -- If stop_exhausted is set to False, iterator will be reset so that iteration can be continued. If stop_exhausted is set to True, iterator will raise StopIteration to stop the loop.

戻り値

DataIterator のインタンス

戻り値の型

DataIterator

nnabla.utils.data_iterator.data_iterator_simple(load_func, num_examples, batch_size, shuffle=False, rng=None, use_thread=True, with_memory_cache=False, with_file_cache=False, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[], stop_exhausted=False)[ソース]

load_func に定義されている通り、ミニバッチデータをタプルとして 生成する ジェネレーターです。提供されたデータからのクエリーにより、随時、無制限にミニバッチを生成します。

パラメータ
  • load_func (function) -- 単一の引数 i 、読み込まれるデータセットの例のインデックスを取り、データのタプルを返します。どのインデックス i から呼ばれる場合も毎回同じ形状の配列のタプルを返す必要があります。

  • num_examples (int) -- データセットにある例の数を表します。この数に従ってインデックスのランダムシーケンスが生成されます。

  • batch_size (int) -- データユニットのサイズ。

  • shuffle (bool) -- データセットがシャッフルされたか否かを表します。デフォルトは False です。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

  • use_thread (bool) -- If use_thread is set to True, iterator will use another thread to fetch data. If use_thread is set to False, iterator will use current thread to fetch data.

  • with_memory_cache (bool) -- If True, use data_source.DataSourceWithMemoryCache to wrap data_source. It is a good idea to set this as true unless data_source provides on-memory data. Default value is False.

  • with_file_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithFileCache を使用します。data_source が遅い場合、このオプションを有効にすることをおすすめします。デフォルトは False です。

  • cache_dir (str) -- file_cache の場所。この値が None の場合、 data_source.DataSourceWithFileCache がファイルキャッシュを暗黙的に一時ディレクトリに作成し、data_iterator 終了時にすべて消去します。 そうでない場合は、 data_source.DataSourceWithFileCache がキャッシュファイルを生成し続けます。デフォルトは None です。

  • epoch_begin_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として取ります。これらはエポックの開始時に呼び出されます。

  • epoch_end_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として受取ります。これらはエポックの終了時に呼び出されます。

  • stop_exhausted (bool) -- If stop_exhausted is set to False, iterator will be reset so that iteration can be continued. If stop_exhausted is set to True, iterator will raise StopIteration to stop the loop.

戻り値

DataIterator のインタンス

戻り値の型

DataIterator

以下に画像と分類ラベルのデータセットを返す load_func の例を示します。

import numpy as np
from nnabla.utils.image_utils import imread
image_paths = load_image_paths()
labels = load_labels()
def my_load_func(i):
    '''
    Returns:
        image: c x h x w array
        label: 0-shape array
    '''
    img = imread(image_paths[i]).astype('float32')
    return np.rollaxis(img, 2), np.array(labels[i])
nnabla.utils.data_iterator.data_iterator_csv_dataset(uri, batch_size, shuffle=False, rng=None, use_thread=True, normalize=True, with_memory_cache=True, with_file_cache=True, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[], stop_exhausted=False)[ソース]

CSV ファイルで提供されたデータセットから直接データを取得します。

ローカルファイルシステムや http サーバー、Amazon AWS S3 ストレージ等に配置されたファイルを読み込むことができます。

例えば、

batch = data_iterator_csv_dataset('CSV_FILE.csv', batch_size, shuffle=True)
パラメータ
  • uri (str) -- CSV ファイルとなるデータセットの場所。

  • batch_size (int) -- データユニットのサイズ。

  • shuffle (bool) -- データセットがシャッフルされたか否かを表します。デフォルトは False です。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

  • use_thread (bool) -- If use_thread is set to True, iterator will use another thread to fetch data. If use_thread is set to False, iterator will use current thread to fetch data.

  • normalize (bool) -- True の場合、データにあるそれぞれのサンプルは 255 の係数で正規化されます。デフォルトは True です。

  • with_memory_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithMemoryCache を使用します。data_source がオンメモリデータを提供しない限り、この値を True に設定することを推奨します。 デフォルトは True です。

  • with_file_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithFileCache を使用します。data_source が遅い場合、このオプションを有効にすることをおすすめします。デフォルトは False です。

  • cache_dir (str) -- file_cache の場所。この値が None の場合、 data_source.DataSourceWithFileCache がファイルキャッシュを暗黙的に一時ディレクトリに作成し、data_iterator 終了時にすべて消去します。 そうでない場合は、 data_source.DataSourceWithFileCache がキャッシュファイルを生成し続けます。デフォルトは None です。

  • epoch_begin_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として取ります。これらはエポックの開始時に呼び出されます。

  • epoch_end_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として受取ります。これらはエポックの終了時に呼び出されます。

  • stop_exhausted (bool) -- If stop_exhausted is set to False, iterator will be reset so that iteration can be continued. If stop_exhausted is set to True, iterator will raise StopIteration to stop the loop.

戻り値

DataIterator のインタンス

戻り値の型

DataIterator

nnabla.utils.data_iterator.data_iterator_cache(uri, batch_size, shuffle=False, rng=None, use_thread=True, normalize=True, with_memory_cache=True, epoch_begin_callbacks=[], epoch_end_callbacks=[], stop_exhausted=False)[ソース]

キャッシュディレクトリーからデータを取得します。

ローカルファイルシステムからキャッシュファイルを読み込みます。

例えば、

batch = data_iterator_cache('CACHE_DIR', batch_size, shuffle=True)
パラメータ
  • uri (str) -- キャッシュファイルのあるディレクトリの場所。

  • batch_size (int) -- データユニットのサイズ。

  • shuffle (bool) -- データセットがシャッフルされたか否かを表します。デフォルトは False です。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

  • use_thread (bool) -- If use_thread is set to True, iterator will use another thread to fetch data. If use_thread is set to False, iterator will use current thread to fetch data.

  • normalize (bool) -- True の場合、データにあるそれぞれのサンプルは 255 の係数で正規化されます。デフォルトは True です。

  • with_memory_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithMemoryCache を使用します。data_source がオンメモリデータを提供しない限り、この値を True に設定することを推奨します。 デフォルトは True です。

  • epoch_begin_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として取ります。これらはエポックの開始時に呼び出されます。

  • epoch_end_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として受取ります。これらはエポックの終了時に呼び出されます。

  • stop_exhausted (bool) -- If stop_exhausted is set to False, iterator will be reset so that iteration can be continued. If stop_exhausted is set to True, iterator will raise StopIteration to stop the loop.

戻り値

DataIterator のインタンス

戻り値の型

DataIterator

nnabla.utils.data_iterator.data_iterator_concat_datasets(data_source_list, batch_size, shuffle=False, rng=None, use_thread=True, with_memory_cache=True, with_file_cache=False, cache_dir=None, epoch_begin_callbacks=[], epoch_end_callbacks=[], stop_exhausted=False)[ソース]

複数のデータセットからデータを取得します。

例えば、

batch = data_iterator_concat_datasets([DataSource0, DataSource1, ...], batch_size)
パラメータ
  • data_source_list (list of DataSource) -- データセットのリスト。

  • batch_size (int) -- データユニットのサイズ。

  • shuffle (bool) -- データセットがシャッフルされたか否かを表します。デフォルトは False です。

  • rng (None or numpy.random.RandomState) -- Numpy 乱数ジェネレーター。

  • use_thread (bool) -- If use_thread is set to True, iterator will use another thread to fetch data. If use_thread is set to False, iterator will use current thread to fetch data.

  • with_memory_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithMemoryCache を使用します。data_source がオンメモリデータを提供しない限り、この値を True に設定することを推奨します。 デフォルトは True です。

  • with_file_cache (bool) -- True の場合、 data_source をラップするため data_source.DataSourceWithFileCache を使用します。data_source が遅い場合、このオプションを有効にすることをおすすめします。デフォルトは False です。

  • cache_dir (str) -- file_cache の場所。この値が None の場合、 data_source.DataSourceWithFileCache がファイルキャッシュを暗黙的に一時ディレクトリに作成し、data_iterator 終了時にすべて消去します。 そうでない場合は、 data_source.DataSourceWithFileCache がキャッシュファイルを生成し続けます。デフォルトは None です。

  • epoch_begin_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として取ります。これらはエポックの開始時に呼び出されます。

  • epoch_end_callbacks (list of functions) -- 1 つの項目が 1 つの関数となり、エポックインデックスを引数として受取ります。これらはエポックの終了時に呼び出されます。

  • stop_exhausted (bool) -- If stop_exhausted is set to False, iterator will be reset so that iteration can be continued. If stop_exhausted is set to True, iterator will raise StopIteration to stop the loop.

戻り値

DataIterator のインタンス

戻り値の型

DataIterator

Debug Utils
Graph Profiler
class nnabla.utils.profiler.GraphProfiler(graph, device_id, ext_name, solver=None, n_run=100, max_measure_execution_time=1, time_scale='m', backward_accum=False)[ソース]

ネットワークに含まれるそれぞれの関数の計算時間を計測するためのクラスです。

以下の項目について、実行時間を計測することができます。

  • 関数ごとのforward演算実行速度

  • 関数ごとのbackward演算実行速度

  • グラフ全体のforward演算実行速度

  • グラフ全体のbackward演算実行速度

  • 学習実行速度 ( forward + backward + update演算実行にかかる合計時間) ( solver が None でない場合)

例:

import nnabla as nn
import nnabla.functions as F
import nnabla.solvers as S
from nnabla.utils.profiler import GraphProfiler

# Set up nnabla context
device = "cpu"  # you can also use GPU ("cudnn")
ctx = get_extension_context(device)
nn.set_default_context(ctx)

# Network building
x = nn.Variable(shape=...)
t = nn.Variable(shape=...)
y = CNN(x) # you can build not only CNN but any networks
loss = F.mean(F.softmax_cross_entropy(y, t)) # any loss functions or variables can be used

# solver setting
solver = S.Sgd()
solver.set_parameters(nn.get_parameters())

# SOME CODE (data loading or so on)

B = GraphProfiler(loss, solver=solver, device_id=0, ext_name=device, n_run=1000)
B.run()
パラメータ
  • graph (nnabla.Variable) -- nnabla.Variable インスタンス。 GraphProfiler は、ルートとなる nnabla.Variable からこの 引数として与えられた nnabla.Variable までに含まれるすべての関数の実行時間を計測します。

  • device_id (str) -- GPU デバイスID。

  • ext_name (str) -- nnablaのctxとして指定できるコンテキスト名。指定されたctx下での実行速度が計測されます。例: ‘cpu’, ‘cuda’, ‘cudnn’ など。

  • solver (nnabla.solvers.Solver) -- nnabla.solvers.Solver のインスタンス。None が与えられた場合には、学習プロセスは計測されません。デフォルトは None です。

  • n_run (int) -- それぞれの関数に対して実行時間を計測する回数。デフォルトは 100 です。

  • max_measure_execution_time (float) -- それぞれの関数の実行時間を計測する最大の時間。この引数は n_run よりも優先されます。すなわち、それぞれの関数での計測時間がこの引数より大きくなる場合、計測した回数が n_run 未満であっても、現在の関数に対する計測を中止して次の関数に進みます。デフォルトは 1 [sec] です。

  • time_scale (str) -- 表示する時間スケール。[‘m’, ‘u’, ‘n’] (それぞれ ‘ミリ’, ‘マイクロ’, ‘ナノ’ の略記号 )

  • backward_accum (bool) -- Accumulation flag passed to the each backward function. The flag will fulfill the all accumulation flags with the same value of backward_accum. This flag is only valid for the time measurement of each function. For whole graph comutation, the NNabla graph engine set the appropriate accumulation flags to functions. Pay attention to inplace flag for your graph because accumulation and inplace flags cannot be set at the same time. If even one inplace flag is true in your graph, this backward_accum must be false. Default value is False.

run()[ソース]

プロファイリングを実行します。

以下の5つの項目についての実行時間を計測します。

  • 関数ごとのforward演算実行速度

  • 関数ごとのbackward演算実行速度

  • グラフ全体のforward演算実行速度

  • グラフ全体のbackward演算実行速度

  • 学習実行速度 ( forward + backward + update演算実行にかかる合計時間) ( solver が None でない場合)

class nnabla.utils.profiler.GraphProfilerCsvWriter(gb, file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>)[ソース]

GraphProfiler によって計測した時間をcsvファイルとして書き出すためのクラスです。

例:

from nnabla.utils.profiler import GraphProfiler, GraphProfilerCsvWriter

# Network building comes above

B = GraphProfiler(variable, solver=solver, device_id=0, ext_name=device, n_run=1000)
B.run()

with open("./profile.csv", "w") as f:
    writer = GraphProfilerCsvWriter(B, file=f)
    writer.write()
パラメータ
  • gb (GraphProfiler) -- GraphProfiler クラスのインスタンス。

  • file (Python file object) -- 出力ファイルオブジェクト。この引数で指定されたファイルにプロファイリングの結果を書き込みます。

write()[ソース]

指定された file に計測結果を出力します。

Time Profiler
class nnabla.utils.inspection.profile.TimeProfiler(ext_name, device_id)[ソース]

An utility API to create function_hook callbacks to profile the execution time of each function. Passing ext_name and device_id, you can define which device time you want to profile. If ext_name = "cuda" or "cudnn", then cudaEvent will be used to measure the execution time. For more information about cudaEvent, see the CUDA document. If `ext_name`="cpu" , then wall-clock-time on host will be used.

例:

ext_name = "cpu"
device_id = "0"

from nnabla.ext_utils import get_extension_context
ctx = get_extension_context(ext_name, device_id=device_id)
nn.set_default_context(ctx)

y = model(...)

from nnabla.utils.inspection import TimeProfiler
tp = TimeProfiler(ext_name=ext_name, device_id=device_id)

for i in range(max_iter):
    # All results of executions under "forward" scope are registered as "forward" execution.
    with tp.scope("forward"):
        y.forward(function_pre_hook=tp.pre_hook, function_post_hook=tp.post_hook)

    # All results of executions under "backward" scope are registered as "backward" execution.
    with tp.scope("backward") as tp:
        y.backward(function_pre_hook=tp.pre_hook, function_post_hook=tp.post_hook)

    # All results are evaluated by passing scopes to .calc_elapsed_time().
    # Be sure to call calc_elapsed_time at each iteration, otherwise nothing is measured.
    tp.calc_elapsed_time(["forward", "backward", "summary"])

# To output results on stdout, call instance as a function.
tp()

# To write out as csv file, call .to_csv().
tp.to_csv(output_file_name)
calc_elapsed_time(names=None)[ソース]

Evaluate all elapsed times. Note that elapsed time is not recorded until calc_elapsed_time is called.

パラメータ

names (str or list of str) -- Scope name(s) to evaluate elapsed time.

property post_hook

Get a callback for function_post_hook. This function can be used like the example below:

tp = TimeProfiler(..)
with tp.scope("forward"):
    v.forward(function_post_hook=tp.post_hook())

with tp.scope("backward"):
    v.backward(function_post_hook=tp.post_hook())
property pre_hook

Get a callback for function_pre_hook. This function can be used like the example below:

tp = TimeProfiler(..)
with tp.scope("forward"):
    v.forward(function_pre_hook=tp.pre_hook())

with tp.scope("backward"):
    v.backward(function_pre_hook=tp.pre_hook())
scope(scope_name)[ソース]

Change a scope to aggregate results. This function is used as context (The with statement statement),

and all results under the context are labeled by scope_name.

In adttion to the execution time of each function, the elapsed times between entering and exiting the each context are also recorded

and they are aggregated as "summary" scope.

パラメータ

scope_name (str) -- Scope name.

to_csv(out_dir='./', ignore_init=True)[ソース]

Writes out to csv file. Output directory can be specified by out_dir. As default, the elapsed times of first iteration will be omitted. If you evaluate the first iteration as well, pass True to ignore_init.

パラメータ
  • out_dir (str) -- Output directory.

  • ignore_init (bool) -- Ignore the result of the first iteration or not.

Nan/Inf Tracer
class nnabla.utils.inspection.value_trace.NanInfTracer(trace_nan=True, trace_inf=True, need_details=True)[ソース]

An utility API to create function_hook callbacks to check whether the outputs of all layers have NaN or inf as their values. During forward and backward execution, passed as function_hook, this API reports ValueError if at least one of all layer outputs has Nan or inf as its values. Otherwise, all tensors passed to next layer or function as is.

例:

pred = model(...)

from nnabla.utils.inspection import NanInfTracer
nit = NanInfTracer(trace_inf=True, trace_nan=True, need_details=True)

with nit.trace():
    pred.forward(function_post_hook=nit.forward_post_hook)
    pred.backward(function_post_hook=nit.backward_post_hook)
property backward_post_hook

Create callback function object which can be used as a function_post_hook argument of backward().

check()[ソース]

Checks nan/inf existence at all outputs of all layers and raises ValueError only if exist.

property forward_post_hook

Create callback function object which can be used as a function_post_hook argument of forward().

trace()[ソース]

Create context manager to check nan/inf existence by using with statement. Using this context manager, checking nan/inf is performed automatically just before exiting with scope. Unless you use this context manager, be sure to call .check() explicitly to check nan/inf.

例:

nit = NanInfTracer()
with nit.trace():
    pred.forward(function_post_hook=nit.forward_post_hook)
    pred.backward(function_post_hook=nit.backward_post_hook)
Pretty Printer
class nnabla.utils.inspection.pretty_print.PrettyPrinter(summary=False, hidden=False)[ソース]

Pretty printer to print the graph structure used with the visit method of a Variable.

functions

List of functions of which element is the dictionary. The (key, value) pair is the (name, function name), (inputs, list of input variables), and (outputs, list of output variables) of a function.

Type

list of dict

nnabla.utils.inspection.pretty_print.pprint(v, forward=False, backward=False, summary=False, hidden=False, printer=False)[ソース]

Pretty print information of a graph from a root variable v.

Note that in order to print the summary statistics, this function stores, i.e., does not reuse the intermediate buffers of a computation graph, increasing the memory usage if either the forward or backward is True.

パラメータ
  • v (nnabla.Variable) -- Root variable.

  • forward (bool) -- Call the forward method of a variable v.

  • backward (bool) -- Call the backward method of a variable v.

  • summary (bool) -- Print statictis of a intermediate variable.

  • hidden (bool) -- Store the intermediate input and output variables if True.

  • printer (bool) -- Return the printer object if True.

例:

pred = Model(...)

from nnabla.utils.inspection import pprint

pprint(pred, summary=True, forward=True, backward=True)
DLPack

Via a DLPack capsule, you can borrow a tensor from external software as a nnabla.NdArray and can share a NdArray to external software.

nnabla.utils.dlpack.from_dlpack(dlp, arr=None)

Decode a DLPack to NdArray.

Example:

# Create a tensor of an external tool, and encode as an DLPack.
import torch
from torch.utils.dlpack import to_dlpack
t = torch.ones((5, 5), dtype=torch.float32,
               device=torch.device('cuda'))
dlp = to_dlpack(t)

# Borrow the DLPack tensor as nnabla.NdArray
from nnabla.utils.dlpack import from_dlpack
arr = from_dlpack(dlp)

If you want to move an ownership of DLPack to an exiting NdArray;

from nnabla import NdArray
arr = NdArray()
from_dlpack(dlp, arr=arr)
パラメータ
  • dlp (PyCapsule) -- A PyCapsule object of a DLManagedTensor (as "dltensor") which internal memory is borrowed by a tensor of an external package. The ownership of the DLManagedTensor is moved to an NdArray object, and the PyCapsule object is marked as "used_dltensor" to inform that the ownership has been moved.

  • arr (NdArray) -- If specified, a given DLPack is decoded to it. Otherwise, it creates a new NdArray object and decodes the DLPack to it.

戻り値

an NdArray object borrowing the DLPack tensor.

戻り値の型

NdArray

nnabla.utils.dlpack.to_dlpack(a, dtype=None, ctx=None)

Returns a DLPack which owns an internal array object borrowed by a specified NdArray.

Example:

# Create a nnabla.NdArray in CUDA.
import nnabla as nn
from nnabla.ext_utils import get_extension_context
ctx = get_extension_context('cudnn')
nn.set_default_context(ctx)

a = nn.NdArray.from_numpy_array(np.ones((5, 5), dtype=np.float32))
a.cast(np.float32, ctx)

# Expose as a DLPack.
from nnabla.utils.dlpack import to_dlpack
dlp = to_dlpack(a)

# Use the DLPack in PyTorch.
import torch
from torch.utils.dlpack import from_dlpack
t = from_dlpack(dlp)

# Changing the values in Torch will also be affected in nnabla
# because they share memory.
t.add_(1)
print(a.data)  # All values become 2.
パラメータ
  • a (NdArray) -- An NdArray object. An internal array which is recently modified or created will be encoded into a DLPack.

  • dtype (numpy.dtype) -- If specified, in-place cast operation may be performed before encoding it to a DLPack.

  • ctx (Context) -- If specified, in-place device transfer operation may be performed before encoding it into a DLPack.

戻り値

A PyCapsule object of a DLManagedTensor (as "dltensor") which internal memory is borrowed by the specified NdArray.

戻り値の型

PyCapsule

RNN Utils
class nnabla.utils.rnn.PackedSequence[ソース]
パラメータ
  • data (nnabla.Variable) -- Packed sequence.

  • batch_sizes (nnabla.Variable) -- Batch size for each time step and always resides in CPU.

  • sorted_indices (nnabla.Variable) -- Sorted indices to reconstruct the original sequences.

  • unsorted_indices (nnabla.Variable) -- Unsorted indices to reconstruct the original sequences.

nnabla.utils.rnn.pad_sequence(sequences, batch_first=False, padding_value=0.0)[ソース]

Pad a list of variable-length Variables.

This method stacks a list of variable-length nnabla.Variable s with the padding_value.

\(T_i\) is the length of the \(i\)-th Variable in the sequences. \(B\) is the batch size equal to the length of the sequences. \(T\) is the max of \(T_i\) for all \(i\). \(*\) is the remaining dimensions including none.

注釈

This function must be used the dynamic computation mode.

Example:

import numpy as np
import nnabla as nn
import nnabla.functions as F
import nnabla.utils.rnn as rnn_utils

nn.set_auto_forward(True)

l2v = lambda ldata: nn.Variable.from_numpy_array(np.asarray(ldata))
a = l2v([1, 1, 1, 1])
b = l2v([2, 2, 2])
c = l2v([2, 2, 2])
d = l2v([3, 3])
e = l2v([3, 3])
sequences = [a, b, c, d, e]

padded_sequence = rnn_utils.pad_sequence(sequences)
print(padded_sequence.d)
パラメータ
  • sequences (list of nnabla.Variable) -- Sequence of the variable of (\(T_i\), \(*\)) shape.

  • batch_first (bool) -- If False, output is of (\(T\), \(B\), \(*\)) shape, otherwise (\(B\), \(T\), \(*\)).

  • padding_value (float) -- Padding value.

戻り値

nnabla.Variable of (\(T\), \(B\), \(*\)) or (\(B\), \(T\), \(*\)) shape

nnabla.utils.rnn.pack_padded_sequence(padded_sequence, lengths, batch_first=False, enforce_sorted=True)[ソース]

Pack a padded variable-length sequences.

This method packs a padded variable-length sequences.

\(T\) is the max length over the lengths of sequences. \(B\) is the batch size equal to the length of the sequences. \(*\) is the remaining dimensions including none.

注釈

This function must be used the dynamic computation mode.

Example:

import numpy as np
import nnabla as nn
import nnabla.functions as F
import nnabla.utils.rnn as rnn_utils

nn.set_auto_forward(True)

l2v = lambda ldata: nn.Variable.from_numpy_array(np.asarray(ldata))
a = l2v([1, 1, 1, 1])
b = l2v([2, 2, 2])
c = l2v([2, 2, 2])
d = l2v([3, 3])
e = l2v([3, 3])
sequences = [a, b, c, d, e]
lengths = l2v([seq.shape[0] for seq in sequences])

padded_sequence = rnn_utils.pad_sequence(sequences)
print(padded_sequence.d)

packed_sequence = rnn_utils.pack_padded_sequence(padded_sequence, lengths)
print(packed_sequence.data.d)
print(packed_sequence.batch_sizes.d)
パラメータ
  • padded_sequence (nnabla.Variable) -- Padded sequence of (\(T \times B \times *\)) or (\(B \times T \times *\)) shape.

  • lengths (nnabla.Variable) -- Sequence length for each batch and always resides in CPU.

  • batch_first (bool) -- padded_sequence is of (\(T\), \(B\), \(*\)) shape if False, otherwise (\(B\), \(T\), \(*\)).

  • enforce_sorted (bool) -- Sequences are sorted by the length in a decreasing order if True. Default is True.

戻り値

PackedSequence

nnabla.utils.rnn.pack_sequence(sequences, batch_first=False, enforce_sorted=True)[ソース]

Pack a list of variable-length Variables.

This method packs a list of variable-length Variables.

\(T_i\) is the length of the \(i\)-th Variable in the sequences. \(T\) is the max of \(T_i\) for all \(i\). \(B\) is the batch size equal to the length of the sequences. \(*\) is the remaining dimensions including none.

注釈

This function must be used the dynamic computation mode.

Example:

import numpy as np
import nnabla as nn
import nnabla.functions as F
import nnabla.utils.rnn as rnn_utils

nn.set_auto_forward(True)

l2v = lambda ldata: nn.Variable.from_numpy_array(np.asarray(ldata))
a = l2v([3, 3])
b = l2v([2, 2, 2])
c = l2v([2, 2, 2])
d = l2v([1, 1, 1, 1])
e = l2v([3, 3])
sequences = [a, b, c, d, e]

packed_sequence = rnn_utils.pack_sequence(sequences, enforce_sorted=False)
print(packed_sequence.data.d)
print(packed_sequence.batch_sizes.d)
パラメータ
  • sequences (list of nnabla.Variable) -- List of nnabla.Variable of (\(T_i\), \(*\)) shape.

  • enforce_sorted (bool) -- Sequences are sorted by the length in a decreasing order if True. Default is True.

戻り値

packed_sequence

戻り値の型

PackedSequence

nnabla.utils.rnn.pad_packed_sequence(sequence, batch_first=False, padding_value=0.0, total_length=None)[ソース]

Pad packed sequence.

This method unpacks the packed sequqnce and pad it, the inverse operation of pack_padded_sequence().

\(T_i\) is the length of the \(i\)-th Variable in the sequences. \(B\) is the batch size equal to the length of the sequences. \(T\) is the max of \(T_i\) for all \(i\). \(*\) is the remaining dimensions including none.

注釈

This function must be used the dynamic computation mode.

Example:

import numpy as np
import nnabla as nn
import nnabla.functions as F
import nnabla.utils.rnn as rnn_utils

nn.set_auto_forward(True)

l2v = lambda ldata: nn.Variable.from_numpy_array(np.asarray(ldata))
a = l2v([3, 3])
b = l2v([2, 2, 2])
c = l2v([2, 2, 2])
d = l2v([1, 1, 1, 1])
e = l2v([3, 3])
sequences = [a, b, c, d, e]

packed_sequence = rnn_utils.pack_sequence(sequences, enforce_sorted=False)
print(packed_sequence.data.d)
print(packed_sequence.batch_sizes.d)

padded_sequence, lengths = rnn_utils.pad_packed_sequence(packed_sequence)
print(padded_sequence.d)
print(lengths.d)
パラメータ
  • sequence (PackedSequence) -- PackedSequence.

  • batch_first (bool) -- If False, output is of (\(T\), \(B\), \(*\)) shape, otherwise (\(B\), \(T\), \(*\)).

  • padding_value (float) -- Padding value.

  • total_length (int) -- If not None, the outputs are padded up to the total_length. If the total_length is less than the max length in the sequences, the error is thrown. This is normally used in the distributed training to align with the longest sequence in a distributed system.

戻り値

nnabla.Variable of (\(T\), \(B\), \(*\)) or (\(B\), \(T\), \(*\)) shape

その他
Python 関数のプロファイラーユーティリティ
nnabla.utils.function_profile.profile(fn=None, condition=None, profile_class=<class 'cProfile.Profile'>, print_freq=0, sort_keys=None, print_restrictions=None)[ソース]

cProfile.Profile のように、Python プロファイラーでプロファイリングされた関数をデコレートします。

注意: ここでの 関数Function を指しません。Python 関数です。

パラメータ
  • fn (function) -- プロファイリングされた関数。None (デフォルト) が指定された場合、新しいデコレーター関数が戻ります。本デコレーター関数のオプション引数を指定したい場合に使用します。

  • condition (function) -- デコレートした関数と同じ入力を受け取り、ブール値を返す関数オブジェクト。 condition 関数が True を返したときのみデコレートした関数がプロファイリングされます。デフォルトでは、常に True を返すため、デコレートした関数を呼び出す度にプロファイリングが実行されます。

  • profile_class (class) -- cProfile.ProfileProfile.Profile のようなプロファイラークラス。デフォルトは cProfile.Profile です。

  • print_freq (int) -- プロファイリング結果は、 print_freq で指定された時間間隔での関数呼び出しで出力されます。 0 (デフォルト) が指定された場合、プロファイリング結果は、 decorated_func.profiler.print_stats() が手動で呼び出されない限り、Python プロセスの最後部のみに出力されます。

  • sort_keys (iterable) -- pstats.Stats.sort_stats() に引数として受け渡す、リストまたは文字列のタプル。デフォルトは ('cumulative', 'time', 'calls')

  • print_restriction (iterable) -- pstats.Stats.print_stats() に引数として受け渡す、リストまたは文字列のタプル。デフォルトは``(40,)`` で、デコレートした関数内のうち 40 の関数がプロファイリング結果に出力されます。

戻り値: function

デコレート関数。 fnNone の場合、オプション引数付きの新しいデコレーター関数が指定されます。

サンプル

次のように関数をデコレートすると、プロファイリング結果は Python プロセスの最後部に出力されます。

from nnabla.utils import function_profile

@function_profile.profile
def foo(a, b, c=None, d=None):
    ...

これまでのプロファイリング結果を手動で出力するには、 profiler 属性としてデコレートした関数にアタッチされた FunctionProfile オブジェクトの FunctionProfile.print_stats() をご使用ください。

foo.profiler.print_stats()

特定の引数が受け渡されたときにのみ関数をプロファイリングする場合、次のように condition 引数を使用してください。

def profile_only_if_c_is_not_none(a, b, c=None, d=None):
    return c is not None

@function_profile.profile(condition=profile_only_if_c_is_not_none)
def foo(a, b, c=None, d=None):
    ...
class nnabla.utils.function_profile.FunctionProfile(fn, condition=None, profile_class=<class 'cProfile.Profile'>, print_freq=0, sort_keys=None, print_restrictions=None)[ソース]

関数プロファイラーオブジェクト

通常、ユーザーが直接使うことはありません。 profile() の実行を通じて生成され、属性 profiler ーとしてデコレートした関数にアタッチされます。詳しくは profile 関数をご覧ください。

print_stats(reset=True)[ソース]

手動でプロファインリング結果を出力します。

パラメータ

reset (bool) -- False が指定された場合、これまでのプロファイリング統計が維持されます。 True (デフォルト) の場合、 reset_stats を呼び出してプロファイリング統計をリセットします。

reset_stats()[ソース]

これまでのプロファイリング統計を手動でリセットします。

Extension

NNabla offers easy extensibility for developers to add new device extensions. The NNabla Python package officially supports the cpu, cuda and cudnn extension, cuda and cudnn extension can dramatically accelerate computation by leveraging NVIDIA CUDA GPUs with cuDNN computation primitives.

以下のように手動でExtensionをインポートできます:

import nnabla_ext.cudnn

See :ref:`python-package-installation` to install the CUDA extension.
Extensionユーティリティ

NNabla Extensionのためのユーティリティ。

nnabla.ext_utils.list_extensions()[ソース]

利用可能なExtensionをリストアップします。

注釈

名前空間パッケージのディレクトリ構成に依存しているため、あるプラットフォームや環境によっては正しく動作しない可能性があります。

戻り値: str のリスト

利用可能なExtension名のリスト。

nnabla.ext_utils.import_extension_module(ext_name)[ソース]

Extensionモジュールの名称でインポートします。

Extensionモジュールは、 nnabla_ext パッケージの下に名前空間パッケージとしてインストールされます。 すべてのExtensionモジュールは、統一した API セットを提供します。

パラメータ

ext_name (str) -- Extension名。例: ‘cpu’, ‘cuda’, ‘cudnn’ 等。

戻り値: module

特定の NNabla Extensionの Python モジュール。

サンプル

ext = import_extension_module('cudnn')
available_devices = ext.get_devices()
print(available_devices)
ext.device_synchronize(available_devices[0])
ext.clear_memory_cache()
nnabla.ext_utils.get_extension_context(ext_name, **kw)[ソース]

指定されたExtensionのContextを取得します。

すべてのExtensionモジュールは context(**kw) 関数を提供する必要があります。

パラメータ
  • ext_name (str) -- nnabla_ext への相対的なモジュールパス

  • kw (dict) -- Extensionモジュールにあるcontext関数への追加のキーワード引数。

戻り値

現在のExtensionのcontext

戻り値の型

nnabla.Context

サンプル

ctx = get_extension_context('cudnn', device_id='0', type_config='half')
nn.set_default_context(ctx)
Extensionモジュールの API

すべてのExtensionモジュールは以下の関数を持つ必要があります。

nnabla.ext_utils.context(*kw)

Extensionモジュールのデフォルトのcontext記述子を返します。本メソッドはExtensionによって異なるオプションとなる引数を取りえます。例えば、 cudnn Extensionでは、計算処理を実行する GPU を指定するため int として device_id を取ります。

nnabla.ext_utils.device_synchronize(*kw)

ホストスレッドに対してデバイス実行ストリームを同期するために本メソッドを使います。例えば CUDA では、カーネル実行をストリームのキューに追加し、ホストスレッドとは非同期に実行します。本関数は、そのような機能を使うデバイス内でのみ有効です。CPU 実装では、本メソッドはダミー関数として実装され、そのため本関数を呼び出しても無視されます。 cudnn Extensionにある本関数は、オプションの引数として device_id を取りますが、これによって同期させたいデバイスを指定できます。

学習済みモデル

nnabla.models パッケージで提供される API を使うことで、推論や数行のコードによる学習のための最先端の学習済みモデルを実行できます。

ImageNet モデル

このサブパッケージは、ImageNet データセットで学習された様々な最先端の学習済みモデルを提供します。

学習済みモデルは、以下のようにして推論や学習に用いることができます。

# Create ResNet-50 for inference
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import numpy as np
from nnabla.models.imagenet import ResNet50
model = ResNet50()
batch_size = 1
# model.input_shape returns (3, 224, 224) when ResNet-50
x = nn.Variable((batch_size,) + model.input_shape)
y = model(x, training=False)

# Execute inference
# Load input image as uint8 array with shape of (3, 224, 224)
from nnabla.utils.image_utils import imread
img = imread('example.jpg', size=model.input_shape[1:], channel_first=True)
x.d[0] = img
y.forward()
predicted_label = np.argmax(y.d[0])
print('Predicted label:', model.category_names[predicted_label])


# Create ResNet-50 for fine-tuning
batch_size=32
x = nn.Variable((batch_size,) + model.input_shape)
# * By training=True, it sets batch normalization mode for training
#   and gives trainable attributes to parameters.
# * By use_up_to='pool', it creats a network up to the output of
#   the final global average pooling.
pool = model(x, training=True, use_up_to='pool')

# Add a classification layer for another 10 category dataset
# and loss function
num_classes = 10
y = PF.affine(pool, num_classes, name='classifier10')
t = nn.Variable((batch_size, 1))
loss = F.sum(F.softmax_cross_entropy(y, t))

# Training...

利用可能なモデルを次の表にまとめます。エラー率は single center crop を用いて算出しています。

利用可能な ImageNet モデル

名前

クラス

Top-1 エラー

Top-5 エラー

学習手法

ResNet-18

ResNet18

30.28

10.90

Neural Network Console

ResNet-34

ResNet34

26.72

8.89

Neural Network Console

ResNet-50

ResNet50

24.59

7.48

Neural Network Console

ResNet-101

ResNet101

23.81

7.01

Neural Network Console

ResNet-152

ResNet152

23.48

7.09

Neural Network Console

MobileNet

MobileNet

29.51

10.34

Neural Network Console

MobileNetV2

MobileNetV2

29.94

10.82

Neural Network Console

SENet-154

SENet

22.04

6.29

Neural Network Console

SqueezeNet v1.0

SqueezeNetV10

42.71

20.12

Neural Network Console

SqueezeNet v1.1

SqueezeNetV11

41.23

19.18

Neural Network Console

VGG-11

VGG11

30.85

11.38

Neural Network Console

VGG-13

VGG13

29.51

10.46

Neural Network Console

VGG-16

VGG16

29.03

10.07

Neural Network Console

NIN

NIN

42.91

20.66

Neural Network Console

DenseNet-161

DenseNet

23.82

7.02

Neural Network Console

InceptionV3

InceptionV3

21.82

5.88

Neural Network Console

Xception

Xception

23.59

6.91

Neural Network Console

GoogLeNet

GoogLeNet

31.22

11.34

Neural Network Console

ResNeXt-50

ResNeXt50

22.95

6.73

Neural Network Console

ResNeXt-101

ResNeXt101

22.80

6.74

Neural Network Console

ShuffleNet

ShuffleNet10

34.15

13.85

Neural Network Console

ShuffleNet-0.5x

ShuffleNet05

41.99

19.64

Neural Network Console

ShuffleNet-2.0x

ShuffleNet20

30.34

11.12

Neural Network Console

共通インターフェイス
class nnabla.models.imagenet.base.ImageNetBase[ソース]

ほとんどの ImageNet 学習済みモデルは、このクラスから継承され、いくつかの共通インターフェイスを提供します。

__call__(input_var=None, use_from=None, use_up_to='classifier', training=False, force_global_pooling=False, check_global_pooling=True, returns_net=False, verbose=0)[ソース]

読み込んだモデルからネットワーク (計算グラフ) を生成します。

パラメータ
  • input_var (Variable, optional) -- 指定された場合、入力Variableは指定されたVariableに置き換えられ、そのVariable上にネットワークが構築されます。特に指定がない場合は、バッチサイズを1としたVariable、 self.input_shape を元にしたデフォルトのShapeとなります。

  • use_up_to (str) -- ネットワークは文字列で指定したVariableまで構築されます。モデルに対応したVariableの文字列のリストは、各モデルクラスのドキュメントに記載されています。

  • training (bool) -- このオプションは、構築されたネットワークの追加学習 (ファインチューニング、転移学習など) を有効にします。True の場合、batch normalization の batch_stat オプションが True になり、学習可能なVariable (conv weights および bn のガンマとベータなど) の need_grad 属性が True になります。 デフォルトは False です。

  • force_global_pooling (bool) -- 入力画像のサイズに関わらず、分類層の前の最終 average pooling は、自動的に global average pooling に変換されます。デフォルトは False です。

  • check_global_pooling (bool) -- True かつ最終 average pooling のストライド設定が global pooling を目的としない場合、例外を発生させます。デフォルトは True です。入力空間サイズに関わらず、 (7, 7) などの学習時のストライド で pooling を実行したい場合、 False を指定してください。

  • returns_net (bool) -- True の場合、 NnpNetwork オブジェクトを返します。それ以外の場合は、単に構築したネットワークの最後のVariableを返します。デフォルトは False です。

  • verbose (bool, or int) -- Verbose レベル。 0 に設定した場合、ネットワーク構築中は何も出力しません。

property category_names

1000 の ImageNet クラスのカテゴリー名を返します。

property input_shape

デフォルトの画像サイズを、 (チャネル、高さ、幅) のタプルとして返します。

モデルのリスト
class nnabla.models.imagenet.ResNet18[ソース]

ResNet (18) のエイリアス。

class nnabla.models.imagenet.ResNet34[ソース]

ResNet (34) のエイリアス。

class nnabla.models.imagenet.ResNet50[ソース]

ResNet (50) のエイリアス。

class nnabla.models.imagenet.ResNet101[ソース]

ResNet (101) のエイリアス。

class nnabla.models.imagenet.ResNet152[ソース]

ResNet (152) のエイリアス。

class nnabla.models.imagenet.ResNet(num_layers=18)[ソース]

18、34、50、101、152 層用の ResNet アーキテクチャ。

パラメータ

num_layers (int) -- 層数 (18、34、50、101、152 のいずれかの値)

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.MobileNet[ソース]

MobileNet アーキテクチャ。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.MobileNetV2[ソース]

MobileNetV2 アーキテクチャ。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.SENet[ソース]

改良された ResNeXt アーキテクチャに SE ブロックを統合する SENet-154 モデル。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.SqueezeNetV10[ソース]

SquezeNetV10 SqueezeNet ('v1.0') のエイリアス。

class nnabla.models.imagenet.SqueezeNetV11[ソース]

SquezeNetV11 SqueezeNet ('v1.1') のエイリアス。

class nnabla.models.imagenet.SqueezeNet(version='v1.1')[ソース]

アーキテクチャ v1.0 および v1.1 のための SqueezeNet モデル。

パラメータ

version (str) -- バージョン ('v1.0' または 'v1.1')

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.VGG11[ソース]

VGG (11) のエイリアス。

class nnabla.models.imagenet.VGG13[ソース]

VGG (13) のエイリアス。

class nnabla.models.imagenet.VGG16[ソース]

VGG (16) のエイリアス。

class nnabla.models.imagenet.VGG(num_layers=11)[ソース]

11, 13, 16 層用の VGG アーキテクチャ。

パラメータ

num_layers (int) -- 層の数 (11、13、16 のいずれかの数)

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

  • 'lastfeature': 活性化を除く、 'classifier' 直前の層までのネットワーク。

参照

class nnabla.models.imagenet.NIN[ソース]

NIN (Network In Network) アーキテクチャ。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.DenseNet[ソース]

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : 最後の denseblock からの出力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.InceptionV3[ソース]

InceptionV3 アーキテクチャ。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 最終 global average pooling の入力。すなわち、最終インセプションブロックの出力。

参照

class nnabla.models.imagenet.Xception[ソース]

Xception モデル。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.GoogLeNet[ソース]

GoogLeNet モデル。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 最終 global average pooling の入力。すなわち、最終インセプションブロックの出力。

参照

class nnabla.models.imagenet.ResNeXt50[ソース]

ResNeXt (50) のエイリアス。

class nnabla.models.imagenet.ResNeXt101[ソース]

ResNeXt (101) のエイリアス。

class nnabla.models.imagenet.ResNeXt(num_layers=50)[ソース]

50 と 101 層用の ResNeXt アーキテクチャ。

パラメータ

num_layers (int) -- 層の数 (50、101 のいずれかの数)

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

class nnabla.models.imagenet.ShuffleNet10[ソース]

ShuffleNet (10) のエイリアス。

class nnabla.models.imagenet.ShuffleNet05[ソース]

ShuffleNet (5) のエイリアス。

class nnabla.models.imagenet.ShuffleNet20[ソース]

ShuffleNet (20) のエイリアス。

class nnabla.models.imagenet.ShuffleNet(scaling_factor=10)[ソース]

ShuffleNet、 ShuffleNet-0.5x、ShufffleNet-2.0x アーキテクチャ用のモデル。

パラメータ

Factor (Scaling) -- ネットワークを希望の複雑さにカスタマイズするには、チャネル数に scale factor を適用するだけで実現できます。'10'、'5' または '20' から指定します。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'classifier' (デフォルト): 分類のための最終 affine 層の出力。

  • 'pool' : 最終 global average pooling の出力。

  • 'lastconv' : ReLU 活性化なしでの最終 global average pooling の入力。

  • 'lastconv+relu': ReLU 活性化に続く 'lastconv' までのネットワーク。

参照

オブジェクト検出モデル

本サブパッケージは、 ImageNet データセットで学習され、 Pascal VOCMS COCO データセットでファインチューニングされたオブジェクト検出のための最先端の学習済みモデルを提供します。

学習済みモデルは、以下のように推論や学習で使うことができます:

# Import required modules
import nnabla as nn
from nnabla.models.object_detection import YoloV2
from nnabla.models.object_detection.utils import (
    LetterBoxTransform,
    draw_bounding_boxes)
from nnabla.utils.image_utils import imread, imsave
import numpy as np

# Set device
from nnabla.ext_utils import get_extension_context
nn.set_default_context(get_extension_context('cudnn', device_id='0'))

# Load and create a detection model
h, w = 608, 608
yolov2 = YoloV2('coco')
x = nn.Variable((1, 3, h, w))
y = yolov2(x)

# Load an image and scale it to fit inside the (h, w) frame
img_orig = imread('dog.jpg')
lbt = LetterBoxTransform(img_orig, h, w)

# Execute detection
x.d = lbt.image.transpose(2, 0, 1)[None]
y.forward(clear_buffer=True)

# Draw bounding boxes to the original image
bboxes = lbt.inverse_coordinate_transform(y.d[0])
img_draw = draw_bounding_boxes(
    img_orig, bboxes, yolov2.get_category_names())
imsave("detected.jpg", img_draw)
COCO データセットで学習した利用可能なモデル

名前

クラス

mAP

学習フレームワーク

備考

YOLO v2

YoloV2

44.12

Darknet

論文著者のモデル から変換した重み

VOC データセットで学習した利用可能なモデル

名前

クラス

mAP

学習フレームワーク

備考

YOLO v2

YoloV2

76.00

Darknet

論文著者のモデル から変換した重み

共通インターフェイス
class nnabla.models.object_detection.base.ObjectDetection[ソース]
__call__(input_var=None, use_from=None, use_up_to='detection', training=False, returns_net=False, verbose=0)[ソース]

読み込んだモデルからネットワーク (計算グラフ) を作成します。

パラメータ
  • input_var (Variable, optional) -- 指定された場合、入力変数は指定された変数に置き換えられ、その変数の上にネットワークが構築されます。それ以外の場合、バッチサイズが1で、 self.input_shape を元にした形状を持つ変数になります。

  • use_up_to (str) -- ネットワークは文字列で指定した変数まで構築されます。モデルに対応した文字列変数リストは、各モデルクラスのドキュメントに記載されています。

  • training (bool) -- このオプションは、構築されたネットワークの追加学習 (ファインチューニング、転移学習など) を有効にします。True の場合、batch normalization の batch_stat オプションが True になり、学習可能な変数 (畳み込み層の重みおよびバッチ正規化層のガンマとベータなど) の need_grad 属性が True になります。 デフォルトは False です。

  • returns_net (bool) -- True の場合、 NnpNetwork オブジェクトを返します。それ以外の場合は、構築したネットワークの最後の変数を返すのみです。デフォルトは False です。

  • verbose (bool, or int) -- 詳細レベル。 0 に設定した場合、ネットワーク構築中は何も出力しません。

property input_shape

デフォルトの画像サイズ (チャネル、高さ、幅) の組として返します。

class nnabla.models.object_detection.utils.LetterBoxTransform(image, height, width)[ソース]

image 属性として新しいレターボックス画像を持つオブジェクトを生成します。

レターボックス化は、元画像のアスペクト比を維持しつつ、入力画像を意図した出力画像フレーム (レターボックス) 内に収めるよう拡縮する処理として定義されます。元画像のピクセルで埋められないピクセルは 127 になります。

作成されたオブジェクトは、バウンディングボックス座標を元画像フレームに変換する機能も提供します。

パラメータ
  • image (numpy.ndarray) -- uint8 の 3チャネル画像

  • height (int) -- レターボックスの高さ

  • width (int) -- レターボックスの幅

inverse_coordinate_transform(coords)[ソース]

バウンディングボックスを元画像フレームに戻す変換を行います。

パラメータ

coords (numpy.ndarray) -- M >= 4 かつ、 M の最初の4つの要素が x, y (境界ボックスの中心座標), w , h (境界ボックスの幅と高さ) となる N x M の配列。

nnabla.models.object_detection.utils.draw_bounding_boxes(img, bboxes, names, colors=None, thresh=0.5)[ソース]

変換された座標は、検出されたオブジェクトのバウンディングボックスを描画するためにさらに使用されます。

パラメータ
  • img (numpy.ndarray) -- 入力画像

  • bboxes (numpy.ndarray) -- Transformed bounding box coorinates from the model.

  • names (list of str) -- データセットにあるカテゴリ名。

  • colors (list of tuple of 3 ints) -- バウンディングボックスの色情報。

  • thresh (float) -- バウンディングボックスの閾値。

モデルのリスト
class nnabla.models.object_detection.YoloV2(dataset='voc')[ソース]

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'detection' (デフォルト): 後処理後の最後の畳み込み (検出層) からの出力。

  • 'convdetect': 後処理していない最後の畳み込みの出力。

  • 'lastconv': 検出畳み込み層の直前の 畳み込み層+relu までのネットワーク。

参照

Semantic Segmentation モデル

本サブパッケージは、 ImageNet データセットで学習され、 Pascal VOCMS COCO データセットでファインチューニングされた Semantic Segmentation (DeepLabv3+, Xception-65 をバックボーンとする) のための最先端の学習済みモデルを提供します。

学習済みモデルは、以下のように推論で使うことができます。

#Import reauired modules
import numpy as np
import nnabla as nn
from nnabla.utils.image_utils import imread
from nnabla.models.semantic_segmentation import DeepLabV3plus
from nnabla.models.semantic_segmentation.utils import ProcessImage

target_h = 513
target_w = 513
# Get context
from nnabla.ext_utils import get_extension_context
nn.set_default_context(get_extension_context('cudnn', device_id='0'))

# Build a Deeplab v3+ network
image = imread("./test.jpg")
x = nn.Variable((1, 3, target_h, target_w), need_grad=False)
deeplabv3 = DeepLabV3plus('voc-coco',output_stride=8)
y = deeplabv3(x)

# preprocess image
processed_image = ProcessImage(image, target_h, target_w)
input_array = processed_image.pre_process()

# Compute inference
x.d = input_array
y.forward(clear_buffer=True)
print ("done")
output = np.argmax(y.d, axis=1)

# Apply post processing
post_processed = processed_image.post_process(output[0])

#Display predicted class names
predicted_classes = np.unique(post_processed).astype(int)
for i in range(predicted_classes.shape[0]):
    print('Classes Segmented: ', deeplabv3.category_names[predicted_classes[i]])

# save inference result
processed_image.save_segmentation_image("./output.png")
voc データセットで学習した利用可能なモデル

名前

クラス

ストライド出力

mIOU

学習フレームワーク

備考

DeepLabv3+

DeepLabv3+

8

81.48

Nnabla

論文著者のモデル から変換し、ファインチューニングに使われるバックボーン (Xception-65) の重み

DeepLabv3+

DeepLabv3+

16

82.20

Nnabla

論文著者のモデル から変換し、ファインチューニングに使われるバックボーン (Xception-65) の重み

Voc と COCO データセットで学習した利用可能なモデル

名前

クラス

ストライド出力

mIOU

学習フレームワーク

備考

DeepLabv3+

DeepLabv3+

8

82.20

Tensorflow

論文著者のモデル から変換した重み

DeepLabv3+

DeepLabv3+

16

83.58

Tensorflow

論文著者のモデル から変換した重み

共通インターフェイス
class nnabla.models.semantic_segmentation.base.SemanticSegmentation[ソース]

Semantic Segmentation 学習済みモデルは、このクラスから継承され、いくつかの共通インターフェイスを提供します。

__call__(input_var=None, use_from=None, use_up_to='segmentation', training=False, returns_net=False, verbose=0)[ソース]

読み込んだモデルからネットワーク (計算グラフ) を生成します。

パラメータ
  • input_var (Variable, optional) -- 指定された場合、入力変数は指定された変数に置き換えられ、その変数の上にネットワークが構築されます。それ以外の場合、バッチサイズが1で、 self.input_shape を元にした形状を持つ変数となります。

  • use_up_to (str) -- ネットワークは文字列で指定した変数まで構築されます。モデルに対応した文字列変数リストは、各モデルクラスのドキュメントに記載されます。

  • training (bool) -- このオプションは、構築されたネットワークの追加学習 (ファインチューニング、転移学習など) を有効にします。 True の場合、batch normalization の batch_stat オプションが True になり、学習可能な変数 (畳み込み層の重み および バッチ正規化層 のガンマとベータなど) の need_grad 属性が True になります。 デフォルトは False です。

  • returns_net (bool) -- True の場合、 NnpNetwork オブジェクトを返します。それ以外の場合、構築したネットワークの最後の変数を返すのみです。デフォルトは False です。

  • verbose (bool, or int) -- 詳細レベル。 0 に設定した場合、ネットワーク構築中は何も出力しません。

property input_shape

デフォルトの画像サイズ (チャネル、高さ、幅) の組として返します。

モデルのリスト
class nnabla.models.semantic_segmentation.DeepLabV3plus(dataset='voc', output_stride=16)[ソース]

DeepLabV3+.

パラメータ
  • dataset (str) -- ‘voc’ または ‘coco’ から学習データセット名を指定します。

  • output_stride (int) -- DeepLabV3 はatrous convolution (別名:dilated convolution) を使います。atrous レートは出力ストライドに依存します。出力ストライドは 8 あるいは 16 から指定される必要があります。デフォルトは 8 です。もし output_stride が 8 の場合、atrous レートは [12,24,36] となり、output_stride が 16 の場合、atrous レートは [6,12,18] となります。

__call__ method にある use_up_to オプションで指定できる文字列リストは以下の通り;

  • 'segmentation' (デフォルト): 最終レイヤーの出力。

  • 'lastconv': 最後の畳み込みからの出力。

  • 'lastconv+relu': ReLU を含む 'lastconv' までのネットワーク。

参照

Out-of-core execution

The nnabla.lms package provides APIs that allow users to execute large-scale networks than allotted GPU memory by utilizing out-of-core algorithm. Out-of-core algorithm, or external memory algorithm, is an algorithm that enables processing data that are too large to fit into a main memory at once.

SwapInOutScheduler
class nnabla.lms.SwapInOutScheduler

Interface class for out-of-core execution / training.

This API enables training neural networks whose size is larger than alloted GPU memory. See https://arxiv.org/abs/2010.14109 for more detail of shcheduling strategy.

注釈

cuda_init.prefer_cuda_virtual_array() used in following example can be used under cuda >= 10.2 and cudnn >= 8. We utilize virtual memory management supported from cuda 10.2. Additionally, when we tested virtual memory management with cuda >= 10.2 and cudnn < 8, we found the computation results of some cuddn functions are inaccurate. So, when your environment has cuda < 10.2 or cudnn < 8, the virtual memory allocator in nnabla will not be built and you can't use it. If you would like to use SwapInOutScheduler to the fullest extent, please install cuda >= 10.2 and cudnn >= 8 and reinstall the corresponding nnabla-ext-cuda package.

Example:

from nnabla.lms import SwapInOutScheduler

# Change memory allocator which is preferable for SwapInOutScheduler.
from nnabla_ext.cuda.init as cuda_init
cuda_init.prefer_cpu_pinned_array()  # To accelerate memory transfer, using pinned memory for cpu memory will be preferable.

# Only for cuda >= 10.2 and cudnn >= 8. This setting is the best for SwapInOutScheduler.
cuda_init.prefer_cuda_virtual_array()  # To reduce memory fragmentation due to cpu-gpu memory transfers, using virtual allocator for gpu memory will be preferable.

# create context for both host and device
from nnabla.ext_utils import get_extension_context
host_ctx = get_extension_context("cpu", device_id="", type_config="float") # device_id is dummy
device_ctx = get_extension_context("cudnn", device_id="0", type_config="float")

scheduler = SwapInOutScheduler(host_ctx, device_ctx, size=max_gpu_memory_size)

# Make sure to call `nn.set_default_context` after calling prefer_xxx_array() to activate a change of memory preference.
nn.set_default_context(device_ctx)

x = nn.Variable(...)
loss = build_network(x)

solver = S.Sgd(nn.get_parameters())

for i in range(iteration):
    # scheduling memory transfers for all tensors appearing under the context of scheduler.
    with scheduler:
        x.d = next_data()

        loss.forward(clear_no_need_grad=True)

        solver.zero_grad()
        loss.backward(clear_buffer=True)

        solver.update()

When you get Out-of-Memory (OOM) error under the SwapInOutScheduler, possibly there are 2 options to avoid this OOM.

  1. Set small budget of GPU memory for scheduling.

  2. Set small size for a physical memory chunk allocated by virtual memory allocator.

These are examplified as follows:

Example:

# 1. Set small budget of GPU memory for scheduling
# You can reduce the below ratio until you can execute your network.
memsize_for_scheduler = max_gpu_memory_size * 0.8
scheduler = SwapInOutScheduler(..., size=memsize_for_scheduler)

# 2. Set small size for a physical memory chunk allocated by virtual memory allocator
# In default, the chunk size is set as 20MB (20 << 20).
from nnabla_ext.cuda.init import set_cuda_virtual_memory_chunk_size
set_cuda_virtual_memory_chunk_size(2 << 20)  # Set 2MB, for example.
end_scheduling(self)

An interface to specify the end point for scheduling. A range between start_scheduling() and end_scheduling() is a target for a single scheduling.

Note that, using with statement of SwapInOutScheduler, end_scheduling() will be automatically called when exiting with statement. In general, avoid to use start_scheduling() and end_scheduling() and use with statement insted (with scheduler:, see an example above).

function_post_hook(self, func)

A callback executed as function_post_hook in forward and backward.

For all forward and backward wrapped by with statement of SwapInOutScheduler, this callback is automatically set. In general, avoid to set this manually and use with statement of SwapInOutScheduler.

function_pre_hook(self, func)

A callback executed as function_pre_hook in forward and backward.

For all forward and backward wrapped by with statement of SwapInOutScheduler, this callback is automatically set. In general, avoid to set this manually and use with statement of SwapInOutScheduler.

start_scheduling(self)

An interface to specify the starting point for scheduling. A range between start_scheduling() and end_scheduling() is a target for a single scheduling.

Note that, using with statement of SwapInOutScheduler, start_scheduling() will be automatically called when entering with statement. In general, avoid to use start_scheduling() and end_scheduling() and use with statement insted (with scheduler:, see an example above).

update_post_hook(self)

A callback executed as post_hook in all solver functions, e.g. solver.update, solver.weight_decay, solver.clip_grad_by_norm, and so on.

For all solver functions wrapped by with statement of SwapInOutScheduler, this callback is automatically set. In general, avoid to set this manually and use with statement of SwapInOutScheduler.

update_pre_hook(self)

A callback executed as pre_hook in all solver functions, e.g. solver.update, solver.weight_decay, solver.clip_grad_by_norm, and so on.

For all solver functions wrapped by with statement of SwapInOutScheduler, this callback is automatically set. In general, avoid to set this manually and use with statement of SwapInOutScheduler.

Modules

The nnabla.core.module.Module class represents a construction block of neural network.

Module
class nnabla.core.module.Module[ソース]

Module is a construction block of a computation model. Modules normally are constructed by lower level operators or other Modules, thus, nesting them in a tree-like structure may construct a more complex computation model.

サンプル

User may construct his model by derived from this class. Like:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.functions as F

class ConvBn(nn.Module):
    def __init__(self, outmaps, kernel=1, stride=1, act=None):
        self.outmaps = outmaps
        self.kernel = kernel
        self.stride = stride
        self.act = act

    def call(self, x, training=True):
        kernel = (self.kernel, self.kernel)
        pad = (self.kernel // 2, self.kernel // 2)
        stride = (self.stride, self.stride)
        h = PF.convolution(x, self.outmaps, kernel,
                           pad, stride, with_bias=False)
        h = PF.batch_normalization(h, batch_stat=training)
        if self.act is None:
            return h
        return self.act(h)


class ResUnit(nn.Module):
    def __init__(self, channels, stride=1, skip_by_conv=True):
        self.conv1 = ConvBn(channels // 4, 1, 1,
                            act=lambda x: F.relu(x, inplace=True))
        self.conv2 = ConvBn(channels // 4, 3, stride,
                            act=lambda x: F.relu(x, inplace=True))
        self.conv3 = ConvBn(channels, 1)
        self.skip_by_conv = skip_by_conv
        self.skip = ConvBn(channels, 1, stride)

    def call(self, x, training=True):
        h = self.conv1(x)
        h = self.conv2(h)
        h = self.conv3(h)

        s = x
        if self.skip_by_conv:
            s = self.skip(s)
        h = F.relu(F.add2(h, s, inplace=True), inplace=True)
        return h

To use this model, user may do like the following code:

res_unit = ResUnit(1024)
x = nn.Variable((64, 3, 32, 32))
x.d = np.random.random(x.shape)
y = res_unit(x)
y.forward(clear_buffer=True)

For working with dynamic network, user may do like the following:

res_unit = ResUnit(1024)
with nn.auto_forward():
    x = nn.Variable.from_numpy_array(np.random.random((1, 3, 32, 32)))
    y = res_unit(x)
    print(y.d)

For training, please set the parameters in module scope to optimizer. For example,

import nnabla.solvers as S

resnet = ResNet(18)
loss = resnet(x, y_)

solver = S.Sgd(lr=1e-3)
solver.set_parameters(resnet.get_parameters())

for _ in range(max_iter):
    x.d, y_.d = data.next()
    loss.forward()
    solver.zero_grad()
    loss.backward()
    solver.weight_decay(1e-5)
    solver.update()

In this example, we supposed ResNet is a derived class of Module, x, y_ is Variable, data is an instance of DataIterator, supposed it has already been attached to a DataSet.

Note:

From this example, we knew that model parameters are owned by model. Here it is variable resnet. These parameters will be referred when network is forward or backward or solve.update(). Hence, it is necessary to keep this module instance from being unexpectedly released, to ensure forward() or backward() can refer to these variables.

call(*args, **kwargs)[ソース]

User needs implement this function to construct their neural network. In the implementation, user may instantiate existing predefined Modules as its members, then use it. For example:

class AModule(nn.Module):
   def __init__(...):
      ...
      self.cnb = ConvBN(128) # A submodule is instantiated here.

   def call(...):
      h = self.cnb(x) # Using beforehand instantiated submodule.

or directly use parametric functions or functions:

class AModule(nn.Module):
    ...
    def call(...):
        ...
        h = PF.convolution(x, self.outmaps, ...)
        return h

注釈

The following usage is currently not supported, it might be supported in future version:

class AModule(nn.Module):
   def __init__(...):
      ...
      self.cnb = [ConvBN(k) for k in [8, 16, 32]] # using an array to hold module instances.
      self.cnb = {f'name_{k}': ConvBN(k) for k in [8, 16, 32]} # using a dict to hold module instances.

注釈

The following method to temporarily instantiate a module is also not allowed:

class AModule(nn.Module):
   def call(...):
      ...
      cnb = ConvBN(k) # Instantiate a temporary instance of Module is not allowed
      y = cnb(x)
      return y

Because when leave this scope, the parameters registered to cnb module will be released, which cause unexpected result.

get_parameters(recursive=True, grad_only=False, memo=None)[ソース]

Obtain an OrderedDict object of all parameters in current Module.

For example,

x = nn.Variable.from_numpy_array((np.random.random((8, 32, 256, 256))))
conv_bn = ConvBn(2)
y = conv_bn(x)

params = conv_bn.get_parameters()
for parameter_name, parameter_value in params.items():
    print("{}:{}".format(parameter_name, parameter_value.shape))

The output looks like:

conv/W:(2, 32, 1, 1)
bn/beta:(1, 2, 1, 1)
bn/gamma:(1, 2, 1, 1)
bn/mean:(1, 2, 1, 1)
bn/var:(1, 2, 1, 1)

Notice that the parameter name looks like a filepath, with splash separated nested scope name. In addition, module name default is used with a prefix @.

パラメータ
  • recursive (bool, optional, default=True) -- Whether obtain the parameters of current module's submodules. Default is True.

  • grad_only (bool, optional, default=False) -- Whether only obtain the grad. Default is False.

戻り値

Flattened parameter's name-value pairs of current Module.

戻り値の型

OrderedDict

load_parameters(path, extension='.h5')[ソース]

Load parameters from a file into this module.

パラメータ

path -- str or file-like object

property parameter_scope

A module has its owned parameter_scope, which can avoid to pollute global parameter name space. User may obtain the parameter_scope of a module by this property.

戻り値

The parameter scope of current Module.

戻り値の型

OrderedDict

save_parameters(path, extension='.h5')[ソース]

Save parameters of this module to a file.

パラメータ

path -- str or file-like object

property training

Return a bool value which indicates whether current Module is in training state or not. A module may be set to training state or not, so that the computation graph created from this module can be changed according to this state. For example,

class ConvBN(Module):
    ...
    def call(self, x):
        h = self.conv1(x)
        if self.training:
            h = self.drop_out(h)
        h = F.relu(h, inplace=True)
        return h

conv_bn = ConvBN()
conv_bn.training = True
train_y = conv_bn(x)

conv_bn.training = False
eval_y = conv_bn(x)
戻り値

which indicates whether current Module is in training state.

戻り値の型

bool

zero_grad()[ソース]

Clear the gradient of the parameters in this module to 0.

Graph Definition

In NNabla, Graph Definition represents a kind of representation of a computation graph which is special designed for storage optimization and format converter.

A computation graph can be defined by the call of NNabla functions. Such computation graph has instantiated the input and output variables of the functions, inherent topology has been established for forward or backward computation. But for persistence of such graph, another abstract representation, so-called protobuf graph(or network), as abbreviation - proto graph is used normally. In this graph, only the information being necessary for persistence are kept, the information only used for computation will be dropped.

Graph Definition provides a group of functions and classes, tends to facilitate user creates protobuf network from their computation graph, and saving and restoring their neural network from a persistent protobuf network representation.

ProtoGraph
class nnabla.graph_def.ProtoGraph(networks=None, parameter_scope=None)

This class represents a group of proto networks. It normally corresponds to a .nnp file. In a .nnp file, there might be one or multiple networks, for example, there might be a network for doing directly inferring, another network with similar network structure, sharing same parameters, using for training. This class works as a container of proto networks, providing a group of functions for accessing proto network by its name. Especially, when there is only one network in it, also some short-cut functions are provided for directly operating with this network. For example,

import nnabla as nn

g = nn.graph_def.load("my_model.nnp") # Suppose there is only one network in this file.
x1 = nn.Variable(input_shape)
x1.d = ... # load data here.
y1 = g.networks['executor_net'](x1)  #<== (1)
y1.forward()
print(y1.d)

x2 = nn.Variable(input_shape)
x2.d = ... # load data here.
y2 = g(x2) #<== (2)
# y2 = g.default_graph()(x2) #<== (3)
y2.forward()
print(y2.d)

The computation graph y1 and y2 are exactly same. (2) and (3) are equal. If there are multiple networks in a graph, the first network being loaded acted as its default network. Please not use default_graph() when there are multiple networks in graph, since the default heavily depends on concrete implementation.

If you know the name of each network, you may access proto network in this graph by its member name. For example,

g = nn.graph_def.load("my_model.nnp") # Suppose there is only one network in this file.
x = nn.Variable(input_shape)
x.d = ... # load data here.
y = g.executor_net(x) # here, we knew there is a network named "executor_net" existed.
y.forward()
print(y.d)
as_proto(include_parameter=False, only_parameter=False, networks=None, variable_batch_size=True)

This function exports a protobuf data structure, which can be manipulated by google protobuf APIs.

パラメータ
  • include_parameter (bool, optional, default=False) -- Whether exports the parameters to protobuf data structure.

  • only_parameter (bool, optional, default=False) -- Whether only exports the parameters to protobuf data structure.

  • networks (array of proto networks, optional, default=None) -- User may provides their networks to export a protobuf data structure.

  • variable_batch_size (bool, optional, default=True) -- Replace batch size of current network with an abstract placeholder, so that batch size can be replaced with other value in use time.

property current_context

Current backend context of this proto network.

default_graph()

This function returns default proto network in this graph. Which network is default graph depends on its loading sequence. Hence, it is safe to be used when there is only one network.

expand_loop_control()

This function expands loop control statements for all networks in this graph.

static from_proto(proto, batch_size=None, param_scope=None, rng=None)

This function create a proto graph object from a protobuf data structure.

パラメータ
  • proto (protobuf object) -- A protobuf data structure.

  • batch_size (int, optional, default=None) -- The batch size will be applied to this graph. If it is None, it is pending to apply a the batch size value.

  • param_scope (OrderedDict, optional, default=None) -- User may provide an owned parameter scope.

  • rng (np.random.RandomState, optional, default=None) -- A random seed, which is used in parameter initialization.

get_parameters(grad_only=False)

Get parameters in current module name scope.

ProtoNetwork
class nnabla.graph_def.ProtoNetwork(owner, name=None, batch_size=None)

This class represents a protobuf network, which comes from a corresponding computation graph or restored from a saved protobuf network(e.g. .nnp file).

This class describes a neural network by the following members:

  • functions: An OrderedDict of name-value pairs, the value is ProtoFunction object.

  • variables: An OrderedDict of name-value pairs, the value is ProtoVariable object.

  • parameters: An OrderedDict of name-value pairs, the value is ProtoVariable object.

  • inputs: A string list, which contains the name of input variables of this network.

  • outputs: A string list, which contains the name of output variables of this network.

variables represents activations in networks, parameters mainly includes weights and all learnable parameters. functions represents functions in networks, the sequence of functions might not equal forward sequence. Please use forward_sequence to obtain exactly forward function sequence.

__call__(*args, **kwargs)

Generate a computation graph of this protonetwork.

パラメータ

args (tuple of nn.Variables or None) --

The inputs of network, which can be different from the inputs of original computation graph as long as the network allows.

For example,

import nnabla as nn
import numpy as np

resnet = nn.graph_def.load("resnet.nnp")
x.d = np.random.random(input_shape)
y = resnet(x)

The variable y corresponding to a computation graph, user may perform forward like:

y.forward()

If user does not provide inputs for this function, because proto network has the memory of network inputs, this function will create corresponding nn.Variable objects as the inputs of this network. This input variables actually are placeholder of input, hence, users need to find these input variables and fill actual value to these placeholders, so that this computation graph is ready for forward or backward.

For example,

g = nn.graph_def.load("resnet.nnp")
y = g() # Not provide input variables

To feed training or evaluation data to this network, user needs to locate input variable, for example:

input = g.networks[network_name].variables[input_name].variable_instance
input.d = np.random.random(input_shape)
batch_size (int, optional, default=None):

If provided, batch_size will be applied for newly created computation graph. For example,

g = nn.graph_def.load("my_model.nnp")
y = g(batch_size=32)

In this sample, batch_size will be used to create a computation graph with specified batch size. Supposed x is the input of network, its original shape is (1, 3, 32, 32), then the actual computation graph will be (32, 3, 32, 32).

as_proto(**kwargs)

This function returns a protobuf data structure, which can be directly accessed by the functions in nnabla.utils.nnabla_pb2. Thus, it allows user further manipulates this protobuf representation, for example, performing format converting, or network structure optimization.

パラメータ

variable_batch_size (bool, optional) -- If true, the batch size of the network will be replaced with an abstract representation, so that it can be replaced with other value in restoring computation graph.

戻り値

A protobuf object.

戻り値の型

protobuf

execute_on_proto(execute)

This function performs a virtual forward, following the sequence from inputs to output. This function does not use recursive call to perform graph-travel, instead, a non-recursive algorithm is used to graph-travel. For each function, execute is called when meet a function, a ProtoFunction object is passed in for further operation with this function.

パラメータ

execute (callable) --

A callback function (or callable object), which is called when each ProtoFunction is met in travelling graph.

execute should look like:

def execute(pf: ProtoFunction):
    # Do what you want to do with pf
    pass

Or:

class MyCallback:
    def __call__(pf: ProtoFunction):
        # Do what you want to do with pf
        pass

expand_loop_control()

This function expand loop control statement and generate a new proto network object without loop control statement. loop control statement cannot be created by python code, it can be only created by interactive neural network design tool. The following briefly introduce its specification:

  • As for variable,

    In nntxt, if the variable includes a field repeat_id, it means that this variable is in surround with a loop control structure. A renaming rule is applied if expanding this network. The variable name will be added a postfix, like:

    • For old style, e.g.:

    BatchNormalization_6/bn/mean --> BatchNormalization_6/bn/mean_RepeatStart[0]
                                                                     ^        ^  repeat_time
                                                                  repeat_id[index]
    
    original_name --> original_name + << _%repeat_id%[%repeat_time%],  for each in repeat_id >>
    
    • For new style, e.g.:

    BatchNormalization_6{RepeatStart}/bn/mean --> BatchNormalization_6[0]/bn/mean_RepeatStart
                                                                       ^
                                                                  repeat_time
    original_name --> original_name + << [%repeat_time%],  for each in repeat_id >>
    
  • As for RepeatStart, RepeatEnd

    The functions or variables nodes between these 2 layers will be repeated. Expanding will create times of functions and variables, and connected them each other.

  • As for RecurrentInput,

    Axis of RecurrentParam points out which axis will be split-ed. And each branch will duplicated the functions and variables with this repeat_id. This layer works like a split function.

  • As for RecurrentOutput,

    RecurrentOutput merge multiple branches into one output, looks like a stack function.

  • As for Delay

    First time, the output is its input[1], after that, the output is its input[0]

forward_sequence()

This function creates an iteratable for iterating functions in network with the sequence of actually forward.

For example,

for pf in proto_network.forward_sequence():
    print(pf.name)
promote(callback)

User may manipulate a proto network by a callback, like NnpNetworkPass.

パラメータ

callback (NnpNetworkPass,) -- Currently, only NnpNetworkPass object is supported as a network promotion callback.

Developers may manipulate a proto network by a modifier, acts as a callback. nnabla.utils.nnp_graph.NnpNetworkPass is a kind of modifier. The following gives a simple example to illustrate this usage:

サンプル

from nnabla as nn
from nnabla.utils import nnp_graph

verbose = 1
callback = nnp_graph.NnpNetworkPass(verbose)

@callback.on_generate_function_by_name('Convolution')
def change_convolution_param(f):
    print('{}'.format(f.proto.convolution_param.pad.dim[:]))
    f.proto.convolution_param.pad.dim[:] = [1, 1]
    return f

g = nn.graph_def.load("my_model.nnp")
n = g.default_graph().promote(callback)
x = nn.Variable(input_shape)
y = n(x)
y.forward()

In this example, a callback is defined to change pad of a Convolution function, locating this target function by the name of function, here, only the function with the name 'Convolution' is located and operated.

save(filename, include_parameter=False, variable_batch_size=True)

This function saves current proto network to a file, which is specified by filename, normally, e.g. a .nnp file.

パラメータ
  • filename (str) -- string filename, its extension name is used to determine the file format. The extension name normally is .nnp.

  • include_parameter (bool, optional, default=False) -- Whether saving parameters to protobuf tree.

  • variable_batch_size (bool, optional, default=True) -- Whether replace current network's batch size dimension with an abstract representation. If it is true, it is possible to use another batch size when this network is reused.

ProtoVariable
class nnabla.graph_def.ProtoVariable(shape, name=None, need_grad=False, var_type='Buffer')

This class represents a variable, so-called proto variable. Passing this variable to network definition, a proto network will be generated in a proto graph scope. If this procedure is done under a with statement as g, a proto network will be generated in g. Otherwise, a global graph scope is used, a proto network will be generated in global graph scope.

ProtoFunction
class nnabla.graph_def.ProtoFunction(func, f_type, args, name=None, owner=None)

This class represent a function that is used to define a proto network.

There are the following properties to describe a proto function:
  • name: The name of this function.

  • type: The type of this function, e.g. ReLU.

  • inputs: An array of string name, which represents the proto variables of inputs.

  • outputs: An array of string name, which represents the proto variables of outputs.

graph_call(**kwargs)

This function create function instance for generating computation graph.

load
nnabla.graph_def.load(filename, batch_size=None, exclude_parameter=False, parameter_only=False, extension='.nntxt', parameter_scope=None, rng=None)

Load network from files

パラメータ
  • filename (str or list or file-like object) -- Filename string ,list of filenames or file-like object.

  • batch_size (int) -- The batch size expected to be set.

  • exclude_parameter (bool) -- If True, only load model, not load parameters of this model. Default is False.

  • parameter_only (bool) -- If True, only load model parameters. Default is False.

  • extension (str) -- This parameter is needed when filename is a file-like object. Default is .nntxt.

  • parameter_scope (OrderedDict) -- User may provide a user owned parameter scope. If this parameter is not provided, loaded parameters will be created in created proto_graph's parameter_scope. This parameter_scope is default initialized with empty dictionary.

  • rng (random state) -- User may specify random state, which cause parameters are initialized by determined random seed.

戻り値

A ProtoGraph object, in which, there are one or multiple ProtoNetwork objects.

戻り値の型

ProtoGraph

サンプル

The following example loads a model and generate the output variable through this model:

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF

def fusion_net(x):
    def unit(i, prefix):
        c1 = PF.convolution(i, 4, (3, 3), pad=(1, 1), name=prefix + '-c1')
        c2 = PF.convolution(F.relu(c1), 4,
                            (3, 3), pad=(1, 1), name=prefix + '-c2')
        c = F.add2(c2, c1, inplace=True)
        return c
    c = unit(x, 'c1')
    c2 = unit(c, 'c2')
    y = PF.affine(c2, 5, name='fc')
    return y

x = nn.ProtoVariable((64, 3, 32, 32))
y = fusion_net(x)
g = nn.graph_def.get_default_graph()  # Get generated graph_def
g.save("fusion_net.nnp")
...
g = nn.graph_def.load("fusion_net.nnp")
x = nn.Variable((64, 3, 32, 32))
x.d = ... # user provided input data for this graph
y = g(x) # create computation graph by passing in nn.Variable()
y.forward() # calculate output by this graph
...

# You may use your special context(e.g. cuda context)
with context_scope(ctx):
   y = g(x) # create computation graph representation with specified backend context.
   y.forward() # forward using specified backend
save
nnabla.graph_def.save(filename, content, include_parameters=False, variable_batch_size=True, extension='.nnp')

Save network

パラメータ
  • filename (str or file object) --

    Filename to store information. The file extension is used to determine the saving file format. .nnp: (Recommended) Creating a zip archive with nntxt (network definition etc.) and h5 (parameters). .nntxt: Protobuf in text format. .protobuf: Protobuf in binary format (unsafe in terms of

    backward compatibility).

  • content (list) -- Currently only ProtoGraph or PhotoNetwork objects are supported.

  • include_parameters (bool) -- Includes parameter into single file. This is ignored when the extension of filename is nnp.

  • variable_batch_size (bool) -- Whether or not convert batch size of computation graph to a special value, so that user may use any other batch_size value when using it.

サンプル

The following example creates a two inputs and two outputs MLP, and save the network structure and the initialized parameters.

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF

def mlp_module(x0, x1):
    h1_0 = PF.affine(x0, 100, name='affine1_0')
    h1_1 = PF.affine(x1, 100, name='affine1_0')
    h1 = F.tanh(h1_0 + h1_1)
    h2 = F.tanh(PF.affine(h1, 50, name='affine2'))
    y0 = PF.affine(h2, 10, name='affiney_0')
    y1 = PF.affine(h2, 10, name='affiney_1')
    return y0, y1

with nn.graph_def.graph() as g:
    x0 = nn.ProtoVariable((64, 100))
    x1 = nn.ProtoVariable((64, 100))
    y0, y1 = mlp_module(x0, x1)

nn.graph_def.save("mlp_net.nnp", [g])
Create Protobuf Representation from Computation Graph
create_graph_from_variable
nnabla.graph_def.create_graph_from_variable(name, variables, names=None, parameter_scope=None)

Create a Proto Graph from one or multiple outputs.

If developers have a computation graph, it means that they have a nn.Variable() object, it might be loss of a network or an output variable of an executor network, this variable inherently corresponds to a computation network. From these variables, we can create corresponding proto network by this function.

パラメータ
  • name (str) -- The name of generated proto_network.

  • variables (nn.Variables) -- One or multiple variables, if multiple variables, this function adds a sink function to reduce these multiple outputs to one.

  • names (dict, optional, default=None) -- A name to nn.Variable mapping table. This function default names all activation variables and parameters with internal naming rule. But sometimes, developers expects specially name some of variables so that these variable can be accessed conveniently. In generating proto network, when the variable occurs in this mapping table, the corresponding name of that variable will be used to name the variable in proto network.

  • parameter_scope (OrderedDict, optional, default=None) -- Developers may provide a parameter scope, thus, when create proto networks, the name will be replaced if corresponding variable is found in specified parameter_scope, which make the name of weights or some parameters meaningful.

サンプル

import nnabla as nn

x = nn.Variable((1, 3, 32, 32))
y = my_model(x)
g = nn.graph_def.create_graph_from_variable("proto_network_name", y)
g.save("my_model.nnp")
get_default_graph
nnabla.graph_def.get_default_graph(*args, **kwargs)

This function obtain current default graph_def.

If user does not create their proto network in a with statement scope, proto network will default be created in a global scope. User may retrieve this proto graph by this function.

サンプル

import nnabla as nn
from nnabla.core.modules import ResUnit

resunit = ResUnit(16)
input = nn.ProtoVariable((64, 3, 32, 32))
y = resunit(input)
graph_def = nn.graph_def.get_graph_graph()

注釈

If user does not ensure whether there is any previous existing proto graph remained in global graph scope. It is better to call reset_default_graph(). If user uses with statement like with nn.graph_def.graph() as g, this point is no need to care about.

戻り値

A proto graph is returned

戻り値の型

ProtoGraph

get_default_graph_by_variable
nnabla.graph_def.get_default_graph_by_variable(proto_variable)

This function obtain a specify network by its outputs.

User may retrieve one of the networks in default proto graph scope, if this network has the specified outputs. Let us image that there is a global proto graph, when user passed a ProtoVariable to model, during the procedure that create output variables, proto network is generated in this global proto graph. By this function, user may retrieve this generated proto network, saving it or do any other operations.

注釈

This proto network will become invalid after reset_default_graph(). For example,

proto_variable_inputs = [nn.ProtoVariable(v.d.shape) for v in inputs]
outputs = module(*proto_variable_inputs)
net = nn.graph_def.get_default_graph_by_variable(outputs[0])
...
nn.graph_def.reset_default_graph()
y = net(x) # Cannot access net anymore, become invalid at this point
graph
nnabla.graph_def.graph(**kwargs)

This function is only used in with statement.

パラメータ
  • name (str, optional, default=None) -- User may specify a name for the generated proto network. This name is useful for saving to .nnp.

  • parameter_scope (OrderedDict, optional, default=None) -- User may specify a parameter scope, thus, the parameters are created during creating model will be placed into this parameter scope.

For example,

import nnabla as nn

proto_variable_inputs = [nn.ProtoVariable(v.d.shape) for v in inputs]
with nn.graph_def.graph() as g:
    outputs = module(*proto_variable_inputs)

g.save("my_model.nnp")

Here, inputs is an array of input nn.Variables. Modules is a module object instantiated from a Module definition.

reset_default_graph
nnabla.graph_def.reset_default_graph()

This function clear all information in global graph scope.

Sequential

The nnabla.core.sequential.Sequential class represents a construction block of neural network.

Sequential
class nnabla.core.sequential.Sequential(*args, **kwargs)[ソース]

A sequential block. User may construct their network by a sequential block. Importantly, the component within sequential block must be an instance of nn.Module.

For intuitive understanding, some small examples as follows:

import nnabla as nn
import nnabla.parametric_functions as PF
import nnabla.functions as F

class ConvLayer(nn.Module):
    def __init__(self, outmaps, kernel, stride=1, pad=0):
        self.outmaps = outmaps
        self.kernel = (kernel, kernel)
        self.pad = (pad, pad)
        self.stride = (stride, stride)

    def call(self, x):
        x = PF.convolution(x, outmaps=self.outmaps, kernel=self.kernel, pad=self.pad, stride=self.stride)
        x = F.relu(x)
        return x

# Example of using Sequentional
layer = nn.Sequential(
    ConvLayer(48, kernel=1),
    ConvLayer(64, kernel=3, pad=1)
)

# Example of using Sequentional with a specify name for each layer
layer = nn.Sequential(
    ('conv1', ConvLayer(48, kernel=1)),
    ('conv2', ConvLayer(64, kernel=3, pad=1))
)

Experimental

Viewers
SimpleGraph
class nnabla.experimental.viewers.SimpleGraph(format='png', verbose=False, fname_color_map=None, vname_color_map=None)[ソース]

Simple Graph with GraphViz.

Example:

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF

import nnabla.experimental.viewers as V

# Model definition
def network(image, test=False):
    h = image
    h /= 255.0
    h = PF.convolution(h, 16, kernel=(3, 3), pad=(1, 1), name="conv")
    h = PF.batch_normalization(h, name="bn", batch_stat=not test)
    h = F.relu(h)
    pred = PF.affine(h, 10, name='fc')
    return pred

# Model
image = nn.Variable([4, 3, 32, 32])
pred = network(image, test=False)

# Graph Viewer
graph = V.SimpleGraph(verbose=False)
graph.view(pred)
graph.save(pred, "sample_grpah")

If the parameters are module-scoped, for example, the pred comes from a module output, parameters should be obtained beforehand then passed to view():

Example:

import nnabla as nn
import nnabla.functions as F
from nnabla.core.modules import ConvBn

import nnabla.experimental.viewers as V

class TSTNetNormal(nn.Module):
    def __init__(self):
        self.conv_bn_1 = ConvBn(1)
        self.conv_bn_2 = ConvBn(1)

    def call(self, x1, x2):
        y1 = self.conv_bn_1(x1)
        y2 = self.conv_bn_2(x2)
        y = F.concatenate(y1, y2, axis=1)
        return y

tnd = TSTNetNormal()

v1 = nn.Variable((4, 3, 32, 32))
v2 = nn.Variable((4, 3, 32, 32))

ya = tnd(v1, v2)

graph = V.SimpleGraph(verbose=False)
graph.view(ya, params=tnd.get_parameters(grad_only=False))
create_graphviz_digraph(vleaf, params=None, format=None)[ソース]

Create a graphviz.Digraph object given the leaf variable of a computation graph.

One of nice things of getting Digraph directly is that the drawn graph can be displayed inline in a Jupyter notebook as described in Graphviz documentation.

パラメータ
  • vleaf (nnabla.Variable) -- End variable. All variables and functions which can be traversed from this variable are shown in the reuslt.

  • params (dict) -- The parameters dictionary, it can be obtained by nn.get_parameters().

  • format (str) -- Force overwrite format ('pdf', 'png', ...)) configuration.

Returns: graphviz.Digraph

save(vleaf, fpath, cleanup=False, format=None)[ソース]

Save the graph to a given file path.

パラメータ
  • vleaf (nnabla.Variable) -- End variable. All variables and functions which can be traversed from this variable are shown in the reuslt.

  • fpath (str) -- The file path used to save.

  • cleanup (bool) -- Clean up the source file after rendering. Default is False.

  • format (str) -- Force overwrite format ('pdf', 'png', ...)) configuration.

view(vleaf, fpath=None, cleanup=True, format=None, params=None)[ソース]

View the graph.

パラメータ
  • vleaf (nnabla.Variable) -- End variable. All variables and functions which can be traversed from this variable are shown in the reuslt.

  • fpath (str) -- The file path used to save.

  • cleanup (bool) -- Clean up the source file after rendering. Default is True.

  • format (str) -- Force overwrite format ('pdf', 'png', ...)) configuration.

  • params (dict) -- Parameter dictionary, which can be obtained by get_parameters() function. Default is None. If params is None, global parameters are obtained.

Show Graph by Tensorboard
TBGraphWriter
Graph Converters
class nnabla.experimental.graph_converters.GraphConverter(modifiers=[])[ソース]

Convert a graph with the modifiers by traversing from output variables.

convert(o)[ソース]
パラメータ

o (list of nnabla.Variable) -- Output variables.

class nnabla.experimental.graph_converters.FunctionModifier[ソース]

Base class of modifiers.

The modify method is called for a function with inputs in a graph topological order when you call the GraphConverter(<modifiers>).convert(<root variable>) method.

finish_up()[ソース]

Finish the very time function modification.

Clean up the internal modifier states.

パラメータ

None --

戻り値

None

get_parameter_scope(v)[ソース]

Get the parameter name corresponding to v

パラメータ

v (nnabla.Variable) -- NNabla Variable Object.

戻り値

Scope name

戻り値の型

str

modify(f, inputs)[ソース]

Modify the function.

Implement this method in a sub class to modify a function.

Examples:

class ReLUToLeakyReLUModifier(FunctionModifier):

  def __init__(self):
    super(ReLUToLeakyReLUModifier, self).__init__()

  def modify(self, f, inputs):
    if f.info.type_name == 'ReLU':
      x = inputs[0]
      return F.leaky_relu(x)

This examples is a simple case since the network topological order does not change. In GraphConverter, we expect the modify method is called along the original network tolopogical order not the modified order. In such a complex case, see themodify method of BatchNormalizationFoldingModifierInner as a reference.

パラメータ
  • f (nnabla.function.Function) -- NNabla function object.

  • inputs (list of Variable) -- New inputs to f. This may be modified one or the same as f.inputs.

戻り値

Variable or list of Variable.

Function Modifiers
class nnabla.experimental.graph_converters.BatchNormalizationFoldingModifier(opposite=False, channel_last=False)[ソース]

Single Convolution -> BatchNormalization pass is folded into one Convolution.

If there is a Convolution -> BatchNormalization pass, fold the batch normalization parameters to the kernel and bias (if it exists) of the preceding convolution, then skip the batch normalization following the convolution.

Supported folding functions: Convolution, Deconvolution, Affine.

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.BatchNormalizationFoldingModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.AddBiasModifier[ソース]

Add bias to Convolution in BatchNormalization folding case if it doesn't have bias.

Supported folding functions: Convolution, Deconvolution, Affine.

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.AddBiasModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.BatchNormalizationFoldingModifierInner(channel_last=False)[ソース]

Single Convolution -> BatchNormalization pass is folded into one Convolution.

If there is a Convolution -> BatchNormalization pass, fold the batch normalization parameters to the kernel and bias (if it exists) of the preceding convolution, then skip the batch normalization following the convolution.

Supported folding functions: Convolution, Deconvolution, Affine.

class nnabla.experimental.graph_converters.BatchNormalizationFoldingOppositeModifierInner(channel_last=False)[ソース]

Single BatchNormalization -> Convolution pass is folded into one Convolution.

If there is a BatchNormalization -> Convolution pass, fold the batch normalization parameters to the kernel and bias (if it exists) of the preceding convolution, then skip the batch normalization following the convolution.

Supported folding functions: Convolution, Deconvolution, Affine.

class nnabla.experimental.graph_converters.BatchNormalizationSelfFoldingModifier(name='bn-self-folding')[ソース]

The parameters of the batch normalization replaced simple scale and bias.

パラメータ

name (str) -- Prefix of the parameter scope.

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.BatchNormalizationSelfFoldingModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.FusedBatchNormalizationModifier[ソース]

Block BatchNormalization -> Add2 -> Non-Linear pass is fused into one FusedBatchNormalization.

If there is a block BatchNormalization -> Add2 -> Non-Linear pass, remove all the block functions and replace the whole block to FusedBatchNormalization.

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.FusedBatchNormalizationModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.UnfusedBatchNormalizationModifier[ソース]

Unfuse FusedBatchNormalization to BatchNormalization -> Add2 -> Non-Linear block.

If there is a FusedBatchNormalization pass, remove the fused batch normalization and replace it with the block BatchNormalization -> Add2 -> Non-Linear.

Supported Non-Linear functions: relu

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.UnfusedBatchNormalizationModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.ChannelLastModifier(inputs, inputs_cl=None)[ソース]

Convert graph shape from Channel first (NCHW) to Channel last (NHWC) format.

Supported functions: Convolution, Deconvolution, BatchNormalization, MaxPooling, AveragePooling, SumPooling, Unpooling, Concatenate

パラメータ
  • inputs (list of nn.Variable) -- Original very begining inputs (NCHW) of a network.

  • inputs_cl (list of nn.Variable) -- Channel last version of very begining inputs (NHWC) of a network. If this is not given, inputs_cl are generated internally and holded.

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.ChannelLastModifier(<inputs of pred>)]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.ChannelFirstModifier(inputs, inputs_cf=None)[ソース]

Convert graph shape from Channel last (NHWC) to Channel first (NCHW) format.

Supported functions: Convolution, Deconvolution, BatchNormalization, MaxPooling, AveragePooling, SumPooling, Unpooling, Concatenate

パラメータ
  • inputs (list of nn.Variable) -- Original channel last version of very begining inputs (NHWC) of a network.

  • inputs_cf (list of nn.Variable) -- Channel first version of very begining inputs (NCHW) of a network. If this is not given, inputs_cf are generated internally and holded.

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.ChannelFirstModifier(<inputs of pred>)]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.RemoveFunctionModifier(rm_funcs=[])[ソース]

Remove specified function layer(s) from a graph.

A convenient converter when one or more functions in an existing graph needs to be removed. This converter remove specified function(s) without recreating a new graph from scratch.

パラメータ

rm_funcs (list of str) -- list of function name

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.RemoveFunctionModifier(rm_funcs=['BatchNormalization', 'MulScalar'])]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.BatchNormBatchStatModifier[ソース]

Change batch_stat to False. Supported functions: BatchNormalization, FusedBatchNormalization, SyncBatchNormalization.

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.BatchNormBatchStatModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.TestModeModifier(rm_funcs=[])[ソース]

This converter combines BatNormBatchStateModifier and RemoveFunctionModifer. It changes batch_stat to False. Supported functions: BatchNormalization, FusedBatchNormalization, SyncBatchNormalization.

Functions that specified rm_funcs will be removed from a graph.

パラメータ

rm_funcs (list of str) -- list of function name

Examples:

pred = Model(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.TestModeModifier(rm_funcs=['MulScalar'])]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.IdentityModifier(inputs={}, copy_value=False)[ソース]

All functions are replaced to the same new function.

パラメータ

inputs (dict) -- Input variable mapping from the original input to another input. Default is the empty dictionary, so the new graph shares the original inputs.

Examples:

pred = Model(...)
x = nn.Variable(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.IdentityModifier({x0: x1})]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
class nnabla.experimental.graph_converters.NoGradModifier[ソース]

All functions are replaced to the same new function.

パラメータ

inputs (dict) -- Input variable mapping from the original input to another input. Default is the empty dictionary, so the new graph shares the original inputs.

Examples:

pred = Model(...)
x = nn.Variable(...)

import nnabla.experimental.graph_converters as GC

modifiers = [GC.NoGradModifier()]
gc = GC.GraphConverter(modifiers)
pred = gc.convert(pred)
Trainers
class nnabla.experimental.trainers.Trainer(updater=None, evaluator=None, model_save_path=None, max_epoch=1, iter_per_epoch=None, callback_on_start=<function Trainer.<lambda>>, callback_on_finish=<function Trainer.<lambda>>, update_callback_on_start=<function Trainer.<lambda>>, update_callback_on_finish=<function Trainer.<lambda>>)[ソース]

Trainer API

Trainer class is the very basic class for training neural network. You can composite this class to your own trainer class and delegate the train method of this class to your class.

パラメータ
  • updater (Updater or list of Updater) -- Updater object.

  • evaluator (Evaluator or list of Evaluator) -- Evaluator object.

  • model_save_path (str) -- Model save path.

  • max_epoch (int) -- Max epoch to train.

  • iter_per_epoch (int, optional) -- Iterations per one epoch.

  • callback_on_start (callable object, function, lambda, or list of these, optional) -- Callback called before the trainer.train.

  • callback_on_finish (callable object, function, lambda, or list of these, optional) -- Callback called after the trainer.train.

  • update_callback_on_start (callable object, function, lambda, or list of these, optional) -- Callback called before the updater.update.

  • update_callback_on_finish (callable object, function, lambda, or list of these, optional) -- Callback called after the updater.update.

The following example is a complete snippet to use this base trainer.

サンプル

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S

from nnabla.monitor import Monitor, MonitorSeries, MonitorTimeElapsed

import numpy as np

from nnabla.experimental.trainers import Trainer, Updater, Evaluator

# Batch, channel, height, width
b, c, h, w = 32, 1, 128, 128

# Train Input
tinput = nn.Variable([b, c, h, w])
tlabel = nn.Variable([b, c, h, w])

# Train Model and Loss
tpred = <training model>.apply(persistent=True)
tloss = F.mean(F.softmax_cross_entropy(tpred, tlabel))

# Test Input
vinput = nn.Variable([b, c, h, w])
vlabel = nn.Variable([b, c, h, w])

# Test Model and Error
vpred = <evaluation model>.apply(persistent=True)
vloss = F.mean(F.softmax_cross_entropy(vpred, vlabel))
verror = F.mean(F.top_n_error(vpred.get_unlinked_variable(), vlabel))

# Solver
solver = S.Adam()
solver.set_parameters(nn.get_parameters())

# DataIterator
tdata = <training_data_iterator>
vdata = <validation_data_iterator>

# Monitor
monitor = Monitor(<monitor_path>)
monitor_loss = MonitorSeries("Training loss", monitor, interval=10)
monitor_err = MonitorSeries("Training error", monitor, interval=10)
monitor_time = MonitorTimeElapsed("Training time", monitor, interval=100)
monitor_verr = MonitorSeries("Valid error", monitor, interval=10)

# Updater
def tdata_feeder():
    tinput.d, tlabel.d = tdata.next()
def update_callback_on_finish(i):
    monitor_loss.add(i, tloss.d)
    monitor_time.add(i)
updater = Updater(solver, tloss,
                  data_feeder=tdata_feeder,
                  update_callback_on_finish=update_callback_on_finish)

# Evaluator
def vdata_feeder():
    vinput.d, vlabel.d = vdata.next()
def eval_callback_on_finish(i, ve):
    monitor_verr.add(i, ve)
evaluator = Evaluator(verror,
                      data_feeder=vdata_feeder,
                      val_iter=vdata.size // b,
                      callback_on_finish=eval_callback_on_finish)

# Trainer
trainer = Trainer(updater, evaluator, <model_save_path>,
                  max_epoch=<max_epoch>, iter_per_epoch=tdata.size // b)
trainer.train()
class nnabla.experimental.trainers.NaiveClassificationTrainer(solver, tinput=None, tlabel=None, tpred=None, tdata=None, vinput=None, vlabel=None, vpred=None, vdata=None, monitor_path=None, model_save_path=None, max_epoch=1, iter_per_epoch=None, val_iter=None)[ソース]

Naive Classification Trainer

パラメータ
  • solver (Solver) -- Solver object.

  • tinput (Variable) -- Input variable for input feature in training.

  • tlabel (Variable) -- Label variable for lable in training.

  • tpred (Variable) -- Root variable for prediction in the training graph.

  • tdata (nnabla.utils.data_iterator.DataIterator) -- DataIterator for training.

  • vinput (Variable) -- Input variable for input feature in evaluation.

  • vlabel (Variable) -- Label variable for label in evaluation.

  • vpred (Variable) -- Root variable for prediction in the evaluation graph.

  • vdata (DataIterator) -- DataIterator for evaluation.

  • monitor_path (str) -- Monitor path.

  • model_save_path (str) -- Model save path.

  • max_epoch (int) -- Max epoch to train.

  • iter_per_epoch (int, optional) -- Iterations per one epoch. If not set, this value are determined by tdata.size // tdata.batch_size.

  • val_iter (int, optional) -- Iterations for evaluation. If not set, this value are determined by vdata.size // vdata.batch_size.

The following example is a complete snippet to use this base trainer.

サンプル

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S

import numpy as np

from nnabla.experimental.trainers import NaiveClassificationTrainer

# Batch, channel, height, width
b, c, h, w = 32, 1, 128, 128

# Train Input
tinput = nn.Variable([b, c, h, w])
tlabel = nn.Variable([b, c, h, w])

# Train Model and Loss
tpred = <training model>

# Test Input
vinput = nn.Variable([b, c, h, w])

# Test Model
vpred = <evaluation model>

# Solver
solver = S.Adam()
solver.set_parameters(nn.get_parameters())

# DataIterator
tdata = <training_data_iterator>
vdata = <validation_data_iterator>

# Trainer
trainer = NaiveClassificationTrainer(solver,
                                     tinput, tlabel, tpred, tdata,
                                     vinput, vlabel, vpred, vdata,
                                     <monitor_path>,
                                     <model_save_path>,
                                     max_epoch=<max_epoch>)
trainer.train()
class nnabla.experimental.trainers.NaiveRegressionTrainer(solver, tinput=None, tlabel=None, tpred=None, tdata=None, vinput=None, vlabel=None, vpred=None, vdata=None, monitor_path=None, model_save_path=None, max_epoch=1, iter_per_epoch=None, val_iter=None)[ソース]

Naive Regression Trainer

パラメータ
  • solver (Solver) -- Solver object.

  • tinput (Variable) -- Input variable for input feature in training.

  • tlabel (Variable) -- Label variable for lable in training.

  • tpred (Variable) -- Root variable for prediction in the training graph.

  • tdata (nnabla.utils.data_iterator.DataIterator) -- DataIterator for training.

  • vinput (Variable) -- Input variable for input feature in evaluation.

  • vlabel (Variable) -- Label variable for label in evaluation.

  • vpred (Variable) -- Root variable for prediction in the evaluation graph.

  • vdata (DataIterator) -- DataIterator for evaluation.

  • monitor_path (str) -- Monitor path.

  • model_save_path (str) -- Model save path.

  • max_epoch (int) -- Max epoch to train.

  • iter_per_epoch (int, optional) -- Iterations per one epoch. If not set, this value are determined by tdata.size // tdata.batch_size.

  • val_iter (int, optional) -- Iterations for evaluation. If not set, this value are determined by vdata.size // vdata.batch_size.

サンプル

import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S

import numpy as np

from nnabla.experimental.trainers import NaiveRegressionTrainer

# Batch, channel, height, width
b, c, h, w = 32, 1, 128, 128

# Train Input
tinput = nn.Variable([b, c, h, w])
tlabel = nn.Variable([b, c, h, w])

# Train Model and Loss
tpred = <training model>

# Test Input
vinput = nn.Variable([b, c, h, w])
vlabel = nn.Variable([b, c, h, w])

# Test Model
vpred = <evaluation model>

# Solver
solver = S.Adam()
solver.set_parameters(nn.get_parameters())

# DataIterator
tdata = <training_data_iterator>
vdata = <validation_data_iterator>

# Trainer
trainer = NaiveRegressionTrainer(solver,
                                 tinput, tlabel, tpred, tdata,
                                 vinput, vlabel, vpred, vdata,
                                 <monitor_path>,
                                 <model_save_path>,
                                 max_epoch=<max_epoch>)
trainer.train()
class nnabla.experimental.trainers.Updater(solver=None, loss=None, data_feeder=<function Updater.<lambda>>, forward_callback_on_start=<function Updater.<lambda>>, forward_callback_on_finish=<function Updater.<lambda>>, backward_callback_on_start=<function Updater.<lambda>>, backward_callback_on_finish=<function Updater.<lambda>>, comm_callback_on_start=<function Updater.<lambda>>, comm_callback_on_finish=<function Updater.<lambda>>, update_callback_on_start=<function Updater.<lambda>>, update_callback_on_finish=<function Updater.<lambda>>, clear_buffer=True, accum_grad=1, comm=None, grads=[])[ソース]
パラメータ
  • solver (nnabla.solvers.Solver) -- Solver object. E.g., Momentum or Adam.

  • loss (nnabla.Variable) -- Loss variable from which the forward and the backward is called.

  • data_feeder (callable object, function, or lambda) -- Data feeder.

  • forward_callback_on_start (callable object, function, lambda, or list of these, optional) -- Callback called before forward function.

  • forward_callback_on_finish (callable object, function, lambda, or list of these, optional) -- Callback called after forward function.

  • backward_callback_on_start (callable object, function, lambda, or list of these, optional) -- Callback called before backward function.

  • backward_callback_on_finish (callable object, function, lambda, or list of these, optional) -- Callback called after backward function.

  • comm_callback_on_start (callable object, function, lambda, or list of these, optional) -- Callback called before comm.all_reduce.

  • comm_callback_on_finish (callable object, function, lambda, or list of these, optional) -- Callback called after comm.all_reduce.

  • update_callback_on_start (callable object, function, lambda, or list of these, optional) -- Callback called before update function.

  • update_callback_on_finish (callable object, function, lambda, or list of these, optional) -- Callback called after update function.

  • clear_buffer (bool, optional) -- Clears the no longer referenced variables during backpropagation to save memory.

  • accum_grad (int, optional) -- Number of accumulation of gradients. Update method of the Solver is called after the accum_grad number of the forward and backward is called. Default is 1.

  • comm (nnabla.communicators.Communicator, optional) -- Communicator when to do distributed training. Default is None.

  • grads (list of nnabla.NdArray, optional) -- The list of gradients to be exchanged when to do distributed training. Default is the empty list.

サンプル

from nnabla.experimental.trainers import Updater

solver = <Solver>
loss = <Loss Variable of Network>

def tdata_feeder():
    ...
def update_callback_on_finish(i):
    ...
updater = Updater(solver, loss, tdata_feeder, updater_callback_on_finish)

# Training iteration
for itr in range(<max_iter>):
    updater.update()
update(i)[ソース]

Monolithic update method.

This method calls the following methods with the dynamic loss scaling.

  1. solver.zerograd

  2. feed data

  3. loss.forward

  4. loss.backward

  5. comm.all_reduce (if it is specified)

  6. solver.update

class nnabla.experimental.trainers.Evaluator(vroot=None, data_feeder=None, val_iter=None, callback_on_start=<function Evaluator.<lambda>>, callback_on_finish=<function Evaluator.<lambda>>, clear_buffer=True, comm=None)[ソース]
パラメータ
  • vroot (Variable) -- Root varible of the evaluation graph.

  • data_feeder (callable object, function, or lambda) -- Data feeder.

  • val_iter (int, optional) -- Iterations for evaluation.

  • callback_on_start (callable object, function, lambda, or list of these, optional) -- Callback called before the evaluator.evalute.

  • callback_on_finish (callable object, function, lambda, or list of these, optional) -- Callback called after the evaluator.evalute.

  • clear_buffer (bool, optional) -- Clears the no longer referenced variables during backpropagation to save memory.

  • comm (nnabla.communicators.Communicator, optional) -- Communicator when to do distributed training. Default is None.

サンプル

from nnabla.experimental.trainers import Evaluator

# Evaluator
def vdata_feeder():
    ...
def eval_callback_on_finish(i, ve):
    ...
evaluator = Evaluator(verror,
                      data_feeder=vdata_feeder,
                      val_iter=<val_iter>,
                      callback_on_finish=eval_callback_on_finish)
Mixed Precision Trainings
DynamicLossScalingUpdater
class nnabla.experimental.mixed_precision_training.DynamicLossScalingUpdater(solver, loss, data_feeder=<function DynamicLossScalingUpdater.<lambda>>, scale=8.0, scaling_factor=2.0, N=2000, clear_buffer=True, accum_grad=1, weight_decay=None, comm=None, grads=[])[ソース]

Dynamic Loss Scaling Updater for the mixed precision training.

パラメータ
  • solver (nnabla.solvers.Solver) -- Solver object. E.g., Momentum or Adam.

  • loss (nnabla.Variable) -- Loss variable from which the forward and the backward is called.

  • data_feeder (callable object, function, or lambda) -- Data feeder

  • scale (float) -- Loss scale constant. This is dynamically changing during training.

  • scaling_factor (float) -- Scaling factor for the dynamic loss scaling.

  • N (int) -- Interval, the number of iterations in training for increasing loss scale by scaling_factor.

  • clear_buffer (bool) -- Clears the no longer referenced variables during backpropagation to save memory.

  • accum_grad (int) -- Number of accumulation of gradients. Update method of the Solver is called after the accum_grad number of the forward and backward is called.

  • weight_decay (float) -- Decay constant. Default is None, not applying the weight decay.

  • comm (nnabla.communicators.Communicator) -- Communicator when to do distributed training. Default is None.

  • grads (list of nnabla.NdArray) -- The list of gradients to be exchanged when to do distributed training. Default is the empty list.

solver

Solver object. E.g., Momentum or Adam.

Type

nnabla.solvers.Solver

loss

Loss variable from which the forward and the backward is called.

Type

nnabla.Variable

data_feeder

Data feeder

Type

callable object, function, lambda

scale

Loss scale constant. This is dynamically changing during training.

Type

float

scaling_factor

Scaling factor for the dynamic loss scaling.

Type

float

N

Interval, the number of iterations in training for increasing loss scale by scaling_factor.

Type

int

clear_buffer

Clears the no longer referenced variables during backpropagation to save memory.

Type

bool

accum_grad

Number of accumulation of gradients. Update method of the Solver is called after the accum_grad number of the forward and backward is called.

Type

int

weight_decay

Decay constant. Default is None, not applying the weight decay.

Type

float

comm

Communicator when to do distributed training.

Type

nnabla.communicators.Communicator

grads

The list of gradients to be exchanged when to do distributed training.

Type

list of nnabla.NdArray

サンプル

Reference:

update()[ソース]

Monolithic update method.

This method calls the following methods with the dynamic loss scaling.

  1. solver.zerograd

  2. feed data

  3. loss.forward

  4. loss.backward

  5. comm.all_reduce (if it is specified)

  6. solver.update

Parametric Function Classes
class nnabla.experimental.parametric_function_class.affine.Affine(n_inmaps, n_outmaps, base_axis=1, w_init=None, b_init=None, fix_parameters=False, rng=None, with_bias=True)[ソース]

The affine layer, also known as the fully connected layer. Computes

\[{\mathbf y} = {\mathbf A} {\mathbf x} + {\mathbf b}.\]

where \({\mathbf x}, {\mathbf y}\) are the inputs and outputs respectively, and \({\mathbf A}, {\mathbf b}\) are constants.

パラメータ
戻り値

\((B + 1)\)-D array. (\(M_0 \times \ldots \times M_{B-1} \times L\))f

戻り値の型

Variable

nnabla.experimental.parametric_function_class.affine.Linear

:py:class:`nnabla.experimental.parametric_function_class.affine.Affine`の別名です。

class nnabla.experimental.parametric_function_class.convolution.Convolution(inmaps, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True)[ソース]

N-D Convolution with a bias term.

For Dilated Convolution (a.k.a. Atrous Convolution), refer to:

注釈

Convolution is a computationally intensive operation that should preferably be run with the cudnn backend. NNabla then uses CuDNN library functions to determine and cache the fastest algorithm for the given set of convolution parameters, which results in additional memory consumption which may pose a problem for GPUs with insufficient memory size. In that case, the NNABLA_CUDNN_WORKSPACE_LIMIT environment variable can be used to restrict the choice of algorithms to those that fit the given workspace memory limit, expressed in bytes. In some cases it may also be desired to restrict the automatic search to algorithms that produce deterministic (reproducable) results. This can be requested by setting the the environment variable NNABLA_CUDNN_DETERMINISTIC to a non-zero value.

パラメータ
  • inp (Variable) -- N-D array.

  • outmaps (int) -- Number of convolution kernels (which is equal to the number of output channels). For example, to apply convolution on an input with 16 types of filters, specify 16.

  • kernel (tuple of int) -- Convolution kernel size. For example, to apply convolution on an image with a 3 (height) by 5 (width) two-dimensional kernel, specify (3,5).

  • pad (tuple of int) -- Padding sizes for dimensions.

  • stride (tuple of int) -- Stride sizes for dimensions.

  • dilation (tuple of int) -- Dilation sizes for dimensions.

  • group (int) -- Number of groups of channels. This makes connections across channels more sparse by grouping connections along map direction.

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for weight. By default, it is initialized with nnabla.initializer.UniformInitializer within the range determined by nnabla.initializer.calc_uniform_lim_glorot.

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for bias. By default, it is initialized with zeros if with_bias is True.

  • base_axis (int) -- Dimensions up to base_axis are treated as the sample dimensions.

  • fix_parameters (bool) -- When set to True, the weights and biases will not be updated.

  • rng (numpy.random.RandomState) -- Random generator for Initializer.

  • with_bias (bool) -- Specify whether to include the bias term.

戻り値

N-D array. See convolution for the output shape.

戻り値の型

Variable

nnabla.experimental.parametric_function_class.convolution.Conv1d

:py:class:`nnabla.experimental.parametric_function_class.convolution.Convolution`の別名です。

nnabla.experimental.parametric_function_class.convolution.Conv2d

:py:class:`nnabla.experimental.parametric_function_class.convolution.Convolution`の別名です。

nnabla.experimental.parametric_function_class.convolution.Conv3d

:py:class:`nnabla.experimental.parametric_function_class.convolution.Convolution`の別名です。

nnabla.experimental.parametric_function_class.convolution.ConvNd

:py:class:`nnabla.experimental.parametric_function_class.convolution.Convolution`の別名です。

class nnabla.experimental.parametric_function_class.deconvolution.Deconvolution(inmaps, outmaps, kernel, pad=None, stride=None, dilation=None, group=1, w_init=None, b_init=None, base_axis=1, fix_parameters=False, rng=None, with_bias=True)[ソース]

Deconvolution layer.

パラメータ
  • inp (Variable) -- N-D array.

  • outmaps (int) -- Number of deconvolution kernels (which is equal to the number of output channels). For example, to apply deconvolution on an input with 16 types of filters, specify 16.

  • kernel (tuple of int) -- Convolution kernel size. For example, to apply deconvolution on an image with a 3 (height) by 5 (width) two-dimensional kernel, specify (3,5).

  • pad (tuple of int) -- Padding sizes for dimensions.

  • stride (tuple of int) -- Stride sizes for dimensions.

  • dilation (tuple of int) -- Dilation sizes for dimensions.

  • group (int) -- Number of groups of channels. This makes connections across channels sparser by grouping connections along map direction.

  • w_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for weight. By default, it is initialized with nnabla.initializer.UniformInitializer within the range determined by nnabla.initializer.calc_uniform_lim_glorot.

  • b_init (nnabla.initializer.BaseInitializer or numpy.ndarray) -- Initializer for bias. By default, it is initialized with zeros if with_bias is True.

  • base_axis (int) -- Dimensions up to base_axis are treated as the sample dimensions.

  • fix_parameters (bool) -- When set to True, the weights and biases will not be updated.

  • rng (numpy.random.RandomState) -- Random generator for Initializer.

  • with_bias (bool) -- Specify whether to include the bias term.

戻り値

N-D array. See deconvolution for the output shape.

戻り値の型

Variable

nnabla.experimental.parametric_function_class.deconvolution.Deconv1d

:py:class:`nnabla.experimental.parametric_function_class.deconvolution.Deconvolution`の別名です。

nnabla.experimental.parametric_function_class.deconvolution.Deconv2d

:py:class:`nnabla.experimental.parametric_function_class.deconvolution.Deconvolution`の別名です。

nnabla.experimental.parametric_function_class.deconvolution.Deconv3d

:py:class:`nnabla.experimental.parametric_function_class.deconvolution.Deconvolution`の別名です。

nnabla.experimental.parametric_function_class.deconvolution.DeconvNd

:py:class:`nnabla.experimental.parametric_function_class.deconvolution.Deconvolution`の別名です。

class nnabla.experimental.parametric_function_class.batch_normalization.BatchNormalization(n_features, n_dims, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None)[ソース]

Batch normalization layer.

\[\begin{split}\begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon }}\\ y_i &= & \hat{x}_i \gamma + \beta. \end{array}\end{split}\]

where \(x_i, y_i\) are the inputs. In testing, the mean and variance computed by moving average calculated during training are used.

パラメータ
  • inp (Variable) -- N-D array of input.

  • axes (tuple of int) -- Mean and variance for each element in axes are calculated using elements on the rest axes. For example, if an input is 4 dimensions, and axes is [1], batch mean is calculated as np.mean(inp.d, axis=(0, 2, 3), keepdims=True) (using numpy expression as an example).

  • decay_rate (float) -- Decay rate of running mean and variance.

  • eps (float) -- Tiny value to avoid zero division by std.

  • batch_stat (bool) -- Use mini-batch statistics rather than running ones.

  • output_stat (bool) -- Output batch mean and variance.

  • fix_parameters (bool) -- When set to True, the beta and gamma will not be updated.

  • param_init (dict) -- Parameter initializers can be set with a dict. A key of the dict must be 'beta', 'gamma', 'mean' or 'var'. A value of the dict must be an Initializer or a numpy.ndarray. E.g. {'beta': ConstantInitializer(0), 'gamma': np.ones(gamma_shape) * 2}.

戻り値

N-D array.

戻り値の型

Variable

参照

The shape of parameters has the same number of dimensions with the input data, and the shapes in axes has the same dimensions with the input, while the rest has 1. If an input is 4-dim and axes=[1], the parameter shape will be param_shape  = np.mean(inp.d, axis=(0, 2, 3), keepdims=True).shape (using numpy expression as an example).

class nnabla.experimental.parametric_function_class.batch_normalization.BatchNorm1d(n_features, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None)[ソース]

Batch normalization layer for 3d-Array or 3d-Variable. This is typically used together with Conv1d.

\[\begin{split}\begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon }}\\ y_i &= & \hat{x}_i \gamma + \beta. \end{array}\end{split}\]

where \(x_i, y_i\) are the inputs. In testing, the mean and variance computed by moving average calculated during training are used.

パラメータ
  • inp (Variable) -- N-D array of input.

  • axes (tuple of int) -- Mean and variance for each element in axes are calculated using elements on the rest axes. For example, if an input is 4 dimensions, and axes is [1], batch mean is calculated as np.mean(inp.d, axis=(0, 2, 3), keepdims=True) (using numpy expression as an example).

  • decay_rate (float) -- Decay rate of running mean and variance.

  • eps (float) -- Tiny value to avoid zero division by std.

  • batch_stat (bool) -- Use mini-batch statistics rather than running ones.

  • output_stat (bool) -- Output batch mean and variance.

  • fix_parameters (bool) -- When set to True, the beta and gamma will not be updated.

  • param_init (dict) -- Parameter initializers can be set with a dict. A key of the dict must be 'beta', 'gamma', 'mean' or 'var'. A value of the dict must be an Initializer or a numpy.ndarray. E.g. {'beta': ConstantInitializer(0), 'gamma': np.ones(gamma_shape) * 2}.

戻り値

N-D array.

戻り値の型

Variable

参照

The shape of parameters has the same number of dimensions with the input data, and the shapes in axes has the same dimensions with the input, while the rest has 1. If an input is 4-dim and axes=[1], the parameter shape will be param_shape  = np.mean(inp.d, axis=(0, 2, 3), keepdims=True).shape (using numpy expression as an example).

class nnabla.experimental.parametric_function_class.batch_normalization.BatchNorm2d(n_features, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None)[ソース]

Batch normalization layer for 4d-Array or 4d-Variable. This is typically used together with Conv2d.

\[\begin{split}\begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon }}\\ y_i &= & \hat{x}_i \gamma + \beta. \end{array}\end{split}\]

where \(x_i, y_i\) are the inputs. In testing, the mean and variance computed by moving average calculated during training are used.

パラメータ
  • inp (Variable) -- N-D array of input.

  • axes (tuple of int) -- Mean and variance for each element in axes are calculated using elements on the rest axes. For example, if an input is 4 dimensions, and axes is [1], batch mean is calculated as np.mean(inp.d, axis=(0, 2, 3), keepdims=True) (using numpy expression as an example).

  • decay_rate (float) -- Decay rate of running mean and variance.

  • eps (float) -- Tiny value to avoid zero division by std.

  • batch_stat (bool) -- Use mini-batch statistics rather than running ones.

  • output_stat (bool) -- Output batch mean and variance.

  • fix_parameters (bool) -- When set to True, the beta and gamma will not be updated.

  • param_init (dict) -- Parameter initializers can be set with a dict. A key of the dict must be 'beta', 'gamma', 'mean' or 'var'. A value of the dict must be an Initializer or a numpy.ndarray. E.g. {'beta': ConstantInitializer(0), 'gamma': np.ones(gamma_shape) * 2}.

戻り値

N-D array.

戻り値の型

Variable

参照

The shape of parameters has the same number of dimensions with the input data, and the shapes in axes has the same dimensions with the input, while the rest has 1. If an input is 4-dim and axes=[1], the parameter shape will be param_shape  = np.mean(inp.d, axis=(0, 2, 3), keepdims=True).shape (using numpy expression as an example).

class nnabla.experimental.parametric_function_class.batch_normalization.BatchNorm3d(n_features, axes=[1], decay_rate=0.9, eps=1e-05, batch_stat=True, output_stat=False, fix_parameters=False, param_init=None)[ソース]

Batch normalization layer for 5d-Array or 5d-Variable. This is typically used together with Conv3d.

\[\begin{split}\begin{array}{lcl} \mu &=& \frac{1}{M} \sum x_i\\ \sigma^2 &=& \frac{1}{M} \left(\sum x_i - \mu\right)^2\\ \hat{x}_i &=& \frac{x_i - \mu}{\sqrt{\sigma^2 + \epsilon }}\\ y_i &= & \hat{x}_i \gamma + \beta. \end{array}\end{split}\]

where \(x_i, y_i\) are the inputs. In testing, the mean and variance computed by moving average calculated during training are used.

パラメータ
  • inp (Variable) -- N-D array of input.

  • axes (tuple of int) -- Mean and variance for each element in axes are calculated using elements on the rest axes. For example, if an input is 4 dimensions, and axes is [1], batch mean is calculated as np.mean(inp.d, axis=(0, 2, 3), keepdims=True) (using numpy expression as an example).

  • decay_rate (float) -- Decay rate of running mean and variance.

  • eps (float) -- Tiny value to avoid zero division by std.

  • batch_stat (bool) -- Use mini-batch statistics rather than running ones.

  • output_stat (bool) -- Output batch mean and variance.

  • fix_parameters (bool) -- When set to True, the beta and gamma will not be updated.

  • param_init (dict) -- Parameter initializers can be set with a dict. A key of the dict must be 'beta', 'gamma', 'mean' or 'var'. A value of the dict must be an Initializer or a numpy.ndarray. E.g. {'beta': ConstantInitializer(0), 'gamma': np.ones(gamma_shape) * 2}.

戻り値

N-D array.

戻り値の型

Variable

参照

The shape of parameters has the same number of dimensions with the input data, and the shapes in axes has the same dimensions with the input, while the rest has 1. If an input is 4-dim and axes=[1], the parameter shape will be param_shape  = np.mean(inp.d, axis=(0, 2, 3), keepdims=True).shape (using numpy expression as an example).

class nnabla.experimental.parametric_function_class.embed.Embed(n_inputs, n_features, w_init=None, fix_parameters=False)[ソース]

Embed.

Embed slices a matrix/tensor with indexing array/tensor. Weights are initialized with nnabla.initializer.UniformInitializer within the range of \(-\sqrt{3}\) and \(\sqrt{3}\).

パラメータ
  • x (Variable) -- [Integer] Indices with shape \((I_0, ..., I_N)\)

  • n_inputs -- number of possible inputs, words or vocabraries

  • n_features -- number of embedding features

  • fix_parameters (bool) -- When set to True, the embedding weight matrix will not be updated.

戻り値

Output with shape \((I_0, ..., I_N, W_1, ..., W_M)\)

戻り値の型

Variable

C++ API

現在、C++ ライブラリーは以下を提供しています。

  • Python APIs とソニーのニューラルネットワーク開発環境 GUI である Neural Network Console で作成された学習済みモデルの推論を実行するための API

  • C++ で書かれた、推論を実行するためのコマンドラインインタフェース

  • 学習済みモデルを使った C++ API の使用例

C++ APIについてのリファレンスは現在準備中ですが、ほとんどのクラスや関数については、Doxygen 形式で書かれたヘッダーファイルをご一読することで詳細が確認できます。ヘッダーファイルは include ディレクトリにあります。

MNIST runtime の例は、ニューラルネットワーク推論の C++ API をどのように使用するかを理解するためのよい出発点です。

C++ ライブラリのビルド

ドキュメントは、 Github リポジトリ に移動しました。

C++ コマンドラインインターフェイス

Nnabla は C++ バージョンのコマンドラインインターフェイスを持っており、学習や推論 ( フォワード ) を実行できます。このコマンドラインインターフェイスを使うことで、開発者は python 環境がなくても学習や推論を実行できます。

usage: nbla (infer|dump|train)

基本機能

Forward
usage: nbla infer -e EXECUTOR [-b BATCHSIZE] [-o OUTPUT] input_files ...

arguments:
   -e EXECUTOR         EXECUTOR is the name of executor network.
   input_files         input_file must be one of followings.
                           *.nnp      : Network structure and parameter.
                           *.nntxt    : Network structure in prototxt format.
                           *.prototxt : Same as nntxt.
                           *.h5       : Parameters in h5 format.
                           *.protobuf : Network structure and parameters in binary.
                           *.bin      : Input data.

optional arguments:
   -b BATCHSIZE        batch size for the input data.
   -o OUTPUT           the filename pattern of output file, default output to stdout.

example:
    Infer using LeNet_input.bin as input, LeNet_output_0.bin as output:
       nbla infer -e Executor -b 1 LeNet.nnp LeNet_input.bin -o LeNet_output

    Infer and output the result to console:
       nbla infer -e Executor -b 1 LeNet.nnp LeNet_input.bin
Dump
usage: nbla dump input_files ...

arguments:
   input_files         input_files must be one of *.nnp, *.nntxt, prototxt, h5, protobuf

example:
    Show network information by dump command:
      nbla dump LeNet.nnp

出力例 :

This configuration has 1 executors.

  Executor No.0 Name [Executor]
    Using default batch size 64 .
     Inputs
      Input No.0 Name [x] Shape ( 64 1 28 28 )
     Outputs
      Output No.0 Name [y'] Shape ( 64 10 )
Finished
学習
usage: nbla train input_file

arguments:
   input_file          input_file must be *.nnp

C++ API 実装例

実装例は リンク を参照してください。

データファイルフォーマット

"Neural Network Library" 向けデータフォーマットです。

.nnp ファイルの現在のバージョンは単なる ZIP 形式の圧縮ファイルですが、ファイルの拡張子は ‘.nnp’ となります。

‘.nnp’ ファイルは次のファイルを含みます。 ‘.nnp’ が他のファイルを含む場合、 nnabla はそれらのファイルを無視します。

  • 'nnp_version.txt'

    • nnpファイルのバージョンを指定します。ファイル内のバージョン文字列は nnp_version() から得ています。

  • '.nntxt' ( または '.prototxt' )

    • Protocol buffer text フォーマットのネットワーク構造です。

  • '*.protobuf'

    • Protocol buffer バイナリフォーマットの学習パラメータです。

  • '*.h5'

    • HDF5 フォーマットの学習パラメータです。 ( まもなく廃止します )

nnabla.utils.nnp_format.nnp_version()[ソース]

現在のバージョンは “0.1” です。

  • バージョン履歴

    • Version 0.1

      • 初版

データフォーマット

ネットワーク構造と学習済みパラメータを交換するためのデータフォーマットです。

ネットワーク構造

ネットワーク構造とパラメータは Google Protocol Buffer 形式として内部的に格納されます。

概要

ネットワーク構造の全体像を以下のように定義します。

skinparam monochrome true
hide circle
hide methods

class NNablaProtoBuf {
  string version
  GlobalConfig global_config
  TrainingConfig training_config
  Network[] network
  Parameter[] parameter
  Dataset[] dataset
  Optimizer[] optimizer
  Monitor[] monitor
  Executor[] executor
}

package common <<Rectangle>> {
  class GlobalConfig {
    Context default_context
  }

  class Network {
    string name
    int batch_size
    RepeatInfo[] repeat_info
    Variable[] variable
    Function[] function
  }

  class Parameter {
    string variable_name
    Shape shape
    float[] data
    bool need_grad
  }
}

package training <<Rectangle>> {
  class TrainingConfig {
    int max_epoch
    int iter_per_epoch
    bool save_best
  }

  class Dataset {
    string name
    string type

    string uri
    int batch_size
    string cache_dir
    bool overwrite_cache
    bool create_cache_explicitly

    bool shuffle
    bool no_image_normalization

    string[] variable
  }

  class Optimizer {
    string name

    int order

    string network_name
    string dataset_name

    Solver solver
    int update_interval

    DataVariable[] data_variable
    GeneratorVariable[] generator_variable
    LossVariable[] loss_variable
    ParameterVariable[] parameter_variable
  }

  class Monitor {
    string name

    string network_name
    string dataset_name

    DataVariable[] data_variable
    GeneratorVariable[] generator_variable
    MonitorVariable[] monitor_variable
  }
}

package inference <<Rectangle>> {
  class Executor {
    string name

    string network_name

    int num_evaluations
    string repeat_evaluation_type

    bool need_back_propagation

    DataVariable[] data_variable
    GeneratorVariable[] generator_variable
    LossVariable[] loss_variable
    OutputVariable[] output_variable
    ParameterVariable[] parameter_variable
  }
}
common <.. training
common <.. inference

NNablaProtoBuf "1" o-- "0,1" GlobalConfig
NNablaProtoBuf "1" o-- "0,1" Parameter

NNablaProtoBuf "1" o-- "0,1" TrainingConfig
NNablaProtoBuf "1" o-- "0..*" Network
NNablaProtoBuf "1" o-- "0..*" Dataset
NNablaProtoBuf "1" o-- "0..*" Optimizer
NNablaProtoBuf "1" o-- "0..*" Monitor

NNablaProtoBuf "1" o-- "0..*" Executor

NNablaProtoBuf

NNabla ネットワーク構造のルートメッセージです。このメッセージには GlobalConfig 、 TrainingConfig 、 Network 、 Parameter 、 Dataset 、 Optimizer 、 Monitor 、 Executor 等が格納されます。

Variable

ニューラルネットワーク I / O のためのテンソルとパラメータを格納する内部データ構造です。

GlobalConfig

学習や推論を実行指示するための環境設定です。

TrainingConfig

学習の設定です。

Network

ネットワーク構造です。

Parameter

学習結果を格納する特別な変数 ( 例 : アフィン層の重みやバイアス値 ) です。

Dataset

学習のためのデータセットを指定します。

Optimizer

学習のためのネットワーク、データセット、入出力変数を定義します。

Monitor

学習状況を監視するネットワーク、データセット、入出力変数を定義します。

Executor

学習のためのネットワーク、入出力変数を定義します。

学習の構造

TBD

推論の構造

TBD

全体構造

skinparam monochrome true
hide circle
hide methods

class Shape {
  int[] dim
}

class Context {
  string backend
  string array_class
  string device_id
  string compute_backend
}

class GlobalConfig {
  Context default_context
}

class NNablaProtoBuf {
  string version
  GlobalConfig global_config
  TrainingConfig training_config
  Network[] network
  Parameter[] parameter
  Dataset[] dataset
  Optimizer[] optimizer
  Monitor[] monitor
  Executor[] executor
}

class TrainingConfig {
  int max_epoch
  int iter_per_epoch
  bool save_best
}

class Network {
  string name
  int batch_size
  RepeatInfo[] repeat_info
  Variable[] variable
  Function[] function
}

class RepeatInfo {
 string id
 int times
}

class RepeatParameter {
  string repeat_id
  int times
}

class RecurrentParameter {
  string repeat_id
  int length
  int axis
}

class Variable {
  string name
  string type
  string[] repeat_id

  Shape shape

  Initializer initializer
}

class Initializer {
  string type
  float multiplier
}

class Parameter {
  string variable_name
  Shape shape
  float[] data
  bool need_grad
}

class Dataset {
  string name
  string type

  string uri
  int batch_size
  string cache_dir
  bool overwrite_cache
  bool create_cache_explicitly

  bool shuffle
  bool no_image_normalization

  string[] variable
}

class Optimizer {
  string name

  int order

  string network_name
  string dataset_name

  Solver solver
  int update_interval

  DataVariable[] data_variable
  GeneratorVariable[] generator_variable
  LossVariable[] loss_variable
  ParameterVariable[] parameter_variable
}

class Solver {
  string type

  Context context

  float weight_decay

  float lr_decay
  int lr_decay_interval

  SolverParameter parameter
}

class DataVariable {
  string variable_name
  string data_name
}

class GeneratorVariable {
  string variable_name
  string type
  float multiplier
}

class LossVariable {
  string variable_name
}

class ParameterVariable {
  string variable_name
  float learning_rate_multiplier
}

class Monitor {
  string name

  string network_name
  string dataset_name

  DataVariable[] data_variable
  GeneratorVariable[] generator_variable
  MonitorVariable[] monitor_variable
}

class MonitorVariable {
  string variable_name
  string type
  string data_name

  float multiplier
}

class Executor {
  string name

  string network_name

  int num_evaluations
  string repeat_evaluation_type

  bool need_back_propagation

  DataVariable[] data_variable
  GeneratorVariable[] generator_variable
  LossVariable[] loss_variable
  OutputVariable[] output_variable
  ParameterVariable[] parameter_variable
}

class OutputVariable {
  string variable_name
  string type
  string data_name
}

class Function {
  string name
  string type
  string[] repeat_id

  Context context
  string[] input
  string[] output

  FunctionParameter parameter

  // Loop Functions
  RepeatParameter repeat_param
  RecurrentParameter recurrent_param
}

abstract class SolverParameter
hide SolverParameter members

abstract class FunctionParameter
hide FunctionParameter members

NNablaProtoBuf "1" o-- "0,1" GlobalConfig
NNablaProtoBuf "1" o-- "0,1" TrainingConfig
NNablaProtoBuf "1" o-- "0..*" Network
NNablaProtoBuf "1" o-- "0..*" Parameter
NNablaProtoBuf "1" o-- "0..*" Dataset

NNablaProtoBuf "1" o-- "0..*" Optimizer
NNablaProtoBuf "1" o-- "0..*" Monitor
NNablaProtoBuf "1" o-- "0..*" Executor

GlobalConfig "1" o-- "1" Context

Network "1" o-- "0..*" RepeatInfo
Network "1" o-- "0..*" Variable
Network "1" o-- "0..*" Function

Parameter "1" ..> "1" Variable
Parameter "1" o-- "1" Shape

Variable "1" o-- "1" Shape
Variable "1" o-- "0,1" Initializer

Optimizer "1" ..> "1" Network
Optimizer "1" ..> "1" Dataset
Optimizer "1" o-- "1" Solver
Optimizer "1" o-- "0..*" DataVariable
Optimizer "1" o-- "0..*" GeneratorVariable
Optimizer "1" o-- "0..*" LossVariable
Optimizer "1" o-- "0..*" ParameterVariable

Monitor "1" ..> "1" Network
Monitor "1" ..> "1" Dataset
Monitor "1" o-- "1" Solver
Monitor "1" o-- "0..*" DataVariable
Monitor "1" o-- "0..*" GeneratorVariable
Monitor "1" o-- "0..*" MonitorVariable

Executor "1" ..> "1" Network
Executor "1" o-- "1" Solver
Executor "1" o-- "0..*" DataVariable
Executor "1" o-- "0..*" GeneratorVariable
Executor "1" o-- "0..*" LossVariable
Executor "1" o-- "0..*" OutputVariable
Executor "1" o-- "0..*" ParameterVariable

DataVariable      "1" ..> "1" Variable
GeneratorVariable "1" ..> "1" Variable
LossVariable      "1" ..> "1" Variable
ParameterVariable "1" ..> "1" Variable
MonitorVariable   "1" ..> "1" Variable
OutputVariable    "1" ..> "1" Variable

Function "1" o-- "0,1" FunctionParameter
Function "1" o-- "0,1" RepeatParameter
Function "1" o-- "0,1" RecurrentParameter

Solver "1" o-- "1" Context
Solver "1" o-- "0,1" SolverParameter

Parameter

パフォーマンスの観点から、パラメータは HDF 5 形式で保存されます。

ファイル形式と拡張子

Protocol buffer がシリアライズされたバイナリファイル

.nntxt または .prototxt

Protocol buffer text 形式ファイル

.protobuf

HDF5

.h5

NNP ( 上記形式での ZIP 形式ファイル )

.nnp

ファイルフォーマットコンバーター

概要

blockdiag NNabla Use NNabla as Runtime Other (Caffe2 etc.) ONNX ONNX NNP NNB C Source code SavedModel, PB, TFlite File Format Converter File Format Converter NNP Tensorflow (.pb,ckpt,.tflite, saved_model) Other runtime NNabla C Runtime Implement to product Tensorflow

ファイルフォーマットコンバーターを使うと、ONNX ファイルフォーマット、および NNabla C Runtime で Neural Network Libraries (または Console) ワークフローを実現できます。

ファイルフォーマットコンバーターには次のような機能があります。

  • NNP のバリエーションを有効な NNP へ変換する

  • ONNX から NNP へ変換する

  • NNP から ONNX へ変換する

  • NNP から NNB へ変換する (NNabla C Runtime のバイナリー形式)

  • Convert NNP to Tensorflow saved_model

  • Convert Tensorflow checkpoint, frozen graph or saved_model to NNP

  • Convert NNP to Tensorflow Lite

  • Convert NNP to INT8 quantized Tensorflow Lite

  • Convert Tensorflow Lite to NNP

  • 試用段階: NNP から NNabla C Runtime の C ソースコードへ変換する

重要なお知らせ: 本ファイルフォーマットコンバーターには、いくつかの既知の問題が残っています。

  • サポートする ONNX オペレーターは制限されています。詳細は Function-Level Support Status をご覧ください。

  • サポートする Tensorflow operator は制限されています。詳細は Function-Level Support Status をご覧ください

  • NNP から C ソースコードへの変換はまだ試用段階です。動作しますが、十分にテストされていません。

アーキテクチャー

blockdiag <<file>> INPUT <<file>> OUTPUT proto Process (Split, Expand, etc.) import export

本ファイルフォーマットコンバーターは、中間形式として Neural Network Libraries 内に定義された protobuf を使います。

汎用のファイルフォーマットコンバーターではありませんが、Neural Network Libraries では指定されたコンバーターです。

本コンバーターは、ONNX ファイルに対する入力および出力を指定可能ですが、ONNX ファイルに Neural Network Libraries がサポートしない機能を含んでいる場合、変換中にエラーが発生する可能性があります。

また本コンバーターは、中間プロセス機能も提供します。詳細は、 プロセス をご覧ください。

Installation

Before using this converter, please use command pip install nnabla_converter to install nnabla_converter.

Note that, flatbuffer package is necessary for TFLite export, please check Tensorflow Lite section in this page for more details.

変換

サポートするフォーマット
NNP

NNP は NNabla のファイルフォーマットです。

NNP フォーマットは データフォーマット に記述されます。

本ファイルフォーマットコンバーターでは、いくつかの NNP バリエーションでしか動作しません。

  • NNP 標準フォーマット (.nnp)

  • NNP ファイルの内容 (.nntxt, .prototxt, .h5, .protobuf)

ONNX
制限事項
  • 学習はサポートしません。

  • Support operator set 7,9,10,11.

  • すべての機能をサポートしているわけではありません。詳細は Function-Level Support Status をご覧ください。

  • 限られた Neural Network Console のプロジェクトのみサポートします。詳細は Model Support Status をご覧ください。

NNB

NNB is compact binary format for NNabla C Runtime. The file format is shown as the following diagram:

_images/nnb.png

There are several concepts, such as buffer, variable, function, input and output in this file. Each of them is represented as a list. Each list is recorded with 2 members: number of object, and index in memory block table. The index points to the position in a memory block index table. The index in memory block index table points to the start address of memory data block.

It is designed for nnabla-c-runtime.

C ソースコード

ファイルフォーマットコンバーターは、 nnabla-c-runtime の C ソースコード出力をサポートします。

Tensorflow
制限事項

Bridged by onnx, tensorflow import and export is supported with some limitations.

As for the importer, 4 formats tends to be supported:
  • .pb, tensorflow frozen graph フォーマット

  • .ckpt, tensorflow check point フォーマット version 1

  • .ckpt.*, tensorflow check point フォーマット version 2

  • saved_model, tensorflow saved_model format

As for the exporter, some of Neural Network Console projects are supported. See Model Support Status. The output of converter is tensorflow saved_model format.

Tensorflow Lite
制限事項
For export to tensorflow lite, please install flatbuffers package:
  • For Windows platform, download package from FlatBuffers and extract.

  • For Linux platform, use command snap install flatbuffers to install flatbuffers.

  • For MaxOS platform, use command brew install flatbuffers to install flatbuffers.

and add the executable file flatc to the system PATH.

After exporting TFLite, a json file with the same name will be generated, recording whether the input and output of the TFLite network need to be transposed to channel_last according to base_axis.

INT8 quantized Tensorflow Lite
制限事項

You should also install flatbuffers package. Please refer to the installation above. You need provide a represent dataset to the converter if you want to convert nnp to int8 quantized tflite. Represent dataset is a subset of training dataset, about 2% - 10% of training data. You can collect represent dataset in your training loop. It should be saved as numpy's .npy format. Here's an example:

rdataset = []
# suppose this is your training loop
for step in range(max_step):
    image, label = dataset.next()
    x.d = image
    rdataset.append(image)
    # your code
    # ...
rdataset = np.array(rdataset).astype(np.float32)
np.save('represent_dataset.npy', rdataset)

Of course, you can create represent dataset by any way you like, but please ensure the shape of each item is equal with the shape of network's input and you have finished the necessary preprocess.

プロセス

繰り返しの拡張と循環

Neural Network Console は LoopControl 擬似関数である RepeatStart, RepeatEnd, RecurrentInput, RecurrentOutput または Delay をサポートしています。

現在、Neural Network Library ではこれらの関数を直接的にはサポートしていません。

ファイルフォーマットコンバーターは、ネットワークを拡張し、デフォルトでこれらの擬似関数を削除します。

これらの関数を保持したい場合、ファイル変換時にコマンドラインオプション --nnp-no-expand-network を指定してください。

ネットワークを分割する

--split オプションを使ってネットワークを分割できます。

この機能を使用する場合、 分割ネットワーク をご覧ください。

使い方

NNP 操作

NNP から NNP への変換

NNP から NNP への変換が必要な場合があります。

たいていの場合、繰り返しの拡張、あるいは循環ネットワークは Neural Network Console ではサポートしていますが、C++ API ではサポートしていません。

$ nnabla_cli convert input.nnp output.nnp
console 出力から単一の NNP ファイルへ変換する

Neural Network Console の現在のバージョンは .nntxt と .h5 を学習結果として出力します。

続いて、分離したファイルを単一の NNP に変換し、パラメータを protobuf 形式で格納する必要があります。

$ nnabla_cli convert net.nntxt parameters.h5 output.nnp
console 出力から単一の NNP ファイルへ 繰り返しの拡張や循環なしに変換する
$ nnabla_cli convert --nnp-no-expand-network net.nntxt parameters.h5 output.nnp
パラメータ形式を hdf5 で保持する
$ nnabla_cli convert --nnp-no-expand-network --nnp-parameter-h5 net.nntxt parameters.h5 output.nnp
すべてを単一の nntxt に入れる
$ nnabla_cli convert --nnp-parameter-nntxt net.nntxt parameters.h5 output.nntxt

ONNX 操作

NNP から ONNX へ変換する
$ nnabla_cli convert input.nnp output.onnx

onnx opset 9 出力を指定する場合、次のように指定してください (デフォルトは opset 7):

$ nnabla_cli convert input.nnp output.onnx -d opset_9
ONNX から NNP へ変換する
$ nnabla_cli convert input.onnx output.nnp

Currently, opset 7,9,10,11 are supported to import.

C Runtime 操作

一般的に、ファイルから C Runtime に変換するときは、バッチサイズを 1 に指定する方がよいとされています。バッチサイズが 1 より大きい場合、バッチサイズを 1 にするためにまとめて処理する必要があります。コマンドラインオプションで -b 1 を追加してください。

NNP から NNB へ変換する
$ nnabla_cli convert -b 1 input.nnp output.nnb
NNP から C ソースコードへ変換する
$ nnabla_cli convert -b 1 -O CSRC input.onnx output-dir
量子化

C-runtime ライブラリは、バイナリ (または固定小数点) の重みをサポートしており、モデル (およびフットプリント) のサイズを劇的に縮小できます。モデルを量子化する方法については、 固定小数点量子化によるネットワークの圧縮 を参照してください。

Tensorflow 操作

Convert NNP to Tensorflow saved_model
$ nnabla_cli convert input.nnp output_saved_model --export-format SAVED_MODEL
NNP から Tensorflow frozen graph へ変換する
$ nnabla_cli convert input.nnp output.pb
NNP から Tensorflow frozen graph へ変換する
$ nnabla_cli convert input.pb output.nnp
Tensorflow checkpoint から NNP へ変換する

checkpoint version 1 の場合:

$ nnabla_cli convert input.ckpt output.nnp --inputs x0,x1 --outputs y0,y1

input.ckpt と同じディレクトリには、 その関連ファイルである checkpoint、input.ckpt.meta などがあることが必要です。 inputs では、モデルの入力名がコンマで区切られていることが必要です。 outputs も同様です。checkpoint 形式の解析では、入力と出力があることが必要です。

checkpoint version 2 の場合:

$ nnabla_cli convert input.ckpt.meta output.nnp --inputs x0,x1 --outputs y0,y1

input.ckpt.meta と同じディレクトリには、その関連ファイルである checkpoint、 *.ckpt.index などがあることが必要です。

Convert Tensorflow saved_model to NNP
$ nnabla_cli convert input_saved_model output.nnp
Convert NNP to Tensorflow Lite
$ nnabla_cli convert -b 1 input.nnp output.tflite
Convert NNP to INT8 quantized Tensorflow Lite
$ nnabla_cli convert -b 1 input.nnp output.tflite --quantization --dataset represent_dataset.npy
Convert Tensorflow Lite to NNP
$ nnabla_cli convert input.tflite output.nnp

分割ネットワーク

分割ネットワークは少し複雑で面倒な場合があります。

NNP ファイルは複数の Executor ネットワークを持つことがありますが、Split は単一ネットワークを分割することしかサポートしません。

まず、NNP の中に executor がいくつあるかを確認し、どの executor を nnabla_cli dump で分割するのか指定してください。

$ nnabla_cli dump squeezenet11.files/SqueezeNet-1.1/*.{nntxt,h5}
2018-08-27 15:02:40,006 [nnabla][INFO]: Initializing CPU extension...
Importing squeezenet11.files/SqueezeNet-1.1/net.nntxt
Importing squeezenet11.files/SqueezeNet-1.1/parameters.h5
 Expanding Training.
 Expanding Top5Error.
 Expanding Top1Error.
 Expanding Runtime.
  Optimizer[0]: Optimizer
  Optimizer[0]:  (In) Data      variable[0]: Name:TrainingInput                  Shape:[-1, 3, 480, 480]
  Optimizer[0]:  (In) Data      variable[1]: Name:SoftmaxCrossEntropy_T          Shape:[-1, 1]
  Optimizer[0]:  (Out)Loss      variable[0]: Name:SoftmaxCrossEntropy            Shape:[-1, 1]
  Monitor  [0]: train_error
  Monitor  [0]:  (In) Data      variable[0]: Name:Input                          Shape:[-1, 3, 320, 320]
  Monitor  [0]:  (In) Data      variable[1]: Name:Top5Error_T                    Shape:[-1, 1]
  Monitor  [0]:  (Out)Monitor   variable[0]: Name:Top5Error                      Shape:[-1, 1]
  Monitor  [1]: valid_error
  Monitor  [1]:  (In) Data      variable[0]: Name:Input                          Shape:[-1, 3, 320, 320]
  Monitor  [1]:  (In) Data      variable[1]: Name:Top1rror_T                     Shape:[-1, 1]
  Monitor  [1]:  (Out)Monitor   variable[0]: Name:Top1rror                       Shape:[-1, 1]
  Executor [0]: Executor
  Executor [0]:  (In) Data      variable[0]: Name:Input                          Shape:[-1, 3, 320, 320]
  Executor [0]:  (Out)Output    variable[0]: Name:y'                             Shape:[-1, 1000]

上記の出力結果によって、1 つの executor のみがあることが分かります。

続いて nnabla_cli dump -E0 で executor の詳細情報を見ることができます。

$ nnabla_cli dump -E0 squeezenet11.files/SqueezeNet-1.1/*.{nntxt,h5}
2018-08-27 15:03:26,547 [nnabla][INFO]: Initializing CPU extension...
Importing squeezenet11.files/SqueezeNet-1.1/net.nntxt
Importing squeezenet11.files/SqueezeNet-1.1/parameters.h5
 Try to leave only executor[Executor].
 Expanding Runtime.
  Executor [0]: Executor
  Executor [0]:  (In) Data      variable[0]: Name:Input                          Shape:[-1, 3, 320, 320]
  Executor [0]:  (Out)Output    variable[0]: Name:y'                             Shape:[-1, 1000]

-F オプションにより、関数リストを取得できます。

$ nnabla_cli dump -FE0 squeezenet11.files/SqueezeNet-1.1/*.{nntxt,h5}
2018-08-27 15:04:10,954 [nnabla][INFO]: Initializing CPU extension...
Importing squeezenet11.files/SqueezeNet-1.1/net.nntxt
Importing squeezenet11.files/SqueezeNet-1.1/parameters.h5
 Try to leave only executor[Executor].
 Expanding Runtime.
  Executor [0]: Executor
  Executor [0]:  (In) Data      variable[0]: Name:Input                          Shape:[-1, 3, 320, 320]
  Executor [0]:  (Out)Output    variable[0]: Name:y'                             Shape:[-1, 1000]
  Executor [0]:   Function[  0  ]: Type: Slice                Name: Slice
  Executor [0]:   Function[  1  ]: Type: ImageAugmentation    Name: ImageAugmentation
  Executor [0]:   Function[  2  ]: Type: MulScalar            Name: SqueezeNet/MulScalar
  Executor [0]:   Function[  3  ]: Type: AddScalar            Name: SqueezeNet/AddScalar
  Executor [0]:   Function[  4  ]: Type: Convolution          Name: SqueezeNet/Convolution
  Executor [0]:   Function[  5  ]: Type: ReLU                 Name: SqueezeNet/ReLU
  Executor [0]:   Function[  6  ]: Type: MaxPooling           Name: SqueezeNet/MaxPooling

    SNIP...

  Executor [0]:   Function[ 63  ]: Type: ReLU                 Name: SqueezeNet/FireModule_8/Expand1x1ReLU
  Executor [0]:   Function[ 64  ]: Type: Concatenate          Name: SqueezeNet/FireModule_8/Concatenate
  Executor [0]:   Function[ 65  ]: Type: Dropout              Name: SqueezeNet/Dropout
  Executor [0]:   Function[ 66  ]: Type: Convolution          Name: SqueezeNet/Convolution_2
  Executor [0]:   Function[ 67  ]: Type: ReLU                 Name: SqueezeNet/ReLU_2
  Executor [0]:   Function[ 68  ]: Type: AveragePooling       Name: SqueezeNet/AveragePooling
  Executor [0]:   Function[ 69  ]: Type: Reshape              Name: SqueezeNet/Reshape
  Executor [0]:   Function[ 70  ]: Type: Identity             Name: y'

ImageAugmentation を除いたネットワークを取得したい場合、上記の出力結果によれば、ImageAugmentation は index 2 に配置されます。index 3 に分割した後、 ImageAugmentation を除いたネットワークを取得できます。 nnabla_cli 変換-E0 -S 3- オプションを指定する必要があります。このコマンドで出力を XXX_S_E.nnp という名前に変更します。 XXX は元の名前で、S は開始関数の index、E は終了関数の index です。

$ nnabla_cli convert -E0 -S 3- squeezenet11.files/SqueezeNet-1.1/*.{nntxt,h5} splitted.nnp
2018-08-27 15:20:21,950 [nnabla][INFO]: Initializing CPU extension...
Importing squeezenet11.files/SqueezeNet-1.1/net.nntxt
Importing squeezenet11.files/SqueezeNet-1.1/parameters.h5
 Try to leave only executor[Executor].
 Expanding Runtime.
   Shrink 3 to 70.
    Output to [splitted_3_70.nnp]

最終的に分割された出力として splitted_3_70.nnp を取得できました。分割された NPP は nnabla_cli dump で確認できます。

注意: Input shape は元のネットワークから変更されました。新しい input shape は開始関数の入力と同じです。

$ nnabla_cli dump splitted_3_70.nnp
2018-08-27 15:20:28,021 [nnabla][INFO]: Initializing CPU extension...
Importing splitted_3_70.nnp
 Expanding Runtime.
  Executor [0]: Executor
  Executor [0]:  (In) Data      variable[0]: Name:SqueezeNet/MulScalar           Shape:[-1, 3, 227, 227]
  Executor [0]:  (Out)Output    variable[0]: Name:y'                             Shape:[-1, 1000]

以上で終了です。

サポート状況

Function-Level Support Status

ONNX Support Status

Note

In this document, the numbers in the header of all tables represent the version of onnx opset.

Import
  • ✓: onnx specification defined, and supported.

  • X: onnx specification defined, but not support yet.

  • Empty: Not defined (Support status follows latest).

Total: 95/159

ONNX Operator

1

2

3

4

5

6

7

8

9

10

11

12

13

NNabla Func

Description

Abs

Abs

Acos

ACos

Acosh

ACosh

Add

Add2, Reshape

And

LogicalAnd, Reshape

ArgMax

X

Flip, Max, RSubScalar

ArgMin

X

Flip, Min, RSubScalar

Asin

ASin

Asinh

ASinh

Atan

ATan

Atanh

ATanh

AveragePool

X

X

AveragePooling, Pad

Not all features are verified. Those features can be verified by ONNXRuntime when opset > 6. Some feature is not supported by Nnabla such as Pad's edge mode. if opset >= 10, the ceil_mode is not supported.

BatchNormalization

X

X

X

BatchNormalization

BitShift

X

Not yet implemented.

Cast

X

X

Ceil

Ceil

Celu

Add2, Constant, Div2, ELU, Exp, MaximumScalar, MinimumScalar, Mul2, MulScalar, Reshape, Sub2

Clip

Identity

Compress

X

X

Not yet implemented.

Concat

X

Concatenate

ConcatFromSequence

X

Not yet implemented.

Constant

X

X

Identity

ConstantOfShape

Constant

Conv

X

Convolution

ConvInteger

X

Not yet implemented.

ConvTranspose

X

Deconvolution, Pad

Cos

Cos

Cosh

Cosh

CumSum

X

Not yet implemented.

DepthToSpace

Reshape, Transpose

DequantizeLinear

DequantizeLinear

Det

X

Not yet implemented.

Div

Div2, Reshape

Dropout

X

Identity

DynamicQuantizeLinear

X

Not yet implemented.

Einsum

X

Not yet implemented.

Elu

ELU

Equal

X

X

Equal, Reshape

Erf

X

X

Not yet implemented.

Exp

Exp

Expand

X

Broadcast, Reshape

EyeLike

X

Not yet implemented.

Flatten

Reshape

Floor

Floor

GRU

X

X

X

Not yet implemented.

Gather

Concatenate, Slice

GatherElements

X

X

Not yet implemented.

GatherND

X

X

Not yet implemented.

Gemm

Add2, BatchMatmul, MulScalar, Reshape

GlobalAveragePool

GlobalAveragePooling

GlobalLpPool

X

X

Not yet implemented.

GlobalMaxPool

X

Not yet implemented.

Greater

Greater, Reshape

GreaterOrEqual

Equal, Greater, GreaterEqual, LogicalOr, Reshape

HardSigmoid

AddScalar, HardSigmoid, MaximumScalar, MinimumScalar, MulScalar

Hardmax

Max, OneHot, Transpose

Identity

Identity

If

X

X

Not yet implemented.

InstanceNormalization

BatchNormalization, Concatenate, Reshape, Split

IsInf

IsInf

IsNaN

IsNaN

LRN

AddScalar, Div2, MulScalar, PowScalar, SumPooling, Transpose

LSTM

X

X

Not yet implemented.

LeakyRelu

LeakyReLU

Less

Less, Reshape

LessOrEqual

Equal, Less, LessEqual, LogicalOr, Reshape

Log

Log

LogSoftmax

Div2, Exp, Log, Max, Sub2, Sum

Loop

X

X

Not yet implemented.

LpNormalization

X

Not yet implemented.

LpPool

X

X

X

Not yet implemented.

MatMul

BatchMatmul, Reshape

MatMulInteger

X

Not yet implemented.

Max

Maximum2

MaxPool

X

X

X

MaxPooling, Pad

Not all features are verified. Those features can be verified by ONNXRuntime. if opset >= 10, the ceil_mode is not supported, dilations is not equal to 1 is not supported.

MaxRoiPool

X

Not yet implemented.

MaxUnpool

X

X

Not yet implemented.

Mean

Identity, Mean, Stack

MeanVarianceNormalization

X

Not yet implemented.

Min

Minimum2

Mod

X

X

Not yet implemented.

Mul

Mul2, Reshape

Multinomial

X

Not yet implemented.

Neg

MulScalar

NonMaxSuppression

X

X

Not yet implemented.

NonZero

X

X

Not yet implemented.

Not

LogicalNot

OneHot

X

X

Not yet implemented.

Or

LogicalOr, Reshape

PRelu

X

PReLU

Pad

Pad

Onnx required to support "edge" mode, while nnabla does not support it.

Pow

Pow2, Reshape

QLinearConv

X

Not yet implemented.

QLinearMatMul

X

Not yet implemented.

QuantizeLinear

QuantizeLinear

RNN

X

X

Not yet implemented.

RandomNormal

X

Not yet implemented.

RandomNormalLike

X

Not yet implemented.

RandomUniform

X

Not yet implemented.

RandomUniformLike

X

Not yet implemented.

Range

X

Not yet implemented.

Reciprocal

RDivScalar

ReduceL1

X

X

Not yet implemented.

ReduceL2

X

X

Not yet implemented.

ReduceLogSum

X

X

Not yet implemented.

ReduceLogSumExp

X

X

Not yet implemented.

ReduceMax

Max

ReduceMean

Mean

ReduceMin

Min

ReduceProd

Prod

ReduceSum

Sum

ReduceSumSquare

PowScalar, Sum

Relu

ReLU

Reshape

Reshape

Resize

X

X

X

Not yet implemented.

ReverseSequence

X

Not yet implemented.

RoiAlign

X

Not yet implemented.

Round

Round

Scan

X

X

X

Not yet implemented.

Scatter

X

X

Not yet implemented.

ScatterElements

X

Not yet implemented.

ScatterND

X

X

Not yet implemented.

Selu

SELU

SequenceAt

X

Not yet implemented.

SequenceConstruct

X

Not yet implemented.

SequenceErase

X

Not yet implemented.

SequenceInsert

X

Not yet implemented.

SequenceLength

X

Not yet implemented.

Shape

X

X

Not yet implemented.

Shrink

X

Not yet implemented.

Sigmoid

Sigmoid

Sign

Sign

Sin

Sin

Sinh

Sinh

Size

X

X

Not yet implemented.

Slice

X

X

Slice

Softmax

Div2, Exp, Max, Sub2, Sum

Softplus

X

X

SoftPlus

Not yet implemented.

Softsign

SoftSign

SpaceToDepth

Reshape, Transpose

Split

Split, Stack

SplitToSequence

X

Not yet implemented.

Sqrt

PowScalar

Squeeze

Reshape

StringNormalizer

X

Not yet implemented.

Sub

Reshape, Sub2

Sum

X

X

AddN

Tan

Tan

Tanh

Tanh

TfIdfVectorizer

X

Not yet implemented.

ThresholdedRelu

Constant, GreaterScalar, Where

Tile

Tile

TopK

X

X

X

Not yet implemented.

Transpose

Transpose

Unique

X

Not yet implemented.

Unsqueeze

Reshape

Upsample

X

X

X

Unpooling

Where

Where

Xor

LogicalXor, Reshape

Export
  • ✓: Support to export this opset.

  • △: Partially support to export this opset (e.g. some cases cannot be supported, or not completely tested).

  • X: Supported, but test failed.

  • Empty: Not support corresponding opset version.

Total: 124/215

Neural Network Layer

Count 11/18

NNabla Function

7

9

10

11

13

ONNX Op

Description

Affine

Gemm, Reshape

RNN

Not yet implemented.

LSTM

Not yet implemented.

GRU

Not yet implemented.

Convolution

Conv, Reshape

FusedConvolution

Not yet implemented.

DepthwiseConvolution

Conv, Reshape

Deconvolution

ConvTranspose, Reshape

DepthwiseDeconvolution

ConvTranspose, Reshape

DeformableConvolution

Not yet implemented.

AdaptiveSeparableConvolution

Not yet implemented.

MaxPooling

Constant, MaxPool, Pad, Reshape

AveragePooling

AveragePool, Constant, Pad, Reshape

Currently only supports the cases where both ignore_border and including_pad are True.

GlobalAveragePooling

GlobalAveragePool

SumPooling

AveragePool, Constant, Mul, Pad, Reshape

Unpooling

Resize

Embed

Gather

RoiAlign

Not yet implemented.

Neural Network Activation Functions

Count 20/22

NNabla Function

7

9

10

11

13

ONNX Op

Description

Sigmoid

Sigmoid

Swish

Mul, Sigmoid

Tanh

Tanh

ReLU

Relu

LeakyReLU

LeakyRelu

Softmax

Div, Exp, ReduceMax, ReduceSum, Sub

LogSoftmax

Exp, Log, ReduceMax, ReduceSum, Sub

ELU

Elu

SELU

Selu

CReLU

Concat, Neg, Relu

CELU

Concat, Elu, Neg

PReLU

PRelu, Reshape

GELU

Add, Constant, Div, Mul, Pow, Sqrt, Tanh

Mish

Not yet implemented.

ReLU6

Constant, Min, Relu

HardSigmoid

HardSigmoid

HardTanh

Constant, Max, Min, Neg

LogSigmoid

Log, Sigmoid

SoftPlus

X

X

X

X

X

Softplus

Not yet implemented.

SoftSign

Softsign

TanhShrink

Sub, Tanh

Sinc

X

X

X

Constant, Div, Equal, Sin, Where

Normalization

Count 7/14

NNabla Function

7

9

10

11

13

ONNX Op

Description

FusedBatchNormalization

Add, BatchNormalization, Constant, Div, Mul, ReduceMean, ReduceSum, Relu, Reshape, Squeeze, Sub

BatchNormalization

BatchNormalization, Constant, Div, Mul, ReduceMean, ReduceSum, Reshape, Squeeze, Sub

GroupNormalization

Not yet implemented.

InstanceNormalization

Add, Constant, Div, Mul, Pow, ReduceMean, ReduceSum, Reshape, Sub

LayerNormalization

Add, Constant, Div, Mul, Pow, ReduceMean, ReduceSum, Sub

NormNormalization

Not yet implemented.

SyncBatchNormalization

Not yet implemented.

TensorNormalization

Not yet implemented.

WeightNormalization

Add, Constant, Mul, Pow, ReduceSum, Reshape

WeightStandardization

Add, Constant, Div, Mul, Pow, ReduceMean, ReduceSum, Sub

SpectralNorm

Add, Constant, Div, Gemm, Pow, ReduceSum, Reshape, Sqrt, Transpose

MeanSubtraction

Not yet implemented.

ClipGradByValue

Not yet implemented.

ClipGradByNorm

Not yet implemented.

Reduction

Count 5/10

NNabla Function

7

9

10

11

13

ONNX Op

Description

Sum

ReduceSum

CumSum

Not yet implemented.

Mean

ReduceMean

Max

ReduceMax

Min

ReduceMin

Norm

Not yet implemented.

Prod

ReduceProd

CumProd

Not yet implemented.

ReduceSum

Not yet implemented.

ReduceMean

Not yet implemented.

Arithmetic

Count 11/14

NNabla Function

7

9

10

11

13

ONNX Op

Description

Add2

Add

AddN

Not yet implemented.

BcAdd2

Not yet implemented.

Sub2

Sub

Mul2

Mul

MulN

Not yet implemented.

Div2

Div

Pow2

Pow

AddScalar

Add, Constant

MulScalar

Constant, Mul

PowScalar

Constant, Pow

RSubScalar

Constant, Sub

RDivScalar

Constant, Div

RPowScalar

Constant, Pow

Logical

Count 29/30

NNabla Function

7

9

10

11

13

ONNX Op

Description

Sign

X

Sign

Minimum2

Add, Constant, Min

Maximum2

Add, Constant, Max

MinimumScalar

Add, Constant, Min

MaximumScalar

Add, Constant, Max

LogicalAnd

And

LogicalOr

Or

LogicalXor

Xor

Equal

X

X

X

Equal

NotEqual

X

X

X

Equal, Not

GreaterEqual

Less, Not

Greater

Greater

LessEqual

Greater, Not

Less

Less

SearchSorted

Not yet implemented.

LogicalAndScalar

And, Constant

LogicalOrScalar

Constant, Or

LogicalXorScalar

Constant, Xor

EqualScalar

X

X

X

Constant, Equal

NotEqualScalar

X

X

X

Constant, Equal, Not

GreaterEqualScalar

Constant, Less, Not

GreaterScalar

Constant, Greater

LessEqualScalar

Constant, Greater, Not

LessScalar

Constant, Less

LogicalNot

Not

IsNaN

X

IsNaN

IsInf

X

X

IsInf

ResetNaN

X

Constant, IsNaN, Where

ResetInf

X

X

Constant, IsInf, Where

Where

X

Where

Math

Count 22/22

NNabla Function

7

9

10

11

13

ONNX Op

Description

Constant

Constant, Identity

Arange

Constant, Identity

Abs

Abs

Exp

Exp

Log

Log

Identity

Identity

BatchMatmul

MatMul, Transpose

Round

X

X

X

Round

Ceil

Ceil

Floor

Floor

Sin

Sin

Cos

Cos

Tan

Tan

Sinh

X

Sinh

Cosh

X

Cosh

ASin

Asin

ACos

Acos

ATan

Atan

ATan2

Atan, Div

ASinh

X

Asinh

ACosh

X

Acosh

ATanh

X

Atanh

Array Manipulation

Count 12/30

NNabla Function

7

9

10

11

13

ONNX Op

Description

Concatenate

Concat

Split

Split, Squeeze

Stack

Concat, Unsqueeze

Slice

Constant, Slice

ONNX slice cannot support step != 1 on opset < 10.

Pad

Constant, Pad

When the mode of the pad is reflect, if the size of the pad exceeds the input size, onnxruntime cannot handle it.

Transpose

Transpose

Broadcast

X

BroadcastTo

Tile

Constant, Reshape, Tile

OneHot

X

Flatten, Gather, Reshape

Flip

Gather, Identity, Transpose

Shift

Not yet implemented.

Sort

Not yet implemented.

Reshape

Constant, Reshape

MatrixDiag

Not yet implemented.

MatrixDiagPart

Not yet implemented.

Meshgrid

Not yet implemented.

BatchDet

Not yet implemented.

BatchInv

Not yet implemented.

BatchLogdet

Not yet implemented.

Assign

Not yet implemented.

Gather

Not yet implemented.

GatherNd

Not yet implemented.

BoolGather

Not yet implemented.

ScatterNd

Not yet implemented.

ScatterAdd

Not yet implemented.

BoolScatter

Not yet implemented.

BoolFill

Not yet implemented.

PackPaddedSequence

Not yet implemented.

PadPackedSequence

Not yet implemented.

Signal Processing

Count 1/5

NNabla Function

7

9

10

11

13

ONNX Op

Description

Interpolate

X

X

Resize

FFT

Not yet implemented.

IFFT

Not yet implemented.

STFT

Not yet implemented.

ISTFT

Not yet implemented.

Stochasticity

Count 0/15

NNabla Function

7

9

10

11

13

ONNX Op

Description

Dropout

X

X

X

X

X

Dropout

The Dropout in nnabla has no test mode and contains random parameters, so the test result is not the same as onnx.

TopKData

Not yet implemented.

TopKGrad

Not yet implemented.

Rand

Not yet implemented.

Randint

Not yet implemented.

Randn

Not yet implemented.

RandBinomial

Not yet implemented.

RandBeta

Not yet implemented.

RandGamma

Not yet implemented.

RandomChoice

Not yet implemented.

RandomCrop

Not yet implemented.

RandomFlip

Not yet implemented.

RandomShift

Not yet implemented.

RandomErase

Not yet implemented.

ImageAugmentation

Not yet implemented.

Loss Functions

Count 0/9

NNabla Function

7

9

10

11

13

ONNX Op

Description

SigmoidCrossEntropy

Not yet implemented.

BinaryCrossEntropy

Not yet implemented.

SoftmaxCrossEntropy

Not yet implemented.

CategoricalCrossEntropy

Not yet implemented.

SquaredError

Not yet implemented.

AbsoluteError

Not yet implemented.

HuberLoss

Not yet implemented.

EpsilonInsensitiveLoss

Not yet implemented.

KLMultinomial

Not yet implemented.

Geometric Neural Network Layers

Count 0/3

NNabla Function

7

9

10

11

13

ONNX Op

Description

AffineGrid

Not yet implemented.

WarpByGrid

Not yet implemented.

WarpByFlow

Not yet implemented.

Quantization Neural Network Layers

Count 6/14

NNabla Function

7

9

10

11

13

ONNX Op

Description

BinarySigmoid

X

Constant, Greater, Where

BinaryTanh

X

Constant, Greater, Where

BinaryConnectAffine

Gemm, Reshape

BinaryConnectConvolution

Conv, Reshape

BinaryWeightAffine

Add, MatMul, Mul, Reshape

BinaryWeightConvolution

Add, Conv, Mul, Reshape

INQAffine

Not yet implemented.

INQConvolution

Not yet implemented.

FixedPointQuantize

Not yet implemented.

MinMaxQuantize

Not yet implemented.

Pow2Quantize

Not yet implemented.

Prune

Not yet implemented.

QuantizeLinear

DequantizeLinear

Validation

Count 0/3

NNabla Function

7

9

10

11

13

ONNX Op

Description

TopNError

Not yet implemented.

BinaryError

Not yet implemented.

ConfusionMatrix

Not yet implemented.

Unsupported, Special Use

Count 0/6

NNabla Function

7

9

10

11

13

ONNX Op

Description

VATNoise

Not yet implemented.

Unlink

Not yet implemented.

Sink

Not yet implemented.

NmsDetection2d

Not yet implemented.

MaxPoolingBackward

Not yet implemented.

PatchCorrelation

Not yet implemented.

Tensorflow Support Status

Import
  • ✓: Supported

  • △: Partially supported

  • X: Supported, but test failed.

  • Empty: Not support yet.

Total: 106/122

Tensorflow support status

Tensorflow Function

Status

NNabla Func

Description

Abs

Abs

Acos

ACos

Acosh

ACosh

Add

Add2

AddN

AddN

All

Greater, Min, Reshape

Any

Greater, Reshape, Sum

ArgMax

Max

ArgMin

Min

Asin

ASin

Asinh

ASinh

Atan

ATan

Atan2

ATan, Add2, Div2, Mul2, Reshape, Sign, Sub2

Atanh

ATanh

AvgPool

AveragePooling, Pad, Transpose

AvgPool3D

AveragePooling, Pad, Transpose

BatchMatMul

BatchMatmul, Transpose

BatchNormalization

Add2, Mul2, PowScalar, RDivScalar, Reshape, Sub2

BiasAdd

Add2, Reshape

BroadcastTo

Cast

X

NA

Not yet implemented.

Ceil

Ceil

ClipByValue

Maximum2, Minimum2, Reshape

Concat

Concatenate

ConcatV2

Concatenate

Const

NA

Conv1D

Convolution, Pad, Reshape, Transpose

Conv1DTranspose

Deconvolution, Reshape, Transpose

Conv2D

Convolution, Pad, Transpose

Conv2DBackpropInput

Deconvolution, Transpose

Conv3D

Convolution, Pad, Transpose

Conv3DBackpropInput

Deconvolution, Pad, Transpose

Cos

Cos

Cosh

Cosh

Crelu

Concatenate, MulScalar, ReLU

Cumsum

X

Not yet implemented.

DepthToSpace

Reshape, Transpose

DepthwiseConv2d

Convolution, Pad, Reshape, Transpose

Div

Div2

Elu

ELU

Equal

Equal

Erf

X

Not yet implemented.

Erfc

X

Not yet implemented.

Exp

Exp

ExpandDims

Reshape

Floor

Floor

FloorDiv

Div2, Floor

FloorMod

Div2, Floor, Mul2, Sub2

GatherNd

X

Not yet implemented.

GatherV2

X

Concatenate, Slice

Not yet implemented.

Greater

Greater

GreaterEqual

Less, LogicalNot

Identity

Identity

IsInf

IsInf

IsNan

IsNaN

LeakyRelu

LeakyReLU

Less

Less

LessEqual

Greater, LogicalNot

Log

Log

LogSigmoid

X

MulScalar, SoftPlus

Not yet implemented.

LogSoftmax

Add2, Exp, Log, Max, Reshape, Sub2, Sum, Transpose

LogicalAnd

LogicalAnd

LogicalNot

LogicalNot

LogicalOr

LogicalOr

LogicalXor

LogicalAnd, LogicalNot, LogicalOr

Max

Max

MaxPool

MaxPooling, Pad, Reshape, Transpose

MaxPool3D

MaxPooling, Pad, Transpose

MaxPoolWithArgmax

X

Not yet implemented.

Maximum

Maximum2

Mean

Mean

Min

Min

Minimum

Minimum2

Mul

Mul2

Neg

MulScalar

NotEqual

Equal, LogicalNot

Pack

Concatenate, Reshape

Pad

Pad

Pow

Pow2

Prod

Prod

RealDiv

Div2

Reciprocal

RDivScalar

Relu

ReLU

Relu6

MaximumScalar, MinimumScalar

Reshape

Reshape

ReverseSequence

X

Not yet implemented.

ReverseV2

X

Not yet implemented.

Round

Round

Rsqrt

PowScalar, RDivScalar

Selu

SELU

Shape

X

Not yet implemented.

Sigmoid

Sigmoid

Sign

Sign

Sin

Sin

Sinh

Sinh

Size

X

Not yet implemented.

Slice

Slice

Softmax

Div2, Exp, Max, Reshape, Sub2, Sum, Transpose

Softplus

X

SoftPlus

Not yet implemented.

Softsign

SoftSign

SpaceToDepth

Reshape, Transpose

Split

Split, Stack

SplitV

Split, Stack

Sqrt

PowScalar

Square

Mul2

SquaredDifference

Mul2, Sub2

Squeeze

Reshape

StopGradient

Identity

StridedSlice

Slice

Sub

Sub2

Sum

Sum

Swish

Mul2, Sigmoid

Tan

Tan

Tanh

Tanh

Tile

Tile

TopKV2

X

Not yet implemented.

Transpose

Transpose

TruncateDiv

X

Div2

Not yet implemented.

TruncateMod

X

Not yet implemented.

Unpack

Reshape, Split, Stack

Where

Where

ZerosLike

NA

Export
  • ✓: Supported

  • △: Partially supported

  • X: Supported, but test failed.

  • Empty: Not support yet.

Total: 124/215

Neural Network Layer

Count 11/18

NNabla Function

Status

Description

Affine

RNN

Not yet implemented.

LSTM

Not yet implemented.

GRU

Not yet implemented.

Convolution

The cases dilations and strides larger than 1 are not supported by tensorflow.

FusedConvolution

Not yet implemented.

DepthwiseConvolution

The cases dilations and strides larger than 1 are not supported by tensorflow.

Deconvolution

The cases dilations larger than 1 are not supported by tensorflow.

DepthwiseDeconvolution

The cases dilations larger than 1 are not supported by tensorflow.

DeformableConvolution

Not yet implemented.

AdaptiveSeparableConvolution

Not yet implemented.

MaxPooling

AveragePooling

Currently only supports the cases both ignore_border and including_pad are True.

GlobalAveragePooling

SumPooling

Unpooling

The kernel only supports 2d.

Embed

RoiAlign

Not yet implemented.

Neural Network Activation Functions

Count 20/22

NNabla Function

Status

Description

Sigmoid

Swish

Tanh

ReLU

LeakyReLU

Softmax

LogSoftmax

ELU

SELU

CReLU

CELU

PReLU

GELU

Mish

Not yet implemented.

ReLU6

HardSigmoid

HardTanh

LogSigmoid

SoftPlus

X

Not yet implemented.

SoftSign

TanhShrink

Sinc

Normalization

Count 7/14

NNabla Function

Status

Description

FusedBatchNormalization

BatchNormalization

GroupNormalization

Not yet implemented.

InstanceNormalization

LayerNormalization

NormNormalization

Not yet implemented.

SyncBatchNormalization

Not yet implemented.

TensorNormalization

Not yet implemented.

WeightNormalization

WeightStandardization

SpectralNorm

MeanSubtraction

Not yet implemented.

ClipGradByValue

Not yet implemented.

ClipGradByNorm

Not yet implemented.

Reduction

Count 5/10

NNabla Function

Status

Description

Sum

CumSum

Not yet implemented.

Mean

Max

Min

Norm

Not yet implemented.

Prod

CumProd

Not yet implemented.

ReduceSum

Not yet implemented.

ReduceMean

Not yet implemented.

Arithmetic

Count 11/14

NNabla Function

Status

Description

Add2

AddN

Not yet implemented.

BcAdd2

Not yet implemented.

Sub2

Mul2

MulN

Not yet implemented.

Div2

Pow2

AddScalar

MulScalar

PowScalar

RSubScalar

RDivScalar

RPowScalar

Logical

Count 29/30

NNabla Function

Status

Description

Sign

Minimum2

Maximum2

MinimumScalar

MaximumScalar

LogicalAnd

LogicalOr

LogicalXor

Equal

NotEqual

GreaterEqual

Greater

LessEqual

Less

SearchSorted

Not yet implemented.

LogicalAndScalar

LogicalOrScalar

LogicalXorScalar

EqualScalar

NotEqualScalar

GreaterEqualScalar

GreaterScalar

LessEqualScalar

LessScalar

LogicalNot

IsNaN

IsInf

ResetNaN

ResetInf

Where

Math

Count 22/22

NNabla Function

Status

Description

Constant

Arange

Abs

Exp

Log

Identity

BatchMatmul

Round

Ceil

Floor

Sin

Cos

Tan

Sinh

Cosh

ASin

ACos

ATan

ATan2

ASinh

ACosh

ATanh

Array Manipulation

Count 12/30

NNabla Function

Status

Description

Concatenate

Split

Stack

Slice

Pad

When the mode of the pad is reflect, if the size of the pad exceeds the input size, tensorflow cannot handle it.

Transpose

Broadcast

BroadcastTo

Tile

OneHot

Flip

Shift

Not yet implemented.

Sort

Not yet implemented.

Reshape

MatrixDiag

Not yet implemented.

MatrixDiagPart

Not yet implemented.

Meshgrid

Not yet implemented.

BatchDet

Not yet implemented.

BatchInv

Not yet implemented.

BatchLogdet

Not yet implemented.

Assign

Not yet implemented.

Gather

Not yet implemented.

GatherNd

Not yet implemented.

BoolGather

Not yet implemented.

ScatterNd

Not yet implemented.

ScatterAdd

Not yet implemented.

BoolScatter

Not yet implemented.

BoolFill

Not yet implemented.

PackPaddedSequence

Not yet implemented.

PadPackedSequence

Not yet implemented.

Signal Processing

Count 1/5

NNabla Function

Status

Description

Interpolate

FFT

Not yet implemented.

IFFT

Not yet implemented.

STFT

Not yet implemented.

ISTFT

Not yet implemented.

Stochasticity

Count 0/15

NNabla Function

Status

Description

Dropout

X

The Dropout in nnabla has no test mode and contains random parameters, so the test result is not the same as tensorflow.

TopKData

Not yet implemented.

TopKGrad

Not yet implemented.

Rand

Not yet implemented.

Randint

Not yet implemented.

Randn

Not yet implemented.

RandBinomial

Not yet implemented.

RandBeta

Not yet implemented.

RandGamma

Not yet implemented.

RandomChoice

Not yet implemented.

RandomCrop

Not yet implemented.

RandomFlip

Not yet implemented.

RandomShift

Not yet implemented.

RandomErase

Not yet implemented.

ImageAugmentation

Not yet implemented.

Loss Functions

Count 0/9

NNabla Function

Status

Description

SigmoidCrossEntropy

Not yet implemented.

BinaryCrossEntropy

Not yet implemented.

SoftmaxCrossEntropy

Not yet implemented.

CategoricalCrossEntropy

Not yet implemented.

SquaredError

Not yet implemented.

AbsoluteError

Not yet implemented.

HuberLoss

Not yet implemented.

EpsilonInsensitiveLoss

Not yet implemented.

KLMultinomial

Not yet implemented.

Geometric Neural Network Layers

Count 0/3

NNabla Function

Status

Description

AffineGrid

Not yet implemented.

WarpByGrid

Not yet implemented.

WarpByFlow

Not yet implemented.

Quantization Neural Network Layers

Count 6/14

NNabla Function

Status

Description

BinarySigmoid

BinaryTanh

BinaryConnectAffine

BinaryConnectConvolution

The cases dilations and strides larger than 1 are not supported by tensorflow.

BinaryWeightAffine

BinaryWeightConvolution

The cases dilations and strides larger than 1 are not supported by tensorflow.

INQAffine

Not yet implemented.

INQConvolution

Not yet implemented.

FixedPointQuantize

Not yet implemented.

MinMaxQuantize

Not yet implemented.

Pow2Quantize

Not yet implemented.

Prune

Not yet implemented.

QuantizeLinear

Not yet implemented.

DequantizeLinear

Not yet implemented.

Validation

Count 0/3

NNabla Function

Status

Description

TopNError

Not yet implemented.

BinaryError

Not yet implemented.

ConfusionMatrix

Not yet implemented.

Unsupported, Special Use

Count 0/6

NNabla Function

Status

Description

VATNoise

Not yet implemented.

Unlink

Not yet implemented.

Sink

Not yet implemented.

NmsDetection2d

Not yet implemented.

MaxPoolingBackward

Not yet implemented.

PatchCorrelation

Not yet implemented.

Tensorflow Lite Support Status

Export
  • ✓: Supported

  • △: Partially supported

  • X: Supported, but test failed.

  • Empty: Not support yet.

Total: 82/215

Neural Network Layer

Count 11/18

NNabla Function

Status

Affine

RNN

LSTM

GRU

Convolution

FusedConvolution

DepthwiseConvolution

Deconvolution

DepthwiseDeconvolution

DeformableConvolution

AdaptiveSeparableConvolution

MaxPooling

AveragePooling

GlobalAveragePooling

SumPooling

Unpooling

Embed

RoiAlign

Neural Network Activation Functions

Count 10/22

NNabla Function

Status

Sigmoid

Swish

Tanh

ReLU

LeakyReLU

Softmax

LogSoftmax

ELU

SELU

X

CReLU

X

CELU

X

PReLU

GELU

X

Mish

ReLU6

HardSigmoid

X

HardTanh

X

LogSigmoid

X

SoftPlus

X

SoftSign

X

TanhShrink

X

Sinc

X

Normalization

Count 1/14

NNabla Function

Status

FusedBatchNormalization

X

BatchNormalization

GroupNormalization

InstanceNormalization

X

LayerNormalization

X

NormNormalization

SyncBatchNormalization

TensorNormalization

WeightNormalization

X

WeightStandardization

X

SpectralNorm

X

MeanSubtraction

ClipGradByValue

ClipGradByNorm

Reduction

Count 5/10

NNabla Function

Status

Sum

CumSum

Mean

Max

Min

Norm

Prod

CumProd

ReduceSum

ReduceMean

Arithmetic

Count 11/14

NNabla Function

Status

Add2

AddN

BcAdd2

Sub2

Mul2

MulN

Div2

Pow2

AddScalar

MulScalar

PowScalar

RSubScalar

RDivScalar

RPowScalar

Logical

Count 23/30

NNabla Function

Status

Sign

X

Minimum2

Maximum2

MinimumScalar

MaximumScalar

LogicalAnd

LogicalOr

LogicalXor

Equal

NotEqual

GreaterEqual

Greater

LessEqual

Less

SearchSorted

LogicalAndScalar

LogicalOrScalar

LogicalXorScalar

EqualScalar

NotEqualScalar

GreaterEqualScalar

GreaterScalar

LessEqualScalar

LessScalar

LogicalNot

IsNaN

X

IsInf

X

ResetNaN

X

ResetInf

X

Where

X

Math

Count 10/22

NNabla Function

Status

Constant

X

Arange

X

Abs

Exp

Log

Identity

X

BatchMatmul

Round

Ceil

Floor

Sin

Cos

Tan

Sinh

X

Cosh

X

ASin

X

ACos

X

ATan

X

ATan2

X

ASinh

X

ACosh

X

ATanh

X

Array Manipulation

Count 10/30

NNabla Function

Status

Concatenate

Split

Stack

Slice

Pad

Transpose

Broadcast

BroadcastTo

X

Tile

OneHot

X

Flip

Shift

Sort

Reshape

MatrixDiag

MatrixDiagPart

Meshgrid

BatchDet

BatchInv

BatchLogdet

Assign

Gather

GatherNd

BoolGather

ScatterNd

ScatterAdd

BoolScatter

BoolFill

PackPaddedSequence

PadPackedSequence

Signal Processing

Count 1/5

NNabla Function

Status

Interpolate

FFT

IFFT

STFT

ISTFT

Stochasticity

Count 0/15

NNabla Function

Status

Dropout

X

TopKData

TopKGrad

Rand

Randint

Randn

RandBinomial

RandBeta

RandGamma

RandomChoice

RandomCrop

RandomFlip

RandomShift

RandomErase

ImageAugmentation

Loss Functions

Count 0/9

NNabla Function

Status

SigmoidCrossEntropy

BinaryCrossEntropy

SoftmaxCrossEntropy

CategoricalCrossEntropy

SquaredError

AbsoluteError

HuberLoss

EpsilonInsensitiveLoss

KLMultinomial

Geometric Neural Network Layers

Count 0/3

NNabla Function

Status

AffineGrid

WarpByGrid

WarpByFlow

Quantization Neural Network Layers

Count 0/14

NNabla Function

Status

BinarySigmoid

X

BinaryTanh

X

BinaryConnectAffine

X

BinaryConnectConvolution

X

BinaryWeightAffine

X

BinaryWeightConvolution

X

INQAffine

INQConvolution

FixedPointQuantize

MinMaxQuantize

Pow2Quantize

Prune

QuantizeLinear

DequantizeLinear

Validation

Count 0/3

NNabla Function

Status

TopNError

BinaryError

ConfusionMatrix

Unsupported, Special Use

Count 0/6

NNabla Function

Status

VATNoise

Unlink

Sink

NmsDetection2d

MaxPoolingBackward

PatchCorrelation

NNabla C Runtime Support Status

NNabla version: None

  • ✓: Supported

  • △: Partially supported

  • X: Supported, but test failed or no test data.

  • Empty: Not support yet.

Export

Total: 56/215

Neural Network Layer

Count 8/18

NNabla Function

Status

Description

Affine

RNN

LSTM

GRU

Convolution

FusedConvolution

DepthwiseConvolution

Deconvolution

DepthwiseDeconvolution

DeformableConvolution

AdaptiveSeparableConvolution

MaxPooling

AveragePooling

GlobalAveragePooling

SumPooling

Unpooling

Embed

RoiAlign

Neural Network Activation Functions

Count 11/22

NNabla Function

Status

Description

Sigmoid

Swish

Tanh

ReLU

LeakyReLU

Softmax

LogSoftmax

ELU

SELU

CReLU

CELU

PReLU

GELU

Mish

ReLU6

HardSigmoid

HardTanh

LogSigmoid

SoftPlus

SoftSign

TanhShrink

Sinc

Normalization

Count 1/14

NNabla Function

Status

Description

FusedBatchNormalization

BatchNormalization

GroupNormalization

InstanceNormalization

LayerNormalization

NormNormalization

SyncBatchNormalization

TensorNormalization

X

WeightNormalization

WeightStandardization

SpectralNorm

MeanSubtraction

X

ClipGradByValue

ClipGradByNorm

Reduction

Count 1/10

NNabla Function

Status

Description

Sum

CumSum

Mean

Max

Min

Norm

Prod

CumProd

ReduceSum

ReduceMean

Arithmetic

Count 11/14

NNabla Function

Status

Description

Add2

AddN

X

BcAdd2

Sub2

Mul2

MulN

X

Div2

Pow2

AddScalar

MulScalar

PowScalar

RSubScalar

RDivScalar

RPowScalar

Logical

Count 5/30

NNabla Function

Status

Description

Sign

Minimum2

Maximum2

MinimumScalar

MaximumScalar

LogicalAnd

LogicalOr

LogicalXor

Equal

NotEqual

GreaterEqual

Greater

LessEqual

Less

SearchSorted

LogicalAndScalar

LogicalOrScalar

LogicalXorScalar

EqualScalar

NotEqualScalar

GreaterEqualScalar

GreaterScalar

LessEqualScalar

LessScalar

LogicalNot

IsNaN

IsInf

ResetNaN

ResetInf

Where

Math

Count 6/22

NNabla Function

Status

Description

Constant

Arange

Abs

Exp

Log

Identity

BatchMatmul

Round

Ceil

Floor

Sin

Cos

Tan

Sinh

Cosh

ASin

ACos

ATan

ATan2

ASinh

ACosh

ATanh

Array Manipulation

Count 7/30

NNabla Function

Status

Description

Concatenate

Split

Stack

Slice

Pad

Transpose

Broadcast

BroadcastTo

Tile

OneHot

Flip

Shift

X

Sort

Reshape

MatrixDiag

X

MatrixDiagPart

X

Meshgrid

BatchDet

BatchInv

BatchLogdet

Assign

Gather

GatherNd

BoolGather

ScatterNd

ScatterAdd

BoolScatter

BoolFill

PackPaddedSequence

PadPackedSequence

Signal Processing

Count 0/5

NNabla Function

Status

Description

Interpolate

FFT

IFFT

STFT

ISTFT

Stochasticity

Count 0/15

NNabla Function

Status

Description

Dropout

X

TopKData

TopKGrad

Rand

Randint

Randn

RandBinomial

RandBeta

RandGamma

RandomChoice

RandomCrop

RandomFlip

RandomShift

RandomErase

ImageAugmentation

Loss Functions

Count 0/9

NNabla Function

Status

Description

SigmoidCrossEntropy

BinaryCrossEntropy

SoftmaxCrossEntropy

CategoricalCrossEntropy

SquaredError

AbsoluteError

HuberLoss

EpsilonInsensitiveLoss

KLMultinomial

Geometric Neural Network Layers

Count 0/3

NNabla Function

Status

Description

AffineGrid

WarpByGrid

WarpByFlow

Quantization Neural Network Layers

Count 6/14

NNabla Function

Status

Description

BinarySigmoid

BinaryTanh

BinaryConnectAffine

BinaryConnectConvolution

BinaryWeightAffine

BinaryWeightConvolution

INQAffine

INQConvolution

FixedPointQuantize

MinMaxQuantize

Pow2Quantize

Prune

QuantizeLinear

DequantizeLinear

Validation

Count 0/3

NNabla Function

Status

Description

TopNError

BinaryError

ConfusionMatrix

Unsupported, Special Use

Count 0/6

NNabla Function

Status

Description

VATNoise

Unlink

Sink

NmsDetection2d

MaxPoolingBackward

PatchCorrelation

Model Support Status

ONNX Support Status

Import
  • ✓: Support to convert

  • X: Not support

Total: 11/12

ONNX Import Sample Test(onnx --> nnp)

Count 11/12

Export
  • ✓: Support to convert

  • X: Not support

Total: 60/65

ONNX Export Sample Test(nnp --> onnx)

Count 34/37

Name

Support

Memo

01_logistic_regression_10

01_logistic_regression_9

02_binary_cnn_15

02_binary_cnn_16

06_auto_encoder_17

06_auto_encoder_18

10_deep_mlp_13

10_deep_mlp_14

11_deconvolution_11

11_deconvolution_12

12_residual_learning_19

12_residual_learning_20

LSTM_auto_encoder_23

LSTM_auto_encoder_24

LeNet_35

LeNet_36

bidirectional_elman_net_25

bidirectional_elman_net_26

binary_connect_mnist_LeNet_5

binary_connect_mnist_MLP_8

binary_net_mnist_LeNet_7

binary_net_mnist_MLP_4

binary_weight_mnist_MLP_6

elman_net_21

elman_net_22

elman_net_with_attention_33

elman_net_with_attention_34

gated_recurrent_unitGRU_31

gated_recurrent_unitGRU_32

long_short_term_memoryLSTM_29

long_short_term_memoryLSTM_30

mnist_dcgan_with_label_1

X

NNabla converter error, will be fixed in the future.

mnist_dcgan_with_label_2

X

NNabla converter error, will be fixed in the future.

mnist_vae_3

semi_supervised_learning_VAT_37

X

NNP with only a single executor is currently supported.

stacked_GRU_27

stacked_GRU_28

ONNX Export Pretrained Model Test(nnp --> onnx)

Count 17/18

ONNX Export Example Model Test(nnp --> onnx)

Count 9/10

Name

Support

Memo

capsules

classification

cycle_gan

deeplabv3plus

meta_learning

pix2pix

siamese_embedding

wavenet

X

The onehot dimension != 2 is not supported.

word_embedding

yolov2

Tensorflow Support Status

Import
  • ✓: Support to convert

  • X: Not support

Total: 15/16

Tensorflow Import Sample Test(tf --> nnp)

Count 15/16

Export
  • ✓: Support to convert

  • X: Not support

Total: 58/65

Tensorflow Export Sample Test(nnp --> tf)

Count 34/37

Name

Support

Memo

01_logistic_regression_10

01_logistic_regression_9

02_binary_cnn_15

02_binary_cnn_16

06_auto_encoder_17

06_auto_encoder_18

10_deep_mlp_13

10_deep_mlp_14

11_deconvolution_11

11_deconvolution_12

12_residual_learning_19

12_residual_learning_20

LSTM_auto_encoder_23

LSTM_auto_encoder_24

LeNet_35

LeNet_36

bidirectional_elman_net_25

bidirectional_elman_net_26

binary_connect_mnist_LeNet_5

binary_connect_mnist_MLP_8

binary_net_mnist_LeNet_7

binary_net_mnist_MLP_4

binary_weight_mnist_MLP_6

elman_net_21

elman_net_22

elman_net_with_attention_33

elman_net_with_attention_34

gated_recurrent_unitGRU_31

gated_recurrent_unitGRU_32

long_short_term_memoryLSTM_29

long_short_term_memoryLSTM_30

mnist_dcgan_with_label_1

X

NNabla converter error, will be fixed in the future.

mnist_dcgan_with_label_2

X

NNabla converter error, will be fixed in the future.

mnist_vae_3

semi_supervised_learning_VAT_37

X

NNP with only a single executor is currently supported.

stacked_GRU_27

stacked_GRU_28

Tensorflow Export Pretrained Models(nnp --> tf)

Count 15/18

Tensorflow Export Example Models(nnp --> tf)

Count 9/10

Name

Support

Memo

capsules

classification

cycle_gan

deeplabv3plus

meta_learning

pix2pix

siamese_embedding

wavenet

X

The onehot dimension != 2 is not supported.

word_embedding

yolov2

Tensorflow Lite Support Status

Export
  • ✓: Support to convert

  • X: Not support

Total: 46/65

Tensorflow Lite Export Sample Test(nnp --> tflite)

Count 29/37

Name

Support

Memo

01_logistic_regression_10

01_logistic_regression_9

02_binary_cnn_15

02_binary_cnn_16

06_auto_encoder_17

06_auto_encoder_18

10_deep_mlp_13

10_deep_mlp_14

11_deconvolution_11

11_deconvolution_12

12_residual_learning_19

12_residual_learning_20

LSTM_auto_encoder_23

LSTM_auto_encoder_24

LeNet_35

LeNet_36

bidirectional_elman_net_25

bidirectional_elman_net_26

binary_connect_mnist_LeNet_5

X

binary_connect_mnist_MLP_8

X

binary_net_mnist_LeNet_7

X

binary_net_mnist_MLP_4

X

binary_weight_mnist_MLP_6

X

elman_net_21

elman_net_22

elman_net_with_attention_33

elman_net_with_attention_34

gated_recurrent_unitGRU_31

gated_recurrent_unitGRU_32

long_short_term_memoryLSTM_29

long_short_term_memoryLSTM_30

mnist_dcgan_with_label_1

X

mnist_dcgan_with_label_2

X

mnist_vae_3

semi_supervised_learning_VAT_37

X

stacked_GRU_27

stacked_GRU_28

Tensorflow Lite Export Pretrained Models(nnp --> tflite)

Count 10/18

Tensorflow Lite Export Example Models(nnp --> tflite)

Count 7/10

NNabla C Runtime Support Status

Export
  • ✓: Support to convert

  • X: Not support

Total: 34/37

NNC Export Sample Test(nnp --> nnb)

Count 34/37

Name

Support

Memo

01_logistic_regression_10

01_logistic_regression_9

02_binary_cnn_15

02_binary_cnn_16

06_auto_encoder_17

06_auto_encoder_18

10_deep_mlp_13

10_deep_mlp_14

11_deconvolution_11

11_deconvolution_12

12_residual_learning_19

12_residual_learning_20

LSTM_auto_encoder_23

LSTM_auto_encoder_24

LeNet_35

LeNet_36

bidirectional_elman_net_25

bidirectional_elman_net_26

binary_connect_mnist_LeNet_5

binary_connect_mnist_MLP_8

binary_net_mnist_LeNet_7

binary_net_mnist_MLP_4

binary_weight_mnist_MLP_6

elman_net_21

elman_net_22

elman_net_with_attention_33

elman_net_with_attention_34

gated_recurrent_unitGRU_31

gated_recurrent_unitGRU_32

long_short_term_memoryLSTM_29

long_short_term_memoryLSTM_30

mnist_dcgan_with_label_1

X

Failed to infer by nnabla.

mnist_dcgan_with_label_2

X

Failed to compare inferring result.

mnist_vae_3

semi_supervised_learning_VAT_37

X

Failed to compare inferring result.

stacked_GRU_27

stacked_GRU_28

INT8 Quantized TFLite Support Status

Only a subset of tflite ops supports INT8 data type. If your model includes an unsupported op, the quantized converter will raise an error.

You can check all INT8 ops below:

  • ADD

  • AVERAGE_POOL_2D

  • CONCATENATION

  • CONV_2D

  • DEPTHWISE_CONV_2D

  • FULLY_CONNECTED

  • L2_NORMALIZATION

  • LOGISTIC

  • MAX_POOL_2D

  • MUL

  • RESHAPE

  • RESIZE_BILINEAR

  • SOFTMAX

  • SPACE_TO_DEPTH

  • TANH

  • PAD

  • GATHER

  • BATCH_TO_SPACE_ND

  • SPACE_TO_BATCH_ND

  • TRANSPOSE

  • MEAN

  • SUB

  • SUM

  • SQUEEZE

  • LOG_SOFTMAX

  • MAXIMUM

  • ARG_MAX

  • MINIMUM

  • LESS

  • PADV2

  • GREATER

  • GREATER_EQUAL

  • LESS_EQUAL

  • SLICE

  • EQUAL

  • NOT_EQUAL

  • SHAPE

  • QUANTIZE

  • RELU

  • LEAKY_RELU

Note that CONCATENATION is in the supported op list, but we recommend that you avoid using it. CONCATENATION will bring additional quantization error and may lead to significant degradation of accuracy.

コントリビューションガイド

Github に移動しました。

License

Copyright (c) 2017 Sony Corporation. All rights reserved.

Apache License

Version 2.0, January 2004

http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

  1. Definitions.

"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

  1. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

  2. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

  3. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.

You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

  1. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

  2. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

  3. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

  4. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: HOW TO APPLY THE APACHE LICENSE TO YOUR WORK To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.

Copyright 2017, Sony Corporation

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

インデックスと表