samples = tf.train.batch(read_and_decode(filename_queue, pr, input_types), batch_size=32)
在生成完TFRecords,然后在通过tf.train.batch()读取的时候遇到了以下问题:
然后我不通过tf.train.batch()来读,samples = read_and_decode(filename_queue, pr, input_types),又提示我如下问题:
tensorflow.python.framework.errors_impl.InvalidArgumentError exception str() failed
这个问题卡了我好几个小时,然后测试的时候发现,tfrecord写入时候shape(21000,),但是读取数据的shape居然翻了4倍,(84000,)。
最开始的时候代码的时候是这样子的:
写入:
snd = sound.load_sound(snd_file).normalized() # float64
samples = snd.samples[:pr.full_samples_len] # ('samples.shape:', (105000, 2))
samples = samples.reshape(samples.size, ) # 双声道转为一个声道 ('samples.shape:', (210000,))
sound_raw = samples.tostring()
# 构造一个样本的example协议块
example = tf.train.Example(features=tf.train.Features(feature={
"sound": _bytes_feature(sound_raw)
}))
#
读取:
example = tf.parse_single_example(serialized_example,
features={
'sound': tf.FixedLenFeature([], dtype=tf.string) })
samples = tf.decode_raw(example['sound'], tf.int16)
后来查资料发现,原因是写入时``samples''的type是float64,读取时类型是 int16,所以shape就不一样了。这是tfrecord读取时因tf.decode_raw的输出类型type和输入不一致,导致的最终的shape前后不一致问题
正确做法是将写入tfrecord和读取tfrecord的数据类型设为一样的,如果想使用tf.decode_raw(example['sound'], np.uint16)则在写入tfrecord时也就是在数据tobytes()的之前将数据变为uint16的类型就可以了。
所以写入时的代码,改成这样就ok了:
samples = snd.samples[:pr.full_samples_len].astype(np.int16) # ('samples.shape:', (105000, 2))
参考:
https://blog.csdn.net/qq_30638831/article/details/82682367
https://blog.csdn.net/qq_42815385/article/details/89241561