renom.layers.function ¶
-
class
renom.layers.function.parameterized.
Model
¶ -
ニューラルネットワークモデルに関する抽象クラス.
-
forward
( ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
train
( ) ¶ -
計算グラフを作成するためのコンテキストを管理するコンテキストマネジャー.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z ... >>> x = rm.Variable(np.random.rand(3, 3)) >>> y = np.random.rand(3, 2) >>> model = Model() >>> z = model(x) >>> >>> with model.train(): ... loss = rm.mean_squared_error(z, y) ... >>> dx1 = loss.grad().get(x) >>> print("Gradient1 of x is \n{}".format(dx1)) Gradient1 of x is array([[ 0.85432934, 0.51205811], [ 0.20379112, 0.62481132], [ 0.49004569, 0.35310219]]) >>> >>> loss = rm.mean_squared_error(z, y) >>> dx2 = loss.grad().get(x) >>> print("Gradient2 of x is \n{}".format(dx2)) Gradient2 of x is None
-
prevent_update
( ) ¶ -
コンテキストマネージャ内においてGradsクラスのupdate()関数による重みパラメータのパラメータを実行した場合, そのコンテキストを持つModelの属性として定義された重みパラメータは更新されない.
Example
>>> import numpy as np >>> import renom as rm >>> model = rm.Sequential([ ... rm.Dense(1) ... ]) >>> x = np.random.rand(2, 2) >>> y = np.random.rand(2, 1) >>> >>> with model.train(): ... loss = rm.mean_squared_error(model(x), y) >>> >>> print("Before", model[0].params.w) Before [[ 0.03417877] [-0.29819158]] >>> loss.grad().update() >>> print("Updated", model[0].params.w) Updated [[ 0.526793 ] [ 0.00882804]] >>> >>> >>> print("Before", model[0].params.w) Before [[ 0.526793 ] [ 0.00882804]] >>> >>> # Performs update inside the context manager. >>> with model.prevent_update(): ... loss.grad().update() >>> print("Not updated", model[0].params.w) Not updated [[ 0.526793 ] [ 0.00882804]]
-
values
( ) ¶ -
Modelオブジェクトが持つ重みパラメータをネストされたタプルとして返す.
Modelオブジェクトは属性としてModelオブジェクトを持つことがある.valuesメソッドを実行すると, それぞれのModelオブジェクトは二つの辞書からなるタプルを返す. ひとつ目の辞書は子要素が持つ重みパラメータを持つ. ふたつ目の辞書にはModel自身(self)が持つ重みパラメータが含まれる.
Example
( # child models of self { 'layer1': ( {}, # child model of self.layer1 { # params of layer1 'w': [1,2], # self.layer1.params.w 'b': [3,4], # self.layer1.params.b } ), 'layer2': ( {}, # child model of self.layer2 { # params of layer2 'w': [1,2], # self.layer2.params.w 'b': [3,4], # self.layer2.params.b } }, # params of self {} )
-
join_grads
( grads , others ) ¶ -
引数gradに与えられたGradsオブジェクトが持つ勾配データに対し,引数others(Model, Gradsオブジェクトのタプル)が持つ勾配データを足し合わせる.引数に与えられるすべてのModelオブジェクトは等しい構造を持つ必要がある.
-
save
( filename ) ¶ -
Modelオブジェクトが持つ属性を保存する. 保存したい属性名を'SERIALIZED'という名前のタプルに登録することで, saveメソッドによる保存対象に含むことができる.Modelオブジェクトが持つ重みパラメータはSERIALIZEDに登録せずとも保存される.
以下にその例を示す.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class MyModel(rm.Model): ... SERIALIZED = ('_moving_avg', ) # Put any attributes for saving. ... def __init__(self): ... super(MyModel, self).__init__() ... self._l1 = rm.Dense(2) ... self._l2 = rm.Dense(1) ... self._moving_avg = 0 ... def forward(self, x): ... h = self._l1(x) ... h = rm.relu(h) ... h = self._l2(h) ... self._moving_avg = np.float32(self._moving_avg*0.5 + rm.sum(h)*0.5) ... return h ... >>> model = MyModel() >>> model(np.random.rand(12, 4)) >>> print(model._moving_avg) 1.95637 >>> model.save("test.h5") # Save >>> model = MyModel() # Reset model object. >>> model.load("test.h5") # Load >>> print(model._moving_avg) 1.95637
パラメータ: filename ( str ) -- モデルを保存する際のパス.
-
load
( filename ) ¶ -
保存した属性値をモデルにロードする.
パラメータ: filename ( str ) -- ロードするモデルのパス Example
>>> model = rm.Dense(2) >>> model.load("model.hd5")
-
set_initializer
( initializer ) ¶ -
前層における重みパラメータを同一条件で初期化.
以下にその例を示す.
パラメータ: initializer ( Initializer ) -- 初期化オブジェクト Example
>>> import renom as rm >>> import numpy as np >>> from renom.utility.initializer import Orthogonal >>> >>> class MyModel(rm.Model): ... def __init__(self): ... super(MyModel, self).__init__() ... self._l1 = rm.Dense(2) ... self._l2 = rm.Dense(1) ... self._moving_avg = 0 ... def forward(self, x): ... h = self._l1(x) ... h = rm.relu(h) ... h = self._l2(h) ... return h >>> >>> model = MyModel() >>> model.set_initializer(Orthogonal()) >>> >>> x = np.random.random((3,4)) >>> y = model(x) >>> >>> weight=model._l1.params.w >>> print("weight\n",weight) weight [[-0.43140578 0.39115947] [-0.53214586 -0.61308974] [-0.5807101 0.5656842 ] [-0.43986994 -0.3887372 ]] >>> >>> print("dot product\n",np.dot(weight.T,weight)) dot product [[1. 0.] [0. 1.]]
-
-
class
renom.layers.function.parameterized.
Sequential
( layers , loss_function=None ) ¶ -
Sequential model.
パラメータ: layers ( list ) -- レイヤオブジェクトのリスト Example
>>> import renom as rm >>> import numpy as np >>> >>> x = np.random.rand(32, 50) >>> sequential = rm.Sequential([ ... rm.Dense(100), ... rm.Relu(), ... rm.Dense(10), ... ]) ... >>> z = sequential(x) >>> z.shape (32, 10)
-
class
renom.layers.function.batch_normalize.
BatchNormalize
( input_size=None , momentum=0.99 , mode='activation' , epsilon=1e-05 , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
Batch normalization関数. [bn]
順伝播時に引数
inference
にFalseがセットされていた場合,バッチごとの平均, 分散を用いてバッチ正規化を行う. さらにそれら平均と分散それぞれの学習時における移動平均が計算される. Trueがセットされていた場合, 学習時に取られた統計量の移動平均を用いてバッチ正規化を行う.引数modeに
activation
が与えらた場合, バッチ正規化は各ユニットの出力に対して適用される. modeにfeature
が与えられた場合, バッチ正規化は各チャンネルに対して行われる.上記の理由から'feature'モードは4次元テンソルが入力された場合のみ有効となる.
'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: Example
>>> import numpy as np >>> import renom as rm >>> x = np.random.rand(3, 2) >>> x.shape (3, 2) >>> layer = rm.BatchNormalize(momentum=0.99) >>> layer(x, inference=False) batch_normalize([[-0.05047419, 0.00471613], [-0.00887055, -0.01459344], [ 0.05934474, 0.00987731]], dtype=float32)
[bn] Sergey Ioffe, Christian Szegedy. Batch Normalization: Accelerating Deep Network Training by Reducing Internal Covariate Shift(2015) -
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
-
class
renom.layers.function.conv2d.
Conv2d
( channel=32 , filter=3 , padding=0 , stride=1 , dilation=1 , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
2D畳み込み関数.
このクラスは畳込フィルタを持ち, 入力に対してフィルタとの畳込み演算を実行する.4次元テンソルデータのみを入力として受け付ける.
インスタンス化時に,フィルタサイズ, パディング, ストッライドなどのパラメータをintもしくはtupleで与えることができる.
'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: - channel ( int ) -- 出力チャンネル数
- filter ( tuple , int ) -- フィルタサイズ
- padding ( tuple , int ) -- ゼロパディングサイズ
- stride ( tuple , int ) -- ストライドサイズ
- dilation ( tupe , int ) -- 膨張サイズ
- input_size ( tuple ) -- 入力データサイズ. (channel, height, width)形式のtupleに対応.
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> n, c, h, w = (10, 3, 32, 32) >>> x = np.random.rand(n, c, h, w) >>> x.shape (10, 3, 32, 32) >>> layer = rm.Conv2d(channel=32) >>> z = layer(x) >>> z.shape (10, 32, 30, 30)
注釈
テンソルデータのフォーマットは NCHW の並び順となっている.
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.convnd.
ConvNd
( channel=2 , filter=3 , padding=0 , stride=1 , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.Gaussian object> ) ¶ -
N次元畳み込み関数.
このクラスは畳込フィルタを持ち, 入力に対してフィルタとの畳込み演算を実行する.CPUモードでは, 任意次元のテンソルデータを, GPUモードでは2~3次元テンソルデータを入力として受け付ける.
インスタンス化時に,フィルタサイズ, パディング, ストッライドなどのパラメータをintもしくはtupleで与えることができる.
'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: - channel ( int ) -- 出力チャンネル数
- filter ( int ) -- フィルタサイズ
- padding ( int ) -- ゼロパディングサイズ
- stride ( int ) -- ストライドサイズ
- input_size ( tuple ) -- 入力データサイズ. (channel, height, width)形式のtupleに対応.
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> n, c, h, w = (10, 3, 32, 32) >>> x = np.random.rand(n, c, h, w) >>> x.shape (10, 3, 32, 32) >>> layer = rm.ConvNd(channel=32) >>> z = layer(x) >>> z.shape (10, 32, 30, 30)
注釈
テンソルデータのフォーマットは NC(D*) の並び順となっている.
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.convnd.
Conv3d
( channel=2 , filter=3 , padding=0 , stride=1 , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.Gaussian object> , weight_decay=0 ) ¶ -
3次元畳み込み関数. ConvNd関数においてN=3とした畳込みと等しい.
注釈
テンソルデータのフォーマットは NCHWD の並び順となっている.
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
-
class
renom.layers.function.group_conv2d.
GroupConv2d
( channel=32 , filter=3 , padding=0 , stride=1 , dilation=1 , groups=1 , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
2Dグループ畳み込み関数.
このクラスは畳込フィルタを持ち, 入力に対してフィルタとの畳込み演算を実行する.4次元テンソルデータのみを入力として受け付ける.
インスタンス化時に,フィルタサイズ, パディング, ストッライドなどのパラメータをintもしくはtupleで与えることができる.
'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: - channel ( int ) -- 出力チャンネル数
- filter ( tuple , int ) -- フィルタサイズ
- padding ( tuple , int ) -- ゼロパディングサイズ
- stride ( tuple , int ) -- ストライドサイズ
- dilation ( tupe , int ) -- 膨張サイズ
- input_size ( tuple ) -- 入力データサイズ. (channel, height, width)形式のtupleに対応.
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
- groups ( int ) -- 畳み込み演算を実行するグループの数. 出力チャネル数と入力チャネル数の約数でなければならない.
Example
>>> import numpy as np >>> import renom as rm >>> n, c, h, w = (10, 3, 32, 32) >>> x = np.random.rand(n, c, h, w) >>> x.shape (10, 16, 32, 32) >>> layer = rm.GroupConv2d(channel=32, groups=8) >>> z = layer(x) >>> z.shape (10, 32, 30, 30)
注釈
テンソルデータのフォーマットは NCHW の並び順となっている.
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.deconv2d.
Deconv2d
( channel=1 , filter=3 , padding=0 , stride=1 , dilation=1 , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
2D畳み込み関数.
このクラスは畳込フィルタを持ち, 入力に対してフィルタとの畳込み演算を実行する.4次元テンソルデータのみを入力として受け付ける.
インスタンス化時に,フィルタサイズ, パディング, ストッライドなどのパラメータをintもしくはtupleで与えることができる.
'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: - channel ( int ) -- 出力チャンネル数
- filter ( tuple , int ) -- フィルタサイズ
- padding ( tuple , int ) -- ゼロパディングサイズ
- stride ( tuple , int ) -- ストライドサイズ
- dilation ( tuple , int ) -- 膨張サイズ
- input_size ( tuple ) -- 入力データサイズ. (channel, height, width)形式のtupleに対応.
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> n, c, h, w = (10, 3, 32, 32) >>> x = np.random.rand(n, c, h, w) >>> x.shape (10, 3, 32, 32) >>> layer = rm.Deconv2d(channel=32) >>> z = layer(x) >>> z.shape (10, 32, 34, 34)
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.deconvnd.
DeconvNd
( channel=2 , filter=3 , padding=0 , stride=1 , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.Gaussian object> ) ¶ -
N次元畳み込み関数.
このクラスは畳込フィルタを持ち, 入力に対してフィルタとの畳込み演算を実行する.CPUモードでは, 任意次元のテンソルデータを, GPUモードでは2~3次元テンソルデータを入力として受け付ける.
インスタンス化時に,フィルタサイズ, パディング, ストッライドなどのパラメータをintもしくはtupleで与えることができる.
'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: - channel ( int ) -- 出力チャンネル数
- filter ( int ) -- フィルタサイズ
- padding ( int ) -- ゼロパディングサイズ
- stride ( int ) -- ストライドサイズ
- input_size ( tuple ) -- 入力データサイズ. (channel, height, width)形式のtupleに対応.
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> n, c, h, w = (10, 3, 32, 32) >>> x = np.random.rand(n, c, h, w) >>> x.shape (10, 3, 32, 32) >>> layer = rm.ConvNd(channel=32) >>> z = layer(x) >>> z.shape (10, 32, 30, 30)
注釈
テンソルデータのフォーマットは NC(D*) の並び順となっている.
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.dense.
Dense
( output_size , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
以下の式で表される全結合レイヤ
f(x)= w \cdot x + b'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: - output_size ( int ) -- 出力ユニットサイズ
- input_size ( int ) -- 入力ユニットサイズ
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> x = np.random.rand(3, 2) >>> x.shape (3, 2) >>> layer = rm.Dense(3) >>> z = layer(x) >>> z.shape (3, 3)
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.dropout.
Dropout
( dropout_ratio=0.5 ) ¶ -
入力に対してドロップアウト [dropout] を適用する.
dropout_ratio
に与えられた割合で入力をランダムに0とする.0とならなかった値に対しては1/(1 - dropout_ratio)
をかけている.パラメータ: dropout_ratio ( float ) -- ドロップアウト率 Example
>>> import numpy as np >>> import renom as rm >>> >>> x = rm.Variable(np.random.rand(3, 2)) >>> x Variable([[ 0.49312586, 0.95414829], [ 0.7346437 , 0.9014256 ], [ 0.09413767, 0.29910043]], dtype=float32) >>> layer = rm.Dropout(0.2) >>> z = layer(x) >>> z dropout([[ 0. , 1.19268537], [ 0.91830462, 1.12678194], [ 0. , 0.37387553]], dtype=float32)
>>> z = rm.dropout(x, 0.75) >>> z dropout([[ 0.65750116, 0. ], [ 0. , 1.20190084], [ 0.12551689, 0.39880058]], dtype=float32)
[dropout] - Hinton, Geoffrey E.; Srivastava, Nitish; Krizhevsky, Alex; Sutskever,
- Ilya; Salakhutdinov, Ruslan R. (2012).
Improving neural networks by preventing co-adaptation of feature detectors
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.dropout.
SpatialDropout
( dropout_ratio=0.5 ) ¶ -
チャンネルごとにドロップアウトを適用する.
パラメータ: dropout_ratio ( float ) -- ドロップアウト率 Raises: 入力テンソルが4次元でない場合, Assertion エラーを発生させる. Example
>>> import numpy as np >>> import renom as rm >>> x = rm.Variable(np.random.rand(3, 3, 1, 1)) Variable([[[[ 0.55784005]], [[ 0.99528867]], [[ 0.77544725]]], [[[ 0.65406305]], [[ 0.27961349]], [[ 0.43104461]]], [[[ 0.66176379]], [[ 0.70499772]], [[ 0.87102354]]]], dtype=float32) >>> z = rm.spatial_dropout(x) >>> z spatial_dropout([[[[ 1.1156801 ]], [[ 0. ]], [[ 1.5508945 ]]], [[[ 1.30812609]], [[ 0.55922699]], [[ 0. ]]], [[[ 0. ]], [[ 1.40999544]], [[ 1.74204707]]]], dtype=float32)
注釈
SpatialDropoutは4次元テンソルのみを入力とする.
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
-
class
renom.layers.function.embedding.
Embedding
( output_size , input_size , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=None ) ¶ -
Embedding層. この層は全結合層の特別なケースを表す.Embedding層は入力データがone-hotエンコーディングされた行列である場合に使用できる.One hotエンコーディングされた行列データはスパースであるため, 全結合層(Dense)による演算は冗長となる. Embedding層ではone-hotエンコーディングされた入力データを省メモリで扱える.
全結合層とEmbedding層の違いは以下のとおりである.
[Dense layer]data -> onehot encoding -> onehot data -> dense layer -> embedded data[Embedding layer]data -> embedding layer -> embedded dataパラメータ: - output_size ( int ) -- 出力ユニットサイズ
- input_size ( int ) -- 入力ユニットサイズ. ここで与えられる数はEmbeddingを行う説明変数の数と等しい必要がある.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> N = 4 >>> a = np.arange(N).reshape(N, 1) >>> layer = rm.Embedding(output_size=1, input_size=8) >>> out = layer(a)
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.flatten.
Flatten
¶ -
入力テンソルを二次元テンソルに変形する.第一軸はバッチサイズ, 第二軸はデータ次元数となる.
Example
>>> x = np.random.rand(3, 3, 32, 32) >>> x = rm.Variable(x) >>> z = rm.flatten(x) >>> x.shape (3, 3, 32, 32) >>> z.shape (3, 3072)
>>> # Use as a instance. >>> layer = rm.Flatten() >>> z = layer(x) >>> z.shape (3, 3072)
-
class
renom.layers.function.gru.
Gru
( output_size , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
Gated Recurrent Unit
LSTMと同様に, 再帰的な構造を持つユニット.
パラメータ: - output_size ( int ) -- 出力ユニットサイズ
- input_size ( int ) -- 入力ユニットサイズ
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> n, d, t = (2, 3, 4) >>> x = rm.Variable(np.random.rand(n,d)) >>> layer = rm.Gru(2) >>> z = 0 >>> for i in range(t): ... z += rm.sum(layer(x)) ... >>> grad = z.grad() >>> grad.get(x) Add([[-8.89559174, -0.58861321, -4.67931843], [-7.27466679, -0.45286781, -3.81758523]], dtype=float32) >>> layer.truncate()
https://arxiv.org/pdf/1409.1259.pdf
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
truncate
( ) ¶ -
時系列方向の計算グラフのつながりを切る.
-
class
renom.layers.function.lrn.
Lrn
( n=5 , k=2 , a=0.0001 , b=0.75 ) ¶ -
局所正規化レイヤ [lrn] .
y_{c_{out},j,i}= \frac{x_{c_{in},i,j}}{(k + a{\sum_{c=max(0, i-n/2)}^{min(N-1, i+n/2)} (x_{c,i,j})})^b}x_{c,i,j} は第cチャンネルの(i, j)ピクセル値を表す.:math: y_{c_{out},j,i} は局所正規化レイヤの出力を表す.:math: N は特徴マップ数. n 正規化に使用される隣接する特徴マップ数.ハイパーパラメータにはデフォルト値を推奨している.
パラメータ: Example
>>> import numpy as np >>> import renom as rm >>> x = np.random.rand(3, 3, 32, 32) >>> layer = rm.Lrn() >>> z=layer(x) >>> z.shape (3, 3, 32, 32)
[lrn] Alex Krizhevsky Krizhevsky, , Ilya IlyaSutskever Sutskever, Geoff. ImageNet Classification with Deep Convolutional Neural Networks
-
class
renom.layers.function.layer_normalize.
LayerNormalize
( gain=0.1 , bias=1.0 ) ¶ -
レイヤ正規化関数.
パラメータ: Example
>>> import numpy as np >>> import renom as rm >>> x = np.random.rand(2,3) >>> layer = rm.LayerNormalize(bias=0) >>> x array([[0.5833913 , 0.39715111, 0.19503325], [0.74007066, 0.34642472, 0.57293373]]) >>> layer(x) layer_normalize([[ 0.12076415, 0.00333703, -0.12410118], [ 0.11587134, -0.12813905, 0.01226771]])
[1] https://arxiv.org/pdf/1607.06450.pdf -
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
-
class
renom.layers.function.weight_normalize.
WeightNormalize
( units , gain=0.1 , initializer=<renom.utility.initializer.GlorotNormal object> , input_size=None , weight_decay=0 ) ¶ -
ウェイト正規化関数.
- The weight in this form is parameterized by the form:
- w = v / ||v|| * gain
- Note that in this version, gain is taken linear on the input s giving:
- gain = s.
The original paper suggests a potential gain parameterization by taking the exponential value of s instead:
gain = exp(s)There might be support for this later.
Example
>>> import numpy as np >>> import renom as rm >>> x = np.random.rand(2,3) >>> layer = rm.WeightNormalization(4) >>> layer(x) weight_normalize([[1.00133252, 1.00713646, 0.98452991, 1.0043143], [0.983392 , 1.01545942, 0.99134618, 1.01834679]], dtype=float32)
[weight_norm] https://arxiv.org/abs/1602.07868 -
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
class
renom.layers.function.lstm.
Lstm
( output_size , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
Lstmレイヤ [lstm] . このレイヤは8個の重みと4つのバイアスを学習パラメータとして持つ.
前の層から入力されるデータに対してかけられる重み. W_{ij}, Wgi_{ij}, Wgf_{ij}, Wgo_{ij}
一時刻前から入力されるデータに対してかけられる重み. R_{ij}, Rgi_{ij}, Rgf_{ij}, Rgo_{ij}
\begin{split}u^t_{i} &= \sum_{j = 0}^{J-1} W_{ij}x^t_{j} + \sum_{k = 0}^{K-1} R_{ik}y^{t-1}_{k} + b_i \\ gi^t_{i} &= \sum_{j = 0}^{J-1} Wgi_{ij}x^t_{j} + \sum_{k = 0}^{K-1} Rgi_{ik}y^{t-1}_{k} + bi_i \\ gf^t_{i} &= \sum_{j = 0}^{J-1} Wgfi_{ij}x^t_{j} + \sum_{k = 0}^{K-1} Rgf_{ik}y^{t-1}_{k} + bi_f \\ go^t_{i} &= \sum_{j = 0}^{J-1} Wgo_{ij}x^t_{j} + \sum_{k = 0}^{K-1} Rgo_{ik}y^{t-1}_{k} + bi_o \\ s^t_i &= sigmoid(gi^t_{i})tanh(u^t_{i}) + s^{t-1}_isigmoid(gf^t_{i}) \\ y^t_{i} &= go^t_{i}tanh(s^t_{i})\end{split}'input_size'が与えられた場合, このレイヤが持つ重みパラメータはレイヤのインスタン化時に初期化される.そうでない場合, 重みパラメータは順伝播計算が初めて実行された際にインスタンス化される.
パラメータ: - output_size ( int ) -- 出力ユニットサイズ
- input_size ( int ) -- 入力ユニットサイズ
- ignore_bias ( bool ) -- True が与えられた場合, biasパラメータは使用されない.
- initializer ( Initializer ) -- 重みパラメータの初期値を与えるInitializerオブジェクト.
Example
>>> import numpy as np >>> import renom as rm >>> >>> n, d, t = (2, 3, 4) >>> x = rm.Variable(np.random.rand(n, d)) >>> layer = rm.Lstm(2) >>> z = 0 >>> for i in range(t): ... z += rm.sum(layer(x)) ... >>> grad = z.grad() # Backpropagation. >>> grad.get(x) # Gradient of x. Add([[-0.01853334, -0.0585249 , 0.01290053], [-0.0205425 , -0.05837972, 0.00467286]], dtype=float32) >>> layer.truncate()
[lstm] Learning Precise Timing with LSTM Recurrent Networks -
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
truncate
( ) ¶ -
時系列方向の計算グラフのつながりを切る.
-
class
renom.layers.function.peephole_lstm.
PeepholeLstm
( output_size , input_size=None , ignore_bias=False , initializer=<renom.utility.initializer.GlorotNormal object> , weight_decay=0 ) ¶ -
Peephole付きLstmレイヤ.このレイヤは8個の重みと4つのバイアスを学習パラメータとして持つ.
前の層から入力されるデータに対してかけられる重み. W_{ij}, Wgi_{ij}, Wgf_{ij}, Wgo_{ij}
一時刻前から入力されるデータに対してかけられる重み. R_{ij}, Rgi_{ij}, Rgf_{ij}, Rgo_{ij}
前の層から入力されるデータに対してかけられる重み. W_{ij}, Wgi_{ij}, Wgf_{ij}, Wgo_{ij}
\begin{split}u^t_{i} &= \sum_{j = 0}^{J-1} W_{ij}x^t_{j} + \sum_{k = 0}^{K-1} R_{ik}y^{t-1}_{k} + P_{i}s^{t-1}_{i} + b_i \\ gi^t_{i} &= \sum_{j = 0}^{J-1} Wgi_{ij}x^t_{j} + \sum_{k = 0}^{K-1} Rgi_{ik}y^{t-1}_{k} + Pgi_{i}s^{t-1}_{i} + bi_i \\ gf^t_{i} &= \sum_{j = 0}^{J-1} Wgfi_{ij}x^t_{j} + \sum_{k = 0}^{K-1} Rgf_{ik}y^{t-1}_{k} + Pgf_{i}s^{t-1}_{i} + bi_f \\ go^t_{i} &= \sum_{j = 0}^{J-1} Wgo_{ij}x^t_{j} + \sum_{k = 0}^{K-1} Rgo_{ik}y^{t-1}_{k} + Pgo_{i}s^{t}_{i} + bi_o \\ s^t_i &= sigmoid(gi^t_{i})tanh(u^t_{i}) + s^{t-1}_isigmoid(gf^t_{i}) \\ y^t_{i} &= go^t_{i}tanh(s^t_{i})\end{split}パラメータ: Example
>>> import numpy as np >>> import renom as rm >>> >>> n, d, t = (2, 3, 4) >>> x = rm.Variable(np.random.rand(n, d)) >>> layer = rm.PeepholeLstm(2) >>> z = 0 >>> for i in range(t): ... z += rm.sum(layer(x)) ... >>> grad = z.grad() # Backpropagation. >>> grad.get(x) # Gradient of x. Add([[-0.01853334, -0.0585249 , 0.01290053], [-0.0205425 , -0.05837972, 0.00467286]], dtype=float32) >>> layer.truncate()
[plstm] Felix A. Gers, Nicol N. Schraudolph, J ̈urgen Schmidhuber. Learning Precise Timing with LSTM Recurrent Networks -
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
truncate
( ) ¶ -
時系列方向の計算グラフのつながりを切る.
-
-
class
renom.layers.function.parameterized.
Model
-
ニューラルネットワークモデルに関する抽象クラス.
-
forward
( ) -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
train
( ) -
計算グラフを作成するためのコンテキストを管理するコンテキストマネジャー.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z ... >>> x = rm.Variable(np.random.rand(3, 3)) >>> y = np.random.rand(3, 2) >>> model = Model() >>> z = model(x) >>> >>> with model.train(): ... loss = rm.mean_squared_error(z, y) ... >>> dx1 = loss.grad().get(x) >>> print("Gradient1 of x is \n{}".format(dx1)) Gradient1 of x is array([[ 0.85432934, 0.51205811], [ 0.20379112, 0.62481132], [ 0.49004569, 0.35310219]]) >>> >>> loss = rm.mean_squared_error(z, y) >>> dx2 = loss.grad().get(x) >>> print("Gradient2 of x is \n{}".format(dx2)) Gradient2 of x is None
-
prevent_update
( ) -
コンテキストマネージャ内においてGradsクラスのupdate()関数による重みパラメータのパラメータを実行した場合, そのコンテキストを持つModelの属性として定義された重みパラメータは更新されない.
Example
>>> import numpy as np >>> import renom as rm >>> model = rm.Sequential([ ... rm.Dense(1) ... ]) >>> x = np.random.rand(2, 2) >>> y = np.random.rand(2, 1) >>> >>> with model.train(): ... loss = rm.mean_squared_error(model(x), y) >>> >>> print("Before", model[0].params.w) Before [[ 0.03417877] [-0.29819158]] >>> loss.grad().update() >>> print("Updated", model[0].params.w) Updated [[ 0.526793 ] [ 0.00882804]] >>> >>> >>> print("Before", model[0].params.w) Before [[ 0.526793 ] [ 0.00882804]] >>> >>> # Performs update inside the context manager. >>> with model.prevent_update(): ... loss.grad().update() >>> print("Not updated", model[0].params.w) Not updated [[ 0.526793 ] [ 0.00882804]]
-
values
( ) -
Modelオブジェクトが持つ重みパラメータをネストされたタプルとして返す.
Modelオブジェクトは属性としてModelオブジェクトを持つことがある.valuesメソッドを実行すると, それぞれのModelオブジェクトは二つの辞書からなるタプルを返す. ひとつ目の辞書は子要素が持つ重みパラメータを持つ. ふたつ目の辞書にはModel自身(self)が持つ重みパラメータが含まれる.
Example
( # child models of self { 'layer1': ( {}, # child model of self.layer1 { # params of layer1 'w': [1,2], # self.layer1.params.w 'b': [3,4], # self.layer1.params.b } ), 'layer2': ( {}, # child model of self.layer2 { # params of layer2 'w': [1,2], # self.layer2.params.w 'b': [3,4], # self.layer2.params.b } }, # params of self {} )
-
join_grads
( grads , others ) -
引数gradに与えられたGradsオブジェクトが持つ勾配データに対し,引数others(Model, Gradsオブジェクトのタプル)が持つ勾配データを足し合わせる.引数に与えられるすべてのModelオブジェクトは等しい構造を持つ必要がある.
-
save
( filename ) -
Modelオブジェクトが持つ属性を保存する. 保存したい属性名を'SERIALIZED'という名前のタプルに登録することで, saveメソッドによる保存対象に含むことができる.Modelオブジェクトが持つ重みパラメータはSERIALIZEDに登録せずとも保存される.
以下にその例を示す.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class MyModel(rm.Model): ... SERIALIZED = ('_moving_avg', ) # Put any attributes for saving. ... def __init__(self): ... super(MyModel, self).__init__() ... self._l1 = rm.Dense(2) ... self._l2 = rm.Dense(1) ... self._moving_avg = 0 ... def forward(self, x): ... h = self._l1(x) ... h = rm.relu(h) ... h = self._l2(h) ... self._moving_avg = np.float32(self._moving_avg*0.5 + rm.sum(h)*0.5) ... return h ... >>> model = MyModel() >>> model(np.random.rand(12, 4)) >>> print(model._moving_avg) 1.95637 >>> model.save("test.h5") # Save >>> model = MyModel() # Reset model object. >>> model.load("test.h5") # Load >>> print(model._moving_avg) 1.95637
パラメータ: filename ( str ) -- モデルを保存する際のパス.
-
load
( filename ) -
保存した属性値をモデルにロードする.
パラメータ: filename ( str ) -- ロードするモデルのパス Example
>>> model = rm.Dense(2) >>> model.load("model.hd5")
-
set_initializer
( initializer ) -
前層における重みパラメータを同一条件で初期化.
以下にその例を示す.
パラメータ: initializer ( Initializer ) -- 初期化オブジェクト Example
>>> import renom as rm >>> import numpy as np >>> from renom.utility.initializer import Orthogonal >>> >>> class MyModel(rm.Model): ... def __init__(self): ... super(MyModel, self).__init__() ... self._l1 = rm.Dense(2) ... self._l2 = rm.Dense(1) ... self._moving_avg = 0 ... def forward(self, x): ... h = self._l1(x) ... h = rm.relu(h) ... h = self._l2(h) ... return h >>> >>> model = MyModel() >>> model.set_initializer(Orthogonal()) >>> >>> x = np.random.random((3,4)) >>> y = model(x) >>> >>> weight=model._l1.params.w >>> print("weight\n",weight) weight [[-0.43140578 0.39115947] [-0.53214586 -0.61308974] [-0.5807101 0.5656842 ] [-0.43986994 -0.3887372 ]] >>> >>> print("dot product\n",np.dot(weight.T,weight)) dot product [[1. 0.] [0. 1.]]
-
-
class
renom.layers.function.parameterized.
Sequential
( layers , loss_function=None ) -
Sequential model.
パラメータ: layers ( list ) -- レイヤオブジェクトのリスト Example
>>> import renom as rm >>> import numpy as np >>> >>> x = np.random.rand(32, 50) >>> sequential = rm.Sequential([ ... rm.Dense(100), ... rm.Relu(), ... rm.Dense(10), ... ]) ... >>> z = sequential(x) >>> z.shape (32, 10)
-
forward
( x ) ¶ -
フォワード計算. オーバーライドしてください.
Example
>>> import renom as rm >>> import numpy as np >>> >>> class Model(rm.Model): ... def __init__(self): ... self._layer1 = rm.Dense(3) ... self._layer2 = rm.Dense(2) ... def forward(self, x): # This part ... h = rm.relu(self._layer1(x)) ... z = self._layer2(h) ... return z
-
-
class
renom.layers.function.pool2d.
MaxPool2d
( filter=3 , padding=0 , stride=1 ) ¶ -
Max poolingクラス.
パラメータ: Example
>>> import numpy as np >>> import renom as rm >>> >>> x = np.random.rand(3, 3, 32, 32) >>> layer = rm.MaxPool2d(filter=3) >>> z = layer(x) >>> z.shape (3, 3, 30, 30) >>> z = rm.max_pool2d(x, filter=(3, 3), stride=(1, 1), padding=(0,0)) >>> z.shape (3, 3, 30, 30)
-
class
renom.layers.function.pool2d.
AveragePool2d
( filter=3 , padding=0 , stride=1 ) ¶ -
Average poolingクラス.
パラメータ: Example
>>> import numpy as np >>> import renom as rm >>> >>> x = np.random.rand(3, 3, 32, 32) >>> layer = rm.AveragePool2d(filter=3) >>> z = layer(x) >>> z.shape (3, 3, 30, 30) >>> z = rm.average_pool2d(x, filter=(3, 3), stride=(1, 1), padding=(0,0)) >>> z.shape (3, 3, 30, 30)
-
class
renom.layers.function.unpool2d.
MaxUnPool2d
¶ -
Max unpooling関数. この関数より先にMax poolingが実行されている必要がある.Max unpooling関数は, Max Pooling時に選択されたインデックスを元にUnpoolingを行う.
パラメータ: 注釈
UnPooling関数に入力されるデータ
x
は 対応するPooling関数の出力previous_pool
が持つshapeと等しい必要がある.x.shape == previous_pool.shape
同様に, UnPooling関数の出力はpooling関数への入力と等しいshapeを持つ.
ret.shape == previous_pool.input.shape
-
class
renom.layers.function.unpool2d.
AverageUnPool2d
¶ -
Average unpooling関数. この関数より先にAverage poolingが実行されている必要がある.Average unpooling関数は, Average pooling時に選択されたインデックスを元にUnpoolingを行う.
パラメータ: 注釈
UnPooling関数に入力されるデータ
x
は 対応するPooling関数の出力previous_pool
が持つshapeと等しい必要がある.x.shape == previous_pool.shape
同様に, UnPooling関数の出力はpooling関数への入力と等しいshapeを持つ.
ret.shape == previous_pool.input.shape