Tensorflow:tf-record处理矩阵或张量数据方法及注意事项

    写这个博客的关键Bug: Input to reshape is a tensor with xxx values, but the requested shape has xxx。本文的先验知识为:tensorflow中tfrecord的创建和导入。

 

问题引入

    tensorflow feature类型只接受list数据,但如果数据类型是矩阵或者张量该如何处理?

    比如我们当前的任务是:目标检测,那就需要我们在tf-record中记录每张图片对应的bounding box的信息。一个bounding box的形状为(1, 4),本身就是list数据,可直接使用。但是一张图片可能对应多个bouning box, 所以形状应该为(?, 4),这是个变长,那么该如何保存呢?假设我们要保存的bouning box如下:

bbox= np.array([[10, 20, 30 ,40],
                [10, 20, 20, 20]])

方案一

  • 转换成list类型,再用list的方式写入
  • 记录形状信息
# 写入矩阵,类型float,将矩阵转化为list,并记录形状信息
features['bbox'] = tf.train.Feature(float_list=tf.train.FloatList(value=bbox.reshape(-1)))
features['bbox_shape'] = tf.train.Feature(int64_list=tf.train.Int64List(value=bbox.shape))

    将bbox保存到tfrecord中后,同样需要解析出来,代码如下:

dics = {'bbox': tf.VarLenFeature(dtype=tf.float32),
        'bbox_shape': tf.FixedLenFeature(shape=(2,), dtype=tf.int64)}

parsed_example = tf.parse_single_example(example_proto, dics)

# 使用VarLen解析bbox,得到的是稀疏tensor,需要转换
parsed_example['bbox'] = tf.sparse_tensor_to_dense(parsed_example['bbox'])
# 根据存储的shape还原形状
parsed_example['bbox'] = tf.reshape(parsed_example['bbox'], parsed_example['bbox_shape'])

    在方案一中,我们并没有遇到文章开始就提示的BUG。

 

方案二

  • 使用.tostring()将张量转换成string类型
  • 记录形状信息,方便恢复
# 将bbox转化为字符类型存储,随后转化为原类型
features['bbox'] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[bbox.tostring()]))
features['bbox_shape'] = tf.train.Feature(int64_list=tf.train.Int64List(value=bbox.shape))

    同样,我们需要解析出来

disc = {'bbox': tf.FixedLenFeature(shape=(), dtype=tf.string),
        'bbox_shape': tf.FixedLenFeature(shape=(2,), dtype=tf.int64)}

parsed_example = tf.parse_single_example(example_proto, dics)

# string类型需要tf.decode_raw(parsed_feature, type)解码,这里的type强烈关注
parsed_example['bbox'] = tf.decode_raw(parsed_example['bbox'], tf.uint16)
# 还原形状
parsed_example['bbox'] = tf.reshape(parsed_example['bbox'], parsed_example['bbox_shape'])

注:需要保证数据格式与解析格式的一致.

如果原数据是由 tf.float32 类型再进行 to_bytes 写入,则tf.decode_raw解码时则也需要使用 tf.float32 数据类型.

如果不一致,会出现 Input to reshape is a tensor with xxx values, but the requested shape has xxx 的类似错误。而我这里的bbox是tf.uint16类型写入的,所以解析的时候需要使用tf.uint16。

 

总结

    本片博客,我们通过一个Bug引入问题,并详细解释了Bug的来源及处理方法,希望对大家有所帮助。若是大家依旧遇到类似的问题,可以留言,定期回复!

备注:本文为作者原创,转载需注明出处!

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值