【问题标题】:Keras - Output Simple Inputs to Test LayersKeras - 输出简单输入到测试层
【发布时间】:2017-03-01 19:39:15
【问题描述】:

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

我尝试了以下方法来查看 1D 最大池如何工作:

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')

有没有办法查看这个的输出?

【问题讨论】:

  • 您可以按照以下步骤获取任意层的输出。 (keras.io/getting-started/faq/…)。您可以简单地构建一个模型,只包含您想要检查的层并检查其输出。
  • 我没有意识到它是如何工作的 - 谢谢!!
  • 我发布我的评论作为答案

标签: python neural-network keras


【解决方案1】:

您可以按照以下步骤获得任何层的输出。 (keras.io/getting-started/faq/…)。您可以简单地构建一个模型,只包含您想要检查的层并检查其输出。

【讨论】:

    【解决方案2】:

    这是一个基于 Krishna 评论的简单示例:

    首先,我们需要构建和训练一个小型模型 - 这是我快速拼凑的一个。

        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>
    

    函数返回传递到层的数组和层的输出,以检查层在其输入上的实际工作方式(X 是您传递到感兴趣层的小数据,索引由上面的摘要确定(当然是从零开始):

    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)
    

    创建小张量,复制进入 Convolution2D 的数据形状(第二层,索引 =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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 2019-03-18
      • 2017-06-28
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多