[英]Use custom operation in Keras layer and make tensor trainable
我有如下操作:
def custom_operation(input):
kernel = tf.constant([3, 4, 5], tf.float32)
frames = tf.signal.frame(input, 3, 1)
return tf.reduce_sum(tf.abs(frames - tf.reshape(kernel, (1, 3))), axis=-1)
custom_operation(tf.constant([1, 2, 3, 4, 5, 6, 7], tf.float32))
# <tf.Tensor: shape=(5,), dtype=float32, numpy=array([6., 3., 0., 3., 6.], dtype=float32)>
我想在 Keras 自定義層中使用它,其中input
是層的輸入, kernel
是具有可訓練值的張量,而不是硬編碼的[3, 4, 5]
。
從Conv1D
調整Conv1D
層以調用custom_operation
而不是tf.nn.conv1d
似乎並不難,但我不知道如何使kernel
可訓練。
這個怎么樣:
import tensorflow as tf
from tensorflow.keras.layers import Layer
class CustomLayer(Layer):
"""``CustomLayer``."""
def __init__(self, name="custom"):
super().__init__(name=name)
def build(self, input_shape):
self.w = self.add_weight(
shape=(1, 3),
initializer="random_normal",
trainable=True)
def call(self, x):
frames = tf.signal.frame(x, 3, 1)
return tf.math.reduce_sum(tf.math.abs(frames - self.w), axis=-1)
測試圖層。
x = tf.constant([1, 2, 3, 4, 5, 6, 7], tf.float32)
CustomLayer()(x)
# <tf.Tensor: shape=(5,),
# dtype=float32,
# numpy= array([ 6.0877113, 9.087711 , 12.087711 , 15.087711 , 18.087711 ],
# dtype=float32)>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.