要确定TensorFlow是在GPU还是CPU上运行,可以使用以下代码:
import tensorflow as tf
if tf.test.gpu_device_name(): # 检查GPU是否可用
print('GPU可用')
device_name = tf.test.gpu_device_name()
else:
print('GPU不可用')
device_name = '/cpu:0'
print('设备名称: {}'.format(device_name))
# 在指定设备上运行代码
with tf.device(device_name):
# 在这里编写训练循环代码
pass
上述代码首先检查是否存在可用的GPU设备,如果有可用的GPU,则选择在GPU上运行,否则选择在CPU上运行。然后,根据选择的设备名称,将训练循环代码放入tf.device()
上下文管理器中。
在自定义Keras训练循环中,您可以使用相同的方法确定TensorFlow是在GPU还是CPU上运行,并在合适的地方使用tf.device()
上下文管理器。以下是一个示例:
import tensorflow as tf
from tensorflow.keras import Model, layers
class CustomModel(Model):
def __init__(self):
super(CustomModel, self).__init__()
self.dense = layers.Dense(10, activation='relu')
def call(self, inputs):
return self.dense(inputs)
model = CustomModel()
if tf.test.gpu_device_name(): # 检查GPU是否可用
print('GPU可用')
device_name = tf.test.gpu_device_name()
else:
print('GPU不可用')
device_name = '/cpu:0'
print('设备名称: {}'.format(device_name))
# 在指定设备上运行代码
with tf.device(device_name):
# 编译模型
model.compile(optimizer='adam', loss='mse')
# 训练模型
model.fit(x_train, y_train, epochs=10)
在上述示例中,首先检查是否存在可用的GPU设备,并选择在GPU上运行还是在CPU上运行。然后,根据选择的设备名称,编译和训练模型时使用tf.device()
上下文管理器。这样可以确保模型在正确的设备上运行。