Keras - 输出简单输入以测试图层

时间:2016-10-20 00:37:03

标签: python neural-network keras

是否可以在Keras中使用图层函数而无需编译和使用神经网络?我想通过传递一个简单的numpy数组并查看输出来了解某些函数的作用 - 这可能吗?

我尝试了以下内容,了解1D max pooling的工作原理:

https://github.com/fchollet/keras/blob/master/keras/layers/pooling.py#L54

from keras.layers import MaxPooling1D
import tensorflow as tf

sess = tf.InteractiveSession()
x=tf.random_normal((1,2,3,3), mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)

h=MaxPooling1D()
h._pooling_function(inputs=x, pool_size=(1,1), strides=(1,1),border_mode="valid", dim_ordering='tf')

有没有办法看到它的输出?

2 个答案:

答案 0 :(得分:1)

Here is a simple example based off of Krishna's comment:

First, we need to build and train a small model - here is one I quickly threw together.

    import numpy as np
    from keras.models import Sequential
    from keras.layers import Dense, Dropout, Activation, Flatten
    from keras.layers import Embedding
    from keras.layers import Convolution1D, MaxPooling1D, Convolution2D, MaxPooling2D
    from keras import backend as K
    from keras.layers.convolutional import ZeroPadding2D

    #FIT A SIMPLE MODEL

    N = 50
    X = np.random.randn(N, 3,5, 5)  #creates the 3 channel data, 5x5 matrices
    y = np.random.randint(1, size=N)

    model = Sequential()

    # number of convolutional filters, this is the number of "neurons"
    n_filters = 2

    # convolution filter size
    # i.e. we will use a n_conv x n_conv filter
    n_conv = 3

    # pooling window size
    # i.e. we will use a n_pool x n_pool pooling window
    n_pool = 2

    # we have a 5x5 image with RGB channel
    # so the input shape should be (3,5,5)
    model.add(ZeroPadding2D(input_shape=(3, 5, 5),padding=(1,1)))  #this makes a 7x7 data input

    model.add(Convolution2D(

            n_filters, n_conv, n_conv,

            # apply the filter to only full parts of the image
            # (i.e. do not "spill over" the border)
            # this is called a narrow convolution
            border_mode='valid',


            subsample=(2, 2) #this is STRIDE (left to right and top to bottom),

    ))

    model.add(Activation('relu'))

    model.add(MaxPooling2D(pool_size=(n_pool, n_pool)))

    # flatten the data for the 1D layers
    model.add(Flatten())

    # Dense(n_outputs)
    model.add(Dense(10))


    # the softmax output layer gives us a probablity for each class
    model.add(Dense(1))
    model.add(Activation('linear'))

    model.compile(loss='mse',
        optimizer='adam',
        metrics=['accuracy'])

    print (model.summary())



    # how many examples to look at during each training iteration
    batch_size = 1

    # how many times to run through the full set of examples
    n_epochs = 1

    model.fit(X,
              y,
              batch_size=batch_size,
              nb_epoch=n_epochs)

____________________________________________________________________________________________________
Layer (type)                     Output Shape          Param #     Connected to                     
====================================================================================================
zeropadding2d_15 (ZeroPadding2D) (None, 3, 7, 7)       0           zeropadding2d_input_13[0][0]     
____________________________________________________________________________________________________
convolution2d_18 (Convolution2D) (None, 2, 3, 3)       56          zeropadding2d_15[0][0]           
____________________________________________________________________________________________________
activation_30 (Activation)       (None, 2, 3, 3)       0           convolution2d_18[0][0]           
____________________________________________________________________________________________________
maxpooling2d_18 (MaxPooling2D)   (None, 2, 1, 1)       0           activation_30[0][0]              
____________________________________________________________________________________________________
flatten_12 (Flatten)             (None, 2)             0           maxpooling2d_18[0][0]            
____________________________________________________________________________________________________
dense_20 (Dense)                 (None, 10)            30          flatten_12[0][0]                 
____________________________________________________________________________________________________
dense_21 (Dense)                 (None, 1)             11          dense_20[0][0]                   
____________________________________________________________________________________________________
activation_31 (Activation)       (None, 1)             0           dense_21[0][0]                   
====================================================================================================
Total params: 97
____________________________________________________________________________________________________
None
Epoch 1/1
50/50 [==============================] - 0s - loss: 0.3463 - acc: 0.6000     

<keras.callbacks.History at 0x7f4927a66f10>

Function to return the array passed into a layer and the output of the layer to examine how a layer actually works on it's input (X is the small data you pass into the layer of interest and the index is determined from the summary above (zero based of course):

def input_output (layer_index,X):
    get_layer_output = K.function([model.layers[layer_index].input], [model.layers[layer_index].output])
    layer_output = get_layer_output([X])[0]
    return (X,layer_output)

Create small tensor replicating the shape of data coming into the Convolution2D (second layer,index =1)

    x=np.random.randn(1,3,7, 7)

    input,output =input_output(1,x)

#After the convolution (shape is 1, 2, 3, 3)
    output 

答案 1 :(得分:0)

您可以按照以下步骤获取任何图层的输出。 (keras.io/getting-started/faq/...)。您只需构建一个仅包含要检查的图层的模型并检查其输出。