3-Tensorflow-demo_04-通过阶乘案例学习Assign和控制依赖



import tensorflow as tf
print(tf.__version__)
"""
使用tf.assign 实现一个累加器,且每一步均输出累加器的结果。
"""

def sum1():
    with tf.Graph().as_default():
        # 一、模型图的构建
        # 1、定义一个占位符,表示输入的数字。
        input_x = tf.placeholder(dtype=tf.float32, shape=None, name='input_x')

        # 2、定一个变量,用于累加值的累加
        sum_x = tf.Variable(
            initial_value=1.0, dtype=tf.float32, name='sum_x'
        )
        # 3、做一个累加的操作
        sum_x += input_x

        # 二、模型图执行
        with tf.Session() as sess:
            # a\变量初始化
            sess.run(tf.global_variables_initializer())

            # 迭代累加的值
            datas = [1,3,5,7,9]
            for data in datas:
                sum_x_ = sess.run(sum_x, feed_dict={input_x: data})
                print(sum_x_)


def sum2():
    with tf.Graph().as_default():
        # 一、模型图的构建
        # 1、定义一个占位符,表示输入的数字。
        input_x = tf.placeholder(dtype=tf.float32, shape=None, name='input_x')

        # 2、定一个变量,用于累加值的累加
        sum_x = tf.Variable(
            initial_value=1.0, dtype=tf.float32, name='sum_x'
        )
        # 3、做一个累加的操作
        # assign_opt = tf.assign_add(
        #     ref=sum_x, value=input_x
        # )

        # fixme 第二种实现方式
        temp = sum_x + input_x
        assign_opt = tf.assign(ref=sum_x, value=temp)

        # 二、模型图执行
        with tf.Session() as sess:
            # a\变量初始化
            sess.run(tf.global_variables_initializer())

            # 迭代累加的值
            datas = [1,3,5,7,9]
            for data in datas:
                _, sum_x_ = sess.run([assign_opt, sum_x], feed_dict={input_x: data})
                print(sum_x_)


def change_varialbe_shape():
    """
    通过tf.assign操作符,实现动态的更新变量的维度数目(实现 变量shape的改变)
    :return:
    """
    with tf.Graph().as_default():
        # 1、定义一个变量
        x = tf.Variable(
            initial_value=[[0.0, 0.0, 0.0, 0.0, 0.0]],
            dtype=tf.float32,
            validate_shape=True       # 设置为False时,表示不进行初始值的shape的验证
        )
        # 2、做一个矩阵合并的操作。
        # todo tf.concat只能沿着存在的轴进行合并,所以这里被合并的必须的(1,5)的矩阵。
        tensor1 = tf.expand_dims(input=[0.0, 0.0, 0.0, 0.0, 0.0], axis=0)

        concat = tf.concat(values=[x, tensor1], axis=0)
        # 3、做一个参数更新的操作
        assign_opt = tf.assign(
            ref=x, value=concat, validate_shape=False
        )
        # 二、执行会话
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            for _ in range(5):
                _, x_ = sess.run([assign_opt, x])
                print(x_)


def factorial():
    """
    实现一个求解n阶乘值乘以3的需求(构建一个控制依赖项),使用tf.control_dependencies
    :return:
    """
    with tf.Graph().as_default():
        # 1、构建输入的占位符,表示一个数字。
        input_x = tf.placeholder(tf.float32, None, 'input_x')

        # 2、定一个变量,表示阶乘的值。
        sum_x = tf.Variable(
            initial_value=1.0, dtype=tf.float32, name='sumx'
        )
        # 3、做一个乘法操作
        temp = sum_x * input_x
        # 将temp这个tensor的值,再次的赋值给sum_x
        assign_opt = tf.assign(
            ref=sum_x, value=temp
        )
        # 4、做一个阶乘的累加值,再乘以3的操作。
        with tf.control_dependencies(control_inputs=[assign_opt]):
            # fixme 当前with语句块中的代码执行之前,一定会触发control_inputs中给定的tensor操作
            y = sum_x * 3

        # 二、执行会话
        with tf.Session() as sess:
            sess.run(tf.global_variables_initializer())
            print('sum_x更新之前的值为:{}'.format(sess.run(sum_x)))
            for data in range(1, 6):
                r = sess.run(y, feed_dict={input_x: data})
                print(r)
            print('sum_x更新之后的值为:{}'.format(sess.run(sum_x)))


if __name__ == '__main__':
    # sum2()
    # change_varialbe_shape()
    factorial()
D:\Anaconda\python.exe D:/AI20/HJZ/04-深度学习/2-TensorFlow基础/tf_基础代码/01_01Graph和Session.py
Tensor("add:0", shape=(3, 5), dtype=float32) Tensor("add_1:0", shape=(5, 3), dtype=float32) Tensor("MatMul:0", shape=(3, 3), dtype=float32)
2019-11-30 21:45:42.128806: I tensorflow/core/platform/cpu_feature_guard.cc:141] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
<tensorflow.python.client.session.InteractiveSession object at 0x00000274AE3D3C50>
[[-0.05291724  0.94708276  1.9470828 ]
 [ 0.94708276  2.9470828   2.9470828 ]
 [40.947083    0.94708276 -0.05291724]
 [-1.0529172   0.94708276  1.9470828 ]
 [ 1.9470828   1.9470828   1.9470828 ]]
[[199.67238   67.1699    69.898544]
 [218.69278   97.1903   102.918945]
 [248.68404   82.18156   85.9102  ]]

Process finished with exit code 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值