reubenjohn
reubenjohn

Reputation: 1409

Tensorflow Keras Input layer does not add _keras_shape

According to the keras documentation, Input adds the _keras_shape attribute to the input tensor. However, as shown below, this is not the case.

import tensorflow as tf
s = tf.keras.layers.Input(shape=[2], dtype=tf.float32, name='s')
print(s._keras_shape)
Traceback (most recent call last):
  File "<input>", line 3, in <module>
AttributeError: 'Tensor' object has no attribute '_keras_shape'

Have I misunderstood something, or is this a bug I should report?

The lack of this attribute makes further Keras functions go haywire:

q_s = q(s)
model = Model(inputs=s, outputs=q_s)
Traceback (most recent call last):
...
File "/home/reuben/.virtualenvs/tensorflow/lib/python3.5/site-packages/keras/engine/network.py", line 253, in <listcomp>
  input_shapes=[x._keras_shape for x in self.inputs],
AttributeError: 'Tensor' object has no attribute '_keras_shape'

I'm using tensorflow version '1.11.0-rc2'

Upvotes: 3

Views: 3529

Answers (2)

Primusa
Primusa

Reputation: 13498

The input layer you get appears to be slightly different depending on whether you are importing from keras or whether you're importing it through tensorflow. The keras documentation you linked is based on importing layers from the keras library directly:

For example:

import tensorflow as tf
from keras.layers import Input

s = Input(shape=[2], dtype=tf.float32, name='2')
s._shape_val # None
s._keras_shape # (None, 2)

However importing through tensorflow appears to save the shape in the tensorflow attribute _shape_val instead:

import tensorflow as tf
s = tf.keras.layers.Input(shape=[2], dtype=tf.float32, name='s')
s._shape_val # TensorShape([Dimension(None), Dimension(2)])
s._keras_shape # Error

Your best bet is to just import the layer from keras directly. If you plan to continue using tf.keras instead of the main implementation of keras, you should refer to the tf.keras docs instead of keras.io.

Upvotes: 6

JoshuaF
JoshuaF

Reputation: 1216

Documentation here does not mention _keras_shape.

"The added Keras attribute is: _keras_history: Last layer applied to the tensor. the entire layer graph is retrievable from that layer, recursively."

When you say "makes further Keras functions go haywire", what do you mean?

Upvotes: 1

Related Questions