Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras-向测试层输出简单输入_Python_Neural Network_Keras - Fatal编程技术网

Python Keras-向测试层输出简单输入

Python Keras-向测试层输出简单输入,python,neural-network,keras,Python,Neural Network,Keras,是否可以在不编译和使用神经网络的情况下在Keras中使用层函数?我想通过向某些函数传递一个简单的numpy数组并查看输出来了解它们的功能—这可能吗 我尝试了以下方法来了解1D max池是如何工作的: 有什么方法可以看到这一结果吗?下面是一个基于奎师那评论的简单例子: 首先,我们需要建立和训练一个小模型——这是我很快拼凑起来的一个 import numpy as np from keras.models import Sequential from keras.layer

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

我尝试了以下方法来了解1D max池是如何工作的:


有什么方法可以看到这一结果吗?

下面是一个基于奎师那评论的简单例子:

首先,我们需要建立和训练一个小模型——这是我很快拼凑起来的一个

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


您可以通过以下步骤获得任何层的输出。(keras.io/getting started/faq/…)。您只需使用要检查的图层构造模型并检查其输出。

您可以通过以下步骤获得任何图层的输出。(). 你可以简单地构造一个模型,只包含你想要检查和检查其输出的层。我不知道它是如何工作的-谢谢!!我把我的评论作为回答
    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>
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)
    x=np.random.randn(1,3,7, 7)

    input,output =input_output(1,x)

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