仅在 TF 中解包 [英] Unpackbits only in TF

查看:22
本文介绍了仅在 TF 中解包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 TF 中解压缩位的方法,就像我可以使用 np.unpackbits.所以恢复操作,如:

I am looking for a way to unpack bits in TF in the same way I can do this with np.unpackbits. So revert the operation like:

import numpy as np
import tensorflow as tf
original = np.random.choice(a=[1, 0], size=(100))
data     = np.packbits(original.astype(np.bool), axis=None)

X = tf.constant(data)

假设我只能访问 X,如何在 TF 中将其转换为原始文件.当然我可以使用 numpy,但这会将数据从 TF 移动到 python,然后再返回到 TF.

Assuming I have access only to X, how to convert it to original in TF. Of course I can use numpy, but this will move data from TF to python and then back to TF.

我的一些想法(还没有实现):

Few thoughts I had in mind (have not implemented any of them):

  1. 使用 tf.map_fn
  2. 使用 tf.contrib.lookup

他们俩的想法是将每个数字映射到一个向量,连接所有向量,重塑,删除不需要的元素.

For both of them the ideas is to map each number to a vector, concat all the vectors, reshape, remove unneeded elements.

这两种方法似乎都比它们应有的复杂.有没有人有一种有效的方法(就速度而言)如何在 tensorflow 中实现 numpy 的解包?

Both of the approaches seems more complicated that they should be. Does anyone has an efficient way (in terms of speed) how to achieve numpy's unpackbits in tensorflow?

推荐答案

也许是这样的:

import tensorflow as tf

x = tf.constant((1, 2, 7, 0, 255), dtype=tf.uint8)

b = tf.constant((128, 64, 32, 16, 8, 4, 2, 1), dtype=tf.uint8)
unpacked = tf.reshape(tf.mod(tf.to_int32(x[:,None] // b), 2), [-1])

unpacked 位于 int32 中,因为 tf.mod 不接受字节,您可能希望将其转换为 uint8再次.

unpacked is in int32 due to tf.mod not accepting bytes, you may want to cast it to uint8 again.

Tensorflow 1.3 将有按位运算,所以最后一行可以替换为

Tensorflow 1.3 will have bitwise operations, so this last line could be replaced with

unpacked = tf.reshape(tf.bitwise.bitwise_and(x, b), [-1])

希望会更快(结果在 uint8 中).

which will hopefully be faster (and the result in uint8).

这篇关于仅在 TF 中解包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