TensorFlow "TypeError: Target data is missing"尽管提供了具有 2 维元组的数据集



我正在尝试使用基于生成器的数据集:

def gen():
return zip(samples,feature)
ds = tf.data.Dataset.from_generator(gen,output_types=tf.dtypes.float32)

model.fit(ds,
epochs=150,
#callbacks=[tensorboard_callback]
)
model.save("/sda/anyone/imagenet-in-np/transformer")

而功能是numpy.ndarray(2D数组) 而功能是numpy.ndarray(4D数组) 我收到以下错误:

TypeError: Target data is missing. Your model has `loss`: BinaryCrossentropy, and therefore expects target data to be passed in `fit()`.

这很奇怪,因为目标数据实际上存在。 每当我将数据集分成两个时

def gen():
return samples
ds = tf.data.Dataset.from_generator(gen,output_types=tf.dtypes.float32)
def gen2():
return feature
ds2= tf.data.Dataset.from_generator(gen2,output_types=tf.dtypes.float32)
model.fit(ds,ds2,
epochs=150,
#callbacks=[tensorboard_callback]
)
model.save("/sda/anyone/imagenet-in-np/transformer")

我得到:

raise ValueError("`y` argument is not supported when using "
ValueError: `y` argument is not supported when using dataset as input.

这意味着 TF 不接受这种拆分。

那么我应该如何使用生成器 API?

编辑#1: 我尝试了如前所述:

def gen():
for element in zip(samples,feature):
yield element
ds = tf.data.Dataset.from_generator(gen(),output_types=tf.dtypes.float32)

我得到 TypeError:generator必须是 Python 可调用的。

所以我试图将其交换为:

def gen():
for element in zip(samples,feature):
yield element
ds = tf.data.Dataset.from_generator(gen,output_types=tf.dtypes.float32)

我再次得到:

TypeError: Target data is missing. Your model has `loss`: BinaryCrossentropy, and therefore expects target data to be passed in `fit()`.
python-BaseException

编辑#2:

我尝试了以下方法:

def gen():
for element in zip(samples,feature):
sample=tf.convert_to_tensor(element[0], dtype=tf.float32)
f=tf.convert_to_tensor(element[1], dtype=tf.float32)
print(sample.shape)
yield (sample,f)
ds = tf.data.Dataset.from_generator(gen,output_types=(tf.float32, tf.float32))

model.fit(ds,
epochs=150
#callbacks=[tensorboard_callback]
)

我得到

2022-01-22 16:50:07.417109: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at conv_ops.cc:675 : INVALID_ARGUMENT: input must be 4-dimensional[16,17,10]

这里有几件事需要注意,
tf.fit如何工作{链接进一步阅读}:主要是它需要两个参数xy,如果你这样设置,就像你的第二种情况一样。否则,您可以在x下输入特征和目标作为tf.Dataset对象。
使用tf .from_generator函数{链接进一步阅读}:首先也是python生成器,而不是函数。[仅供参考;不要使用return,而是使用yield]通常tf from_generator()仅在极端情况下使用[例如,导入带有多边形注释的图像等],并且会减慢模型训练的输入管道。

由于这里您只需输入两个numpy ndarrays,因此可以直接使用tf. Dataset对象轻松完成: 工作示例

最新更新