Tensorflow的一些基本用法

Posted yqtaowhu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Tensorflow的一些基本用法相关的知识,希望对你有一定的参考价值。

在使用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]])
#计算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)

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

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 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)

以上是关于Tensorflow的一些基本用法的主要内容,如果未能解决你的问题,请参考以下文章

第一节,基本用法

TensorFlow 学习小结 - 基本用法

Tensorflow 2.0—— 跟着官方demo学习Tensorflow 2.0框架基本API和用法

HCIA-AI_深度学习_TensorFlow2模块tf.keras基本用法

HCIA-AI_深度学习_TensorFlow2模块tf.keras基本用法

HCIA-AI_深度学习_TensorFlow2模块tf.keras基本用法