温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

tf.ConfigProto()如何在Tensorflow中使用

发布时间:2021-01-11 15:49:16 来源:亿速云 阅读:243 作者:Leah 栏目:开发技术

tf.ConfigProto()如何在Tensorflow中使用?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

tf.ConfigProto()主要的作用是配置tf.Session的运算方式,比如gpu运算或者cpu运算

具体代码如下:

import tensorflow as tf

session_config = tf.ConfigProto(
   log_device_placement=True,
   inter_op_parallelism_threads=0,
   intra_op_parallelism_threads=0,
   allow_soft_placement=True)

sess = tf.Session(config=session_config)

a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2,3], name='b')
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)
print(sess.run(c))

具体解释

log_device_placement=True

设置为True时,会打印出TensorFlow使用了那种操作

inter_op_parallelism_threads=0

设置线程一个操作内部并行运算的线程数,比如矩阵乘法,如果设置为0,则表示以最优的线程数处理

intra_op_parallelism_threads=0

设置多个操作并行运算的线程数,比如 c = a + b,d = e + f . 可以并行运算

allow_soft_placement=True

有时候,不同的设备,它的cpu和gpu是不同的,如果将这个选项设置成True,那么当运行设备不满足要求时,会自动分配GPU或者CPU。

其他选项

当使用GPU时候,Tensorflow运行自动慢慢达到最大GPU的内存

session_config.gpu_options.allow_growth = True

当使用GPU时,设置GPU内存使用最大比例

session_config.gpu_options.per_process_gpu_memory_fraction = 0.4

是否能够使用GPU进行运算

tf.test.is_built_with_cuda()

另外的处理方法

import tensorflow as tf

sess = tf.Session()

with tf.device('/cpu:0'):
  a = tf.constant([1.0, 3.0, 5.0], shape=[1, 3])
  b = tf.constant([2.0, 4.0, 6.0], shape=[3, 1])

  with tf.device('/gpu:0'):
    c = tf.matmul(a, b)
    c = tf.reshape(c, [-1])

  with tf.device('/gpu:0'):
    d = tf.matmul(b, a)
    flat_d = tf.reshape(d, [-1])

  combined = tf.multiply(c, flat_d)
  print(sess.run(combined))

看完上述内容,你们掌握tf.ConfigProto()如何在Tensorflow中使用的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI