Use keras layer in tensorflow code

后端 未结 1 1517
情深已故
情深已故 2021-02-05 14:17

Lets say I have a simple neural network with an input layer and a single convolution layer programmed in tensorflow:

  # Input Layer
  input_layer = tf.reshape(f         


        
1条回答
  •  误落风尘
    2021-02-05 14:40

    Yes, this is possible.

    Import both TensorFlow and Keras and link your Keras session to the TF one:

    import tensorflow as tf
    import keras
    from keras import backend as K
    
    tf_sess = tf.Session()
    K.set_session(tf_sess)
    

    Now, in your model definition, you can mix TF and Keras layers like so:

    # Input Layer
    input_layer = tf.reshape(features["x"], [-1, 28, 28, 1])
    
    # Convolutional Layer #1
    conv1 = tf.layers.conv2d(
        inputs=input_layer,
        filters=32,
        kernel_size=[5, 5],
        padding="same",
        activation=tf.nn.relu)
    
    # Flatten conv output
    flat = tf.contrib.layers.flatten(conv1)
    
    # Fully-connected Keras layer
    layer2_dense = keras.layers.Dense(128, activation='relu')(flat)
    
    # Fully-connected TF layer (output)
    output_preds = tf.layers.dense(layer2_dense, units=10)
    

    This answer is adopted from a Keras blog post by Francois Chollet.

    0 讨论(0)
提交回复
热议问题