3-Tensorflow-demo_05-tf_device的使用


import tensorflow as tf

"""
学习tf.device()添加运行设备号
注意:
  如果不使用tf.device()来给定具体的运行设备,那么tf会根据你的tf版本来选择默认的设备进行运算。
  1、如果时tf cpu版本,那么运行再cpu上。
  2、如果是tensorflow-gpu版本,那么运算操作一定会在第一块gpu上运行,在所有gpu上面分配内存。
  如果你通过tf.device()明确指定运行设备,那么运算操作一定会在你指定的设备上运行,如果没有该设备,就会报错。
  这时,可以通过 Session中的参数,allow_soft_placement=True来设置。
"""


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

            # 2、定一个变量,表示阶乘的值。
            sum_x = tf.Variable(
                initial_value=1.0, dtype=tf.float32, name='sumx'
            )

        with tf.device('/GPU:0'):
            # 3、做一个乘法操作
            temp = sum_x * input_x
            # 将temp这个tensor的值,再次的赋值给sum_x
            assign_opt = tf.assign(
                ref=sum_x, value=temp
            )
        with tf.device('/GPU:1'):
            # 4、做一个阶乘的累加值,再乘以3的操作。
            with tf.control_dependencies(control_inputs=[assign_opt]):
                # fixme 当前with语句块中的代码执行之前,一定会触发control_inputs中给定的tensor操作
                y = sum_x * 3

        # 二、执行会话
        config = tf.ConfigProto(
            log_device_placement=True,
            allow_soft_placement=True
        )
        with tf.Session(config=config) 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__':
    show_device()
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:46:51.063066: 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 0x0000024229BA2C88>
[[ 0.50495124  1.5049512   2.5049512 ]
 [ 1.5049512   3.5049512   3.5049512 ]
 [41.50495     1.5049512   0.50495124]
 [-0.49504876  1.5049512   2.5049512 ]
 [ 2.5049512   2.5049512   2.5049512 ]]
[[245.80153 110.2257  113.04215]
 [280.03595 155.46011 161.27657]
 [303.50693 133.93108 137.74753]]

Process finished with exit code 0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值