tensorflow keras适合,输入验证数据(数据,(target1,target2)),发生错误:'未预期数据,但得到:'

时间:2019-02-11 16:20:08

标签: python tensorflow keras tensorflow-datasets

构建具有多个输出的子类模型,使用tensorflow数据集作为输入。自定义定义的数据集。

使用适合的keras训练模型。

当我仅使用火车数据集时,它可以运行。但是一旦我使用相同类型的数据集作为验证输入,它就会出错:      “检查模型目标时出错:预期没有数据,但是得到了:”

数据类型类似于'tuple(data,(target [0],target [1]))'

tensorflow-gpu == 1.12,tensorflow.keras

错误信息

File "/home/god/anaconda3/envs/tensorflow_n/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 1574, in fit
steps=validation_steps)    

File "/home/god/anaconda3/envs/tensorflow_n/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 992, in _standardize_user_data
class_weight, batch_size)

File "/home/god/anaconda3/envs/tensorflow_n/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 1154, in _standardize_weights
exception_prefix='target')

File "/home/god/anaconda3/envs/tensorflow_n/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_utils.py", line 257, in standardize_input_data
'expected no data, but got:', data)

ValueError: ('Error when checking model target: expected no data, but got:', (<tf.Tensor 'IteratorGetNext_1:1' shape=(16, 16, 513) dtype=float32>, <tf.Tensor 'IteratorGetNext_1:2' shape=(16, 16, 513) dtype=float32>))

简化代码会导致相同的错误

import tensorflow as tf


class Model(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.dense1 = tf.keras.layers.Dense(units=16)
        self.dense2 = tf.keras.layers.Dense(units=16)

    def compute_output_shape(self, input_shape):
        return input_shape, input_shape

    def call(self, inputs, training=None, mask=None):
        out1 = self.dense1(inputs)
        out2 = self.dense2(inputs)
        return out1, out2


train_dataset = tf.data.Dataset.from_tensor_slices(
    (tf.constant(0., shape=[1024, 16]), (tf.constant(0., shape=[1024, 16]), tf.constant(0., shape=[1024, 16])))).repeat().batch(32)

valid_dataset = tf.data.Dataset.from_tensor_slices(
    (tf.constant(0., shape=[128, 16]), (tf.constant(0., shape=[128, 16]), tf.constant(0., shape=[128, 16])))).repeat(1).batch(32)

model = Model()
model.compile(
    optimizer=tf.train.AdamOptimizer(learning_rate=1e-4),
    loss=[tf.keras.losses.mse, tf.keras.losses.mse],
    loss_weights=[1, 1]
)
model.fit(
    train_dataset,
    validation_data=valid_dataset,
    epochs=10,
    steps_per_epoch=30,
    validation_steps=4,
)

1 个答案:

答案 0 :(得分:1)

Keras不是PyTorch,没有高级的理由就不应该对模型进行子类化。

inputs = Input(input_shape)
out1 = Dense(16)(inputs)
out2 = Dense(16)(inputs)

model = tf.keras.Model(inputs, [out1,out2])

训练时将xy分开:

x_train = your_tuple[0]
y_train = your_tuple[1]

model.fit(x_train, y_train, ....)