Tensorflow_v1_12_0 自己的说明文档

Tensorflow_v1_12_0 自己的说明文档

Author: Xin Pan

Date: 2020.03.06
Update: 2020.03.26



最近使用Tensorflow比较多,很多函数不是很清楚怎么使用,反复的查。这里简单记录一下。使用的环境 python==3.5.3 tensorflow-gpu=1.12.0 and numpy==1.14.6

tf.cast

tf.cast(x, DstT, Truncate=False, name=None)

它将x的类型转换成DstT,将结果返回给输出变量。

import os
import tensorflow as tf

t1 = tf.Variable(1)
t2 = tf.cast(t1, dtype=tf.float32)

print("t1: {}".format(t1))
print("t2: {}".format(t2))

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    sess.run(t2)
    print(t2.eval())

得到如下结果:

t1: <tf.Variable 'Variable:0' shape=() dtype=int32_ref>
t2: Tensor("Cast:0", shape=(), dtype=float32)
1.0 # t2

对于tensorflow中所拥有的数据类型dtype请参见DType in tensorflow

tf.concat

tf.concat(values, axis, name='concat')

在一个维度上拼接tensor。产生新的tensor。通过下边的例子:

import tensorflow as tf

t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
value_1 = tf.concat([t1, t2], 0) # [] 也可以替换成(),结果不变
value_2 = tf.concat([t1, t2], 1)

tf.shape(value_1)  # [4, 3]
tf.shape(value_2)  # [2, 6]
with tf.Session() as sess:
    print(value_1.eval(), "=value_1")
    print(value_2.eval(), "=value_2")
    print(tf.shape(value_1).eval(), tf.shape(value_2).eval())

结果如下:

[[ 1  2  3]
 [ 4  5  6]
 [ 7  8  9]
 [10 11 12]] =value_1
[[ 1  2  3  7  8  9]
 [ 4  5  6 10 11 12]] =value_2
[4 3] [2 6]

关键在于这里的axis怎么理解。从例子可以看到t1.shape=[2,3] t2.shape=[2,3],那么shape这个list可以通过index访问,如shape[0] or shape[1]。这里的axis就可以理解成index。因此axis=0表明在shape[0]上相加,由此可知value_1.shape=[4,3]。如果axis<0,就是倒数

tf.convert_to_tensor

tf.convert_to_tensor(value, dtype=None, name=None, preferred_dtype=None)

可以将给定的value转换为一个tensor类型。value可以使是 Tensor 对象,numpy arrays,Python lists,Python scalars(标量)。

返回值是一个基于value构建的tensor。例如:

import numpy as np
import tensorflow as tf


def my_func(arg):
    arg = tf.convert_to_tensor(arg, dtype=tf.float32)
    return tf.matmul(arg, arg) + arg


# The following calls are equivalent.
value_1 = my_func(tf.constant([[1.0, 2.0], [3.0, 4.0]])) # value_[1,3]是同样的意思
value_2 = my_func([[1.0, 2.0], [3.0, 4.0]])
value_3 = my_func(np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32))
value_4 = tf.convert_to_tensor(True)
value_5 = tf.convert_to_tensor(5.4)
with tf.Session() as sess:
    print(value_1.eval(), "=value_1")
    print(value_2.eval(), "=value_2")
    print(value_3.eval(), "=value_3")
    print(value_4.eval(), "=value_4")
    print(value_5.eval(), "=value_5")

下边是运行的结果:

[[ 8. 12.]
 [18. 26.]] =value_1
[[ 8. 12.]
 [18. 26.]] =value_2
[[ 8. 12.]
 [18. 26.]] =value_3
True =value_4
5.4 =value_5

tf.equal

tf.equal(x, y, name=None)

对输入的xy逐元素(element-wise)判断是否相等。xy必须有相同的维度,该函数而且还可以广播(broadcasting)。返回值是一个bool类型的tensor

请看如下示例:

import tensorflow as tf

a = tf.constant([1, 2], tf.int32)
b = tf.constant([2, 2], tf.int32)

x = tf.constant(["hehe", "haha", "hoho", "kaka"], tf.string)
y = tf.constant("hoho", tf.string)

with tf.Session() as sess:
    print(sess.run(tf.equal(a, b)))
    print(sess.run(tf.equal(x, y)))

有如下结果:

[False  True] =value1
[False False  True False] =value2

从x,y的对比中可以看出广播的作用。

tf.expand_dims

