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
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 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 !
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 :)
I've built a binary classifier using Tensorflow and now I would like to evaluate the classifier using AUC and accuracy.
As far as accuracy is concerned, I can easily do like this:
X = tf.placeholder('float', [None, n_input])
y = tf.placeholder('float', [None, n_classes])
pred = mlp(X, weights, biases, dropout_keep_prob)
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
When calculating AUC I use the following:
print(tf.argmax(pred, 1).dtype.name)
print(tf.argmax(pred, 1).dtype.name)
a = tf.cast(tf.argmax(pred, 1),tf.float32)
b = tf.cast(tf.argmax(y,1),tf.float32)
auc = tf.contrib.metrics.streaming_auc(a, b)
and in the training loop:
train_acc = sess.run(accuracy, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})
train_auc = sess.run(auc, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})
which gives me the following output (and error) error:
int64
int64
/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/array_ops.py:1197: VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future
result_shape.insert(dim, 1)
Net built successfully...
Starting training...
Epoch: 000/300 cost: 0.618990561
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 715, in _do_call
return fn(*args)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 697, in _run_fn
status, run_metadata)
File "/usr/lib/python3.5/contextlib.py", line 66, in __exit__
next(self.gen)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/errors.py", line 450, in raise_exception_on_not_ok_status
pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value auc/false_positives
[[Node: auc/false_positives/read = Identity[T=DT_FLOAT, _class=["loc:#auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"](auc/false_positives)]]
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./mlp_.py", line 152, in <module>
train_auc = sess.run(auc, feed_dict={X: batch_xs, y: batch_ys, dropout_keep_prob:1.})
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 372, in run
run_metadata_ptr)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 636, in _run
feed_dict_string, options, run_metadata)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 708, in _do_run
target_list, options, run_metadata)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/client/session.py", line 728, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors.FailedPreconditionError: Attempting to use uninitialized value auc/false_positives
[[Node: auc/false_positives/read = Identity[T=DT_FLOAT, _class=["loc:#auc/false_positives"], _device="/job:localhost/replica:0/task:0/cpu:0"](auc/false_positives)]]
Caused by op 'auc/false_positives/read', defined at:
File "./mlp_.py", line 121, in <module>
auc = tf.contrib.metrics.streaming_auc(a, b)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/metrics/python/ops/metric_ops.py", line 718, in streaming_auc
predictions, labels, thresholds, ignore_mask)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/metrics/python/ops/metric_ops.py", line 603, in _tp_fn_tn_fp
false_positives = _create_local('false_positives', shape=[num_thresholds])
File "/usr/local/lib/python3.5/dist-packages/tensorflow/contrib/metrics/python/ops/metric_ops.py", line 75, in _create_local
collections=collections)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/variables.py", line 211, in __init__
dtype=dtype)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/variables.py", line 319, in _init_from_args
self._snapshot = array_ops.identity(self._variable, name="read")
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 831, in identity
result = _op_def_lib.apply_op("Identity", input=input, name=name)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/ops/op_def_library.py", line 704, in apply_op
op_def=op_def)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 2260, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/framework/ops.py", line 1230, in __init__
self._traceback = _extract_stack()
I don't understand what I am doing wrong and why when using accuracy only the code runs fine but when using AUC it throws this error.
Could you please hint me in the right direction to understand how to fix this?
My objective is to calculate AUC and ROC for better evaluating the binary classifier performances.
I've found the same issue on github. At the moment, it seems that you also need to run sess.run(tf.initialize_local_variables()) in order to make tf.contrib.metrics.streaming_auc() work. They're working on it.
Here you have an example demonstrating how you can solve this issue:
import tensorflow as tf
a = tf.Variable([0.1, 0.5])
b = tf.Variable([0.2, 0.6])
auc = tf.contrib.metrics.streaming_auc(a, b)
sess = tf.Session()
sess.run(tf.initialize_all_variables())
sess.run(tf.initialize_local_variables()) # try commenting this line and you'll get the error
train_auc = sess.run(auc)
print(train_auc)