TensorFlow 코드 스타일 가이드
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Python 스타일
TensorFlow가 4개 대신 2개의 공백을 사용하는 것을 제외하고 PEP 8 Python 스타일 가이드를 따르세요. 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 매개변수가 있어야 합니다. 마지막 인수는 기본값이
None
인 name
입니다.
- 텐서 인수는 단일 텐서이거나 반복 가능한 텐서여야 합니다. 즉, "텐서 또는 텐서 목록"이 너무 광범위합니다.
assert_proper_iterable
을 참조하세요.
- 텐서를 인수로 사용하는 연산은 C++ 연산을 사용하는 경우 텐서가 아닌 입력을 텐서로 변환하기 위해
convert_to_tensor
를 호출해야 합니다. 인수는 여전히 설명서에서 특정 dtype의 Tensor
객체로 설명됩니다.
- 각 Python 연산에는
name_scope
가 있어야 합니다. 아래와 같이 op의 이름을 문자열로 전달합니다.
- 연산에는 각 값의 유형과 의미를 모두 설명하는 Args 및 Returns 선언을 포함한 광범위한 Python 주석이 포함되어야 합니다. 설명에서 가능한 형상, dtype 또는 순위가 지정되어야 합니다. 자세한 내용은 설명서를 참조하세요.
- 사용 편의성을 높이려면 예제 섹션에 op의 입력/출력 사용 예를 포함합니다.
tf.Tensor.eval
또는 tf.Session.run
을 명시적으로 사용하지 마세요. 예를 들어, Tensor 값에 의존하는 로직을 작성하려면 TensorFlow 제어 플로우를 사용합니다. 또는 즉시 실행이 활성화된 경우에만 연산이 실행되도록 제한합니다(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')
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2024-02-12(UTC)
[null,null,["최종 업데이트: 2024-02-12(UTC)"],[],[],null,["# TensorFlow code style guide\n\nPython style\n------------\n\nFollow the [PEP 8 Python style\nguide](https://www.python.org/dev/peps/pep-0008/), except TensorFlow uses 2\nspaces instead of 4. Please conform to the\n[Google Python Style Guide](https://github.com/google/styleguide/blob/gh-pages/pyguide.md),\nand use [pylint](https://www.pylint.org/) to check your Python changes.\n\n### pylint\n\nTo install `pylint`: \n\n $ pip install pylint\n\nTo check a file with `pylint` from the TensorFlow source code root directory: \n\n $ pylint --rcfile=tensorflow/tools/ci_build/pylintrc tensorflow/python/keras/losses.py\n\n### Supported Python versions\n\nFor supported Python versions, see the TensorFlow\n[installation guide](https://www.tensorflow.org/install).\n\nSee the TensorFlow\n[continuous build status](https://github.com/tensorflow/tensorflow/blob/master/README.md#continuous-build-status)\nfor official and community supported builds.\n\nC++ coding style\n----------------\n\nChanges to TensorFlow C++ code should conform to the [Google C++ Style\nGuide](https://google.github.io/styleguide/cppguide.html) and [TensorFlow specific style details](https://github.com/tensorflow/community/blob/master/governance/cpp-style.md). Use `clang-format` to check your C/C++ changes.\n\nTo install on Ubuntu 16+, do: \n\n $ apt-get install -y clang-format\n\nYou can check the format of a C/C++ file with the following: \n\n $ clang-format \u003cmy_cc_file\u003e --style=google \u003e /tmp/my_cc_file.cc\n $ diff \u003cmy_cc_file\u003e /tmp/my_cc_file.cc\n\nOther languages\n---------------\n\n- [Google Java Style Guide](https://google.github.io/styleguide/javaguide.html)\n- [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html)\n- [Google Shell Style Guide](https://google.github.io/styleguide/shell.xml)\n- [Google Objective-C Style Guide](https://google.github.io/styleguide/objcguide.html)\n\nTensorFlow conventions and special uses\n---------------------------------------\n\n### Python operations\n\nA TensorFlow *operation* is a function that, given input tensors returns output\ntensors (or adds an op to a graph when building graphs).\n\n- The first argument should be tensors, followed by basic Python parameters. The last argument is `name` with a default value of `None`.\n- Tensor arguments should be either a single tensor or an iterable of tensors. That is, a \"Tensor or list of Tensors\" is too broad. See `assert_proper_iterable`.\n- Operations that take tensors as arguments should call `convert_to_tensor` to convert non-tensor inputs into tensors if they are using C++ operations. Note that the arguments are still described as a `Tensor` object of a specific dtype in the documentation.\n- Each Python operation should have a `name_scope`. As seen below, pass the name of the op as a string.\n- Operations should contain an extensive Python comment with Args and Returns declarations that explain both the type and meaning of each value. Possible shapes, dtypes, or ranks should be specified in the description. See documentation details.\n- For increased usability, include an example of usage with inputs / outputs of the op in Example section.\n- Avoid making explicit use of [`tf.Tensor.eval`](https://www.tensorflow.org/api_docs/python/tf/Tensor#eval) or `tf.Session.run`. For example, to write logic that depends on the Tensor value, use the TensorFlow control flow. Alternatively, restrict the operation to only run when eager execution is enabled ([`tf.executing_eagerly()`](https://www.tensorflow.org/api_docs/python/tf/executing_eagerly)).\n\nExample: \n\n def my_op(tensor_in, other_tensor_in, my_param, other_param=0.5,\n output_collections=(), name=None):\n \"\"\"My operation that adds two tensors with given coefficients.\n\n Args:\n tensor_in: `Tensor`, input tensor.\n other_tensor_in: `Tensor`, same shape as `tensor_in`, other input tensor.\n my_param: `float`, coefficient for `tensor_in`.\n other_param: `float`, coefficient for `other_tensor_in`.\n output_collections: `tuple` of `string`s, name of the collection to\n collect result of this op.\n name: `string`, name of the operation.\n\n Returns:\n `Tensor` of same shape as `tensor_in`, sum of input values with coefficients.\n\n Example:\n \u003e\u003e\u003e my_op([1., 2.], [3., 4.], my_param=0.5, other_param=0.6,\n output_collections=['MY_OPS'], name='add_t1t2')\n [2.3, 3.4]\n \"\"\"\n with tf.name_scope(name or \"my_op\"):\n tensor_in = tf.convert_to_tensor(tensor_in)\n other_tensor_in = tf.convert_to_tensor(other_tensor_in)\n result = my_param * tensor_in + other_param * other_tensor_in\n tf.add_to_collection(output_collections, result)\n return result\n\nUsage: \n\n output = my_op(t1, t2, my_param=0.5, other_param=0.6,\n output_collections=['MY_OPS'], name='add_t1t2')"]]