tf.expand_dims(input, axis, name=None)

在输入的input的维度索引axis处插入维度1,只是改变维度,不会增加新的值。

import tensorflow as tf
import numpy as np
sess = tf.Session()

a = tf.random_normal([2, 3, 5])
value_1 = tf.expand_dims(a, 0)
value_2 = tf.expand_dims(a, 1)
value_3 = tf.expand_dims(a, 2)
value_4 = tf.expand_dims(a, 3)
value_5 = tf.expand_dims(a, -1)

with sess:
    sess.run(tf.global_variables_initializer())
    print(a.get_shape())
    print(tf.shape(value_1))
    print(value_1.get_shape())
    print(value_2.get_shape())
    print(value_3.get_shape())
    print(value_4.get_shape())
    print(value_5.get_shape())

得到下边结果:

(2, 3, 5)
Tensor("Shape:0", shape=(4,), dtype=int32)
(1, 2, 3, 5) =value_1
(2, 1, 3, 5) =value_2
(2, 3, 1, 5) =value_3
(2, 3, 5, 1) =value_4
(2, 3, 5, 1) =value_1

tf.Graph

我们知道tensorflow的计算都是以数据流(dataflow)的形式在图(graph)上进行的操作。这个图上包含数据的添加和操作计算(op)等这些东西。当我们用多线程运算时,也许会有很多的图,但是默认图只有一个。我使用了如下例子:

import tensorflow as tf
c = tf.constant(4.0)
assert c.graph is tf.get_default_graph()  #看看主程序中新建的一个变量是不是在默认图里
g = tf.Graph()
# g = tf.get_default_graph()
with g.as_default():
    c1 = tf.constant(30.0)
    assert c1.graph is g
    assert c.graph is c1.graph

这时我们得到下边的错误

graph是否相同

我们可以看到cc1的确来自不同的graph:

c.graph
<tensorflow.python.framework.ops.Graph object at 0x000001EFF8ED1AC8>
c1.graph
<tensorflow.python.framework.ops.Graph object at 0x000001EF8E7287B8>

我们对上边的程序更改一下:

import tensorflow as tf
c = tf.constant(4.0)
assert c.graph is tf.get_default_graph()  #看看主程序中新建的一个变量是不是在默认图里
# g = tf.Graph()
g = tf.get_default_graph()
with g.as_default():
    c1 = tf.constant(30.0)
    assert c1.graph is g
    assert c.graph is c1.graph

结果如下:

c.graph
<tensorflow.python.framework.ops.Graph object at 0x000001A068E42BE0>
c1.graph
<tensorflow.python.framework.ops.Graph object at 0x000001A068E42BE0>

我们看到cc1来自同一个图了。

tf.layers.dense

tf.dense(
    inputs, units,
    activation=None,
    use_bias=True,
    kernel_initializer=None,
    bias_initializer=init_ops.zeros_initializer(),
    kernel_regularizer=None,
    bias_regularizer=None,
    activity_regularizer=None,
    kernel_constraint=None,
    bias_constraint=None,
    trainable=True,
    name=None,
    reuse=None)

相当于一个全连接层。inputs是输入,units是这层的输出维度,也就是神经元的数量。相当于outputs = activation(inputs * kernel + bias)进行了这个操作。就是全连接结算。

import tensorflow as tf
import numpy as np

a = [[0.1, 0.2, 0.3], [1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3],
     [4.1, 4.2, 4.3]]
a = tf.convert_to_tensor(a)
value_1 = tf.layers.dense(a, 8, activation=tf.nn.relu)
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(value_1))
    print(value_1.get_shape())

结果如下:

[[0.11100598 0.09830266 0.         0.         0.20589873 0.
  0.         0.        ]
 [0.69379926 0.60935396 0.         0.         1.2389872  0.
  0.         0.        ]
 [1.2765925  1.1204053  0.         0.         2.2720757  0.
  0.         0.        ]
 [1.8593858  1.6314565  0.         0.         3.305164   0.
  0.         0.        ]
 [2.4421792  2.142508   0.         0.         4.338252   0.
  0.         0.        ]] =value_1
(5, 8)

可以看到这个层是随机数初始化的,所以结果也是随机数。

tf.linalg.LinearOperatorLowerTriangluar

如函数名所示,这个函数可以产生下三角矩阵(对角线及以下元素不是0,其余位置都是0的矩阵)。但是它返回的是一个op,而不是一个tensor。即一个包含LowerTriangluar计算的op。那么我们怎么得到这个计算结果的tensor呢?使用to_dense这个函数。

to_dense(name='to_dense')

它返回一个dense(batch) matrix代表这个op。这么说可能不直观。我们往下看:

import tensorflow as tf

a = tf.range(1, 10, dtype=tf.float32)
a_re = tf.reshape(a, [3, 3])

tri1 = tf.linalg.LinearOperatorLowerTriangular(a_re)
sess = tf.InteractiveSession()
print(a_re.eval())
print(sess.run(tri1.to_dense()))

结果如下:

[[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]] =a_re
[[1. 0. 0.]
 [4. 5. 0.]
 [7. 8. 9.]] =tri1

tf.nn.embedding_lookup

tf.nn.embedding_lookup(params, ids, partition_strategy='mod', name=None, validate_indices=True, max_norm=None)

paramsids这些位置的元素查找出来。partition_strategy定义了两种表达位置的方式包含mod平均分配和div切分。例子:

import tensorflow as tf
import numpy as np

a = [[0.1, 0.2, 0.3], [1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3],
     [4.1, 4.2, 4.3]]
a = np.asarray(a)
idx1 = tf.Variable([0, 2, 3, 1], tf.int32)
idx2 = tf.Variable([[0, 2, 3, 1], [4, 0, 2, 2]], tf.int32)
out1 = tf.nn.embedding_lookup(a, idx1)
out2 = tf.nn.embedding_lookup(a, idx2)
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    print(sess.run(out1))
    print('==================')
    print(sess.run(out2))

得到结果:

[[0.1 0.2 0.3]
 [2.1 2.2 2.3]
 [3.1 3.2 3.3]
 [1.1 1.2 1.3]] =out1
==================
[[[0.1 0.2 0.3]
  [2.1 2.2 2.3]
  [3.1 3.2 3.3]
  [1.1 1.2 1.3]]

 [[4.1 4.2 4.3]
  [0.1 0.2 0.3]
  [2.1 2.2 2.3]
  [2.1 2.2 2.3]]] =out2

tf.ones_like

tf.ones_like(x, name=None)

产生和x具有相同维度和类型的全部由1组成的tensor。注意,其中的x必须是以下类型之一。bfloat16half, float32float64int8uint8int16uint16int32int64complex64complex128bool。返回值是一个和x相同类型的全1tensor

import tensorflow as tf

value_1 = tf.ones_like(4)
value_2 = tf.ones_like([3, 18, 3])
value_3 = tf.ones_like([8, 2])
value_4 = tf.ones_like(tf.random_normal([2, 2, 2]))

with tf.Session() as sess:
    print(value_1.eval(), "=value_1")
    print(value_2.eval(), "=value_2")
    print(value_3.eval(), "=value_3")
    print(value_4.eval(), "=value_4")

得到如下结果:

1 =value_1
[1 1 1] =value_2
[1 1] =value_3
[[[1. 1.]
  [1. 1.]]

 [[1. 1.]
  [1. 1.]]] =value_4

tf.range

tf.range(start, limit=None, delta=1, dtype=None, name="range")

产生一个数字序列。从start开始,直到limit但是不包含limit这个值,其中的增量值为delta。range(n) = range(0, n),因为python的range函数默认的start是0,这里也是一样的

import tensorflow as tf

value_1 = tf.range(4)
value_2 = tf.range(3, 18, 3)
value_3 = tf.range(8, 13, 2)

with tf.Session() as sess:
    print(value_1.eval(), "=value_1")
    print(value_2.eval(), "=value_2")
    print(value_3.eval(), "=value_3")

得到如下的运行结果:

[0 1 2 3] =value_1
[ 3  6  9 12 15] =value_2
[ 8 10 12] =value_3

tf.reduce_sum

tf.reduce_sum(input_tensor, axis=None, keepdims=None, name=None, reduction_indices=None, keep_dims=None)

计算一个tensor中一个方向上的所有元素之和。如果axisNone的话,那么tensor中的所有蒜素都会被计算一次。如果keepdims是真,那么每个返回的值得维度都是1。例子如下:

import tensorflow as tf

x = tf.constant([[1, 1, 1], [1, 1, 1]])

with tf.Session() as sess:
    print(tf.reduce_sum(x).eval())  # 6
    print(tf.reduce_sum(x, 0).eval())  # [2, 2, 2]
    print(tf.reduce_sum(x, 1).eval())  # [3, 3]
    print(tf.reduce_sum(x, 1, keepdims=True).eval())  # [[3], [3]]
    print(tf.reduce_sum(x, [0, 1]).eval())  # 6

结果:

6
[2 2 2]
[3 3]
[[3]
 [3]]
6

tf.Session 和 tf.InteractiveSession

InteractiveSession相比于Session的最大区别就是InteractiveSession把自己当做默认的上下文会话(Session)。tf.Tensor.eval and tf.Operation.run会使用这个Session作为默认的会话来运行ops。但是tf.Session不会把自己当做默认的会话,当我们执行eval或者ops.run这些操作时需要指定sess=Session这样的参数才可以执行。请看示例:

import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    a = tf.constant([1, 2], tf.float32, name="a")
    b = tf.constant([2.0, 3.0], name="b")
    result = tf.add(a, b, name="result")
    sess = tf.Session()
    #case 1
    with sess.as_default():
        print(result.eval())

    #case 2
    print(result.eval(session=sess))
    print(result.eval())

我们得到如下的结果:

[3. 5.] =case1
[3. 5.] =case2
Cannot evaluate tensor using eval(): No default session is registered. Use with sess.as_default() or pass an explicit session to eval(session=sess)

可以看出最后的print(result.eval())报错了,因为它不知道使用什么会话。但是用了tf.InteractiveSession就不一样了。

import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
    a = tf.constant([1, 2], tf.float32, name="a")
    b = tf.constant([2.0, 3.0], name="b")
    result = tf.add(a, b, name="result")
    # sess = tf.Session()
    # #case 1
    # with sess.as_default():
    #     print(result.eval())

    # #case 2
    # print(result.eval(session=sess))
    # print(result.eval())

    # case 3
    Sess = tf.InteractiveSession()
    print(result.eval())
    Sess.close()

结果可以直接计算出来:

[3. 5.]

tf.sign

tf.sign(x, name=None)

返回一个逐元素的数字标号tensor。什么意思

s i g n ( x ) = { − 1 , i f   x   <   0 0 , i f   x   = =   0 1 , i f   x   >   0 sign(x)= \begin{cases} -1, &if\ x\ <\ 0\\ 0, &if\ x\ ==\ 0\\ 1, &if\ x\ >\ 0 \end{cases} sign(x)=1,0,1,if x < 0if x == 0if x > 0
请看下边的示例:

import tensorflow as tf

a = tf.range(-5, 7)
b = tf.sign(a)

with tf.Session() as sess:
    print(a.eval())
    print(b.eval())

结果如下:

[-5 -4 -3 -2 -1  0  1  2  3  4  5  6] =a
[-1 -1 -1 -1 -1  0  1  1  1  1  1  1] =b

tf.split

tf.split(value, num_or_size_splits, axis=0, num=None, name='split')

将一个tensor切分成几个subtensor。将valueaxis这个维度切分成num_or_size_splits个。num_or_size_splits可以是一个整数也可以是一个list。

如下示例:

import tensorflow as tf

a = tf.range(20)
a_re = tf.reshape(a, [4, 5])

b = tf.split(a_re, 5, 1)
c = tf.split(a_re, [1, 3, 1], 1)

with tf.Session() as sess:
    print(a.eval())
    print(a_re.eval())
    print(sess.run(b))
    print(sess.run(c))

得到如下的结果:

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19] =a
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]] =a+re
[array([[ 0],       [ 5],       [10],       [15]]), 
array([[ 1],       [ 6],       [11],       [16]]),
array([[ 2],       [ 7],       [12],       [17]]), 
array([[ 3],       [ 8],       [13],       [18]]), 
array([[ 4],       [ 9],       [14],       [19]])] =b
[array([[ 0],       [ 5],       [10],       [15]]),
array([[ 1,  2,  3],       [ 6,  7,  8],       [11, 12, 13],       [16, 17, 18]]), 
array([[ 4],       [ 9],       [14],       [19]])] =c

tf.squared_difference

tf.squared_difference(x, y, name=None)

这个函数计算x与y张量中逐元素的平方差(x-y)(x-y)并将结果返回。其中的x与y是输入的两个张量。它们的类型必须是如下之一:bfloat16, half, float32, float64, int32, int64, complex64, complex128。请看下边示例:

import os
import tensorflow as tf

t1 = tf.Variable([1, 2, 3, 4, 5])
t2 = tf.Variable([1, 2, 3, 4, 5])
loss = tf.squared_difference(t1, t2)
sess = tf.InteractiveSession()
t3 = tf.Variable([2, 3, 4, 5, 6])
loss2 = tf.squared_difference(t1, t3)
loss3 = tf.squared_difference(t1, 3)

sess.run(tf.global_variables_initializer())
print(loss.eval())
print(t3.eval())
print(loss2.eval())
print(loss3.eval())

结果如下:

[0 0 0 0 0] # loss
[2 3 4 5 6] # t3
[1 1 1 1 1] # loss2
[4 1 0 1 4] # loss3

tf.tile

tf.tile(input, multiples, name=None)

这个函数将input复制multiples次。但是shape的rank是不变的。这里说的复制就是[a,b,c]*2->[a,b,c,a,b,c]这种复制。请看示例:

import tensorflow as tf
import numpy as np
sess = tf.Session()

a = np.array([[1, 0, -1], [0, 1, 1]])
value_1 = tf.tile(a, [2, 0])
value_2 = tf.tile(a, [2, 1])
value_3 = tf.tile(a, [2, 3])

with sess:
    print(value_1.eval())
    print(value_2.eval())
    print(value_3.eval())

得到如下结果:

[] =value_1
[[ 1  0 -1]
 [ 0  1  1]
 [ 1  0 -1]
 [ 0  1  1]] =value_2
[[ 1  0 -1  1  0 -1  1  0 -1]
 [ 0  1  1  0  1  1  0  1  1]
 [ 1  0 -1  1  0 -1  1  0 -1]
 [ 0  1  1  0  1  1  0  1  1]] =value_3

tf.train.slice_input_producer

tf.slice_input_producer(tensor_list, num_epochs=None, shuffle=True, seed=None, capacity=32, shared_name=None, name=None):

产生tensor_list中的每个tensor所组成的切片(slice)。这个函数一般用于处理输入数据用。借用参考博文大佬写的例子,并更改了一个函数:

import tensorflow as tf
import numpy as np

# 样本个数
sample_num = 5
epoch_num = 2
# 设置一个批次中包含样本个数
batch_size = 3
# 计算每一轮epoch中含有的batch个数
batch_total = int(sample_num / batch_size) + 1


# 生成4个数据和标签
def generate_data(sample_num=sample_num):
    labels = np.asarray(range(0, sample_num))
    images = np.random.random([sample_num, 224, 224, 3])
    print('image size {},label size :{}'.format(images.shape, labels.shape))

    return images, labels


def get_batch_data(batch_size=batch_size):
    images, label = generate_data()
    # 数据类型转换为tf.float32
    images = tf.cast(images, tf.float32)
    label = tf.cast(label, tf.int32)

    #从tensor列表中按顺序或随机抽取一个tensor
    input_queue = tf.train.slice_input_producer([images, label], shuffle=False)

    image_batch, label_batch = tf.train.shuffle_batch(
        input_queue,
        batch_size=batch_size,
        min_after_dequeue=batch_size * 2,
        num_threads=1,
        capacity=64)
    return image_batch, label_batch


image_batch, label_batch = get_batch_data(batch_size=batch_size)

with tf.Session() as sess:
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess, coord)
    try:
        for i in range(epoch_num):  # 每一轮迭代
            print('************')
            for j in range(batch_total):  #每一个batch
                print('--------')
                # 获取每一个batch中batch_size个样本和标签
                image_batch_v, label_batch_v = sess.run(
                    [image_batch, label_batch])
                # for k in
                print(image_batch_v.shape, label_batch_v)
    except tf.errors.OutOfRangeError:
        print("done")
    finally:
        coord.request_stop()
    coord.join(threads)

结果如下:

************
--------
(3, 224, 224, 3) [1 4 0]
--------
(3, 224, 224, 3) [2 3 4]
************
--------
(3, 224, 224, 3) [3 2 1]
--------
(3, 224, 224, 3) [1 0 2]

tf.train.Supervisor

def __init__(self,
               graph=None,
               ready_op=USE_DEFAULT,
               ready_for_local_init_op=USE_DEFAULT,
               is_chief=True,
               init_op=USE_DEFAULT,
               init_feed_dict=None,
               local_init_op=USE_DEFAULT,
               logdir=None,
               summary_op=USE_DEFAULT,
               saver=USE_DEFAULT,
               global_step=USE_DEFAULT,
               save_summaries_secs=120,
               save_model_secs=600,
               recovery_wait_secs=30,
               stop_grace_secs=120,
               checkpoint_basename="model.ckpt",
               session_manager=None,
               summary_writer=USE_DEFAULT,
               init_fn=None,
               local_init_run_options=None):

这是这个类的__init__函数。tf.train.Supervisor是一个类。他可以帮助我们在训练中检查检查点模型,并且计算图表这些操作。

在我们用这个类之前我们的结构大概是这样的:

saver = tf.train.Saver()
init = tf.global_variables_initializer()

# Launch the graph.
sess = tf.Session()
sess.run(init)
merged_summary_op = tf.merge_all_summaries()
writer = tf.tf.train.SummaryWriter()

if len(os.listdir(log_path)) != 0:  # 已经有模型直接读取
    saver.restore(sess, os.path.join(log_path, log_name))
for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(W), sess.run(b))
        merged_summary = sess.run(merge_all_summarie)
        writer.add_summary(merged_summary,i)
saver.save(sess, os.path.join(log_path, log_name))

现在我们可以这么写:

init = tf.global_variables_initializer()

merged_summary_op = tf.merge_all_summaries()
sv = tf.train.Supervisor(logdir=log_path, init_op=init)  # logdir用来保存checkpoint和summary
saver = sv.saver  # 创建saver
with sv.managed_session() as sess:  # 会自动去logdir中去找checkpoint,如果没有的话,自动执行初始化
    for i in range(201):
        sess.run(train)
        if i % 20 == 0:
            print(i, sess.run(W), sess.run(b))
            merged_summary = sess.run(merged_summary_op)
            sv.summary_computed(sess, merged_summary,global_step=i)
    saver.save(sess, os.path.join(log_path, log_name))

这里引用参考博文里的一个结论:

tf.train.Supervisor().managed_session()

Supervisor() 帮助我们处理一些事情:
(a) 自动去 checkpoint 加载数据或者初始化数据

(b) 自动有一个 Saver ,可以用来保存 checkpoint,eg: sv.saver.save(sess, save_path)

© 有一个 summary_computed 用来保存 Summary

因此我们可以省略了以下内容:

(a)手动初始化或者从 checkpoint 中加载数据

(b)不需要创建 Saver 类, 使用 sv 内部的就可以

©不需要创建 Summary_Writer()

tf.where

tf.where(condition, name=None)
tf.where(condition, x=None, y=None, name=None)

这个函数有两种形式。第一行中,where将condition中为True的值所在的位置显式出来。第二行中,where将condition中为True的值所在的位置用x替换,为假的部分用y替换。例子如下:

import tensorflow as tf
import numpy as np
sess = tf.Session()

a = np.array([[1, 0, -1], [0, 1, 1]])
a1 = np.array([[3, 2, 3], [4, 5, 6]])
value_1 = tf.where(a)

with sess:
    print(sess.run(tf.equal(a, 1)))
    print(value_1.eval())
    print(sess.run(tf.where(tf.equal(a, 1), a1, 1 - a1)))

结果如下:

[[ True False False]
 [False  True  True]]
[[0 0]
 [0 2]
 [1 1]
 [1 2]] =value_1
[[ 3 -1 -2]
 [-3  5  6]]

Reference

  1. tf.cast一个博文
  2. DType in tensorflow
  3. tf.concat一个博文
  4. tf.equal一个写的详细的博文
  5. tf.convert_to_tensor官网doc
  6. tf.Graph博文1
  7. tf.Graph博文2
  8. tf.linalg.LinearOperatorLowerTriangluar官方doc
  9. tf.linalg.LinearOperatorLowerTriangluar一个博文
  10. tf.nn.embedding_lookup一个不错的博文
  11. tf.nn.embedding_lookup官方doc
  12. tf.split官网doc
  13. tf.split一个博文
  14. tf.tile一个博文
  15. tf.tile官方doc
  16. tf.train.slice_input_prodicer一个写的挺好的博文
  17. tf.train.Supervisor一个博文
  18. tf.where一个博文

Appendix

DType in tensorflow

Tensorflow 中的DType定义了如下的类型:

除此之外,变量的类型以_ref结尾表明它们是引用类型的张量(with the _ref suffix are defined for reference-typed tensors.)

tf.as_dtype() 函数可以将numpy类型和string类型的名字转换为DType对象。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值