Keras后端函数,仅当值在a和b之间时才给出

时间:2019-10-05 00:27:48

标签: python python-3.x tensorflow keras

我正在尝试编写Keras后端函数,如果输入x在a和b之间,则给出1;否则,它为零。我无法使用Keras后端中提供的功能来执行此操作。如果它很麻木,我会写:

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后端中编写函数?

2 个答案:

答案 0 :(得分:0)

对于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))

答案 1 :(得分:0)

这是我经常用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 应该包含预期的输出数据类型的列表。

相关问题