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


Python tf.compat.v1.constant用法及代碼示例

創建一個常數張量。

用法

tf.compat.v1.constant(
    value, dtype=None, shape=None, name='Const', verify_shape=False
)

參數

  • value 輸出類型為 dtype 的常量值(或列表)。
  • dtype 結果張量的元素類型。
  • shape 結果張量的可選尺寸。
  • name 張量的可選名稱。
  • verify_shape 用於驗證值形狀的布爾值。

返回

  • 一個常數張量。

拋出

  • TypeError 如果形狀指定不正確或不受支持。

生成的張量由 dtype 類型的值填充,由參數 value 和(可選)shape 指定(參見下麵的示例)。

參數 value 可以是常量值,也可以是類型為 dtype 的值的列表。如果 value 是一個列表,則列表的長度必須小於或等於 shape 參數(如果指定)隱含的元素數。在列表長度小於 shape 指定的元素數量的情況下,列表中的最後一個元素將用於填充剩餘的條目。

參數shape 是可選的。如果存在,它指定結果張量的維度。如果不存在,則使用 value 的形狀。

如果未指定參數 dtype ,則從 value 的類型推斷類型。

例如:

# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]

# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
                                             [-1. -1. -1.]]

tf.constant 在以下幾個方麵與 tf.fill 不同:

  • tf.constant 支持任意常量,而不僅僅是像 tf.fill 這樣的統一標量張量。
  • tf.constant 在計算圖中創建一個 Const 節點,該節點在圖構建時具有精確值。另一方麵,tf.fill 在運行時擴展的圖中創建一個 Op。
  • 因為tf.constant 僅在圖中嵌入常量值,它不支持基於其他運行時張量的動態形狀,而tf.fill 支持。

相關用法


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