用python实现one-hot编码

使用TensorFlow的tf.one_hot()可能会导致内存泄漏和模型运行变慢。为解决此问题,可以自定义one_hot函数,如示例中所示,通过numpy实现。这有助于控制模型的资源消耗。
摘要由CSDN通过智能技术生成
失败不可怕,怕的是偶然的成功。码代码跑实验谈恋爱找工作莫不如此。
之前用TensorFlow 跑了I3D的模型,很顺利。Loss完美下降,视频数据读入也没遇到大问题。 偶然的成功,让我以为tensorflow So-easy嘛。
现在自己想做点东西,才发现有些坑你没遇到是因为你做的太少太简单Too young, Too simple.

tensorflow 封装的函数tf.one_hot():
import tensorflow as tf
import numpy as np
z=np.random.randint(0,10,size=[10])
y=tf.one_hot(z,10,on_value=1,off_value=None,axis=0)
with tf.Session()as sess:
    print(z)
    print(sess.run(y))
[5 7 7 0 5 5 2 0 0 0]
[[0 0 0 1 0 0 0 1 1 1]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 1 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [1 0 0 0 1 1 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 1 1 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 0 0]]
瞅上去很完美,但是,tf.one_hot()会让你的graph动态增添节点,可能导致的后果就是内存泄露,模型越来越慢.....

所以当你发现模型占用内存越来越大,然后执行以下操作tf.get_default_graph().finalize()  报错的时候
就应该考虑自己实现one-hot()功能了。

def one_hot ( labels , Label_class ):
one_hot_label = np.array([[ int (i == int (labels[j])) for i in range (Label_class)] for j in range ( len (labels))])
return one_hot_label

举例:
import numpy as np
def one_hot(labels,Label_class):
    one_hot_label = np.array([[int(i == int(labels[j])) for i in range(Label_class)] for j in range(len(labels))])   
    return one_hot_label

y = [2,5,6,7,8]
Label_class = 20
print one_hot(y,Label_class)
[[0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0]
 [0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0]]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值