1,指定那片GPU
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0" #指定在第0块GPU上跑
2,多GPU使用
import numpy as np
import tensorflow as tf
n = 10
A = np.random.rand(2, 2).astype('float32')
B = np.random.rand(2, 2).astype('float32')
c1 = []
# 递归的思想求解幂次方
def matpow(M,n):
if n < 1:
return M
else:
return tf.matmul(M,matpow(M,n-1))
#分配第一个GPU:3
with tf.device('/gpu:3'):
a = tf.placeholder(tf.float32,[2, 2])
c1.append(matpow(a, n))
#分配第二GPU:4
with tf.device('/gpu:4'):
b = tf.placeholder(tf.float32, [2, 2])
c1.append(matpow(b, n))
# tf.add_n([p1, p2, p3....])函数是实现一个列表的元素的相加
with tf.device('/gpu:7'):
sum = tf.add_n(c1)
with tf.Session() as sess:
print(sess.run(sum, {a:A,b:B}))