TypeError: Expected tensorflow.python.framework.tensor_spec.TensorSpec, found numpy.ndarray

Viewed 345

I am getting the following error when i would like to migrate from TFF 0.12.0 to TFF 0.18.0, Knowing that I have an image dataset, Here is my sample_batch

images, labels = next(img_gen.flow_from_directory(path0,target_size=(224, 224), batch_size=2))
sample_batch = (images,labels)
...

def model_fn():

  keras_model = create_keras_model()
  return tff.learning.from_keras_model(
      keras_model,
      input_spec=sample_batch,
      loss=tf.keras.losses.SparseCategoricalCrossentropy(),
      metrics=[tf.keras.metrics.SparseCategoricalAccuracy()])

So how can I modifiy my sample_batch to be correct with this version ? please Help !! thanks

1 Answers

In version 0.13.0 the sample_batch parameter was deprecated. The input_spec parameter must be a tff.Type or tf.TensorSpec as per the documentation.

To build a structure of tf.TensorSpec from a numpy.ndarray:

def tensor_spec_from_ndarray(a):
  return tf.TensorSpec(dtype=tf.dtypes.as_dtype(a.dtype),
                       shape=a.shape)

sample_batch = (images,labels)  # assumes images and labels are np.ndarray
input_spec = tf.nest.map_structure(
  tensor_spec_from_ndarray, sample_batch)
Related