2017-07-26 53 views
1

所以我有一个凯拉斯模型。我想把模型的渐变和它的输入结合起来。这是我做的Keras模型与衍生物的投入是返回所有零

import tensorflow as tf 
from keras.models import Sequential 
from keras.layers import Dense 
from keras import backend as K 

num_features = 5 

model = Sequential() 
model.add(Dense(60, input_shape=(num_features,), activation='relu')) 
model.add(Dense(50, activation='relu')) 
model.add(Dense(1, activation='softmax')) 
model.compile(optimizer='adam', loss='binary_crossentropy') 
#Run predict to initialize weights 
model.predict(np.random.rand(1, num_features)) 

x = tf.random_uniform(shape=(1, num_features)) 
model_grad = tf.gradients(model(x), x)[0] 

但是,当我打印出dmodel_dx的值时,我得到全0。

sess = K.get_session() 
print(model_grad.eval(session=sess)) 
>>>array([[ 0., 0., 0., 0., 0.]], dtype=float32) 

任何人都知道我在做什么错?

+0

尝试'model.layers [-1] .output'代替'模型(X)'。 –

回答

0

检查是否SOFTMAX饱和,所以给你很小的梯度 - 尝试

model_grad = K.gradients(K.dot(model.layers[-1].input,model.layers[-1].kernel)+model.layers[-1].bias, model.input)