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


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

TensorFlow是Google設計的開源Python庫,用於開發機器學習模型和深度學習神經網絡。

watch()用於通過磁帶開始跟蹤Tensor。

用法:watch( tensor )

參數:

  • tensor:它是一個張量或要監視的張量列表。

返回值:



提高:

  • ValueError:如果passs參數不是Tensor,它將引發ValueError。

範例1:

Python3

# Importing the library 
import tensorflow as tf 
  
x = tf.constant(4.0) 
  
# Using GradientTape 
with tf.GradientTape() as gfg:
  
  # Starting the recording x 
  gfg.watch(x) 
  y = x * x 
  
# Computing gradient 
res = gfg.gradient(y, x)  
  
# Printing result 
print("res:", res)

輸出:

res: tf.Tensor(8.0, shape=(), dtype=float32)

範例2:

Python3

# Importing the library 
import tensorflow as tf 
  
x = tf.constant(4.0) 
z = tf.constant(5.0) 
  
# Using GradientTape 
with tf.GradientTape(persistent = True) as gfg:
  
  # Starting the recording x and z 
  gfg.watch([x, z]) 
  y = z * z 
  u = x * x 
  
# Computing gradient 
grad_y = gfg.gradient(y, z)  
grad_u = gfg.gradient(u, x) 
  
# Printing result 
print("grad_y:", grad_y) 
print("grad_u:", grad_u)

輸出:

grad_y: tf.Tensor(10.0, shape=(), dtype=float32)
grad_u: tf.Tensor(8.0, shape=(), dtype=float32)





相關用法


注:本文由純淨天空篩選整理自aman neekhara大神的英文原創作品 Python – tensorflow.GradientTape.watch()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。