2017-07-26 56 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)