I have a Seq2Seq model. I am interested to print out the matrix value of the output of the encoder per iteration.
So for example as the dimension of the matrix in the encoder is (?,20) and the epoch =5 and in each epoch, there are 10 iteration,
I would like to see 10 matrix of the dimension (?,20) per epoch.
I have gone to several links as here but it still does not print out the value matrix.
With this code as mentioned in the aboved link:
import keras.backend as K
k_value = K.print_tensor(encoded)
print(k_value)
I got:
Tensor("Print:0", shape=(?, 20), dtype=float32)
Is there any straightforward way of showing the tensor value of each layer in Keras?
Update 1
by trying this code: K_value = K.eval(encoded) it raises this error:
Traceback (most recent call last):
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1278, in _do_call
return fn(*args)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1263, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1350, in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input' with dtype float and shape [?,45,50]
[[Node: input = Placeholder[dtype=DT_FLOAT, shape=[?,45,50], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: encoder_lstm/add_16/_25 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_460_encoder_lstm/add_16", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/sgnbx/Downloads/projects/LSTM_autoencoder/justfun.py", line 121, in <module>
k_value = K.eval(encoded)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 671, in eval
return to_dense(x).eval(session=get_session())
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 680, in eval
return _eval_using_default_session(self, feed_dict, self.graph, session)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 4951, in _eval_using_default_session
return session.run(tensors, feed_dict)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 877, in run
run_metadata_ptr)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1100, in _run
feed_dict_tensor, options, run_metadata)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1272, in _do_run
run_metadata)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1291, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input' with dtype float and shape [?,45,50]
[[Node: input = Placeholder[dtype=DT_FLOAT, shape=[?,45,50], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: encoder_lstm/add_16/_25 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_460_encoder_lstm/add_16", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
Caused by op 'input', defined at:
File "/home/sgnbx/Downloads/projects/LSTM_autoencoder/justfun.py", line 113, in <module>
inputs = Input(shape=(SEQUENCE_LEN, EMBED_SIZE), name="input")
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/keras/engine/input_layer.py", line 177, in Input
input_tensor=tensor)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/keras/engine/input_layer.py", line 86, in __init__
name=self.name)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py", line 515, in placeholder
x = tf.placeholder(dtype, shape=shape, name=name)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/ops/array_ops.py", line 1735, in placeholder
return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/ops/gen_array_ops.py", line 4925, in placeholder
"Placeholder", dtype=dtype, shape=shape, name=name)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/util/deprecation.py", line 454, in new_func
return func(*args, **kwargs)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 3155, in create_op
op_def=op_def)
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/framework/ops.py", line 1717, in __init__
self._traceback = tf_stack.extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input' with dtype float and shape [?,45,50]
[[Node: input = Placeholder[dtype=DT_FLOAT, shape=[?,45,50], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[Node: encoder_lstm/add_16/_25 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_460_encoder_lstm/add_16", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
Exception ignored in: <bound method BaseSession.__del__ of <tensorflow.python.client.session.Session object at 0x7fd900525c50>>
Traceback (most recent call last):
File "/home/sgnbx/anaconda3/envs/py3/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 686, in __del__
TypeError: 'NoneType' object is not callable
Process finished with exit code 1
Very simple way to print a tensor :
from keras import backend as K
k_value = K.eval(tensor)
print(k_value)
UPDATE 1
Create a callback to print at the end of each epoch :
class callback(Callback):
def __init__(self, model, X_train):
self.model = model
self.x = X_train
def on_train_begin(self, logs={}):
return
def on_train_end(self, logs={}):
return
def on_epoch_begin(self, epoch, logs={}):
return
def on_epoch_end(self, epoch, logs={}):
inp = model.input # input placeholder
outputs = model.layers[N].output # get output of N's layer
functors = K.function([inp, K.learning_phase()], [outputs])
layer_outs = functors([self.x, 1.])
print('\r OUTPUT TENSOR : %s' % layer_outs)
return
def on_batch_begin(self, batch, logs={}):
return
def on_batch_end(self, batch, logs={}):
return
Call this function in your fit() method like that :
callbacks=[callback(model = model, X_train = X_train)])
Inspired from Keras, How to get the output of each layer?
Hope this will finally help you !
Related
I am currently trying to better understand Tensorflows CustomLayer feature. While implementing such a custom layer, I ran into the following error:
/usr/lib/python3/dist-packages/skimage/util/dtype.py:110: UserWarning: Possible precision loss when converting from float64 to uint16
"%s to %s" % (dtypeobj_in, dtypeobj))
/usr/lib/python3/dist-packages/skimage/exposure/exposure.py:307: RuntimeWarning: invalid value encountered in true_divide
image = (image - imin) / float(imax - imin)
Traceback (most recent call last):
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/client/session.py", line 1323, in _do_call
return fn(*args)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/client/session.py", line 1302, in _run_fn
status, run_metadata)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/framework/errors_impl.py", line 473, in __exit__
c_api.TF_GetCode(self.status.status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: 0-th value returned by pyfunc_0 is double, but expects float
[[Node: model/pretrained/custom_layer_1/map/while/custom_image_op = PyFuncStateless[Tin=[DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_0", _device="/job:localhost/replica:0/task:0/device:CPU:0"](model/pretrained/custom_layer_1/map/while/TensorArrayReadV3/_49)]]
[[Node: model/pretrained/custom_layer_1/map/while/TensorArrayWrite/TensorArrayWriteV3/_55 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_126_model/pretrained/custom_layer_1/map/while/TensorArrayWrite/TensorArrayWriteV3", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](^_cloopmodel/pretrained/custom_layer_1/map/while/NextIteration_1/_20)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "train.py", line 94, in <module>
trainer.run(sess)
File "/home//Downloads/dl_ss_19-master/Ex4/train/trainer.py", line 128, in run
self._train_epoch(sess)
File "/home/train/trainer.py", line 49, in _train_epoch
self._model_is_training: True})
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/client/session.py", line 889, in run
run_metadata_ptr)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/client/session.py", line 1120, in _run
feed_dict_tensor, options, run_metadata)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/client/session.py", line 1317, in _do_run
options, run_metadata)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/client/session.py", line 1336, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: 0-th value returned by pyfunc_0 is double, but expects float
[[Node: model/pretrained/custom_layer_1/map/while/custom_image_op = PyFuncStateless[Tin=[DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_0", _device="/job:localhost/replica:0/task:0/device:CPU:0"](model/pretrained/custom_layer_1/map/while/TensorArrayReadV3/_49)]]
[[Node: model/pretrained/custom_layer_1/map/while/TensorArrayWrite/TensorArrayWriteV3/_55 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_126_model/pretrained/custom_layer_1/map/while/TensorArrayWrite/TensorArrayWriteV3", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](^_cloopmodel/pretrained/custom_layer_1/map/while/NextIteration_1/_20)]]
Caused by op 'model/pretrained/custom_layer_1/map/while/custom_image_op', defined at:
File "train.py", line 61, in <module>
prediction_logits = model.pretrained(img_conc)
File "/home/model/pretrained.py", line 56, in create
x = CustomLayer(output_dim=(224, 224, 3))(inputs)
File "/local/tensorflow-1.4.0/python3.5/keras/engine/topology.py", line 603, in __call__
output = self.call(inputs, **kwargs)
File "/home/model/pretrained.py", line 41, in call
res = tf.map_fn(preprocess_input, x)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/ops/functional_ops.py", line 389, in map_fn
swap_memory=swap_memory)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/ops/control_flow_ops.py", line 2816, in while_loop
result = loop_context.BuildLoop(cond, body, loop_vars, shape_invariants)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/ops/control_flow_ops.py", line 2640, in BuildLoop
pred, body, original_loop_vars, loop_vars, shape_invariants)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/ops/control_flow_ops.py", line 2590, in _BuildLoop
body_result = body(*packed_vars_for_body)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/ops/functional_ops.py", line 379, in compute
packed_fn_values = fn(packed_values)
File "/home/model/pretrained.py", line 30, in preprocess_input
name='custom_image_op')
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/ops/script_ops.py", line 215, in py_func
input=inp, token=token, Tout=Tout, name=name)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/ops/gen_script_ops.py", line 90, in _py_func_stateless
"PyFuncStateless", input=input, token=token, Tout=Tout, name=name)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/framework/ops.py", line 2956, in create_op
op_def=op_def)
File "/local/tensorflow-1.4.0/python3.5/tensorflow/python/framework/ops.py", line 1470, in __init__
self._traceback = self._graph._extract_stack() # pylint: disable=protected-access
InvalidArgumentError (see above for traceback): 0-th value returned by pyfunc_0 is double, but expects float
[[Node: model/pretrained/custom_layer_1/map/while/custom_image_op = PyFuncStateless[Tin=[DT_FLOAT], Tout=[DT_FLOAT], token="pyfunc_0", _device="/job:localhost/replica:0/task:0/device:CPU:0"](model/pretrained/custom_layer_1/map/while/TensorArrayReadV3/_49)]]
[[Node: model/pretrained/custom_layer_1/map/while/TensorArrayWrite/TensorArrayWriteV3/_55 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device_incarnation=1, tensor_name="edge_126_model/pretrained/custom_layer_1/map/while/TensorArrayWrite/TensorArrayWriteV3", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](^_cloopmodel/pretrained/custom_layer_1/map/while/NextIteration_1/_20)]]
Thus far I tried to cast the various parameters and change the arguments of the function. This however didn't influence the result at all. I am at a loss. Does someone have experience with pyfunc_0? If yes, how can I fix below's code?
Links I found useful:
https://github.com/cesc-park/attend2u/issues/2
https://github.com/rstudio/tensorflow/issues/169
"0-th value returned by pyfunc_0 is double, but expects float" though I think it returns float
Including advanced computation (scikit-like) in a keras custom layer
def equalize(img):
img_adapteq = 255 * exposure.equalize_adapthist(img // 255)
return img_adapteq.astype(np.float)
def preprocess_input(img):
x = tf.py_func(equalize,
[img],
'float32',
stateful=False,
name='custom_image_op')
return tf.cast(x, tf.float32)
class CustomLayer(Layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
self.trainable = False
super(CustomLayer, self).__init__(**kwargs)
def call(self, x):
res = tf.map_fn(preprocess_input, x)
res.set_shape([x.shape[0],
self.output_dim[1],
self.output_dim[0],
x.shape[-1]])
return res
inputs = Input(shape=(224, 224, 3), tensor=x)
x = CustomLayer(output_dim=(224, 224, 3))(inputs)
I'm training a multilabel classifier using tf.keras and horovod that has 14 classes. AucRoc is used as the metric to evaluate the performance of the classifier. I want to be able to use scikit learn's AucRoc calculator as mentioned here: How to compute Receiving Operating Characteristic (ROC) and AUC in keras?. If I feed the tensors as is for the following function:
def sci_auc_roc(y_true, y_pred):
return tf.py_func(roc_auc_score(y_true, y_pred), tf.double)
I get an error that looks like this:
/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/keras_applications/resnet50.py:265: UserWarning: The output shape of `ResNet50(include_top=False)` has been changed since Keras 2.2.0.
warnings.warn('The output shape of `ResNet50(include_top=False)` '
Traceback (most recent call last):
File "official_resnet_tf_1.12.0_auc.py", line 531, in <module>
main()
File "official_resnet_tf_1.12.0_auc.py", line 420, in main
model = chexnet_model(FLAGS)
File "official_resnet_tf_1.12.0_auc.py", line 375, in chexnet_model
metrics=[tf_auc_roc,sci_auc_roc])
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/training/checkpointable/base.py", line 474, in _method_wrapper
method(self, *args, **kwargs)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 648, in compile
sample_weights=self.sample_weights)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 313, in _handle_metrics
output, output_mask))
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 270, in _handle_per_output_metrics
y_true, y_pred, weights=weights, mask=mask)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_utils.py", line 598, in weighted
score_array = fn(y_true, y_pred)
File "official_resnet_tf_1.12.0_auc.py", line 327, in sci_auc_roc
return tf.py_func(roc_auc_score(y_true, y_pred), tf.double)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/sklearn/metrics/ranking.py", line 349, in roc_auc_score
y_type = type_of_target(y_true)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/sklearn/utils/multiclass.py", line 243, in type_of_target
'got %r' % y)
ValueError: Expected array-like (array or non-string sequence), got <tf.Tensor 'dense_target:0' shape=(?, ?) dtype=float32>
I'm trying to convert tf tensors into a numpy array and then feed them to the roc_auc_score method like so:
def sci_auc_roc(y_true, y_pred):
with tf.Session() as sess:
y_true, y_pred = sess.run([y_true, y_pred])
return tf.py_func(roc_auc_score(y_true, y_pred), tf.double)
I get the following error:
warnings.warn('The output shape of `ResNet50(include_top=False)` '
Traceback (most recent call last):
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1334, in _do_call
return fn(*args)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1319, in _run_fn
options, feed_dict, fetch_list, target_list, run_metadata)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1407, in _call_tf_sessionrun
run_metadata)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,256,256,3]
[[{{node input_1}} = Placeholder[dtype=DT_FLOAT, shape=[?,256,256,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[{{node dense_target/_5}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_2237_dense_target", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "official_resnet_tf_1.12.0_auc.py", line 531, in <module>
main()
File "official_resnet_tf_1.12.0_auc.py", line 420, in main
model = chexnet_model(FLAGS)
File "official_resnet_tf_1.12.0_auc.py", line 375, in chexnet_model
metrics=[tf_auc_roc,sci_auc_roc])
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/training/checkpointable/base.py", line 474, in _method_wrapper
method(self, *args, **kwargs)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 648, in compile
sample_weights=self.sample_weights)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 313, in _handle_metrics
output, output_mask))
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 270, in _handle_per_output_metrics
y_true, y_pred, weights=weights, mask=mask)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_utils.py", line 598, in weighted
score_array = fn(y_true, y_pred)
File "official_resnet_tf_1.12.0_auc.py", line 324, in sci_auc_roc
y_true, y_pred = sess.run([y_true, y_pred])
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 929, in run
run_metadata_ptr)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1152, in _run
feed_dict_tensor, options, run_metadata)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1328, in _do_run
run_metadata)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1348, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,256,256,3]
[[node input_1 (defined at /mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/keras_applications/resnet50.py:214) = Placeholder[dtype=DT_FLOAT, shape=[?,256,256,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[{{node dense_target/_5}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_2237_dense_target", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
Caused by op 'input_1', defined at:
File "official_resnet_tf_1.12.0_auc.py", line 531, in <module>
main()
File "official_resnet_tf_1.12.0_auc.py", line 420, in main
model = chexnet_model(FLAGS)
File "official_resnet_tf_1.12.0_auc.py", line 339, in chexnet_model
input_shape=(FLAGS.image_size, FLAGS.image_size, 3))
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/applications/__init__.py", line 70, in wrapper
return base_fun(*args, **kwargs)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/applications/resnet50.py", line 32, in ResNet50
return resnet50.ResNet50(*args, **kwargs)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/keras_applications/resnet50.py", line 214, in ResNet50
img_input = layers.Input(shape=input_shape)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/input_layer.py", line 229, in Input
input_tensor=tensor)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/keras/engine/input_layer.py", line 112, in __init__
name=self.name)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/ops/array_ops.py", line 1747, in placeholder
return gen_array_ops.placeholder(dtype=dtype, shape=shape, name=name)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/ops/gen_array_ops.py", line 5206, in placeholder
"Placeholder", dtype=dtype, shape=shape, name=name)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 3274, in create_op
op_def=op_def)
File "/mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1770, in __init__
self._traceback = tf_stack.extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_1' with dtype float and shape [?,256,256,3]
[[node input_1 (defined at /mnt/lustrefs/rakvee/miniconda3/envs/docker_pip2/lib/python3.6/site-packages/keras_applications/resnet50.py:214) = Placeholder[dtype=DT_FLOAT, shape=[?,256,256,3], _device="/job:localhost/replica:0/task:0/device:GPU:0"]()]]
[[{{node dense_target/_5}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_2237_dense_target", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
--------------------------------------------------------------------------
Primary job terminated normally, but 1 process returned
a non-zero exit code. Per user-direction, the job has been aborted.
--------------------------------------------------------------------------
--------------------------------------------------------------------------
mpirun detected that one or more processes exited with non-zero status, thus causing
the job to be terminated. The first process to do so was:
Process name: [[52342,1],0]
Exit code: 1
--------------------------------------------------------------------------
I've also tried tensorflow's https://www.tensorflow.org/api_docs/python/tf/metrics/auc like so:
def tf_auc_roc(y_true, y_pred):
auc = tf.metrics.auc(y_true, y_pred)[1]
K.get_session().run(tf.local_variables_initializer())
return auc
It works just fine. However, it gives me a single number for aucroc. I wonder what that number represents, is it an average aucroc value for all the 14 classes? or max aucscores of all the classes? or how does it get to a single number?
1216/1216 [==============================] - 413s 340ms/step - loss: 0.1513 - tf_auc_roc: 0.7944 - val_loss: 0.2212 - val_tf_auc_roc: 0.8074
Epoch 2/15
582/1216 [=============>................] - ETA: 3:16 - loss: 0.1459 - tf_auc_roc: 0.8053
1) How do I fix the error with roc_auc_score?
2) What does that single number represent?
I think that the result of a metric should be a single tensor value that represents the average of the results as described here in the Keras documentation (which I find is the better documentation than that from TensorFlow).
You could instead use a custom callback to achieve your desired result, most probably you would want to write to disc the result on_epoch_end
I'm trying to train a model with an input layer similar to DNNClassifier.
I used feature_column_lib.input_layer, which is how DNNClassifier constructs its input layer.
However, I got an error when I tried to optimize the loss of my graph. I feel it has something to do with the categorical feature spec, when I removed the categorical feature, it works fine. Is there a way to solve this?
Thanks.
tensorflow/core/framework/op_kernel.cc:1318] OP_REQUIRES failed at sparse_to_dense_op.cc:126 : Invalid argument: indices[1] = [1,0] is out of bounds: need 0 <= index < [1,1]
Traceback (most recent call last):
File "tf_exp.py", line 120, in <module>
print sess.run(loss)
File "lib/python2.7/site-packages/tensorflow/python/client/session.py", line 900, in run
run_metadata_ptr)
File "lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1135, in _run
feed_dict_tensor, options, run_metadata)
File "lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1316, in _do_run
run_metadata)
File "lib/python2.7/site-packages/tensorflow/python/client/session.py", line 1335, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: indices[1] = [1,0] is out of bounds: need 0 <= index < [1,1]
[[Node: input_layer/a4_indicator/SparseToDense = SparseToDense[T=DT_INT64, Tindices=DT_INT64, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](input_layer/a4_indicator/to_sparse_input/indices, input_layer/a4_indicator/to_sparse_input/dense_shape, input_layer/a4_indicator/Select, input_layer/a4_indicator/SparseToDense/default_value)]]
Caused by op u'input_layer/a4_indicator/SparseToDense', defined at:
File "tf_exp.py", line 102, in <module>
features=features, feature_columns=feature_columns)
File "lib/python2.7/site-packages/tensorflow/python/feature_column/feature_column.py", line 277, in input_layer
trainable, cols_to_vars)
File "lib/python2.7/site-packages/tensorflow/python/feature_column/feature_column.py", line 202, in _internal_input_layer
trainable=trainable)
File "lib/python2.7/site-packages/tensorflow/python/feature_column/feature_column.py", line 3332, in _get_dense_tensor
return inputs.get(self)
File "lib/python2.7/site-packages/tensorflow/python/feature_column/feature_column.py", line 2175, in get
transformed = column._transform_feature(self) # pylint: disable=protected-access
File "lib/python2.7/site-packages/tensorflow/python/feature_column/feature_column.py", line 3277, in _transform_feature
id_tensor, default_value=-1)
File "lib/python2.7/site-packages/tensorflow/python/ops/sparse_ops.py", line 996, in sparse_tensor_to_dense
name=name)
File "lib/python2.7/site-packages/tensorflow/python/ops/sparse_ops.py", line 776, in sparse_to_dense
name=name)
File "lib/python2.7/site-packages/tensorflow/python/ops/gen_sparse_ops.py", line 2824, in sparse_to_dense
name=name)
File "lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3414, in create_op
op_def=op_def)
File "lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1740, in __init__
self._traceback = self._graph._extract_stack() # pylint: disable=protected-access
InvalidArgumentError (see above for traceback): indices[1] = [1,0] is out of bounds: need 0 <= index < [1,1]
[[Node: input_layer/a4_indicator/SparseToDense = SparseToDense[T=DT_INT64, Tindices=DT_INT64, validate_indices=true, _device="/job:localhost/replica:0/task:0/device:CPU:0"](input_layer/a4_indicator/to_sparse_input/indices, input_layer/a4_indicator/to_sparse_input/dense_shape, input_layer/a4_indicator/Select, input_layer/a4_indicator/SparseToDense/default_value)]]
Here is my program
dataset = tf.data.TextLineDataset('test_input.txt')
dataset = dataset.shuffle(5)
dataset = dataset.batch(5)
dataset = dataset.repeat(configs.get('epochs',10))
train_data_iterator = dataset.make_one_shot_iterator()
features, labels= _parse_example(train_data_iterator.get_next())
feature_columns = []
feature_columns.append(tf.feature_column.numeric_column(key='f0', dtype=tf.float32))
feature_columns.append(tf.feature_column.numeric_column(key='f1', dtype=tf.float32))
feature_columns.append(tf.feature_column.numeric_column(key='f2', dtype=tf.float32))
feature_columns.append(tf.feature_column.numeric_column(key='f3', dtype=tf.float32))
feature_columns.append(tf.feature_column.indicator_column(
tf.feature_column.categorical_column_with_identity(key='a4', num_buckets=11,
default_value=0)))
input_layer = feature_column_lib.input_layer(
features=features, feature_columns=feature_columns)
logits = tf.layers.dense(inputs=input_layer, units=1)
loss = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(labels=labels, logits=logits))
optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(loss, global_step = global_step)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print sess.run(loss)
Figured it out, the real problem is labels dimension didn't match with logits.
Traceback (most recent call last):
File "C:/Users/ljz/PycharmProjects/TFConvLSTM/LSTMnetwork.py", line 136, in <module>
sess.run(train_step, feed_dict={x: X_train[start:end], y_: y_train[start:end]})
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 767, in run
run_metadata_ptr)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 965, in _run
feed_dict_string, options, run_metadata)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1015, in _do_run
target_list, options, run_metadata)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\client\session.py", line 1035, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: Incompatible shapes: [1500,18] vs. [22500,18]
[[Node: mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_1_0, Log)]]
Caused by op 'mul', defined at:
File "C:/Users/ljz/PycharmProjects/TFConvLSTM/LSTMnetwork.py", line 113, in <module>
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\math_ops.py", line 884, in binary_op_wrapper
return func(x, y, name=name)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\math_ops.py", line 1105, in _mul_dispatch
return gen_math_ops._mul(x, y, name=name)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 1625, in _mul
result = _op_def_lib.apply_op("Mul", x=x, y=y, name=name)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 763, in apply_op
op_def=op_def)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 2395, in create_op
original_op=self._default_original_op, op_def=op_def)
File "C:\Users\ljz\AppData\Local\Programs\Python\Python35\lib\site-packages\tensorflow\python\framework\ops.py", line 1264, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): Incompatible shapes: [1500,18] vs. [22500,18]
[[Node: mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_1_0, Log)]]
Caused by op 'mul', defined at: File "C:/Users/ljz/PycharmProjects/TFConvLSTM/LSTMnetwork.py", line 113, in cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))
and
InvalidArgumentError (see above for traceback): Incompatible shapes: [1500,18] vs. [22500,18] [[Node: mul = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"](_recv_Placeholder_1_0, Log)]]
=> Make sure y and y_conv have identical or broadcastable shape.
Problematic code:
cross_entropy=tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))
As you are trying to multiply two tensors y_ and y_conv, they must have the same shape, i.e. either both [1500,18] or both [22500,18]
In your case y_ should be input labels and y_conv should be calculated logits, and 18 should be the number of output neurons. Therefore I guess your batch size of input data (x) and label(y_) are not the same. Check it and make them the same.
I get the unexpected error "You must feed a value for placeholder tensor 'input_1' with dtype float" when training the discriminator of a GAN
here the error:
W tensorflow/core/framework/op_kernel.cc:975] Invalid argument: You must feed a value for placeholder tensor 'input_1' with dtype float
[[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
W tensorflow/core/framework/op_kernel.cc:975] Invalid argument: You must feed a value for placeholder tensor 'input_1' with dtype float
[[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
Traceback (most recent call last):
File "new_model.py", line 204, in <module>
main()
File "new_model.py", line 201, in main
train(nb_epoch=10, BATCH_SIZE=5)
File "new_model.py", line 176, in train
d_loss = discriminator.train_on_batch(image_to_dis, label_to_dis)
File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 766, in train_on_batch
class_weight=class_weight)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1320, in train_on_batch
outputs = self.train_function(ins)
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 1943, in __call__
feed_dict=feed_dict)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 766, in run
run_metadata_ptr)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 964, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1014, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 1034, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InvalidArgumentError: You must feed a value for placeholder tensor 'input_1' with dtype float
[[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
[[Node: moments_4/sufficient_statistics/Shape/_217 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_1267_moments_4/sufficient_statistics/Shape", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
Caused by op u'input_1', defined at:
File "new_model.py", line 204, in <module>
main()
File "new_model.py", line 201, in main
train(nb_epoch=10, BATCH_SIZE=5)
File "new_model.py", line 134, in train
transformer0 = transform_model()
File "new_model.py", line 22, in transform_model
inputs = Input(shape=( 128, 128, 3))
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1198, in Input
input_tensor=tensor)
File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 1116, in __init__
name=self.name)
File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 321, in placeholder
x = tf.placeholder(dtype, shape=shape, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 1587, in placeholder
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 2043, in _placeholder
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2240, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1128, in __init__
self._traceback = _extract_stack()
InvalidArgumentError (see above for traceback): You must feed a value for placeholder tensor 'input_1' with dtype float
[[Node: input_1 = Placeholder[dtype=DT_FLOAT, shape=[], _device="/job:localhost/replica:0/task:0/gpu:0"]()]]
[[Node: moments_4/sufficient_statistics/Shape/_217 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_1267_moments_4/sufficient_statistics/Shape", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
it seems the error happens at
d_loss = discriminator.train_on_batch(image_to_dis, label_to_dis)
I'm sure image_to_dis and label_to_dis fit the input of dicriminator
however, the error message here
Caused by op u'input_1', defined at:
File "new_model.py", line 204, in <module>
main()
File "new_model.py", line 201, in main
train(nb_epoch=10, BATCH_SIZE=5)
File "new_model.py", line 134, in train
transformer0 = transform_model()
File "new_model.py", line 22, in transform_model
inputs = Input(shape=( 128, 128, 3))
it says the error is caused by the input tensor of 'transformer'(it is the generator in this GAN).
my code contains something like 'transformer_with_discriminator = discriminator(transformer)', but the discriminator is compiled without the transformer. I think training the discriminator has nothing to do with the input of 'transformer0'
the whole script is a little long, may I put the link of my model here?
https://github.com/wkcw/keras-face-attribute/blob/master/model%26train.py
image_to_dis.dtype and label_to_dis.dtype are both float32, and I've tried to convert label_to_dis.dtype to int
I really have no idea about this......
It comes from the batchnormalization. You can see here : https://stackoverflow.com/a/42470757/7137636 how to fix this issue.
If you need more info, ask in comments :)