関数

すべての NNabla 関数は nnabla.function.Function クラスから派生しています。

Function

class nnabla.function.Function

Function のインターフェイスクラス。

nnabla.function.Function のインスタンスはユーザによって直接生成されることはありません。 nnabla.functions が提供する関数によって間接的に生成されます。これらの関数は、親プロパティとして生成された関数のインスタンスを保持する nnabla.Variable を返します。

args

Experimental

Get args of the function.

auto_grad_depends_input_data(self, int i, int j)
auto_grad_depends_output_data(self, int i, int o)
backward(self, inputs, outputs, accum=None)
forward(self, inputs, outputs)
grad_depends_input_data(self, int i, int j)
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)
set_active_input_mask(self, mask)
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 function implements Elman RNN with nonlinearity to input sequence. RNN function is defined as following:

\[{\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 -- A tuple of top, bottom, left and right padding extent. A tuple of two values yields identical top/bottom and left/right padding from the first and second tuple value. A single integer expands to identical padding extent for all sides.

  • 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.\]

A channel size of the output is calculated as

\[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.batch_cholesky(x, upper=False, n_outputs=-1, outputs=None)[ソース]

Batch-wise cholesky decomposition of symmetric positive definite matrix. The gradient of this function will be a symmetric matrix. This function does not check whether given matrix is symmetric positive define matrix or not.

パラメータ:
  • x (Variable) -- バッチ化されたN-D配列

  • upper (bool) -- If true, will return an upper triangular matrix. Otherwise will return a lower triangular matrix. [default= False ]

戻り値:

batched N-D array of lower/upper triangular matrix.

戻り値の型:

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

nnabla.functions.erf(x, n_outputs=-1, outputs=None)[ソース]

Element-wise Error function.

\[y_i = \text{erf} (x_i)\]
パラメータ:

x (Variable) -- N-D 配列

戻り値:

x と同じ形状の N-D 配列

戻り値の型:

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)[ソース]

Slice arrays along specified axis. This function complies with python slice where slice(None, None, -1) and slice(-1, None, -1) are the special case, which flips the input array and results in the output array from the end to the beginning of the input array along the corresponding dimension.

パラメータ:
  • 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 outputs

\[\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)[ソース]

Sorts the elements of x along a given axis in ascending order by value. A negative axis counts from the last dimension of x, so the default of -1 sorts along the last dimension. If reverse is True, then the elements are sorted in descending order.

もし 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.shape(x, start=None, end=None, n_outputs=-1, outputs=None)[ソース]

Get the shape of a tensor. Optional attributes start and end can be used to compute a slice of the input tensor's shape. If start axis is omitted, the slice starts from axis 0.

パラメータ:
  • x (Variable) -- N-D 配列。

  • start (int) -- If start axis is omitted, the slice starts from axis 0. [default= 0 ]

  • end (int) -- The end axis, if specified, is exclusive (and the returned value will not include. [default= 0 ]

戻り値:

1-D array

戻り値の型:

Variable

注釈

nnabla.functions にあるすべての nnabla 関数は nnabla.function_bases.function_api デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。

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)[ソース]

This function creates one-hot vector based on input indices. The range [-shape[i], -1] of input indices are regarded as [0, shape[i]-1], and an input index outside [-shape[i], shape[i]-1] generates a vector filled with zero.

例 :

import nnabla as nn
import nnabla.functions as F
import numpy as np

labels = nn.Variable.from_numpy_array(np.array([[9], [4], [5], [-9], [10]]))
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.]
#  [0. 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) -- Number of classes. When nd-labels are given, dimensions must match. See the example above.

戻り値:

ベクトル / テンソルの 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, largest=True, with_index=False, 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 ]

  • largest (bool) -- Whether to select the k largest or smallest values. [default= True ]

  • with_index (bool) -- Return top-k values and indices. [default= False ]

戻り値:

N-D array. ~nnabla.Variable: N-D array of top-k indices.

戻り値の型:

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 デコレーターを使ってデコレートされ、デコレーターは現在のコンテキストを問い合わせて元の関数の第一引数に渡します。元の関数は常に第一引数としてコンテキストを取ります。