如何在TensorFlow或Numpy中将整数数组转换为二进制编码? [英] How to convert array of Integers to binary encoding in TensorFlow or Numpy?

查看:648
本文介绍了如何在TensorFlow或Numpy中将整数数组转换为二进制编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字输入,范围为[0, 15],我想将其作为4位二进制代码馈入我的网络.例如,输入[0,1,4,7]应该变为[[0,0,0,0],[0,0,0,1],[0,1,0,0],[0,1,1,1]].

I have an input of numbers, ranging on [0, 15], which I want to feed to my network as a binary code with 4 bits. For example, the input [0,1,4,7] should become [[0,0,0,0],[0,0,0,1],[0,1,0,0],[0,1,1,1]].

tf.one_hot操作已关闭,但不完全是我想要的.是否可以通过Numpy或TensorFlow用任何优雅的方式将我的输入转换为二进制编码,以便将其输入到我的网络中?

The tf.one_hot operation is close, but not exactly what I want. Is there any elegant way, either with Numpy or TensorFlow, to convert my input into its binary encoding, in order to feed it into my network?

我最好的解决方案是对每个值使用np.binary_repr,然后将其从string转换为integers的数组,但是我觉得这不是一个好解决方案(先转换两次,然后转换为字符串,然后转换为字符串)进入数组).

My best solution was to use np.binary_repr for each value, and convert it from a string into an array of integers, but I feel this is not a good solution (converting twice, first into string, then into array).

推荐答案

类似以下内容:

np.unpackbits(np.array([[0,1,4,7]],np.uint8)).reshape(-1,4)[1::2,:]

我确定它可以完善,但至少是矢量化的

I'm sure it can be refined but at least it's vectorized

或者这可能更有意义:

np.unpackbits(np.array([[0,1,4,7]],np.uint8)).reshape(-1,8)[:,4:]

这篇关于如何在TensorFlow或Numpy中将整数数组转换为二进制编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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