請參閱變量指南。
用法
tf.Variable(
initial_value=None, trainable=None, validate_shape=True, caching_device=None,
name=None, variable_def=None, dtype=None, import_scope=None, constraint=None,
synchronization=tf.VariableSynchronization.AUTO,
aggregation=tf.compat.v1.VariableAggregation.NONE, shape=None
)
參數
-
initial_value
Tensor
或可轉換為Tensor
的 Python 對象,這是變量的初始值。除非validate_shape
設置為 False,否則初始值必須具有指定的形狀。也可以是不帶參數的可調用對象,在調用時返回初始值。在這種情況下,必須指定dtype
。 (請注意,init_ops.py 中的初始化函數必須先綁定到形狀,然後才能在此處使用。) -
trainable
如果True
,GradientTapes 會自動監視此變量的使用。默認為True
,除非synchronization
設置為ON_READ
,在這種情況下它默認為False
。 -
validate_shape
如果False
,允許使用未知形狀的值初始化變量。如果True
是默認值,則必須知道initial_value
的形狀。 -
caching_device
注意:此參數僅在使用 v1 樣式Session
時有效。可選的設備字符串,說明應緩存變量以供讀取的位置。默認為變量的設備。如果不是None
,則緩存在另一台設備上。典型用途是在使用變量的操作所在的設備上進行緩存,通過Switch
和其他條件語句進行重複數據刪除。 -
name
變量的可選名稱。默認為'Variable'
並自動獲取唯一性。 -
variable_def
VariableDef
協議緩衝區。如果不是None
,則使用其內容重新創建變量對象,引用圖中必須已經存在的變量節點。圖表沒有改變。variable_def
和其他參數是互斥的。 -
dtype
如果設置,initial_value 將被轉換為給定的類型。如果None
,或者保留數據類型(如果initial_value
是張量),或者convert_to_tensor
將決定。 -
import_scope
可選string
。要添加到Variable.
的名稱範圍僅在從協議緩衝區初始化時使用。 -
constraint
由Optimizer
更新後應用於變量的可選投影函數(例如,用於實現層權重的範數約束或值約束)。該函數必須將表示變量值的未投影張量作為輸入,並返回投影值的張量(必須具有相同的形狀)。在進行異步分布式訓練時使用約束是不安全的。 -
synchronization
指示何時聚合分布式變量。接受的值是在類tf.VariableSynchronization
中定義的常量。默認情況下,同步設置為AUTO
,當前的DistributionStrategy
選擇何時同步。 -
aggregation
指示如何聚合分布式變量。接受的值是在類tf.VariableAggregation
中定義的常量。 -
shape
(可選)此變量的形狀。如果沒有,將使用initial_value
的形狀。當將此參數設置為tf.TensorShape(None)
(表示未指定的形狀)時,可以為變量分配不同形狀的值。
拋出
-
ValueError
如果同時指定variable_def
和 initial_value。 -
ValueError
如果未指定初始值,或沒有形狀且validate_shape
為True
。
屬性
-
aggregation
-
constraint
返回與此變量關聯的約束函數。 -
device
此變量的設備。 -
dtype
該變量的DType
。 -
graph
該變量的Graph
。 -
initial_value
返回用作變量初始值的張量。請注意,這與
initialized_value()
不同,後者在返回其值之前運行初始化變量的操作。此方法返回初始化變量的操作所使用的張量。 -
initializer
此變量的初始化操作。 -
name
此變量的名稱。 -
op
該變量的Operation
。 -
shape
該變量的TensorShape
。 -
synchronization
-
trainable
變量維護由程序操作的共享的、持久的狀態。
Variable()
構造函數需要變量的初始值,它可以是任何類型和形狀的 Tensor
。這個初始值定義了變量的類型和形狀。構造後,變量的類型和形狀是固定的。可以使用其中一種分配方法更改該值。
v = tf.Variable(1.)
v.assign(2.)
<tf.Variable ... shape=() dtype=float32, numpy=2.0>
v.assign_add(0.5)
<tf.Variable ... shape=() dtype=float32, numpy=2.5>
Variable
的構造函數的 shape
參數允許您構造一個形狀比其 initial_value
定義更少的變量:
v = tf.Variable(1., shape=tf.TensorShape(None))
v.assign([[1.]])
<tf.Variable ... shape=<unknown> dtype=float32, numpy=array([[1.]], ...)>
就像任何 Tensor
一樣,使用 Variable()
創建的變量可以用作操作的輸入。此外,為Tensor
類重載的所有運算符都被轉移到變量中。
w = tf.Variable([[1.], [2.]])
x = tf.constant([[3., 4.]])
tf.matmul(w, x)
<tf.Tensor:... shape=(2, 2), ... numpy=
array([[3., 4.],
[6., 8.]], dtype=float32)>
tf.sigmoid(w + x)
<tf.Tensor:... shape=(2, 2), ...>
在構建機器學習模型時,通常可以方便地區分包含可訓練模型參數的變量和其他變量,例如用於計算訓練步數的 step
變量。為了使這更容易,變量構造函數支持trainable=<bool>
參數。 tf.GradientTape
默認監視可訓練變量:
with tf.GradientTape(persistent=True) as tape:
trainable = tf.Variable(1.)
non_trainable = tf.Variable(2., trainable=False)
x1 = trainable * 2.
x2 = non_trainable * 3.
tape.gradient(x1, trainable)
<tf.Tensor:... shape=(), dtype=float32, numpy=2.0>
assert tape.gradient(x2, non_trainable) is None # Unwatched
當分配給從 tf.Module
繼承的類型的屬性時,會自動跟蹤變量。
m = tf.Module()
m.v = tf.Variable([1.])
m.trainable_variables
(<tf.Variable ... shape=(1,) ... numpy=array([1.], dtype=float32)>,)
然後,此跟蹤允許將變量值保存到訓練檢查點或包含序列化 TensorFlow 圖的 SavedModel。
變量通常由tf.function
s 捕獲和操作。這與 un-decorated 函數的工作方式相同:
v = tf.Variable(0.)
read_and_decrement = tf.function(lambda:v.assign_sub(0.1))
read_and_decrement()
<tf.Tensor:shape=(), dtype=float32, numpy=-0.1>
read_and_decrement()
<tf.Tensor:shape=(), dtype=float32, numpy=-0.2>
在 tf.function
內創建的變量必須在函數外部擁有並且隻能創建一次:
class M(tf.Module):
@tf.function
def __call__(self, x):
if not hasattr(self, "v"): # Or set self.v to None in __init__
self.v = tf.Variable(x)
return self.v * x
m = M()
m(2.)
<tf.Tensor:shape=(), dtype=float32, numpy=4.0>
m(3.)
<tf.Tensor:shape=(), dtype=float32, numpy=6.0>
m.v
<tf.Variable ... shape=() dtype=float32, numpy=2.0>
有關詳細信息,請參閱tf.function
文檔。
子類
相關用法
- Python tf.Variable.__lt__用法及代碼示例
- Python tf.Variable.__pow__用法及代碼示例
- Python tf.Variable.__le__用法及代碼示例
- Python tf.Variable.initialized_value用法及代碼示例
- Python tf.Variable.__matmul__用法及代碼示例
- Python tf.Variable.ref用法及代碼示例
- Python tf.Variable.__getitem__用法及代碼示例
- Python tf.Variable.load用法及代碼示例
- Python tf.Variable.__gt__用法及代碼示例
- Python tf.Variable.__rpow__用法及代碼示例
- Python tf.Variable.__abs__用法及代碼示例
- Python tf.Variable.scatter_nd_add用法及代碼示例
- Python tf.Variable.eval用法及代碼示例
- Python tf.Variable.scatter_nd_sub用法及代碼示例
- Python tf.Variable.__sub__用法及代碼示例
- Python tf.Variable.__rmatmul__用法及代碼示例
- Python tf.Variable.__rsub__用法及代碼示例
- Python tf.Variable.scatter_nd_update用法及代碼示例
- Python tf.Variable.__ge__用法及代碼示例
- Python tf.compat.v1.distributions.Multinomial.stddev用法及代碼示例
注:本文由純淨天空篩選整理自tensorflow.org大神的英文原創作品 tf.Variable。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。