TensorFlow是Google设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
device()用于显式指定应在其中执行操作的设备。
用法:tesorflow.device( device_name )
参数:
- device_name:它指定在此上下文中使用的设备名称。
返回值:它返回一个上下文管理器,该上下文管理器指定用于新创建的操作的默认设备。
范例1:
Python3
# Importing the library
import tensorflow as tf
# Initializing Device Specification
device_spec = tf.DeviceSpec(job ="localhost", replica = 0, device_type = "CPU")
# Printing the DeviceSpec
print('Device Spec:', device_spec.to_string())
# Enabling device logging
tf.debugging.set_log_device_placement(True)
# Specifying the device
with tf.device(device_spec):
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
输出:
Device Spec: /job:localhost/replica:0/device:CPU:* Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
范例2:在此示例设备规范中指定了要使用的GPU,但系统找不到GPU,因此它将在CPU上运行操作。
Python3
# Importing the library
import tensorflow as tf
# Initializing Device Specification
device_spec = tf.DeviceSpec(job ="localhost", replica = 0, device_type = "GPU")
# Printing the DeviceSpec
print('Device Spec:', device_spec.to_string())
# Enabling device logging
tf.debugging.set_log_device_placement(True)
# Specifying the device
with tf.device(device_spec):
a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
c = tf.matmul(a, b)
输出:
Device Spec: /job:localhost/replica:0/device:GPU:* Executing op MatMul in device /job:localhost/replica:0/task:0/device:CPU:0
相关用法
注:本文由纯净天空筛选整理自aman neekhara大神的英文原创作品 Python – tensorflow.device()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。