TensorFlow 程式碼風格指南

Python 風格

遵循 PEP 8 Python 風格指南,但 TensorFlow 使用 2 個空格而非 4 個。請遵守 Google Python 風格指南,並使用 pylint 檢查您的 Python 變更。

pylint

若要安裝 pylint

$ pip install pylint

若要使用 pylint 從 TensorFlow 原始碼根目錄檢查檔案

$ pylint --rcfile=tensorflow/tools/ci_build/pylintrc tensorflow/python/keras/losses.py

支援的 Python 版本

如需瞭解支援的 Python 版本,請參閱 TensorFlow 安裝指南

請參閱 TensorFlow 持續建構狀態,瞭解官方和社群支援的建構版本。

C++ 程式碼風格

TensorFlow C++ 程式碼的變更應符合 Google C++ 風格指南TensorFlow 特定風格詳細資料。使用 clang-format 檢查您的 C/C++ 變更。

若要在 Ubuntu 16 以上版本安裝,請執行

$ apt-get install -y clang-format

您可以使用以下指令檢查 C/C++ 檔案的格式

$ clang-format <my_cc_file> --style=google > /tmp/my_cc_file.cc
$ diff <my_cc_file> /tmp/my_cc_file.cc

其他語言

TensorFlow 慣例和特殊用法

Python 運算

TensorFlow *運算* 是一種函式,可接受輸入張量並傳回輸出張量 (或在建立圖表時將運算元新增至圖表)。

  • 第一個引數應為張量,後面接著基本 Python 參數。最後一個引數是 name,預設值為 None
  • 張量引數應為單一張量或張量的可迭代物件。也就是說,「張量或張量清單」的範圍太廣。請參閱 assert_proper_iterable
  • 接受張量做為引數的運算應呼叫 convert_to_tensor,以便在使用 C++ 運算時,將非張量輸入轉換為張量。請注意,引數在文件中仍說明為特定 dtype 的 Tensor 物件。
  • 每個 Python 運算都應具有 name_scope。如下所示,傳入運算的名稱做為字串。
  • 運算應包含詳盡的 Python 註解,其中包含 Args 和 Returns 宣告,以說明每個值的類型和意義。可能的形狀、dtype 或等級應在說明中指定。請參閱文件詳細資料。
  • 為了提高可用性,請在「範例」區段中加入運算用法的範例,其中包含運算的輸入/輸出。
  • 避免明確使用 tf.Tensor.evaltf.Session.run。例如,若要編寫取決於張量值的邏輯,請使用 TensorFlow 控制流程。或者,將運算限制為僅在啟用 Eager Execution 時執行 (tf.executing_eagerly())。

範例

def my_op(tensor_in, other_tensor_in, my_param, other_param=0.5,
          output_collections=(), name=None):
  """My operation that adds two tensors with given coefficients.

  Args:
    tensor_in: `Tensor`, input tensor.
    other_tensor_in: `Tensor`, same shape as `tensor_in`, other input tensor.
    my_param: `float`, coefficient for `tensor_in`.
    other_param: `float`, coefficient for `other_tensor_in`.
    output_collections: `tuple` of `string`s, name of the collection to
                        collect result of this op.
    name: `string`, name of the operation.

  Returns:
    `Tensor` of same shape as `tensor_in`, sum of input values with coefficients.

  Example:
    >>> my_op([1., 2.], [3., 4.], my_param=0.5, other_param=0.6,
              output_collections=['MY_OPS'], name='add_t1t2')
    [2.3, 3.4]
  """
  with tf.name_scope(name or "my_op"):
    tensor_in = tf.convert_to_tensor(tensor_in)
    other_tensor_in = tf.convert_to_tensor(other_tensor_in)
    result = my_param * tensor_in + other_param * other_tensor_in
    tf.add_to_collection(output_collections, result)
    return result

用法

output = my_op(t1, t2, my_param=0.5, other_param=0.6,
               output_collections=['MY_OPS'], name='add_t1t2')