基本使用与常用函数

基本使用

1)常量、变量

#常量不可改变

a = tf.constant(10)

#变量值可以更新

b = tf.variable(tf.zeros([784,10]))

2)占位符

占位符用来接收值

#定义两个placeholder

x = tf.placeholder(tf.float32, [None,784])

y = tf.placeholder(tf.float32, [None,10])

3)构建图,feed数据,初始化全局变量

init = tf.global_variables_initializer()

with tf.Session() as sess:

    sess.run(init)

sess.run(train_step, feed_dict={x:batch_xs,y:batch_ys})

常见函数

1、tf.argmin(input, dimension, name=None) 返回input最小值的索引index

2、tf.trainable_variables和tf.all_variables的对比

tf.trainable_variables返回的是需要训练的变量列表

tf.all_variables返回的是所有变量的列表

3、tf.reduce_max、tf.sequence_mask

tf.reduce_max函数的作用:计算张量的各个维度上的元素的最大值。

tf.sequence_mask的作用是构建序列长度的mask标志

import tensorflow as tf

mask = tf.sequence_mask([1, 3, 2], 5)

with tf.Session() as sess:

    mask = sess.run(mask)

    print(mask)

>>> 

[[ True False False False False]

 [ True  True  True False False]

 [ True  True False False False]]

两个函数结合使用:

根据目标序列长度,选出其中最大值,然后使用该值构建序列长度的mask标志,代码:

import tensorflow as tf

max_value = tf.reduce_max([1, 3, 2])

mask = tf.sequence_mask([1, 3, 2], max_value)

with tf.Session() as sess:

    mask = sess.run(mask)

print(mask)

>>> 

[[ True False False]

 [ True  True  True]

 [ True  True False]]

原文地址:https://www.cnblogs.com/yongfuxue/p/10095865.html