1# Copyright 2020 The TensorFlow Authors. All Rights Reserved. 2# 3# Licensed under the Apache License, Version 2.0 (the "License"); 4# you may not use this file except in compliance with the License. 5# You may obtain a copy of the License at 6# 7# http://www.apache.org/licenses/LICENSE-2.0 8# 9# Unless required by applicable law or agreed to in writing, software 10# distributed under the License is distributed on an "AS IS" BASIS, 11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12# See the License for the specific language governing permissions and 13# limitations under the License. 14# ============================================================================== 15"""Config functions for TF NumPy.""" 16 17from tensorflow.python.framework import ops 18from tensorflow.python.ops.numpy_ops import np_dtypes 19from tensorflow.python.ops.numpy_ops import np_export 20from tensorflow.python.ops.numpy_ops import np_math_ops 21 22 23@np_export.np_export("experimental_enable_numpy_behavior") 24def enable_numpy_behavior(prefer_float32=False): 25 """Enable NumPy behavior on Tensors. 26 27 Enabling NumPy behavior has three effects: 28 * It adds to `tf.Tensor` some common NumPy methods such as `T`, 29 `reshape` and `ravel`. 30 * It changes dtype promotion in `tf.Tensor` operators to be 31 compatible with NumPy. For example, 32 `tf.ones([], tf.int32) + tf.ones([], tf.float32)` used to throw a 33 "dtype incompatible" error, but after this it will return a 34 float64 tensor (obeying NumPy's promotion rules). 35 * It enhances `tf.Tensor`'s indexing capability to be on par with 36 [NumPy's](https://numpy.org/doc/stable/reference/arrays.indexing.html). 37 38 Args: 39 prefer_float32: Controls whether dtype inference will use float32 40 for Python floats, or float64 (the default and the 41 NumPy-compatible behavior). 42 """ 43 ops.enable_numpy_style_type_promotion() 44 ops.enable_numpy_style_slicing() 45 np_math_ops.enable_numpy_methods_on_tensor() 46 np_dtypes.set_prefer_float32(prefer_float32) 47