一、指定CPU运行
具体语句如下,tf.ConfigProto是TensorFlow 1.x版本的语句,由于我使用的是 TensorFlow 2.x 版本的,所以要用 tf.compat.v1 切换一下才能运行,否则报错,如果是 TensorFlow 1.x版本的,则直接用tf.ConfigProto 即可,具体我未尝试(一开始用的tf.ConfigProto运行报错,后来用的tf.compat.v1.ConfigProto)。
tf.compat.v1.placeholder与tf.compat.v1.Session也是一样的:
import tensorflow as tf
config = tf.compat.v1.ConfigProto(log_device_placement=True, allow_soft_placement=True)
with tf.compat.v1.Session(config=config) as sess:
with tf.device('/cpu:0'):
a = tf.compat.v1.placeholder(tf.int32)
b = tf.compat.v1.placeholder(tf.int32)
add = tf.add(a, b)
sum = sess.run(add, feed_dict={a: 3, b: 4})
print(sum)
config = tf.compat.v1.ConfigProto(log_device_placement=True, allow_soft_placement=True)#此语句用来显示在输出时,是否显示配置信息(log_device_placement=True),手动设置内容不存在,则使用默认配置(allow_soft_placement=True)
with tf.device('/cpu:0'): #指定 with 下面的内容使用CPU运行,如果有两个CPU,则0可以变成1,来选择不同的CPU运行
如下图所示,显示的是CPU

二、指定GPU运行
具体语句如下:
tf.compat.v1.placeholder与tf.compat.v1.Session也是一样的:
import tensorflow as tf
config = tf.compat.v1.ConfigProto(log_device_placement=True, allow_soft_placement=True)
with tf.compat.v1.Session(config=config) as sess:
with tf.device('/gpu:0'):
a = tf.compat.v1.placeholder(tf.int32)
b = tf.compat.v1.placeholder(tf.int32)
add = tf.add(a, b)
sum = sess.run(add, feed_dict={a: 3, b: 4})
print(sum)
with tf.device('/gpu:0'): #指定 with 下面的内容使用GPU运行,如果有两个GPU,则0可以变成1,来选择不同的GPU运行
with tf.device('/gpu:0'):只能保证其包含的内容是指定的配置
如下图所示,显示的是GPU

三、既有CPU又有GPU
如果要区分开来,则可以同时使用CPU与GPU参与运算,代码如下,为CPU与GPU同时进行相同运算的时间对比,定义两个方法,一个使用CPU一个使用GPU,然后分别调用方法。
import tensorflow as tf
#指定在cpu上运行
def cpu_run():
with tf.device('/cpu:0'):
cpu_a = tf.random.normal([20000, 2000])
cpu_b = tf.random.normal([2000, 4000])
cpu_c = tf.matmul(cpu_a, cpu_b)
# print( "cpu_a: ", cpu_a.device)
# print( "cpu_b: ", cpu_b.device)
# print("cpu_c:", cpu_c.device)
return cpu_c
#指定在gpu上运行
def gpu_run():
with tf.device( '/gpu:0'):
gpu_a = tf.random.normal([ 20000,2000])
gpu_b = tf.random.normal([ 2000, 4000])
gpu_c = tf.matmul(gpu_a, gpu_b)
# print( "gpu_a: ", gpu_a.device)
# print("gpu_b: ", gpu_b.device)
# print("gpu_c: ", gpu_c.device)
return gpu_c
cpu_time = timeit.timeit(cpu_run, number = 20)
gpu_time = timeit.timeit(gpu_run, number = 20)
print('cpu:',cpu_time, 'gpu:',gpu_time)
具体结果对比如下图:左边为CPU运算时间,右边为GPU运算时间,运算时间相差明显:

四、总结与一些经验
当同时安装CPU版本与GPU版本的TensorFlow时,默认是如果版本相同,默认是使用GPU版本的(如我使用的版本)。如果版本不同,据说是哪个版本领先,使用哪个版本,具体我没试过,装来装去太麻烦了。
如果安装过程中一些包版本不一致导致代码无法运行,比如numpy与pandas包版本不兼容,numpy版本太旧,pandas版本较新,则建议尽量和tensorflow版本保持一致(不然可能还要重新安装TensorFlow版本,比较麻烦),比如2.5版本的tensorflow需要1.19版本的numpy,那么就尽量不要改变numpy版本,可以降低pandas版本,使得pandas与numpy的版本兼容。

670

被折叠的 条评论
为什么被折叠?



