Keras-layers

提供:Dev Guides
移動先:案内検索

ケラス-レイヤー

以前に学習したように、KerasレイヤーはKerasモデルの主要なビルディングブロックです。 各層は入力情報を受け取り、何らかの計算を行い、最終的に変換された情報を出力します。 1つのレイヤーの出力は、その入力として次のレイヤーに流れ込みます。 この章では、レイヤーの詳細について学びます。

前書き

Kerasレイヤーは、入力データの構造を理解するために 入力の形状(input_shape) を必要とし、各入力の重みを設定する initializer を必要とし、最終的に出力を変換して非線形にするためにアクティベーターを必要とします。 その間、制約は、生成される入力データの重みの範囲を制限および指定し、レギュライザーは、最適化プロセス中に重みにペナルティを動的に適用することにより、レイヤー(およびモデル)を最適化しようとします。

要約すると、Kerasレイヤーは、完全なレイヤーを作成するために最低限の詳細以下を必要とします。

  • 入力データの形状
  • 層のニューロン/ユニットの数
  • 初期化子
  • レギュラライザー
  • 制約
  • アクティベーション

次の章で基本的な概念を理解しましょう。 基本的な概念を理解する前に、シーケンシャルモデルAPIを使用して単純なKerasレイヤーを作成し、Kerasモデルとレイヤーがどのように機能するかを理解してみましょう。

from keras.models import Sequential
from keras.layers import Activation, Dense
from keras import initializers
from keras import regularizers
from keras import constraints

model = Sequential()

model.add(Dense(32, input_shape=(16,), kernel_initializer = 'he_uniform',
   kernel_regularizer = None, kernel_constraint = 'MaxNorm', activation = 'relu'))
model.add(Dense(16, activation = 'relu'))
model.add(Dense(8))

どこで、

  • *行1-5 *は必要なモジュールをインポートします。
  • *行7 *は、シーケンシャルAPIを使用して新しいモデルを作成します。
  • 行9 *は新しい *Dense レイヤーを作成し、モデルに追加します。 Dense は、Kerasが提供するエントリーレベルのレイヤーで、ニューロンまたはユニットの数(32)を必須パラメーターとして受け入れます。 レイヤーが最初のレイヤーの場合は、*入力形状(16、)*も指定する必要があります。 それ以外の場合は、前のレイヤーの出力が次のレイヤーの入力として使用されます。 他のすべてのパラメーターはオプションです。
  • 最初のパラメーターは単位(ニューロン)の数を表します。
  • input_shape は入力データの形状を表します。
  • kernel_initializer は、使用するイニシャライザを表します。 he_uniform 関数が値として設定されています。
  • kernel_regularizer は、使用される regularizer を表します。 値として設定されるものはありません。
  • kernel_constraint は、使用される制約を表します。 MaxNorm 関数が値として設定されます。
  • activation は、使用するアクティベーションを表します。 relu機能が値として設定されています。
  • Line 10 は、16ユニットの2番目の Dense レイヤーを作成し、アクティベーション関数として relu を設定します。
  • Line 11 は、8ユニットの最終的な高密度レイヤーを作成します。

レイヤーの基本概念

レイヤーの基本的な概念と、Kerasが各概念をどのようにサポートするかを理解しましょう。

入力形状

機械学習では、テキスト、画像、動画などのすべてのタイプの入力データが最初に数値の配列に変換され、次にアルゴリズムにフィードされます。 入力数値は、1次元配列、2次元配列(行列)、または多次元配列です。 整数のタプルである shape を使用して次元情報を指定できます。 たとえば、*(4,2)*は4行2列の行列を表します。

>>> import numpy as np
>>> shape = (4, 2)
>>> input = np.zeros(shape)
>>> print(input)
[
   [0. 0.]
   [0. 0.]
   [0. 0.]
   [0. 0.]
]
>>>

同様に、*(3,4,2)*は、4x2マトリックス(2行と4列)の3つのコレクションを持つ3次元マトリックスです。

