如何为Keras网络提供样本矩阵进行调试?

问题描述:

我正在通过this tutorial的方式工作,我想了解图层操作的工作原理。所以我扩展了第一个例子,如下所示。我不确定我会从这个网络中得到什么,所以我想用正确的尺寸输入张量并查看输出结果。我怎么做?如何为Keras网络提供样本矩阵进行调试?

使用:keras 2.0.2

from keras.models import Sequential 
from keras.layers import Dense, Activation 
from keras.layers import Lambda 

model = Sequential([ 
    Dense(32, input_shape=(10, 12, 14)), 
    Activation('relu'), 
    Dense(16), 
    Activation('softmax'), 
]) 
def output_of_lambda(input_shape): 
    return (input_shape[0], 1, input_shape[2]) 

def mean(x): 
    return K.mean(x, axis=1, keepdims=True) 

model.add(Lambda(mean, output_shape=output_of_lambda)) 

model.summary() 

输出:

_________________________________________________________________ 
Layer (type)     Output Shape    Param # 
================================================================= 
dense_9 (Dense)    (None, 10, 12, 32)  480  
_________________________________________________________________ 
activation_9 (Activation) (None, 10, 12, 32)  0   
_________________________________________________________________ 
dense_10 (Dense)    (None, 10, 12, 16)  528  
_________________________________________________________________ 
activation_10 (Activation) (None, 10, 12, 16)  0   
_________________________________________________________________ 
lambda_6 (Lambda)   (None, 1, 12)    0   
================================================================= 

你只是做一个predictions = model.predict(data)

其中数据是您的输入数据,其数据格式必须为(any,10,12,14)

对于传递单个样品而不是批次,形状必须是(1,10,12,14)

丹尼尔是正确的,也可以使用后端

下面是一个例子创建一个keras功能:

from keras import backend as K 
from keras.models import Sequential 
from keras.layers import Dense, Activation 
from keras.layers import Lambda 


model = Sequential([ 
    Dense(32, input_shape=(10, 12, 14)), 
    Activation('relu'), 
    Dense(16), 
    Activation('softmax'), 
]) 
def output_of_lambda(input_shape): 
    return (input_shape[0], 1, input_shape[2]) 

def mean(x): 
    return K.mean(x, axis=1, keepdims=True) 

model.add(Lambda(mean, output_shape=output_of_lambda)) 
model.summary() 

# add a function to push some data through the model 
func = K.function([model.inputs[0], K.learning_phase()], [model.outputs[0]] 

X = np.random.randn(100, 10, 12, 14) 
print(func([X, 0])) 

这使您可以灵活地看到任何层的输出,只是 通过改变K.function ... [model.outputs[0]] to [model.layers[2].output]它给你输出的第二个致密层

查看关于此事的keras faq:how-can-i-obtain-the-output-of-an-intermediate-layer

+0

谢谢你的提示! – user1982118