Pythonスタイル
PEP 8 Pythonスタイルガイドに従ってください。ただし、TensorFlowでは4文字ではなく2文字の半角空白文字を使用します。Google Pythonスタイルガイドに準拠し、pylint を使用してPythonの変更を確認してください。
pylint
pylint
をインストールしてTensorFlowのカスタムスタイル定義を取得します。
$ pip install pylint
$ wget -O /tmp/pylintrc https://raw.githubusercontent.com/tensorflow/tensorflow/master/tensorflow/tools/ci_build/pylintrc
pylint
でファイルを確認します。
$ pylint --rcfile=/tmp/pylintrc myfile.py
サポートされているPythonバージョン
TensorFlowはPython 3.5以降をサポートしています。 詳しくは、「インストールガイド」を参照してください。
公式およびコミュニティでサポートされているビルドについては、TensorFlow継続的ビルドステータスを参照してください。
C++ コードスタイル
TensorFlow C ++コードへの変更は、Google C ++スタイルガイドに準拠する必要があります。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演算は、指定された入力テンソルが出力テンソルを返す関数です(またはグラフ作成時にグラフにopを追加します)。
- 最初の引数は必ずテンソルで、その後に基本的なPythonパラメータが続きます。最後の引数は
name
で、デフォルト値はNone
です。 - テンソル引数は、単一のテンソルまたは反復可能なテンソルのいずれかである必要があります。つまり、「テンソルまたはテンソルのリスト」では広すぎます。
assert_proper_iterable
を参照してください。 - テンソルを引数として受け取る演算では、
convert_to_tensor
を呼び出して、テンソル以外の入力をテンソルに変換する必要があります(C ++演算を使用している場合)。引数は、ドキュメントでは特定のdtypeのTensor
オブジェクトとして説明されていることに注意してください。 - それぞれのPython演算には、
name_scope
が必要です。 以下に示すように、opの名前を文字列として渡します。 - 演算には、各値のタイプと意味の両方を説明する引数および戻り値について詳しく説明するPythonコメントを記述する必要があります。可能な形状、dtype、またはランクは、説明で指定する必要があります。詳細はドキュメントを参照してください。
- より使いやすくするために、例のセクションにopの入力/出力の使用例を含めてください。
tf.Tensor.eval
またはtf.Session.run
を明示的に使用しないでください。たとえば、テンソル値に依存するロジックを作成するには、TensorFlow制御フローを使用します。または、eager実行が有効な場合(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')