1

Reluニューラル ネットワークの構築中に活性化関数のしきい値を変更しようとしています。

したがって、最初のコードは以下に記述されたもので、relu しきい値のデフォルト値は 0 です。

model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, ), activation = 'relu'),
    Dense(32, activation = 'relu'),
    Dense(2, activation='softmax')
])

ただし、Keras は同じ機能の実装を提供しており、ここで参照でき、スクリーンショットも追加できます。

ここに画像の説明を入力

そのため、次のエラーを取得するためだけにカスタム関数を渡すようにコードを次のように変更しました。

from keras.activations import relu
model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, ), activation = relu(threshold = 2)), 
    Dense(32, activation = relu(threshold = 2)),
    Dense(2, activation='softmax')
])

エラー: TypeError: relu() missing 1 required positional argument: 'x'

エラーは、relu 関数で x を使用していないことを理解していますが、そのようなものを渡す方法はありません。構文は私が書くことを期待していますmodel.add(layers.Activation(activations.relu))が、その後、しきい値を変更することはできません。これは、回避策または解決策が必要な場所です。

次に、以下に示すように機能するReLU関数のレイヤー実装を使用しましたが、レイヤーを追加するのが常に便利であるとは限らず、作成したいため、アクティベーション関数の実装を機能させる方法があるかどうかを調べたいと思いますDense 関数内のその他の変更。

私のために働いたコード:-

from keras.layers import ReLU
model = Sequential([
    Dense(n_inputs, input_shape=(n_inputs, )),
    ReLU(threshold=4), 
    Dense(32),
    ReLU(threshold=4),
    Dense(2, activation='softmax')
])
4

1 に答える 1

1

あなたが直面しているエラーは合理的です。reluただし、作業の関数で次のトリックを使用できます。alphaこのようになど必要な引数を取る関数を定義thresholdし、関数本体にrelu それらの引数で活性化を計算する別の関数を定義し、最後は上の関数に戻ります。

# help(tf.keras.backend.relu)
from tensorflow.keras import backend as K
def relu_advanced(alpha=0.0, max_value=None, threshold=0):        
    def relu_plus(x):
        return K.relu(x, 
                      alpha = tf.cast(alpha, tf.float32), 
                      max_value = max_value,
                      threshold= tf.cast(threshold, tf.float32))
    return relu_plus

サンプル:

foo = tf.constant([-10, -5, 0.0, 5, 10], dtype = tf.float32)
tf.keras.activations.relu(foo).numpy()
array([ 0.,  0.,  0.,  5., 10.], dtype=float32)

x = relu_advanced(threshold=1)
x(foo).numpy()
array([-0., -0.,  0.,  5., 10.], dtype=float32)

あなたの場合、単に次のように使用します。

model = Sequential([
    Dense(64, input_shape=(32, ), activation = relu_advanced(threshold=2)), 
    Dense(32, activation = relu_advanced(threshold=2)),
    Dense(2, activation='softmax')
])
于 2021-05-08T18:42:20.730 に答える