3-Tensorflow-demo_01_02-会话中Config的参数设置


import tensorflow as tf
import numpy as np

"""
介绍 tf.Session() 中参数config协议。
"""

def show_session_config():
    # 1、构建2个常量的矩阵
    a = tf.constant(value=[1,2,3,4,5,6,7,3,2,4,3,4],
                    dtype=tf.float32, shape=[3, 5])
    b = tf.constant(value=[2,3,4,3,5,5,43,3,2,1,3,4],
                    dtype=tf.float32, shape=[5, 3])
    # 2、2个常量tensor分别加一个随机数
    v1 = a + np.random.random_sample()
    v2 = b + tf.random_normal(shape=[], dtype=tf.float32)

    # 3、矩阵相乘
    rezult = tf.matmul(v1, v2)
    print(v1, v2, rezult)
    # 二、构建会话
    gpu_options = tf.GPUOptions(
        allow_growth=True,             # 不预先分配整个gpu显存计算,而是从小到大,按需增加。
        per_process_gpu_memory_fraction=0.9  # value-(0, 1) 限制使用该gpu设备的显存使用的百分比。一般建议设置0.8--0.9左右。
    )
    config = tf.ConfigProto(
        allow_soft_placement=True,     # 是否允许tf动态的使用cpu和gpu。当我们的版本是gpu版本,那么tf会默认调用你的gpu:0来运算,如果你的gpu无法工作,那么tf就会报错。所以建议有gpu版本的同学,将这个参数设置为True。
        log_device_placement=True,      # bool值,是否打印设备位置的日志文件。
        gpu_options=gpu_options
    )
    with tf.Session(config=config) as sess:
        v1_, v2_, rezult_ = sess.run([v1, v2, rezult])
        print(tf.get_default_session())
        print(v1_, v2_, rezult_)


if __name__ == '__main__':
    show_session_config()


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:41:45.163586: 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 0x0000015446943C50>
[[ 3.0295024  4.0295024  5.0295024]
 [ 4.0295024  6.0295024  6.0295024]
 [44.029503   4.0295024  3.0295024]
 [ 2.0295024  4.0295024  5.0295024]
 [ 5.0295024  5.0295024  5.0295024]]
[[169.57771   47.04595   49.489716]
 [182.50339   70.971634  76.4154  ]
 [215.10666   58.574913  62.01868 ]]

Process finished with exit code 0

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值