Keras Conv2d own filters

前端 未结 2 1577
自闭症患者
自闭症患者 2021-01-14 02:38

it is possible to set as param filter array with own filters instead of number of filters in Conv2D

filters = [[[1,0,0],[1,0,0],[1,0,0]],
     [[1,0,0],[0,1,         


        
2条回答
  •  再見小時候
    2021-01-14 03:20

    The accepted answer is right but it would certainly be more useful with a complete example, similar to the one provided in this excellent tensorflow example showing what Conv2d does.

    For keras, this is,

    from keras.models import Sequential
    from keras.layers import Conv2D
    
    import numpy as np
    
    # Keras version of this example:
    # https://stackoverflow.com/questions/34619177/what-does-tf-nn-conv2d-do-in-tensorflow
    # Requires a custom kernel initialise to set to value from example
    # kernel = [[1,0,1],[2,1,0],[0,0,1]]
    # image = [[4,3,1,0],[2,1,0,1],[1,2,4,1],[3,1,0,2]]
    # output = [[14, 6],[6,12]] 
    
    #Set Image
    image = [[4,3,1,0],[2,1,0,1],[1,2,4,1],[3,1,0,2]]
    
    # Pad to "channels_last" format 
    # which is [batch, width, height, channels]=[1,4,4,1]
    image = np.expand_dims(np.expand_dims(np.array(image),2),0)
    
    #Initialise to set kernel to required value
    def kernel_init(shape):
        kernel = np.zeros(shape)
        kernel[:,:,0,0] = np.array([[1,0,1],[2,1,0],[0,0,1]])
        return kernel
    
    #Build Keras model
    model = Sequential()
    model.add(Conv2D(1, [3,3], kernel_initializer=kernel_init, 
                     input_shape=(4,4,1), padding="valid"))
    model.build()
    
    # To apply existing filter, we use predict with no training
    out = model.predict(image)
    print(out[0,:,:,0])
    

    which outputs

    [[14, 6]
     [6, 12]]
    

    as expected.

提交回复
热议问题