>>> import numpy as np
>>> shape = (3, 4, 2)
>>> input = np.zeros(shape)
>>> print(input)
[
   [[To create the first layer of the model (or input layer of the model), shape of the input data should be specified.

=== Initializers

In Machine Learning, weight will be assigned to all input data. *_Initializers_ *module provides different functions to set these initial weight. Some of the* _Keras Initializer_ *function are as follows −

==== Zeros

Generates* 0 *for all input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.Zeros()model = Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

Where,* _kernel_initializer_ *represent the initializer for kernel of the model.

==== Ones

Generates* 1 *for all input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.Ones()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

==== Constant

Generates a constant value (say,* 5*) specified by the user for all input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.Constant(value = 0)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

where, *value* represent the constant value

==== RandomNormal

Generates value using normal distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.RandomNormal(mean = 0.0、stddev = 0.05、seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

where,

* *_mean_* represent the mean of the random values to generate
* *_stddev_* represent the standard deviation of the random values to generate
* *_seed_* represent the values to generate random number

==== RandomUniform

Generates value using uniform distribution of input data.

[source,prettyprint,notranslate]

kerasインポート初期化子から

my_init = initializers.RandomUniform(minval = -0.05、maxval = 0.05、seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

where,

* *_minval_* represent the lower bound of the random values to generate
* *_maxval_* represent the upper bound of the random values to generate

==== TruncatedNormal

Generates value using truncated normal distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.TruncatedNormal(mean = 0.0、stddev = 0.05、seed = None model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

==== VarianceScaling

Generates value based on the input shape and output shape of the layer along with the specified scale.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.VarianceScaling(scale = 1.0、mode = 'fan_in'、distribution = 'normal'、seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、skernel_initializer = my_init ))

where,

* *scale* represent the scaling factor
* *mode *represent any one of* fan_in, fan_out *and* fan_avg* values
* *distribution *represent either of* normal *or* uniform*

==== VarianceScaling

It finds the *_stddev_ *value for normal distribution using below formula and then find the weights using normal distribution,

[source,result,notranslate]

stddev = sqrt(scale/n)

where* n* represent,

* number of input units for mode = fan_in
* number of out units for mode = fan_out
 *average number of input and output units for mode = fan_avg

Similarly, it finds the _limit_ for uniform distribution using below formula and then find the weights using uniform distribution,

[source,result,notranslate]

制限= sqrt(3* スケール/n)

==== lecun_normal

Generates value using lecun normal distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.RandomUniform(minval = -0.05、maxval = 0.05、seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

It finds the *_stddev_ *using the below formula and then apply normal distribution

[source,result,notranslate]

stddev = sqrt(1/fan_in)

where,* _fan_in_ *represent the number of input units.

==== lecun_uniform

Generates value using lecun uniform distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.lecun_uniform(seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

It finds the* _limit_* using the below formula and then apply uniform distribution

[source,result,notranslate]

limit = sqrt(3/fan_in)

where,

* *_fan_in_* represents the number of input units
* *_fan_out_ *represents the number of output units

==== glorot_normal

Generates value using glorot normal distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.glorot_normal(seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

It finds the* _stddev_* using the below formula and then apply normal distribution

[source,result,notranslate]

stddev = sqrt(2/(fan_in + fan_out))

where,

* *_fan_in_* represents the number of input units
* *_fan_out_ *represents the number of output units

==== glorot_uniform

Generates value using glorot uniform distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.glorot_uniform(seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

It finds the* _limit_* using the below formula and then apply uniform distribution

[source,result,notranslate]

制限= sqrt(6/(fan_in + fan_out))

where,

* *_fan_in_* represent the number of input units.
* *_fan_out_ *represents the number of output units

==== he_normal

Generates value using he normal distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.RandomUniform(minval = -0.05、maxval = 0.05、seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

It finds the _stddev_ using the below formula and then apply normal distribution.

[source,result,notranslate]

stddev = sqrt(2/fan_in)

where,* _fan_in_ *represent the number of input units.

==== he_uniform

Generates value using he uniform distribution of input data.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.he_normal(seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

It finds the* _limit_ *using the below formula and then apply uniform distribution.

[source,result,notranslate]

制限= sqrt(6/fan_in)

where,* _fan_in_ *represent the number of input units.

==== Orthogonal

Generates a random orthogonal matrix.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.Orthogonal(gain = 1.0、seed = None)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

where,* _gain_ *represent the multiplication factor of the matrix.

==== Identity

Generates identity matrix.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.Identity(gain = 1.0)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

=== Constraints

In machine learning, a constraint will be set on the parameter (weight) during optimization phase. <>Constraints module provides different functions to set the constraint on the layer. Some of the constraint functions are as follows.

==== NonNeg

Constrains weights to be non-negative.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import initializers

my_init = initializers.Identity(gain = 1.0)model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_initializer = my_init))

where,* _kernel_constraint_* represent the constraint to be used in the layer.

==== UnitNorm

Constrains weights to be unit norm.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import constraint

my_constrain = constraint.UnitNorm(axis = 0)model = Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_constraint = my_constrain))

==== MaxNorm

Constrains weight to norm less than or equals to the given value.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import constraint

my_constrain = constraint.MaxNorm(max_value = 2、axis = 0)model = Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_constraint = my_constrain))

where,

* *_max_value_* represent the upper bound
 *_axis_ represent the dimension in which the constraint to be applied. e.g. in Shape (2,3,4) axis 0 denotes first dimension, 1 denotes second dimension and 2 denotes third dimension

==== MinMaxNorm

Constrains weights to be norm between specified minimum and maximum values.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense from keras import constraint

my_constrain = constraint.MinMaxNorm(min_value = 0.0、max_value = 1.0、rate = 1.0、axis = 0)model = Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_constraint = my_constrain))

where,* _rate_ *represent the rate at which the weight constrain is applied.

=== Regularizers

In machine learning, regularizers are used in the optimization phase. It applies some penalties on the layer parameter during optimization. Keras regularization module provides below functions to set penalties on the layer. Regularization applies per-layer basis only.

==== L1 Regularizer

It provides L1 based regularization.

[source,result,notranslate]

keras.modelsからインポートimport keras.layersからシーケンシャルインポートアクティベーション、kerasから高密度インポートレギュラライザー

my_regularizer = regularizers.l1(0。)model = Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_regularizer = my_regularizer))

where,* _kernel_regularizer_* represent the rate at which the weight constrain is applied.

==== L2 Regularizer

It provides L2 based regularization.

[source,prettyprint,notranslate]

keras.modelsからインポートimport keras.layersからシーケンシャルインポートアクティベーション、kerasから高密度インポートレギュラライザー

my_regularizer = regularizers.l2(0。)model = Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_regularizer = my_regularizer))

