您的位置:首页 > 其它

TensorFlow 官方文档中文版解读之2——tf.sparse_to_dense的用法

2017-03-01 22:36 603 查看
原文地址:http://blog.csdn.net/mao_xiao_feng/article/details/53365889TensorFlow是一个很坑的东西,在没有session运行的时候,所有数据都看不到结果,很难去print而且TF还没有中文的API手册,很多东西很难体会在这里记录一下比较难理解的几个方法的用法,以便后面用到


tf.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value, name=None)

除去name参数用以指定该操作的name,与方法有关的一共四个参数
第一个参数sparse_indices:稀疏矩阵中那些个别元素对应的索引值。
有三种情况:
sparse_indices
是个数,那么它只能指定一维矩阵的某一个元素[/code]
sparse_indices
是个向量,那么它可以指定一维矩阵的多个元素[/code]
sparse_indices
是个矩阵,那么它可以指定二维矩阵的多个元素[/code]
第二个参数output_shape:输出的稀疏矩阵的shape
第三个参数sparse_values:个别元素的值。
分为两种情况:
sparse_values
是个数:所有索引指定的位置都用这个数
sparse_values
是个向量:输出矩阵的某一行向量里某一行对应的数(所以这里向量的长度应该和输出矩阵的行数对应,不然报错)
第四个参数default_value:未指定元素的默认值,一般如果是稀疏矩阵的话就是0了
举一个例子:
在mnist里面有一个把数字标签转化成onehot标签的操作,所谓
onehot标签
就是:
如果标签是6那么对应onehot就是[ 0.  0.  0.  0.  0.  0.  1.  0.  0.  0.]
如果标签是1那么对应onehot就是[ 0.  1.  0.  0.  0.  0.  0.  0.  0.  0.]
[/code]
如果标签是0那么对应onehot就是[ 1.  0.  0.  0.  0.  0.  0.  0.  0.  0.]
就是把标签变为适用于神经网络输出的形式。
[python] view
plain copyBATCHSIZE=6label=tf.expand_dims(tf.constant([0,2,3,6,7,9]),1)假设一个batch有6个样本,每个样本的label是0,2,3,6,7,9[python] view
plain copyindex=tf.expand_dims(tf.range(0, BATCHSIZE),1)生成一个index表明一个batch里面每个样本对应的序号(至于这里为什么要调用tf.expand_dims我在上一篇博客已经解释过了,链接:http://blog.csdn.net/mao_xiao_feng/article/details/53366163)[python] view
plain copyconcated = tf.concat(1, [index, label])最后把他们两个矩阵进行连接,连接以后的矩阵是这样的[python] view
plain copy[[0 0][1 2][2 3][3 6][4 7][5 9]][python] view
plain copyonehot_labels = tf.sparse_to_dense(concated, tf.pack([BATCHSIZE,10]), 1.0, 0.0)最后一步,调用tf.sparse_to_dense输出一个onehot标签的矩阵,输出的shape就是行数为BATCHSIZE,列数为10的矩阵,指定元素值为1.0,其余元素值为0.0程序源码:[python] view
plain copyimport tensorflow as tfimport numpyBATCHSIZE=6label=tf.expand_dims(tf.constant([0,2,3,6,7,9]),1)index=tf.expand_dims(tf.range(0, BATCHSIZE),1)#use a matrixconcated = tf.concat(1, [index, label])onehot_labels = tf.sparse_to_dense(concated, tf.pack([BATCHSIZE,10]), 1.0, 0.0)#use a vectorconcated2=tf.constant([1,3,4])#onehot_labels2 = tf.sparse_to_dense(concated2, tf.pack([BATCHSIZE,10]), 1.0, 0.0)#cant use ,because output_shape is not a vectoronehot_labels2 = tf.sparse_to_dense(concated2, tf.pack([10]), 1.0, 0.0)#can use#use a scalarconcated3=tf.constant(5)onehot_labels3 = tf.sparse_to_dense(concated3, tf.pack([10]), 1.0, 0.0)with tf.Session() as sess:result1=sess.run(onehot_labels)result2 = sess.run(onehot_labels2)result3 = sess.run(onehot_labels3)print ("This is result1:")print (result1)print ("This is result2:")print (result2)print ("This is result3:")print (result3)输出结果:[python] view
plain copy



This is result1:[[ 1. 0. 0. 0. 0. 0. 0. 0. 0. 0.][ 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.][ 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.][ 0. 0. 0. 0. 0. 0. 1. 0. 0. 0.][ 0. 0. 0. 0. 0. 0. 0. 1. 0. 0.][ 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]This is result2:[ 0. 1. 0. 1. 1. 0. 0. 0. 0. 0.]This is result3:[ 0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: