[英]Evaluating Tensorflow Tensors
要獲得輸出相對於輸入的梯度,可以使用
grads = tf.gradients(model.output, model.input)
其中 grads =
[<tf.Tensor 'gradients_81/dense/MatMul_grad/MatMul:0' shape=(?, 18) dtype=float32>]
這是一個模型,其中有 18 個連續輸入和 1 個連續輸出。
我假設,這是一個符號表達式,需要一個包含 18 個條目的列表才能將其提供給張量,以便它以浮點數形式給出導數。
我會用
Test =[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]
with tf.Session() as sess:
alpha = sess.run(grads, feed_dict = {model.input : Test})
print(alpha)
但我得到了錯誤
FailedPreconditionError (see above for traceback): Error while reading resource variable dense_2/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/dense_2/bias)
[[Node: dense_2/BiasAdd/ReadVariableOp = ReadVariableOp[dtype=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"](dense_2/bias)]]
怎么了?
編輯:這是,之前發生的事情:
def build_model():
model = keras.Sequential([
...])
optimizer = ...
model.compile(loss='mse'... )
return model
model = build_model()
history= model.fit(data_train,train_labels,...)
loss, mae, mse = model.evaluate(data_eval,...)
迄今為止的進展:
Test =[1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]
with tf.Session() as sess:
tf.keras.backend.set_session(sess)
tf.initializers.variables(model.output)
alpha = sess.run(grads, feed_dict = {model.input : Test})
也不工作,給出錯誤:
TypeError: Using a `tf.Tensor` as a Python `bool` is not allowed. Use `if t is not None:` instead of `if t:` to test if a tensor is defined, and use TensorFlow ops such as tf.cond to execute subgraphs conditioned on the value of a tensor.
您正在嘗試使用未初始化的變量。 您所要做的就是添加
sess.run(tf.global_variables_initializer())
with tf.Session() as sess:
編輯:您需要使用 Keras 注冊會話
with tf.Session() as sess:
tf.keras.backend.set_session(sess)
並使用tf.initializers.variables(var_list)
而不是tf.global_variables_initializer()
見https://blog.keras.io/keras-as-a-simplified-interface-to-tensorflow-tutorial.html
編輯:
Test = np.ones((1, 18), dtype=np.float32)
inputs = layers.Input(shape=[18,])
layer = layers.Dense(10, activation='sigmoid')(inputs)
model = tf.keras.Model(inputs=inputs, outputs=layer)
model.compile(optimizer='adam', loss='mse')
checkpointer = tf.keras.callbacks.ModelCheckpoint(filepath='path/weights.hdf5')
model.fit(Test, nb_epoch=1, batch_size=1, callbacks=[checkpointer])
grads = tf.gradients(model.output, model.input)
with tf.Session() as sess:
tf.keras.backend.set_session(sess)
sess.run(tf.global_variables_initializer())
model.load_weights('path/weights.hdf5')
alpha = sess.run(grads, feed_dict={model.input: Test})
print(alpha)
這顯示了一致的結果
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.