Skip to content

Instantly share code, notes, and snippets.

@docPhil99
Created December 7, 2020 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save docPhil99/0624be8e55c42f9b100213c08820f316 to your computer and use it in GitHub Desktop.
Save docPhil99/0624be8e55c42f9b100213c08820f316 to your computer and use it in GitHub Desktop.
Code for testing a custom layer in tensorflow 2 Keras

A simple example of code for testing a custom tensorflow Keras layer

    def my_init(shape, dtype=None):
        """This function is a custom kernel initialiser. It loads the weights from a matlab file. Adapt as need"""
        matlab = io.loadmat('../matlab/weights.mat')
        wfilter = matlab['wfilter']
        if shape != wfilter.shape:
            raise Exception('Shaped do not match')
        return tf.constant(wfilter, dtype=dtype)


    from scipy import io
   
    # weights.mat holds input data inp of shape [1,16,16,2] (batch,w,h,channels) and 
    # weights wfilter of size [3,3,2,3] (ie w,h,num_input,numn_outputs )
    tf.keras.backend.set_floatx('float64')
    matlab = io.loadmat('../matlab/weights.mat')
    inp = matlab['inp']
    
    input_shape = (16, 16, 2) # should match shape from inp minus batch
    input_data = tf.keras.layers.Input(shape=input_shape)  # make the input layer
    
    # experimental layer
    layer = Conv2DPhase(3,  use_bias=False, kernel_size=(3, 3), kernel_initializer=my_init, input_shape=input_data.shape)
    output = layer(input_data)
    func1 = tf.keras.backend.function([input_data], [layer.output])
    layer_output = func1(inp)
    
    # save output
    dic = {'keras': layer_output}
    io.savemat('../matlab/keras_layer_output_conv2doptical_no_fft_noflip.mat', dic)
    ```
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment