• Tensorflow中的会话、张量、变量


    1.会话

    1.1 定义

    一个运行TensorFlow operation的类。会话包含以下两种开启方式

    • tf.Session:用于完整的程序当中
    • tf.InteractiveSession:用于交互式上下文中的TensorFlow ,例如shell

    1 TensorFlow 使用 tf.Session 类来表示客户端程序(通常为 Python 程序,但也提供了使用其他语言的类似接口)与 C++ 运行时之间的连接

    2 tf.Session 对象使用分布式 TensorFlow 运行时提供对本地计算机中的设备和远程设备的访问权限。

    1.2 _init_(target=‘’, graph=None, config=None)

    	会话可能拥有的资源,如 tf.Variable,tf.QueueBase和tf.ReaderBase。当这些资源不再需要时,释放这些资源非常重要。因此,需要调用tf.Session.close会话中的方法,或将会话用作上下文管理器。
    
    • 1
    def session_demo():
        """
        会话演示
        :return:
        """
        a_t = tf.constant(10)
        b_t = tf.constant(20)
    
        c_t = tf.add(a_t, b_t)
        print("tensorflow实现加法运算:", c_t)
        # tensorflow实现加法运算: Tensor("Add:0", shape=(), dtype=int32)
        
        # 开启会话
        with tf.Session() as sess:
            print(sess.run([a_t, b_t]))
            # 获取张量值的方法
            # eval() 函数用来执行一个字符串表达式,并返回表达式的值。
            print("在sess当中的sum_t:", c_t.eval())
            # 获取张量图的属性
            print("会话的图属性:", sess.graph)
        return None
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    _init_()参数详解:

    • target:如果将此参数留空(默认设置),会话将仅使用本地计算机中的设备。 可以指定 grpc:// 网址,以便指定 TensorFlow 服务器的地址,这使得会话可以访问该服务器控制的计算机上的所有设备。
    • graph:默认情况下,新的 tf.Session 将绑定到当前的默认图。
    • config:此参数允许您指定一个 tf.ConfigProto 以便控制会话的行为。例如,ConfigProto协议用于打印设备使用信息
    # 运行会话并打印设备信息
    sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                            log_device_placement=True))
    # /job:localhost/replica:0/task:0/device:XLA_CPU:0 -> device: XLA_CPU device
    
    • 1
    • 2
    • 3
    • 4

    1.3 run()

    run(fetches,feed_dict=None, options=None, run_metadata=None)

    • 通过使用sess.run()来运行operation
    • fetches:单一的operation,或者列表、元组(其它不属于tensorflow的类型不行)
    • feed_dict:参数允许调用者覆盖图中张量的值,运行时赋值
      • 与tf.placeholder搭配使用,则会检查值的形状是否与占位符兼容
    def session_run_demo1():
        """
        session中的run方法
        placeholder提供占位符,run时候通过feed_dict指定参数
        在编写 TensorFlow 程序时,程序传递和运算的主要目标是tf.Tensor
        """
        # 定义占位符
        a = tf.placeholder(tf.float32)
        b = tf.placeholder(tf.float32)
        sum_ab = tf.add(a, b)
        print("sum_ab:", sum_ab) # sum_ab: Tensor("Add_1:0", dtype=float32)
        # 开启会话
        with tf.Session() as sess:
            print("占位符的结果", sess.run(sum_ab, feed_dict={a: 3.0, b: 4.0}))
        return None
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2.张量

    TensorFlow 的张量就是一个 n 维数组, 类型为tf.Tensor。Tensor具有以下两个重要的属性

    • type:数据类型
    • shape:形状(阶)

    一般将零维的张量称为标量或者常数,一维的张量可理解为向量,二维张量可理解为矩阵,三维则是三维数组

    2.1 张量的类型

    数据类型Python 类型描述
    DT_FLOATtf.float3232 位浮点数.
    DT_DOUBLEtf.float6464 位浮点数.
    DT_INT64tf.int6464 位有符号整型.
    DT_INT32tf.int3232 位有符号整型.
    DT_INT16tf.int1616 位有符号整型.
    DT_INT8tf.int88 位有符号整型.
    DT_UINT8tf.uint88 位无符号整型.
    DT_STRINGtf.string可变长度的字节数组.每一个张量元素都是一个字节数组.
    DT_BOOLtf.bool布尔型.
    DT_COMPLEX64tf.complex64由两个32位浮点数组成的复数:实数和虚数.
    DT_QINT32tf.qint32用于量化Ops的32位有符号整型.
    DT_QINT8tf.qint8用于量化Ops的8位有符号整型.
    DT_QUINT8tf.quint8用于量化Ops的8位无符号整型.

    2.2 张量的阶

    数学实例Python例子
    0纯量(只有大小)s = 483
    1向量(大小和方向)v = [1.1, 2.2, 3.3]
    2矩阵(数据表)m = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    33阶张量(数据立体)t = [[[2], [4], [6]], [[8], [10], [12]], [[14], [16], [18]]]
    nn阶(自己想想看)

    2.3 创建张量

    2.3.1 创建固定张量

    • tf.zeros(shape, dtype=dtypes.float32, name=None) 创建所有元素设置为零的张量
    • tf.ones(shape, dtype=dtypes.float32, name=None) 创建所有元素设置为1的张量
    • tf.constant_v1(
      value, dtype=None, shape=None, name=“Const”, verify_shape=False) 创建一个常数张量
    # 创建一维张量 4个元素
    a = tf.zeros(4)
    print(a)  # Tensor("zeros:0", shape=(4,), dtype=float32)
    
    # 创建一维张量 4个元素
    aa = tf.zeros([4])
    print(aa)  # Tensor("zeros_1:0", shape=(4,), dtype=float32)
    
    # 创建3行3列的二维张量
    b = tf.zeros([3, 3])
    print(b)  # Tensor("zeros_1:0", shape=(3, 3), dtype=float32)
    
    # 创建3行3列的二维张量
    bb = tf.zeros((3, 3))
    print(bb)  # Tensor("zeros_2:0", shape=(3, 3), dtype=float32)
    
    # 指定类型
    c = tf.zeros([3, 3], tf.int8)
    print(c)  # Tensor("zeros_3:0", shape=(3, 3), dtype=int8)
    
    # 创建常数张量
    t = tf.constant(value=30.0, dtype=tf.float32, name='t')
    # # Tensor("t:0", shape=(), dtype=float32)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    2.3.2 创建随机张量

    • tf.random_normal(shape,mean=0.0,stddev=1.0,dtype=dtypes.float32,seed=None,name=None) 从正态分布中输出随机值,由正态分布数字组成的矩阵
    # 创建2行2列均值为0标准差为1的随机数张量
    a = tf.random_normal([2, 2], mean=0, stddev=1)
    print(a)  # Tensor("random_normal:0", shape=(2, 2), dtype=float32)
    
    • 1
    • 2
    • 3

    2.4 张量的变换

    2.4.1 类型变换

    • tf.string_to_number(string_tensor, out_type=_dtypes.float32, name=None)将输入张量中的每个字符串转换为指定的数值类型
    • tf.to_double(x, name=“ToDouble”) 将Tensor类型转换为float64
    • tf.to_float(x, name=“ToFloat”) 将Tensor类型转换为float32
    • tf.to_bfloat16(x, name=“ToBFloat16”) 将Tensor类型转换为bfloat16
    • tf.to_int32(x, name=“ToInt32”) 将Tensor类型转换为int32
    • tf.to_int64(x, name=“ToInt64”) 将Tensor类型转换为int64
    • tf.cast(x, dtype, name=None) 将Tensor类型转换为新的类型
    t1 = tf.Variable([1, 2, 3, 4, 5])
    t2 = tf.cast(t1, dtype=tf.float32)
    
    print('t1: {}'.format(t1))  # t1: 
    print('t2: {}'.format(t2))  # t2: Tensor("Cast:0", shape=(5,), dtype=float32)
    
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        sess.run(t2)
        print(t2.eval())  # [1. 2. 3. 4. 5.]
        print(sess.run(t2))
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.4.2 形状变换

    • 张量形状:
      • 静态形状:初始形状,存储数据
        • 一旦固定,不能修改。
      • 动态形状:运算过程中的形状
        • reshape函数,可以返回一个新的张量。
        • 可以多次修改、跨阶修改,元素总数量保持一致。

    张量形状改变时,要注意元素个数一致。且静态张量形状一旦确定,不能进行修改。

    import tensorflow as tf
    
    pld = tf.placeholder(tf.float32, [None, 3])  # n行三列的张量
    print(pld)  # Tensor("Placeholder:0", shape=(?, 3), dtype=float32)
    # 静态形状,一旦确定不能修改
    pld.set_shape([4, 3])  # ok
    print(pld)  # Tensor("Placeholder:0", shape=(4, 3), dtype=float32)
    # pld.set_shape([2,3])     # error ,静态张量形状一旦确定不能修改
    
    # 动态张量
    new_pld = tf.reshape(pld, [3, 4])  # ok ,动态形状可以再设置
    print(new_pld)  # Tensor("Reshape:0", shape=(3, 4), dtype=float32)
    new_pld1 = tf.reshape(pld, [2, 6])  # ok,
    print(new_pld1)  # Tensor("Reshape_1:0", shape=(2, 6), dtype=float32)
    new_pld2 = tf.reshape(pld, [2, 4])  # error,元素个数不一致
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2.5 张量的数学运算

    计算类型函数
    基本数学计算tf.math.add、subtract、multiply、divide、abs、pow、sqrt、log、exp、square、reduce_sum
    三角函数计算sin、asin
    特殊的三角函数igamma、zeta
    复数计算imag、angle
    数据分割segment_sum
    最值运算argmax

    加减乘除

    # 定义张量常量
    a = tf.constant([3, 8])
    b = tf.constant([2, 5])
    add = tf.add(a, b)  # 加法
    sub = tf.subtract(a, b)  # 减法
    mul = tf.multiply(a, b)  # 乘法
    div = tf.divide(a, b)  # 除法
    
    =====================================================================================
    a = tf.constant([[1.0, 2], [-3, 4.0]], name='a')
    b = tf.constant([[5.0, 6], [7.0, 8.0]], name='b')
    print('a: {}'.format(a))  # a: Tensor("a:0", shape=(2, 2), dtype=float32)
    print('b: {}'.format(b))  # b: Tensor("b:0", shape=(2, 2), dtype=float32)
    sum_ab = tf.add(a, b)
    
    with tf.Session() as sess:
        sess.run(sum_ab)
        print("a与b的和为:\n{}".format(sum_ab.eval()))
        
    x = tf.constant([2.6, -2.7])
    
    with tf.Session() as sess:
        print(sess.run(tf.math.round(x)))  # 保留整数部分,四舍五入 [3 -3]
        print(sess.run(tf.math.floor(x)))  # 保留整数部分,向下归整 [2 -3]
        print(sess.run(tf.math.ceil(x)))  # 保留整数部分,向上归整  [3 -2]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    指数、开方、对数

    a = tf.constant([[1.,2.],[3.,4.]])
    # 指数为2
    b = tf.pow(a,2)
    # 开方 
    c = tf.sqrt(b)  
     # 自然指数运算
    d = tf.exp(a) 
    # 对数运算,以自然常数e为底的对数
    e = tf.math.log(a)
    # 对各个元素求平方
    f = tf.square(a) 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    矩阵相乘

    matrix1 = tf.constant([[1,2],[3,4]])
    matrix2 = tf.constant([[5,6],[7,8]])
    result = tf.matmul(matrix1,matrix2)
    
    • 1
    • 2
    • 3

    3.变量OP

    TensorFlow变量是表示程序处理的共享持久状态的最佳方法。变量通过 tf.Variable OP类进行操作。变量的特点:

    • 存储持久化
    • 可修改值
    • 可指定被训练

    3.1 创建变量

    • tf.Variable(initial_value=None,trainable=True,collections=None,name=None)
      • initial_value:初始化的值
      • trainable:是否被训练
      • collections:新变量将添加到列出的图的集合中collections,默认为[GraphKeys.GLOBAL_VARIABLES],如果trainable是True变量也被添加到图形集合 GraphKeys.TRAINABLE_VARIABLES
    • 变量需要显式初始化,才能运行值
     # 定义变量
        a = tf.Variable(initial_value=30)
        b = tf.Variable(initial_value=40)
        sum_ab = tf.add(a, b)
    
        # 初始化变量
        init = tf.global_variables_initializer()
    
        # 开启会话
        with tf.Session() as sess:
            # 变量初始化
            sess.run(init)
            print("sum:", sess.run(sum_ab)) # sum: 70
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    3.2 使用tf.variable_scope()修改变量的命名空间

    with tf.variable_scope("name"):
        var = tf.Variable(name='var', initial_value=[4], dtype=tf.float32)
        var_double = tf.Variable(name='var', initial_value=[4], dtype=tf.float32)
    # 打印结果:
    <tf.Variable 'name/var:0' shape=(1,) dtype=float32_ref>
    <tf.Variable 'name/var_1:0' shape=(1,) dtype=float32_ref>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  • 相关阅读:
    JavaScript个人笔记
    JAVA:实现Sudoku数独算法(附完整源码)
    2022年06月 Python(四级)真题解析#中国电子学会#全国青少年软件编程等级考试
    【JAVA】总结线程Thread的基本用法
    LeetCode 2609. 最长平衡子字符串
    计算机毕业设计之java+ssm的鲜活农产品销售系统
    KylinV10系统如何查找JDK路径和安装JDK
    在Oracle的ADR中设置自动删除trace文件的策略
    quarkus依赖注入之九:bean读写锁
    JTS:04 读取数据库数据
  • 原文地址:https://blog.csdn.net/weixin_44852067/article/details/126372702