當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python tensorflow.device()用法及代碼示例


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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。