类型错误:预期 tensorflow.python.framework.tensor_spec.TensorSpec,找到 numpy.ndarray

问题描述

当我想从 TFF 0.12.0 迁移到 TFF 0.18.0 时出现以下错误, 知道我有一个图像数据集,这是我的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()])

那么我怎样才能修改我的 sample_batch 以使其与这个版本正确?请帮忙 !!谢谢

解决方法

在版本 0.13.0 中,sample_batch 参数已弃用。 input_spec 参数必须是 tff.Typetf.TensorSpec,根据 the documentation

tf.TensorSpec 构建 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)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...