簡體   English   中英

在 Keras 層中使用自定義操作並使張量可訓練

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM