【问题标题】:Keras backend function that gives one only if values are between a and bKeras 后端函数,仅当值介于 a 和 b 之间时才给出
【发布时间】:2020-02-03 06:24:27
【问题描述】:

我正在尝试编写一个 Keras 后端函数,如果输入 x 在 a 和 b 之间,它给出 1;否则,它给出零。我无法使用 Keras 后端中提供的功能来做到这一点。如果是 numpy,我会写:

def my_function(x):
    import numpy as np
    y=np.int64(np.logical_and(x>=a, x<=b))
    return y

问题 1:如何使用 Keras 后端做到这一点?我知道我可以使用这样的东西,但效率不高

def my_function(x):
    from keras import backend as K
    y=x
    for i in y:
        if i<=b and i>=a:
            i=1
        else:
            i=0
 return y

问题 2: 我已经安装了 TensorFlow 1.14.0 和 Keras 2.2.6,所以我认为后端是 Tensorflow。如果我不能在 Keras 后端做到这一点。如何在 TensorFlow 后端编写函数?

【问题讨论】:

  • 输入的形状是什么?
  • @zihaozhihao 我不知道。它是一个层的输出。我们可以为一般输入形状编写它吗?
  • 哦,我明白了。也许它应用于 logits 或 probs。
  • 将用于神经网络

标签: python python-3.x tensorflow keras


【解决方案1】:

对于 TensorFlow 上的问题 2,您可以尝试使用 TF.cond 或 TF.case 导出所需的输出。如下所示:

import tensorflow as tf
x = tf.constant(20)
y = tf.constant(22)
z = tf.constant(25)
result1 = tf.cond(tf.logical_and(x > y, x <z), lambda: tf.constant(1), lambda: tf.constant(0))

【讨论】:

    【解决方案2】:

    这是我经常使用 opencv 调整图像大小的代码:

    import tensorflow as tf
    import cv2
    
    def resize_function(image, target_height, target_width):
      img = cv2.resize(image, (target_height, target_width))
      return image.astype(np.float32)
    
    image = tf.numpy_function(
        func=resize_function,
        inp=[tf.cast(image, tf.uint8),resize_height, resize_width],
        Tout=tf.float32)
    

    tensorflow 有 tf.numpy_function 用于定义您的自定义 numpy 函数。 这会将您的自定义函数转换为张量流图

    如果一个函数需要多个输出,修改为:

    output_1, output_2, output_3 = tf.numpy_function(
        func=compute_input_output, 
        inp=[inp_1, inp_2, inp_3,inp4], 
        Tout=[tf.float32,tf.float32,tf.float32])
    

    Tout 应包含预期输出数据类型的列表。

    【讨论】:

      猜你喜欢
      • 2014-05-05
      • 1970-01-01
      • 1970-01-01
      • 2017-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-18
      • 1970-01-01
      相关资源
      最近更新 更多