我正试图让TensorBoard与Keras合作。 看起来我能够使用tf(1.12.0)和keras(2.1.6-tf)运行初始模型。我有一些简单的代码。列出如下:
%matplotlib inline
from io import StringIO
import numpy as np
import pandas as pd
import tensorflow as tf
csv = StringIO('''a,b,c,y
0,1,2,0
1,2,0,1
0,2,1,0
3,2,1,1
3,1,2,0''')
data = pd.read_csv(csv)
def tb_cb(batch_size):
# visualize graphs and grandient
tb = tf.keras.callbacks.TensorBoard(log_dir='/tmp/test/',
histogram_freq=1,
batch_size=batch_size, write_graph=True,
write_grads=True)
return tb
m = tf.keras.Sequential([
# going to change 1 in the line below
tf.keras.layers.Dense(1, activation='relu', input_shape=(3,), name='hidden1'),
tf.keras.layers.Dense(1, activation='linear', name='output')
])
m.compile(loss='mse', optimizer='adam', metrics=['mae'])
X = data.iloc[:,:3]
y = data.y
hist = m.fit(X, y, epochs=10, verbose=1, callbacks=[tb_cb(10)],
validation_data=(X,y))
我第一次运行此命令时,会得到TensorBoard输出。然后,我更改了隐藏层中神经元的数量,然后重新运行模型。
我收到以下错误:
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
<ipython-input-11-4e4fb6f60bf0> in <module>
15 y = data.y
16 hist = m.fit(X, y, epochs=10, verbose=1, callbacks=[tb_cb(10)],
---> 17 validation_data=(X,y))
~/.env/364/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, max_queue_size, workers, use_multiprocessing, **kwargs)
1637 initial_epoch=initial_epoch,
1638 steps_per_epoch=steps_per_epoch,
-> 1639 validation_steps=validation_steps)
1640
1641 def evaluate(self,
~/.env/364/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_arrays.py in fit_loop(model, inputs, targets, sample_weights, batch_size, epochs, verbose, callbacks, val_inputs, val_targets, val_sample_weights, shuffle, initial_epoch, steps_per_epoch, validation_steps)
231 sample_weights=val_sample_weights,
232 batch_size=batch_size,
--> 233 verbose=0)
234 if not isinstance(val_outs, list):
235 val_outs = [val_outs]
~/.env/364/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_arrays.py in test_loop(model, inputs, targets, sample_weights, batch_size, verbose, steps)
437 ins_batch[i] = ins_batch[i].toarray()
438
--> 439 batch_outs = f(ins_batch)
440
441 if isinstance(batch_outs, list):
~/.env/364/lib/python3.6/site-packages/tensorflow/python/keras/backend.py in __call__(self, inputs)
2984
2985 fetched = self._callable_fn(*array_vals,
-> 2986 run_metadata=self.run_metadata)
2987 self._call_fetch_callbacks(fetched[-len(self._fetches):])
2988 return fetched[:len(self.outputs)]
~/.env/364/lib/python3.6/site-packages/tensorflow/python/client/session.py in __call__(self, *args, **kwargs)
1437 ret = tf_session.TF_SessionRunCallable(
1438 self._session._session, self._handle, args, status,
-> 1439 run_metadata_ptr)
1440 if run_metadata:
1441 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
~/.env/364/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py in __exit__(self, type_arg, value_arg, traceback_arg)
526 None, None,
527 compat.as_text(c_api.TF_Message(self.status.status)),
--> 528 c_api.TF_GetCode(self.status.status))
529 # Delete the underlying status object from memory otherwise it stays alive
530 # as there is a reference to status from this from the traceback due to
InvalidArgumentError: You must feed a value for placeholder tensor 'dense_9_target' with dtype float and shape [?,?]
[[{{node dense_9_target}} = Placeholder[dtype=DT_FLOAT, shape=[?,?], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
答案 0 :(得分:0)
在构建模型之前,应始终调用Keras.clear_session(),以避免tf图中先前运行的剩余节点。
因此,请在创建模型之前添加keras.backend.clear_session()。