Tensorflow的一些基本用法

来源:互联网 发布:儿童 编程网站 编辑:程序博客网 时间:2024/05/04 13:45

在使用TensorFlow中会遇到一些其基本的用法,再次作为记录备忘!

tf.add_to_collection

在计算整体的loss是会将不同部分的loss放入一个集合中,最后计算整体的loss,因此会用到tf.add_to_collection,具体参考TensorFlow中的cifar10的例子,用法如下所示:

tf.add_to_collection:把变量放入一个集合,把很多变量变成一个列表tf.get_collection:从一个结合中取出全部变量,是一个列表tf.add_n:把一个列表的东西都依次加起来

一般这样用:

tf.add_n(tf.get_collection("losses"),name='name')其中losses是一个集合

softmax

关于TensorFlow中softmax和entropy的计算:

pre = tf.Variable([[10.0,0.0,0.0],[0.0,10.0,0.0],[0.0,0.0,10.0]])lab =tf.Variable([[1.0,0.0,0.0],[0.0,1.0,0.0],[0.0,0.0,1.0]])#计算softmaxy = tf.nn.softmax(pre)#计算交叉熵cross_entropy = tf.reduce_mean(-tf.reduce_sum(lab*tf.log(y),reduction_indices=[1]))#一次性计算softmax and entropyloss = tf.contrib.losses.softmax_cross_entropy(pre,lab)

大部分应用中标识的分布都会比较稀疏,可以使用下面方式提高效率:

tf.contib.losses.sparse_softmax_cross_entropy(logits,labels)

tf.nn.embedding_lookup

http://blog.csdn.net/john_xyz/article/details/60882535

layers_core.Dense

import tensorflow as tffrom tensorflow.python.layers import core as layers_coreones = tf.Variable([[1.0,2],[3,4]])output_layer = layers_core.Dense(5)logits = output_layer(ones)with tf.Session() as sess:    sess.run(tf.global_variables_initializer())    print sess.run(ones)    print sess.run(logits)