首页 技术 正文
技术 2022年11月18日
0 收藏 706 点赞 5,242 浏览 1815 个字

1.指定GPU运算

如果安装的是GPU版本,在运行的过程中TensorFlow能够自动检测。如果检测到GPU,TensorFlow会尽可能的利用找到的第一个GPU来执行操作。

如果机器上有超过一个可用的GPU,除了第一个之外的其他的GPU默认是不参与计算的。为了让TensorFlow使用这些GPU,必须将OP明确指派给他们执行。with……device语句能够用来指派特定的CPU或者GPU执行操作:

import tensorflow as tf
import numpy as npwith tf.Session() as sess:
with tf.device('/cpu:0'):
a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)
add = tf.add(a, b)
sum = sess.run(add, feed_dict={a: 3, b: 4})
print(sum)

设备的字符串标识,当前支持的设备包括以下的几种:

cpu:0  机器的第一个cpu。

gpu:0  机器的第一个gpu,如果有的话

gpu:1  机器的第二个gpu,依次类推

类似的还有tf.ConfigProto来构建一个config,在config中指定相关的GPU,并且在session中传入参数config=“自己创建的config”来指定gpu操作

其中,tf.ConfigProto函数的参数如下:

log_device_placement=True: 是否打印设备分配日志

allow_soft_placement=True: 如果指定的设备不存在,允许TF自动分配设备

import tensorflow as tf
import numpy as npconfig = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)with tf.Session(config=config) as sess:
a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)
add = tf.add(a, b)
sum = sess.run(add, feed_dict={a: 3, b: 4})
print(sum)

2.设置GPU使用资源

上文的tf.ConfigProto函数生成的config之后,还可以设置其属性来分配GPU的运算资源,如下代码就是按需分配

import tensorflow as tf
import numpy as npconfig = tf.ConfigProto(log_device_placement=True, allow_soft_placement=True)
config.gpu_options.allow_growth = Truewith tf.Session(config=config) as sess:
a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)
add = tf.add(a, b)
sum = sess.run(add, feed_dict={a: 3, b: 4})
print(sum)

使用 allow_growth option,刚开始会分配少量的GPU容量,然后按需要慢慢的增加,有与不会释放内存,随意会导致内存碎片。

同样,上述的代码也可以在config创建时指定,

import tensorflow as tf
import numpy as npgpu_options = tf.GPUOptions(allow_growth=True)
config = tf.ConfigProto(gpu_options=gpu_options)with tf.Session(config=config) as sess:
a = tf.placeholder(tf.int32)
b = tf.placeholder(tf.int32)
add = tf.add(a, b)
sum = sess.run(add, feed_dict={a: 3, b: 4})
print(sum)

我们还可以给gpu分配固定大小的计算资源。

gpu_options = tf.GPUOptions(allow_growth=True, per_process_gpu_memory_fraction=0.5)

上述代码的含义是分配给tensorflow的GPU显存大小为:GPU的实际显存*0.5

TensorFlow——tensorflow指定CPU与GPU运算

TensorFlow——tensorflow指定CPU与GPU运算

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,293