Tensorflow: 基础函数

import tensorflow as tf

这里会记录Tensorflow包中一些常用的模块, 以及相关的函数方法. 使用Ctrl+F查找函数名或关键字.

  • tf.app.run()
'''
作用: 一般用来启动主函数, 将模型逻辑定义在脚本中的main()函数中, 调用这个方法启动main()函数.
参数:
    main: 指定的运行函数, 默认为启动的py脚本的main()函数;
    argv: 向main函数中传递的参数.
'''
def main():
    pass
if __name__ == "__main__":
    tf.app.run()
  • tf.assign()
'''
作用: 为变量指定一个新的值
参数:
    ref: Tensor, 要更改的Tensor, 来自变量Variable
    value: Tensor, 新值;
    validate_shape: bool, True则value的shape必须与ref相同, False, ref的大小将会转换为value的shape;
    use_locking: bool, True则在线程中对assign操作使用locking;
    name: op的名称
输出: op, 更新的操作
'''
a = tf.get_variable("a", shape=[5])
b = tf.Variable(1.0, name="b")
c = tf.add(a, b, name="c")
as_op = tf.assign(a, c)
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print("a原值:", a.eval())
    result, _ = sess.run([c, as_op])
    print("add操作的结果:", result)
    print("a更新后的值:", a.eval())
'''
结果:
a原值: [ 0.7083354  -0.5660187   0.68339312 -0.22521102 -0.24268919]
add操作的结果: [ 1.7083354   0.4339813   1.68339312  0.77478898  0.75731081]
a更新后的值: [ 1.7083354   0.4339813   1.68339312  0.77478898  0.75731081]
'''
  • tf.ConfigProto()
'''
作用: tensorflow中传递参数(特别是在创建tf.Session时, 给config参数传递)的量
参数:
    log_device_placement: bool, True表示记录op和tensor被指派到哪个设备上执行;
    allow_soft_placement: bool, True时, 当指定运行的设备不存在时, 不会报错, tensorFlow会自动选择一个存在并且支持的设备来运行 operation.
返回: ConfigProto对象
'''
with tf.device('/cpu:0'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print("result:\n", sess.run(c))
'''
结果: (除了返回执行产生的结果外, 还会有执行设备的信息)
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GTX 1060, pci bus id: 0000:01:00.0
MatMul: (MatMul): /job:localhost/replica:0/task:0/gpu:0
b: (Const): /job:localhost/replica:0/task:0/gpu:0
a: (Const): /job:localhost/replica:0/task:0/cpu:0
result:
 [[ 22.  28.]
 [ 49.  64.]]
'''
# 当使用不存在的设备时会报错
with tf.device('/gpu:1'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))
print("result:\n", sess.run(c))
'''
结果: (报错)
InvalidArgumentError (see above for traceback): Cannot assign a device to node 'a': Could not satisfy explicit device specification '/device:GPU:1' because no devices matching that specification are registered in this process; available devices: /job:localhost/replica:0/task:0/cpu:0, /job:localhost/replica:0/task:0/gpu:0
     [[Node: a = Const[dtype=DT_FLOAT, value=Tensor<type: float shape: [2,3] values: [1 2 3]...>, _device="/device:GPU:1"]()]]
'''
# 设置allow_soft_placement为True
with tf.device('/gpu:1'):
    a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a')
b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')
c = tf.matmul(a, b)
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True))
print("result:\n", sess.run(c))
'''
结果:
Device mapping:
/job:localhost/replica:0/task:0/gpu:0 -> device: 0, name: GeForce GTX 1060, pci bus id: 0000:01:00.0
MatMul: (MatMul): /job:localhost/replica:0/task:0/gpu:0
b: (Const): /job:localhost/replica:0/task:0/gpu:0
a: (Const): /job:localhost/replica:0/task:0/gpu:0
result:
 [[ 22.  28.]
 [ 49.  64.]]
'''
  • tf.constant()
'''
作用: 创建一个常量Tensor
变量: 
    value: (must)常量的值, 可以为标量, 也可以是list;
    dtype: 元素的值类型;
    shepe: tensor的大小, 如果value输入一个标量值, shape给出各维的大小, 则用value填充tensor中的每一个位置;
    name: Tensor的名称;
    verify_shape: ;
返回: Tensor
'''
with tf.Session():
    a = tf.constant(1.0).eval()
    b = tf.constant([[1,2],[3,4]]).eval()
    c = tf.constant(1, dtype=tf.float32, shape=[3,3,3]).eval()
    d = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a').eval()
    print("a:", a)
    print("b:\n", b)
    print("c:\n", c)
    print("d:\n", d)
'''
结果:
a: 1.0
b:
 [[1 2]
 [3 4]]
c:
 [[[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]

 [[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]

 [[ 1.  1.  1.]
  [ 1.  1.  1.]
  [ 1.  1.  1.]]]
d:
 [[ 1.  2.  3.]
 [ 4.  5.  6.]]
'''
  • tf.get_default_graph()
'''
作用: 获取当前的图Graph
返回值: Graph对象
'''
with tf.Graph().as_default():
    g = tf.get_default_graph()
    print(g)
'''
结果: <tensorflow.python.framework.ops.Graph object at 0x0000028B8EF6B3C8>
'''
  • tf.get_default_session()
'''
作用: 获取当前的会话Session
返回值: Session对象
'''
with tf.Session():
    sess = tf.get_default_session()
    print(sess)
'''
结果: <tensorflow.python.client.session.Session object at 0x00000261E707B5C0>
'''
  • tf.get_variable()
'''
作用: 根据名称获取变量Variable, 如果没有则创建一个新的Variable
参数:
    name: 变量名称;
    shape: 变量大小;
    dtype: 变量中元素类型;
    initializer: 初始化方法;
    regularizer: ;
    trainable: bool, True则把此变量添加到GraphKeys.TRAINABLE_VARIABLES(全局图的可训练变量中), 在Optimizer进行操作时, 会对这些变量进行更新. False则不会添加到GraphKeys.TRAINABLE_VARIABLES这个图和相应集合之中;
    collections: graph的collection的列表, 此变量将会添加到这个graph collection中, 默认为GraphKeys.GLOBAL_VARIABLES;
    caching_device: device string, 此变量cache的位置, 注意, 这同该变量在哪个设备中创建不同;
    partitioner: ;
    validate_shape: bool, True: 变量在初始化时(initializer的设置)必须指定大小, False时则可以不指定shape大小;
    use_resource: ;
    custom_getter: ;
输出: 变量Variable, 创建一个新的Variable, 或已经存在的由本方法tf.get_variable()创建的变量
'''
a = tf.get_variable("a", shape=[2,2])
b = tf.Variable(1, name="b")
print(a, type(a))
print(b, type(b))
结果:
'''
<tf.Variable 'a:0' shape=(2, 2) dtype=float32_ref> <class 'tensorflow.python.ops.variables.Variable'>
<tf.Variable 'b:0' shape=() dtype=int32_ref> <class 'tensorflow.python.ops.variables.Variable'>
'''
with tf.variable_scope("test", reuse=None):
    a = tf.get_variable("a", shape=[2,2])
    b = tf.Variable(1, name="b")
with tf.variable_scope("test", reuse=True):
    c = tf.get_variable("a")
    print(c)
    d = tf.get_variable("b")
    print(d)
'''
结果:
<tf.Variable 'test/a:0' shape=(2, 2) dtype=float32_ref>
ValueError: Variable test/b does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?
由此可见, 使用tf.get_variable()获取已有变量时, 只能获取tf.get_variable()方法创建的, 不能获取由tf.Variable()直接创建的变量Variable对象.
'''
  • tf.global_variables()
'''
作用: 获取全局变量, 即GraphKeys.GLOBAL_VARIABLES中的变量, tf.get_variable()与tf.Variable()创建的未指定collection的变量会自动的添加到其中.
输出: list, 元素为各个全局变量
'''
with tf.variable_scope("test", reuse=None):
    a = tf.get_variable("a", shape=[2, 2])
    b = tf.Variable(1, name="b")
with tf.variable_scope("test2", reuse=None):
    c = tf.get_variable("c", shape=[2, 2])
    d = tf.get_variable("d", trainable=False, shape=[2, 2])
    e = tf.get_variable("e", shape=[2, 2], collections=["test2"])
var_list = tf.global_variables()
print(len(var_list))
print(var_list)
'''
结果:
4
[<tf.Variable 'test/a:0' shape=(2, 2) dtype=float32_ref>, <tf.Variable 'test/b:0' shape=() dtype=int32_ref>, <tf.Variable 'test2/c:0' shape=(2, 2) dtype=float32_ref>, <tf.Variable 'test2/d:0' shape=(2, 2) dtype=float32_ref>]
可见变量'e'因为指定了collections, 因此没有被添加到全局变量中
'''
  • tf.global_variables_initializer()
'''
作用: 对全局变量, 即GraphKeys.GLOBAL_VARIABLES中的变量进行初始化
输出: op, 对全局所有变量进行初始化的op
'''
a = tf.get_variable("a", shape=[5])
b = tf.get_variable("b", shape=[3])
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    print(a.eval())
    print(b.eval())
'''
结果:
[-0.3238093  -0.17979407  0.6277442   0.6556567  -0.74592763]
[ 0.02501893 -0.18490672  0.38854003]
'''
  • tf.name_scope()
  • tf.variable_scope()
'''
作用: 
    name_scope: 返回一个上下文管理器, 为图中的Op创建层级的名称;
    variable_scope: 返回一个上下文管理器, 为Op以及tf.get_variable()方法得到的变量Variable创建层级名称
参数:
    name: 该层scope的名称
注意:
    1. name_scope只给Op(操作)加前缀(tf.Variable也是操作), 不会给通过tf.get_variable()获取的Variable加前缀(没有Op产生这个变量, 或者产生这个变量的Op不受管理?)
    2. variable_scope即给通过tf.get_variable()获取的Variable加前缀, 也给Op加前缀.
'''
with tf.Graph().as_default():
    a = tf.constant(1.0, name="a")
    with tf.name_scope("level1_a"):
        b = tf.constant([1.1, 1.2], name="b")
        c = tf.Variable(0, name="c")
        with tf.name_scope("level2_a"):
            d = tf.get_variable(shape=[3, 3, 3], name="d")
            e = tf.nn.relu(b, name="e")
        with tf.variable_scope("level2_b"):
            f = tf.zeros(shape=[3, 3], dtype=tf.float32, name="f")
            g = tf.get_variable(shape=[1, 1], name="g")
            h = tf.Variable(0, name="h")
    with tf.variable_scope("level1_b"):
        i = tf.get_variable("i", shape=[1])
        j = tf.nn.l2_loss(i, name="j")

print(a.op.name)
print(b.op.name)
print(c.op.name)
print(d.op.name)
print(e.op.name)
print(f.op.name)
print(g.op.name)
print(h.op.name)
print(i.op.name)
print(j.op.name)
'''
结果:
a
level1_a/b
level1_a/c
d
level1_a/level2_a/e
level1_a/level2_b/f
level2_b/g
level1_a/level2_b/h
level1_b/i
level1_b/j
'''
  • tf.Session()
'''
作用: 创建一个会话Session
参数: 
    target: (不明)连接的执行引擎, 用于分布式Tensorflow;
    graph: 绑定在此Session上的Graph, 为None则绑定默认的图;
    config: 值为tf.ConfigProto, 多在设置使用哪些设备时, 设置该Session的配置(显示内容, 跳过不存在的设备等);
返回: Session, 即创建的此Session
'''
with tf.Session() as sess:
    print("sess:" ,sess)
    print(sess.run(tf.constant(1)))
'''
结果:
sess: <tensorflow.python.client.session.Session object at 0x000002FB2569BE48>
1
'''
'''
关于config属性的使用一例: 查阅tf.ConfigProto()
'''
  • tf.placeholder()
'''
作用: 占位符, 一般用在不知道这里将会是什么值, 先占住位置来后续构建图, 在session的run时, 通过feed方法将真正的值输入.
参数:
    dtype: (must)数据类型;
    shape: tensor的大小, 可以不指定, 可以传入任意形状的数据;
    name: 此op的名称
输出: Tensor, 用来接收数据的Tensor
'''
a = tf.get_variable("a", shape=[5])
b = tf.placeholder(tf.float32, name="b")
c = tf.add(a, b, name="c")
init_op = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init_op)
    result = sess.run(c, feed_dict={b: 10.32})
    print(result)
'''
结果: (这里占位符最后传入一个浮点标量)
[  9.65142155  10.37230587  10.75956821  10.57368183  11.05453682]
'''
  • tf.variables_initializer()
'''
作用: 创建一个对变量(或若干变量)进行初始化的op(操作), 将变量列表作为这个op的数据, 然后之后run这个op, 就能对这些变量按照各自的初始化方法进行初始化.
参数:
    var_list: (must)list, 变量列表, 需要被这个op初始化的变量列表;
    name: 此op的名称
输出: op, 用来初始化变量的op
'''
# 使用默认的初始化方法(我也不知道是啥方法)对变量进行初始化
a = tf.get_variable("a", shape=[5])
init_op = tf.variables_initializer([a])
with tf.Session() as sess:
    sess.run(init_op)
    print(a.eval())
'''
结果:
[ 0.22596931 -0.56050253  0.55380261 -0.26351404 -0.50784725]
'''
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值