==== L1 and L2 Regularizer

It provides both L1 and L2 based regularization.

[source,prettyprint,notranslate]

keras.modelsからインポートimport keras.layersからシーケンシャルインポートアクティベーション、kerasから高密度インポートレギュラライザー

my_regularizer = regularizers.l2(0。)model = Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)、kernel_regularizer = my_regularizer))

=== Activations

In machine learning, activation function is a special function used to find whether a specific neuron is activated or not. Basically, the activation function does a nonlinear transformation of the input data and thus enable the neurons to learn better. Output of a neuron depends on the activation function.

As you recall the concept of single perception, the output of a perceptron (neuron) is simply the result of the activation function, which accepts the summation of all input multiplied with its corresponding weight plus overall bias, if any available.

[source,result,notranslate]

結果=アクティベーション(SUMOF(入力*重み)+バイアス)

So, activation function plays an important role in the successful learning of the model. Keras provides a lot of activation function in the activations module. Let us learn all the activations available in the module.

==== linear

Applies Linear function. Does nothing.

[source,result,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'linear'、input_shape =(784、)))

Where, *_activation_* refers the activation function of the layer. It can be specified simply by the name of the function and the layer will use corresponding activators.

==== elu

Applies Exponential linear unit.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'elu'、input_shape =(784、)))

==== selu

Applies Scaled exponential linear unit.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'selu'、input_shape =(784、)))

==== relu

Applies Rectified Linear Unit.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'relu'、input_shape =(784、)))

==== softmax

Applies Softmax function.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'softmax'、input_shape =(784、)))

==== softplus

Applies Softplus function.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'softplus'、input_shape =(784、)))

==== softsign

Applies Softsign function.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'softsign'、input_shape =(784、)))

==== tanh

Applies Hyperbolic tangent function.

[source,prettyprint,notranslate]

from keras.models import Sequential from keras.layers import Activation、Dense model = Sequential()model.add(Dense(512、activation = 'tanh'、input_shape =(784、)))

==== sigmoid

Applies Sigmoid function.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'sigmoid'、input_shape =(784、)))

==== hard_sigmoid

Applies Hard Sigmoid function.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'hard_sigmoid'、input_shape =(784、)))

==== exponential

Applies exponential function.

[source,prettyprint,notranslate]

keras.modelsインポートから順次keras.layersから順次インポートアクティベーション、高密度

モデル= Sequential()model.add(Dense(512、activation = 'exponential'、input_shape =(784、)))

[width="100%",cols="50%,50%",options="header",]
|===
|Sr.No |Layers & Description
|1 a|
link:/keras/keras_dense_layer[Dense Layer]

*Dense layer* is the regular deeply connected neural network layer.

|2 a|
link:/keras/keras_dropout_layers[Dropout Layers]

*_Dropout_* is one of the important concept in the machine learning.

|3 a|
link:/keras/keras_flatten_layers[Flatten Layers]

*Flatten* is used to flatten the input.

|4 a|
link:/keras/keras_reshape_layers[Reshape Layers]

*_Reshape_* is used to change the shape of the input.

|5 a|
link:/keras/keras_permute_layers[Permute Layers]

*Permute* is also used to change the shape of the input using pattern.

|6 a|
link:/keras/keras_repeatvector_layers[RepeatVector Layers]

*_RepeatVector_* is used to repeat the input for set number, n of times.

|7 a|
link:/keras/keras_lambda_layers[Lambda Layers]

*_Lambda_* is used to transform the input data using an expression or function.

|8 a|
link:/keras/keras_convolution_layers[Convolution Layers]

Keras contains a lot of layers for creating Convolution based ANN, popularly called as _Convolution Neural Network (CNN)_.

|9 a|
link:/keras/keras_pooling_layer[Pooling Layer]

It is used to perform max pooling operations on temporal data.

|10 a|
link:/keras/keras_locally_connected_layer[Locally connected layer]

Locally connected layers are similar to Conv1D layer but the difference is Conv1D layer weights are shared but here weights are unshared.

|11 a|
link:/keras/keras_merge_layer[Merge Layer]

It is used to merge a list of inputs.

|12 a|
link:/keras/keras_embedding_layer[Embedding Layer]

It performs embedding operations in input layer.

|===