Stefan Falk
Stefan Falk

Reputation: 25487

Could not build a TypeSpec for KerasTensor

Running the following:

import tensorflow as tf

from tensorflow.keras import layers
from tensorflow import keras


feat_shape = (50, 66, 3)

inputs = layers.Input(shape=(None,) + feat_shape[1:], dtype=tf.float32)
x = inputs

shape = tf.shape(x)
b, t, f, c = x.get_shape().as_list()
x = layers.Lambda(tf.reshape, arguments=dict(shape=(shape[0], shape[1], shape[2] * shape[3])))(x)
x.set_shape((b, t, f * c))

x = layers.Dense(filters)(x)

lstm_out = layers.LSTM(lstm_units, return_sequences=True, return_state=True)(x)
x = lstm_out[0]

model = keras.Model(inputs=inputs, outputs=x)

Throws me this error:

TypeError: Could not build a TypeSpec for <KerasTensor: shape=(None, None, None) dtype=float32 (created by layer 'tf.reshape')> with type KerasTensor

The Tensorflow version I am using is 2.4.0 and I am rather certain that something like this should work.

What is the problem here and how can I resolve this?

Upvotes: 3

Views: 2693

Answers (1)

Stefan Falk
Stefan Falk

Reputation: 25487

def reshape_(t):
    shape = tf.shape(t)
    B, T, F, C = t.get_shape().as_list()
    t = tf.reshape(t, shape=(shape[0], shape[1], shape[2] * shape[3]))
    t.set_shape((B, T, F * C))
    return t

inputs = layers.Input(shape=(None,) + feat_shape[1:], dtype=tf.float32)
x = inputs
x = layers.Lambda(reshape_)(x)
x = layers.Dense(filters)(x)

lstm_out = layers.LSTM(lstm_units, return_sequences=True, return_state=True)(x)
x = lstm_out[0]

model = keras.Model(inputs=inputs, outputs=x)

enter image description here

Upvotes: 2

Related Questions