【问题标题】:How to fix "Invalid argument: Key: feature. Can't parse serialized Example."如何修复“无效参数:键:功能。无法解析序列化示例。”
【发布时间】:2020-08-08 02:13:00
【问题描述】:

我正在尝试使用 TFRecordDataset 加载我的数据,但是,我遇到了这个错误,我搜索了很多,但仍然无法修复它。

我的 TensorFlow 版本是 1.14.0。

写入 tfrecords:

raw_data = pd.read_csv(data_file, header=None, delim_whitespace=True)
data_x = raw_data.iloc[:, 1:-4].values
data_y = raw_data.iloc[:, -3:].values
writer = tf.io.TFRecordWriter('test.tfrecord')
for i in range(100):
    example = tf.train.Example(features=tf.train.Features(
        feature={
            'feature': tf.train.Feature(float_list=tf.train.FloatList(value=data_x[i])),
            'target': tf.train.Feature(float_list=tf.train.FloatList(value=data_y[i]))
        }))
    writer.write(example.SerializeToString())

data_x 的形状为 (n, 736),data_y 的形状为 (n, 3)。

解析 tfrecord:

def parse_function(record):
    features = {
        'feature': tf.FixedLenFeature([736], dtype=tf.float32),
        'target': tf.FixedLenFeature([3], dtype=tf.float32)
    }
    example = tf.io.parse_single_example(record, features)
    return example['feature'], example['target']

然后从 tfrecords 中读取数据:

dataset = tf.data.TFRecordDataset('test.tfrecord')
dataset = dataset.shuffle(BUFFER_SIZE)
dataset = dataset.map(parse_function)
dataset = dataset.batch(BATCH_SIZE)
dataset = dataset.prefetch(BUFFER_SIZE)

以同样的方式创建test_dataset。然后构建并编译模型:

model = keras.Sequential([
        keras.layers.Dense(400, activation=tf.nn.tanh),
        keras.layers.Dense(400, activation=tf.nn.tanh),
        keras.layers.Dense(400, activation=tf.nn.tanh),
        keras.layers.Dense(3)
    ])
#     print(model.summary())
optim = tf.train.AdamOptimizer(learning_rate=LEARNING_RATE)
model.compile(optimizer=optim,
                  loss=rmse_and_norm_mae,
                  metrics=[rmse_and_norm_mae])

最后,训练模型并触发错误:

cp_callback = keras.callbacks.ModelCheckpoint(save_weights_path, verbose=0, save_weights_only=True,save_freq=SAVE_PERIOD)
model.fit(dataset, epochs=EPOCHS,steps_per_epoch=10, validation_data=test_dataset,validation_steps=10, callbacks=[cp_callback], verbose=2)

错误:

InvalidArgumentError: 2 root error(s) found.
  (0) Invalid argument: Key: feature.  Can't parse serialized Example.
     [[{{node ParseSingleExample/ParseSingleExample}}]]
     [[IteratorGetNext_64]]
     [[training_32/gradients/loss_16/dense_139_loss/Sum_grad/Shape/_2055]]
  (1) Invalid argument: Key: feature.  Can't parse serialized Example.
     [[{{node ParseSingleExample/ParseSingleExample}}]]
     [[IteratorGetNext_64]]
0 successful operations.
0 derived errors ignored.

我怎样才能让它工作?非常感谢您的帮助!

【问题讨论】:

    标签: tensorflow keras deep-learning


    【解决方案1】:

    问题在于您正在创建数据。你的data_x 的形状是(100, 734) 而不是(100, 736)。运行此行时,您排除了第一列和第 736 列:

    data_x = raw_data.iloc[:, 1:-4].values
    

    如果这是摆脱这两列的理想方法,您必须在 tf.FixedLenFeature 中指定 734 的大小,如下所示:

    'feature': tf.FixedLenFeature([734], dtype=tf.float32),
    

    【讨论】:

      【解决方案2】:

      在 tf2 中,您可以使用如下所示的可变形状特征:

      'feature': tf.VarLenFeature(dtype=tf.float32)
      

      【讨论】:

        猜你喜欢
        • 2020-01-20
        • 1970-01-01
        • 2019-11-27
        • 1970-01-01
        • 2020-03-09
        • 1970-01-01
        • 2022-10-18
        • 2020-11-15
        • 1970-01-01
        相关资源
        最近更新 更多