代码之家  ›  专栏  ›  技术社区  ›  user25004

如何对Keras中的数据应用(调用)单个层?

  •  1
  • user25004  · 技术社区  · 6 年前

    有没有一种简单的方法可以将数据提供给Keras中的一个层(在TF上)并查看返回值,以便进行测试,而不必实际构建完整的模型并将数据拟合到它?

    如果没有,如何测试他们开发的定制层?

    1 回复  |  直到 6 年前
        1
  •  2
  •   today    6 年前

    您可以定义和使用 backend function 为此目的:

    from keras import backend as K
    
    # my_layer could be a layer from a previously built model, like:
    # my_layer = model.layers[3]
    func = K.function(model.inputs, [my_layer.output])
    
    # or it is a layer with customized weights, like:
    # my_layer = Dense(...)
    # my_layer.set_weights(...)
    # out = my_layer(input_data)
    input_data = Input(shape=...)
    func = K.function([input_data], [my_layer.output])
    
    # to use the function:
    layer_output = func(layer_input)   # layer_input is a list of numpy array(s)
    
        2
  •  1
  •   nbro kai    5 年前

    this answer

    import numpy as np
    import tensorflow as tf
    # import tensorflow_probability as tfp 
    
    
    def main():
        input_data = tf.keras.layers.Input(shape=(1,))
    
        layer1 = tf.keras.layers.Dense(1)
        out1 = layer1(input_data)
    
        # Get weights only returns a non-empty list after we need the input_data
        print("layer1.get_weights() =", layer1.get_weights())
    
        # This is actually the required object for weights.
        new_weights = [np.array([[1]]), np.array([0])] 
        layer1.set_weights(new_weights)
    
        out1 = layer1(input_data)
        print("layer1.get_weights() =", layer1.get_weights())
    
        func1 =  tf.keras.backend.function([input_data], [layer1.output])
    
        #layer2 = tfp.layers.DenseReparameterization(1)
        #out2 = layer2(input_data)
        #func2 = tf.keras.backend.function([input_data], [layer2.output])
    
        # The input to the layer.
        data = np.array([[1], [3], [4]])
        print(data)
    
        # The output of layer1
        layer1_output = func1(data)
        print("layer1_output =", layer1_output)
    
        # The output of layer2
        # layer2_output = func2(data)
        # print("layer2_output =", layer2_output)
    
    
    if __name__ == "__main__":
        main()