Skip to main content
 首页 » 编程设计

python之如何用 keras.layers.Lambda 包装 tf.cond 函数

2024年11月24日8虾米姐

我试图在 keras 中定义一个自定义层,但我找不到用 layers.Lambda 函数扭曲 tf.cond 的方法

        matches = tf.cond( 
            tf.greater(N, 0), 
            lambda: match_boxes( 
                anchors, groundtruth_boxes, 
                positives_threshold=positives_threshold, 
                negatives_threshold=negatives_threshold, 
                force_match_groundtruth=True 
            ), 
            lambda: only_background 
        ) 

请您参考如下方法:

因为你的真实函数体非常大,你可以像这样创建一个自定义层:

import tensorflow as tf 
 
class CustomLayer(tf.keras.layers.Layer): 
 
  def __init__(self, **kwargs): 
    super(CustomLayer, self).__init__() 
    self.pred = kwargs.get('pred', False) 
 
  def call(self, inputs): 
    def true_fn(x): 
      return x + 1. 
 
    return tf.cond(self.pred, 
                   true_fn=lambda: true_fn(inputs), 
                   false_fn=lambda: tf.identity(inputs)) 

测试:

inputs = tf.placeholder(tf.float32, shape=(None, 1)) 
pred = tf.placeholder(tf.bool, shape=()) 
 
model = tf.keras.models.Sequential() 
model.add(tf.keras.layers.Dense(1, kernel_initializer=tf.initializers.ones)) 
model.add(CustomLayer(pred=pred)) 
 
outputs = model(inputs) 
 
with tf.Session() as sess: 
  sess.run(tf.global_variables_initializer()) 
  print(outputs.eval({inputs: [[1.]], pred: False})) # [[1.]] 
  print(outputs.eval({inputs: [[1.]], pred: True})) # [[2.]]