我正在尝试使用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)。
解析tfrecords:
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.
我如何使其起作用?预先非常感谢您的帮助!
答案 0 :(得分:0)
问题是在创建数据时。您的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),
答案 1 :(得分:0)
在tf2中,您可以使用形状可变的特征,如下所示:
'feature': tf.VarLenFeature(dtype=tf.float32)