python - Keras - 将简单输入输出到测试层

标签 python neural-network keras

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

我尝试了以下方法以查看一维最大池化如何工作:

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

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

最佳答案

这是一个基于 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 

关于python - Keras - 将简单输入输出到测试层,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40143676/

相关文章:

Python - 如何在字典中搜索特定字符串?

python - 使用 flask 的 socketio 扩展从线程发出

python - 类型错误 : 'numpy.float64' object is not iterable Keras

machine-learning - 了解计算机视觉卷积网络中滤波器的概念

python - Keras InvalidArgumentError 未知输入节点

tensorflow - 如何卡住 keras 或 tf.keras 中的选定权重?

python - 如何处理没有结尾斜杠的空 HTML 元素?

python - 在 virtualenv 中更改已安装的 Python 模块

python - 使用 Tensorflow,使用神经网络进行 2 类分类

machine-learning - 是否有可能在几个时期内对 250,000 个示例进行过度拟合?