Tensorflow的一些基本用法

xiaoxiao2021-02-28  82

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

tf.add_to_collection

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

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

一般这样用:

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

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]]) #计算softmax y = tf.nn.softmax(pre) #计算交叉熵 cross_entropy = tf.reduce_mean(-tf.reduce_sum(lab*tf.log(y),reduction_indices=[1])) #一次性计算softmax and entropy loss = tf.contrib.losses.softmax_cross_entropy(pre,lab) 12345678 12345678

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

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

tf.nn.embedding_lookup

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

layers_core.Dense

import tensorflow as tf from tensorflow.python.layers import core as layers_core ones = 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)
转载请注明原文地址: https://www.6miu.com/read-45956.html

最新回复(0)