The following issues were found

keras/premade/linear.py
88 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Built-in linear model classes."""

import tensorflow.compat.v2 as tf
from keras import activations
from keras import initializers
from keras import regularizers
from keras.engine import base_layer
from keras.engine import input_spec

            

Reported by Pylint.

Bad option value 'g-direct-tensorflow-import'
Error

Line: 25 Column: 1

              from keras.engine import input_spec
from keras.engine import training
from keras.layers import core
from tensorflow.python.util import deprecation  # pylint: disable=g-direct-tensorflow-import
from tensorflow.python.util.tf_export import keras_export


@keras_export(
    'keras.experimental.LinearModel',

            

Reported by Pylint.

Unable to import 'tensorflow.python.util'
Error

Line: 25 Column: 1

              from keras.engine import input_spec
from keras.engine import training
from keras.layers import core
from tensorflow.python.util import deprecation  # pylint: disable=g-direct-tensorflow-import
from tensorflow.python.util.tf_export import keras_export


@keras_export(
    'keras.experimental.LinearModel',

            

Reported by Pylint.

Unable to import 'tensorflow.python.util.tf_export'
Error

Line: 26 Column: 1

              from keras.engine import training
from keras.layers import core
from tensorflow.python.util import deprecation  # pylint: disable=g-direct-tensorflow-import
from tensorflow.python.util.tf_export import keras_export


@keras_export(
    'keras.experimental.LinearModel',
    v1=['keras.experimental.LinearModel', 'keras.models.LinearModel'])

            

Reported by Pylint.

Attribute 'input_specs' defined outside __init__
Error

Line: 102 Column: 7

                def build(self, input_shape):
    if isinstance(input_shape, dict):
      names = sorted(list(input_shape.keys()))
      self.input_specs = []
      self.dense_layers = []
      for name in names:
        shape = input_shape[name]
        layer = core.Dense(
            units=self.units,

            

Reported by Pylint.

Attribute 'dense_layers' defined outside __init__
Error

Line: 103 Column: 7

                  if isinstance(input_shape, dict):
      names = sorted(list(input_shape.keys()))
      self.input_specs = []
      self.dense_layers = []
      for name in names:
        shape = input_shape[name]
        layer = core.Dense(
            units=self.units,
            use_bias=False,

            

Reported by Pylint.

Attribute 'dense_layers' defined outside __init__
Error

Line: 118 Column: 7

                      self.dense_layers.append(layer)
    elif isinstance(input_shape, (tuple, list)) and all(
        isinstance(shape, tf.TensorShape) for shape in input_shape):
      self.dense_layers = []
      for shape in input_shape:
        layer = core.Dense(
            units=self.units,
            use_bias=False,
            kernel_initializer=self.kernel_initializer,

            

Reported by Pylint.

Attribute 'dense_layers' defined outside __init__
Error

Line: 135 Column: 7

                        kernel_initializer=self.kernel_initializer,
          kernel_regularizer=self.kernel_regularizer)
      layer.build(input_shape)
      self.dense_layers = [layer]

    if self.use_bias:
      self.bias = self.add_weight(
          'bias',
          shape=self.units,

            

Reported by Pylint.

Attribute 'bias' defined outside __init__
Error

Line: 138 Column: 7

                    self.dense_layers = [layer]

    if self.use_bias:
      self.bias = self.add_weight(
          'bias',
          shape=self.units,
          initializer=self.bias_initializer,
          regularizer=self.bias_regularizer,
          dtype=self.dtype,

            

Reported by Pylint.

Attribute 'bias' defined outside __init__
Error

Line: 146 Column: 7

                        dtype=self.dtype,
          trainable=True)
    else:
      self.bias = None
    self.built = True

  def call(self, inputs):
    result = None
    if isinstance(inputs, dict):

            

Reported by Pylint.

keras/engine/functional_utils.py
88 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 22 Column: 1

              from keras.engine import keras_tensor
from keras.engine import node as node_module

import tensorflow.compat.v2 as tf

_KERAS_TENSOR_TYPE_CHECK_ERROR_MSG = (
    'Found unexpected instance while processing input tensors for keras '
    'functional model. Expecting KerasTensor which is from tf.keras.Input() '
    'or output from keras layer call(). Got: {}')

            

Reported by Pylint.

Context manager 'generator' doesn't implement __enter__ and __exit__.
Error

Line: 245 Column: 3

                  An identical copy of the input KerasTensor.
  """
  # Create a scratch graph since we don't intend to use the placeholders.
  with backend._scratch_graph() as scratch_graph:  # pylint: disable=protected-access
    with scratch_graph.as_default():
      placeholder = keras_tensor.keras_tensor_to_placeholder(kt)
      return keras_tensor.keras_tensor_from_tensor(placeholder)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 31 Column: 1

              

def is_input_keras_tensor(tensor):
  """Check if tensor is directly generated from `tf.keras.Input`.

  This check is useful when constructing the functional model, since we will
  need to clone Nodes and KerasTensors if the model is building from non input
  tensor.


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 46 Column: 1

                Raises:
    ValueError: if the tensor is not a KerasTensor instance.
  """
  if not node_module.is_keras_tensor(tensor):
    raise ValueError(_KERAS_TENSOR_TYPE_CHECK_ERROR_MSG.format(tensor))
  return tensor.node.is_input


def find_nodes_by_inputs_and_outputs(inputs, outputs):

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 47 Column: 1

                  ValueError: if the tensor is not a KerasTensor instance.
  """
  if not node_module.is_keras_tensor(tensor):
    raise ValueError(_KERAS_TENSOR_TYPE_CHECK_ERROR_MSG.format(tensor))
  return tensor.node.is_input


def find_nodes_by_inputs_and_outputs(inputs, outputs):
  """Fetch all Nodes in the graph defined by "inputs" and "outputs".

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 48 Column: 1

                """
  if not node_module.is_keras_tensor(tensor):
    raise ValueError(_KERAS_TENSOR_TYPE_CHECK_ERROR_MSG.format(tensor))
  return tensor.node.is_input


def find_nodes_by_inputs_and_outputs(inputs, outputs):
  """Fetch all Nodes in the graph defined by "inputs" and "outputs".


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 52 Column: 1

              

def find_nodes_by_inputs_and_outputs(inputs, outputs):
  """Fetch all Nodes in the graph defined by "inputs" and "outputs".

  This method is used to find and then clone Nodes when creating a new
  sub-model from an existing functional model.

  Args:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 76 Column: 1

                # The bottom up approach will ensure all the nodes we visit are actually
  # in use. If we reach the top and didn't find the nodes in the `inputs`,
  # that's an error, since the user didn't specify the correct inputs.
  start_keras_tensors = tf.nest.flatten(outputs)
  end_keras_tensors = tf.nest.flatten(inputs)

  for t in start_keras_tensors + end_keras_tensors:
    if not node_module.is_keras_tensor(t):
      raise ValueError(_KERAS_TENSOR_TYPE_CHECK_ERROR_MSG.format(t))

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 77 Column: 1

                # in use. If we reach the top and didn't find the nodes in the `inputs`,
  # that's an error, since the user didn't specify the correct inputs.
  start_keras_tensors = tf.nest.flatten(outputs)
  end_keras_tensors = tf.nest.flatten(inputs)

  for t in start_keras_tensors + end_keras_tensors:
    if not node_module.is_keras_tensor(t):
      raise ValueError(_KERAS_TENSOR_TYPE_CHECK_ERROR_MSG.format(t))
  end_ids = set([id(kt) for kt in end_keras_tensors])

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 79 Column: 1

                start_keras_tensors = tf.nest.flatten(outputs)
  end_keras_tensors = tf.nest.flatten(inputs)

  for t in start_keras_tensors + end_keras_tensors:
    if not node_module.is_keras_tensor(t):
      raise ValueError(_KERAS_TENSOR_TYPE_CHECK_ERROR_MSG.format(t))
  end_ids = set([id(kt) for kt in end_keras_tensors])
  # Track all the end tensors we found so far, if we didn't reach all the
  # user-specified keras inputs after we finish the search, then that's an

            

Reported by Pylint.

keras/mixed_precision/loss_scale_benchmark.py
87 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Benchmarks for LossScaleOptimizer."""

import tensorflow.compat.v2 as tf

import time
from keras.mixed_precision import loss_scale_optimizer
from keras.optimizer_v2 import adam


            

Reported by Pylint.

standard import "import time" should be placed before "import tensorflow.compat.v2 as tf"
Error

Line: 19 Column: 1

              
import tensorflow.compat.v2 as tf

import time
from keras.mixed_precision import loss_scale_optimizer
from keras.optimizer_v2 import adam


def _get_strategy(num_gpus):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 25 Column: 1

              

def _get_strategy(num_gpus):
  if num_gpus > 1:
    return tf.distribute.MirroredStrategy(
        ['/GPU:%d' % i for i in range(num_gpus)])
  else:
    return tf.distribute.get_strategy()  # The default strategy


            

Reported by Pylint.

Unnecessary "else" after "return"
Error

Line: 25 Column: 3

              

def _get_strategy(num_gpus):
  if num_gpus > 1:
    return tf.distribute.MirroredStrategy(
        ['/GPU:%d' % i for i in range(num_gpus)])
  else:
    return tf.distribute.get_strategy()  # The default strategy


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 26 Column: 1

              
def _get_strategy(num_gpus):
  if num_gpus > 1:
    return tf.distribute.MirroredStrategy(
        ['/GPU:%d' % i for i in range(num_gpus)])
  else:
    return tf.distribute.get_strategy()  # The default strategy



            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 28 Column: 1

                if num_gpus > 1:
    return tf.distribute.MirroredStrategy(
        ['/GPU:%d' % i for i in range(num_gpus)])
  else:
    return tf.distribute.get_strategy()  # The default strategy


class LossScaleBenchmark(tf.test.Benchmark):
  """Benchmark for loss scaling."""

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 29 Column: 1

                  return tf.distribute.MirroredStrategy(
        ['/GPU:%d' % i for i in range(num_gpus)])
  else:
    return tf.distribute.get_strategy()  # The default strategy


class LossScaleBenchmark(tf.test.Benchmark):
  """Benchmark for loss scaling."""


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

              

class LossScaleBenchmark(tf.test.Benchmark):
  """Benchmark for loss scaling."""

  def _benchmark(self, gradient_type, num_gpus, mode, loss_scaling):
    """Benchmarks loss scaling.

    We run a simple model with several scalar variables. The loss is the sum of

            

Reported by Pylint.

Too many local variables (21/15)
Error

Line: 35 Column: 3

              class LossScaleBenchmark(tf.test.Benchmark):
  """Benchmark for loss scaling."""

  def _benchmark(self, gradient_type, num_gpus, mode, loss_scaling):
    """Benchmarks loss scaling.

    We run a simple model with several scalar variables. The loss is the sum of
    all variables. The model is simple because we want to measure only the
    performance of loss scaling, not the performance of the model itself.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 35 Column: 1

              class LossScaleBenchmark(tf.test.Benchmark):
  """Benchmark for loss scaling."""

  def _benchmark(self, gradient_type, num_gpus, mode, loss_scaling):
    """Benchmarks loss scaling.

    We run a simple model with several scalar variables. The loss is the sum of
    all variables. The model is simple because we want to measure only the
    performance of loss scaling, not the performance of the model itself.

            

Reported by Pylint.

keras/metrics_functional_test.py
87 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for Keras metrics functions."""

import tensorflow.compat.v2 as tf

from absl.testing import parameterized
import numpy as np

from keras import backend

            

Reported by Pylint.

Unable to import 'absl.testing'
Error

Line: 19 Column: 1

              
import tensorflow.compat.v2 as tf

from absl.testing import parameterized
import numpy as np

from keras import backend
from keras import combinations
from keras import metrics

            

Reported by Pylint.

Missing class docstring
Error

Line: 27 Column: 1

              from keras import metrics


class KerasFunctionalMetricsTest(tf.test.TestCase, parameterized.TestCase):

  def test_metrics(self):
    with self.cached_session():
      y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 29 Column: 1

              
class KerasFunctionalMetricsTest(tf.test.TestCase, parameterized.TestCase):

  def test_metrics(self):
    with self.cached_session():
      y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))
      for metric in [metrics.binary_accuracy, metrics.categorical_accuracy]:
        output = metric(y_a, y_b)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 29 Column: 3

              
class KerasFunctionalMetricsTest(tf.test.TestCase, parameterized.TestCase):

  def test_metrics(self):
    with self.cached_session():
      y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))
      for metric in [metrics.binary_accuracy, metrics.categorical_accuracy]:
        output = metric(y_a, y_b)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 30 Column: 1

              class KerasFunctionalMetricsTest(tf.test.TestCase, parameterized.TestCase):

  def test_metrics(self):
    with self.cached_session():
      y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))
      for metric in [metrics.binary_accuracy, metrics.categorical_accuracy]:
        output = metric(y_a, y_b)
        self.assertEqual(backend.eval(output).shape, (6,))

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 31 Column: 1

              
  def test_metrics(self):
    with self.cached_session():
      y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))
      for metric in [metrics.binary_accuracy, metrics.categorical_accuracy]:
        output = metric(y_a, y_b)
        self.assertEqual(backend.eval(output).shape, (6,))


            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 32 Column: 1

                def test_metrics(self):
    with self.cached_session():
      y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))
      for metric in [metrics.binary_accuracy, metrics.categorical_accuracy]:
        output = metric(y_a, y_b)
        self.assertEqual(backend.eval(output).shape, (6,))

  def test_sparse_categorical_accuracy_int(self):

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 33 Column: 1

                  with self.cached_session():
      y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))
      for metric in [metrics.binary_accuracy, metrics.categorical_accuracy]:
        output = metric(y_a, y_b)
        self.assertEqual(backend.eval(output).shape, (6,))

  def test_sparse_categorical_accuracy_int(self):
    with self.cached_session():

            

Reported by Pylint.

Bad indentation. Found 8 spaces, expected 16
Style

Line: 34 Column: 1

                    y_a = backend.variable(np.random.random((6, 7)))
      y_b = backend.variable(np.random.random((6, 7)))
      for metric in [metrics.binary_accuracy, metrics.categorical_accuracy]:
        output = metric(y_a, y_b)
        self.assertEqual(backend.eval(output).shape, (6,))

  def test_sparse_categorical_accuracy_int(self):
    with self.cached_session():
      metric = metrics.sparse_categorical_accuracy

            

Reported by Pylint.

keras/feature_column/base_feature_layer.py
85 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 24 Column: 1

              from __future__ import division
from __future__ import print_function

import tensorflow.compat.v2 as tf

import collections
import re
from keras.engine.base_layer import Layer
from keras.utils import generic_utils

            

Reported by Pylint.

Parameters differ from overridden 'from_config' method
Error

Line: 131 Column: 3

                  return dict(list(base_config.items()) + list(config.items()))

  @classmethod
  def from_config(cls, config, custom_objects=None):
    config_cp = config.copy()
    columns_by_name = {}
    config_cp['feature_columns'] = [tf.__internal__.feature_column.deserialize_feature_column(
        c, custom_objects, columns_by_name) for c in config['feature_columns']]
    config_cp['partitioner'] = generic_utils.deserialize_keras_object(

            

Reported by Pylint.

standard import "import collections" should be placed before "import tensorflow.compat.v2 as tf"
Error

Line: 26 Column: 1

              
import tensorflow.compat.v2 as tf

import collections
import re
from keras.engine.base_layer import Layer
from keras.utils import generic_utils



            

Reported by Pylint.

standard import "import re" should be placed before "import tensorflow.compat.v2 as tf"
Error

Line: 27 Column: 1

              import tensorflow.compat.v2 as tf

import collections
import re
from keras.engine.base_layer import Layer
from keras.utils import generic_utils


class _BaseFeaturesLayer(Layer):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

              

class _BaseFeaturesLayer(Layer):
  """Base class for DenseFeatures and SequenceFeatures.

  Defines common methods and helpers.

  Args:
    feature_columns: An iterable containing the FeatureColumns to use as

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 51 Column: 1

                    `expected_column_type`.
  """

  def __init__(self,
               feature_columns,
               expected_column_type,
               trainable,
               name,
               partitioner=None,

            

Reported by Pylint.

Too many arguments (6/5)
Error

Line: 51 Column: 3

                    `expected_column_type`.
  """

  def __init__(self,
               feature_columns,
               expected_column_type,
               trainable,
               name,
               partitioner=None,

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 58 Column: 5

                             name,
               partitioner=None,
               **kwargs):
    super(_BaseFeaturesLayer, self).__init__(
        name=name, trainable=trainable, **kwargs)
    self._feature_columns = _normalize_feature_columns(
        feature_columns)
    self._state_manager = tf.__internal__.feature_column.StateManager(  # pylint: disable=protected-access
        self, self.trainable)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 58 Column: 1

                             name,
               partitioner=None,
               **kwargs):
    super(_BaseFeaturesLayer, self).__init__(
        name=name, trainable=trainable, **kwargs)
    self._feature_columns = _normalize_feature_columns(
        feature_columns)
    self._state_manager = tf.__internal__.feature_column.StateManager(  # pylint: disable=protected-access
        self, self.trainable)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 60 Column: 1

                             **kwargs):
    super(_BaseFeaturesLayer, self).__init__(
        name=name, trainable=trainable, **kwargs)
    self._feature_columns = _normalize_feature_columns(
        feature_columns)
    self._state_manager = tf.__internal__.feature_column.StateManager(  # pylint: disable=protected-access
        self, self.trainable)
    self._partitioner = partitioner
    for column in self._feature_columns:

            

Reported by Pylint.

keras/layers/preprocessing/category_crossing.py
83 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Keras category crossing preprocessing layers."""

import tensorflow.compat.v2 as tf
# pylint: disable=g-classes-have-attributes

import itertools
import numpy as np
from keras.engine import base_layer

            

Reported by Pylint.

Bad option value 'g-classes-have-attributes'
Error

Line: 18 Column: 1

              """Keras category crossing preprocessing layers."""

import tensorflow.compat.v2 as tf
# pylint: disable=g-classes-have-attributes

import itertools
import numpy as np
from keras.engine import base_layer
from keras.engine import base_preprocessing_layer

            

Reported by Pylint.

Unable to import 'tensorflow.python.util.tf_export'
Error

Line: 25 Column: 1

              from keras.engine import base_layer
from keras.engine import base_preprocessing_layer
from keras.utils import tf_utils
from tensorflow.python.util.tf_export import keras_export


@keras_export('keras.layers.experimental.preprocessing.CategoryCrossing')
class CategoryCrossing(base_layer.Layer):
  """Category crossing layer.

            

Reported by Pylint.

TODO(momernick): Support separator with ragged_cross.
Error

Line: 122 Column: 3

                  """Gets the crossed output from a partial list/tuple of inputs."""
    # If ragged_out=True, convert output from sparse to ragged.
    if ragged_out:
      # TODO(momernick): Support separator with ragged_cross.
      if self.separator != '_X_':
        raise ValueError(
            f'Non-default separator with ragged input is not implemented. '
            f'Received separator: {self.separator}.')
      return tf.ragged.cross(partial_inputs)

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 141 Column: 3

                    inp = tf.expand_dims(inp, axis=-1)
    return inp

  def call(self, inputs):
    inputs = [self._preprocess_input(inp) for inp in inputs]
    depth_tuple = self._depth_tuple if self.depth else (len(inputs),)
    ragged_out = sparse_out = False
    if any(tf_utils.is_ragged(inp) for inp in inputs):
      ragged_out = True

            

Reported by Pylint.

Parameters differ from overridden 'compute_output_signature' method
Error

Line: 182 Column: 3

                  output_shape = [batch_size, None]
    return tf.TensorShape(output_shape)

  def compute_output_signature(self, input_spec):
    input_shapes = [x.shape for x in input_spec]
    output_shape = self.compute_output_shape(input_shapes)
    if any(
        isinstance(inp_spec, tf.RaggedTensorSpec)
        for inp_spec in input_spec):

            

Reported by Pylint.

standard import "import itertools" should be placed before "import tensorflow.compat.v2 as tf"
Error

Line: 20 Column: 1

              import tensorflow.compat.v2 as tf
# pylint: disable=g-classes-have-attributes

import itertools
import numpy as np
from keras.engine import base_layer
from keras.engine import base_preprocessing_layer
from keras.utils import tf_utils
from tensorflow.python.util.tf_export import keras_export

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 30 Column: 1

              
@keras_export('keras.layers.experimental.preprocessing.CategoryCrossing')
class CategoryCrossing(base_layer.Layer):
  """Category crossing layer.

  This layer concatenates multiple categorical inputs into a single categorical
  output (similar to Cartesian product). The output dtype is string.

  Usage:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 107 Column: 1

                  `[[b'1_X_2_X_3'], [b'4_X_5_X_6']]`
  """

  def __init__(self, depth=None, name=None, separator='_X_', **kwargs):
    super(CategoryCrossing, self).__init__(name=name, **kwargs)
    base_preprocessing_layer.keras_kpl_gauge.get_cell(
        'CategoryCrossing').set(True)
    self.depth = depth
    self.separator = separator

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 108 Column: 5

                """

  def __init__(self, depth=None, name=None, separator='_X_', **kwargs):
    super(CategoryCrossing, self).__init__(name=name, **kwargs)
    base_preprocessing_layer.keras_kpl_gauge.get_cell(
        'CategoryCrossing').set(True)
    self.depth = depth
    self.separator = separator
    if isinstance(depth, (tuple, list)):

            

Reported by Pylint.

keras/engine/control_flow_test.py
83 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for dynamic control flow behavior with Keras."""

import tensorflow.compat.v2 as tf

from absl.testing import parameterized
import numpy as np

import keras

            

Reported by Pylint.

Unable to import 'absl.testing'
Error

Line: 19 Column: 1

              
import tensorflow.compat.v2 as tf

from absl.testing import parameterized
import numpy as np

import keras
from keras import keras_parameterized
from keras import testing_utils

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 32 Column: 3

              class ControlFlowLayer1(base_layer.Layer):
  """Layer with an `if` condition in call."""

  def call(self, inputs):
    if tf.reduce_sum(inputs) > 0:
      return tf.sqrt(inputs)
    else:
      return tf.square(inputs)


            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 42 Column: 3

              class ControlFlowLayer2(base_layer.Layer):
  """Layer with a `for` loop in call."""

  def call(self, inputs):
    samples = tf.TensorArray(
        dtype=tf.float32, size=tf.shape(inputs)[0])
    i = 0
    for sample in inputs:
      samples = samples.write(i, tf.square(sample))

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 59 Column: 3

                  super(NestedControlFlowLayer, self).__init__(**kwargs)
    self.layer = ControlFlowLayer1()

  def call(self, inputs):
    return self.layer(inputs)


class ControlFlowModel(keras.Model):
  """Model with an `if` condition in call."""

            

Reported by Pylint.

Method 'get_config' is abstract in class 'Model' but is not overridden
Error

Line: 63 Column: 1

                  return self.layer(inputs)


class ControlFlowModel(keras.Model):
  """Model with an `if` condition in call."""

  def call(self, inputs):
    if tf.reduce_sum(inputs) > 0:
      return tf.sqrt(inputs)

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 66 Column: 3

              class ControlFlowModel(keras.Model):
  """Model with an `if` condition in call."""

  def call(self, inputs):
    if tf.reduce_sum(inputs) > 0:
      return tf.sqrt(inputs)
    else:
      return tf.square(inputs)


            

Reported by Pylint.

Method 'get_config' is abstract in class 'Model' but is not overridden
Error

Line: 73 Column: 1

                    return tf.square(inputs)


class NestedControlFlowModel(keras.Model):
  """Model with an `if` condition in call using a control flow layer."""

  def __init__(self, **kwargs):
    super(NestedControlFlowModel, self).__init__(**kwargs)
    self.layer = NestedControlFlowLayer()

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 80 Column: 3

                  super(NestedControlFlowModel, self).__init__(**kwargs)
    self.layer = NestedControlFlowLayer()

  def call(self, inputs):
    inputs = self.layer(inputs)
    if tf.reduce_sum(inputs) > 0:
      return tf.sqrt(inputs)
    else:
      return tf.square(inputs)

            

Reported by Pylint.

Method 'get_config' is abstract in class 'Model' but is not overridden
Error

Line: 88 Column: 1

                    return tf.square(inputs)


class FunctionControlFlowModel(keras.Model):
  """Model with control flow where `call` is wrapped in function already."""

  @tf.function
  def call(self, inputs):
    if tf.reduce_sum(inputs) > 0:

            

Reported by Pylint.

keras/layers/preprocessing/benchmarks/index_lookup_forward_benchmark.py
82 issues
Unable to import 'tensorflow'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Benchmark for Keras text vectorization preprocessing layer's adapt method."""

import tensorflow as tf

import os
import random
import string
import time

            

Reported by Pylint.

Unable to import 'keras'
Error

Line: 26 Column: 1

              
import numpy as np

import keras
from keras.layers.preprocessing import index_lookup

tf.compat.v1.enable_v2_behavior()



            

Reported by Pylint.

Unable to import 'keras.layers.preprocessing'
Error

Line: 27 Column: 1

              import numpy as np

import keras
from keras.layers.preprocessing import index_lookup

tf.compat.v1.enable_v2_behavior()


# word_gen creates random sequences of ASCII letters (both lowercase and upper).

            

Reported by Pylint.

Bad option value 'g-complex-comprehension'
Error

Line: 48 Column: 1

              
def get_vocab():
  vocab = list(
      set([a + b for a in string.ascii_letters for b in string.ascii_letters]))  # pylint:disable=g-complex-comprehension
  vocab.sort()
  return vocab


# This class uses TestCase for get_temp_dir().

            

Reported by Pylint.

standard import "import os" should be placed before "import tensorflow as tf"
Error

Line: 19 Column: 1

              
import tensorflow as tf

import os
import random
import string
import time

import numpy as np

            

Reported by Pylint.

standard import "import random" should be placed before "import tensorflow as tf"
Error

Line: 20 Column: 1

              import tensorflow as tf

import os
import random
import string
import time

import numpy as np


            

Reported by Pylint.

standard import "import string" should be placed before "import tensorflow as tf"
Error

Line: 21 Column: 1

              
import os
import random
import string
import time

import numpy as np

import keras

            

Reported by Pylint.

standard import "import time" should be placed before "import tensorflow as tf"
Error

Line: 22 Column: 1

              import os
import random
import string
import time

import numpy as np

import keras
from keras.layers.preprocessing import index_lookup

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 34 Column: 1

              
# word_gen creates random sequences of ASCII letters (both lowercase and upper).
# The number of unique strings is ~2,700.
def tensor_gen(batch, num_elements):
  data = []
  for _ in range(batch):
    batch_element = []
    for _ in range(num_elements - 1):
      tok = "".join(random.choice(string.ascii_letters) for i in range(2))

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 35 Column: 1

              # word_gen creates random sequences of ASCII letters (both lowercase and upper).
# The number of unique strings is ~2,700.
def tensor_gen(batch, num_elements):
  data = []
  for _ in range(batch):
    batch_element = []
    for _ in range(num_elements - 1):
      tok = "".join(random.choice(string.ascii_letters) for i in range(2))
      batch_element.append(tok)

            

Reported by Pylint.

keras/regularizers.py
82 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Built-in regularizers."""

import tensorflow.compat.v2 as tf
# pylint: disable=invalid-name

import math

from keras import backend

            

Reported by Pylint.

Unable to import 'tensorflow.python.util.tf_export'
Error

Line: 25 Column: 1

              from keras import backend
from keras.utils.generic_utils import deserialize_keras_object
from keras.utils.generic_utils import serialize_keras_object
from tensorflow.python.util.tf_export import keras_export


def _check_penalty_number(x):
  """check penalty number availability, raise ValueError if failed."""
  if not isinstance(x, (float, int)):

            

Reported by Pylint.

standard import "import math" should be placed before "import tensorflow.compat.v2 as tf"
Error

Line: 20 Column: 1

              import tensorflow.compat.v2 as tf
# pylint: disable=invalid-name

import math

from keras import backend
from keras.utils.generic_utils import deserialize_keras_object
from keras.utils.generic_utils import serialize_keras_object
from tensorflow.python.util.tf_export import keras_export

            

Reported by Pylint.

third party import "from tensorflow.python.util.tf_export import keras_export" should be placed before "from keras import backend"
Error

Line: 25 Column: 1

              from keras import backend
from keras.utils.generic_utils import deserialize_keras_object
from keras.utils.generic_utils import serialize_keras_object
from tensorflow.python.util.tf_export import keras_export


def _check_penalty_number(x):
  """check penalty number availability, raise ValueError if failed."""
  if not isinstance(x, (float, int)):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 29 Column: 1

              

def _check_penalty_number(x):
  """check penalty number availability, raise ValueError if failed."""
  if not isinstance(x, (float, int)):
    raise ValueError(
        f'Value: {x} is not a valid regularization penalty number, '
        'expected an int or float value')


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 30 Column: 1

              
def _check_penalty_number(x):
  """check penalty number availability, raise ValueError if failed."""
  if not isinstance(x, (float, int)):
    raise ValueError(
        f'Value: {x} is not a valid regularization penalty number, '
        'expected an int or float value')

  if math.isinf(x) or math.isnan(x):

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 31 Column: 1

              def _check_penalty_number(x):
  """check penalty number availability, raise ValueError if failed."""
  if not isinstance(x, (float, int)):
    raise ValueError(
        f'Value: {x} is not a valid regularization penalty number, '
        'expected an int or float value')

  if math.isinf(x) or math.isnan(x):
    raise ValueError(

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 35 Column: 1

                      f'Value: {x} is not a valid regularization penalty number, '
        'expected an int or float value')

  if math.isinf(x) or math.isnan(x):
    raise ValueError(
        f'Value: {x} is not a valid regularization penalty number, '
        'an infinity nubmer or NaN are not valid value')



            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 36 Column: 1

                      'expected an int or float value')

  if math.isinf(x) or math.isnan(x):
    raise ValueError(
        f'Value: {x} is not a valid regularization penalty number, '
        'an infinity nubmer or NaN are not valid value')


def _none_to_default(inputs, default):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 42 Column: 1

              

def _none_to_default(inputs, default):
  return default if inputs is None else default


@keras_export('keras.regularizers.Regularizer')
class Regularizer:
  """Regularizer base class.

            

Reported by Pylint.

keras/saving/metrics_serialization_test.py
82 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for Keras metrics serialization."""

import tensorflow.compat.v2 as tf

import os
import shutil

from absl.testing import parameterized

            

Reported by Pylint.

Unable to import 'absl.testing'
Error

Line: 22 Column: 1

              import os
import shutil

from absl.testing import parameterized
import numpy as np

import keras
from keras import keras_parameterized
from keras import layers

            

Reported by Pylint.

Bad option value 'g-import-not-at-top'
Error

Line: 34 Column: 1

              from keras.utils import generic_utils

try:
  import h5py  # pylint:disable=g-import-not-at-top
except ImportError:
  h5py = None


# Custom metric

            

Reported by Pylint.

standard import "import os" should be placed before "import tensorflow.compat.v2 as tf"
Error

Line: 19 Column: 1

              
import tensorflow.compat.v2 as tf

import os
import shutil

from absl.testing import parameterized
import numpy as np


            

Reported by Pylint.

standard import "import shutil" should be placed before "import tensorflow.compat.v2 as tf"
Error

Line: 20 Column: 1

              import tensorflow.compat.v2 as tf

import os
import shutil

from absl.testing import parameterized
import numpy as np

import keras

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 34 Column: 1

              from keras.utils import generic_utils

try:
  import h5py  # pylint:disable=g-import-not-at-top
except ImportError:
  h5py = None


# Custom metric

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 36 Column: 1

              try:
  import h5py  # pylint:disable=g-import-not-at-top
except ImportError:
  h5py = None


# Custom metric
class MyMeanAbsoluteError(metrics.MeanMetricWrapper):


            

Reported by Pylint.

Missing class docstring
Error

Line: 40 Column: 1

              

# Custom metric
class MyMeanAbsoluteError(metrics.MeanMetricWrapper):

  def __init__(self, name='my_mae', dtype=None):
    super(MyMeanAbsoluteError, self).__init__(_my_mae, name, dtype=dtype)



            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 42 Column: 1

              # Custom metric
class MyMeanAbsoluteError(metrics.MeanMetricWrapper):

  def __init__(self, name='my_mae', dtype=None):
    super(MyMeanAbsoluteError, self).__init__(_my_mae, name, dtype=dtype)


# Custom metric function
def _my_mae(y_true, y_pred):

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 43 Column: 1

              class MyMeanAbsoluteError(metrics.MeanMetricWrapper):

  def __init__(self, name='my_mae', dtype=None):
    super(MyMeanAbsoluteError, self).__init__(_my_mae, name, dtype=dtype)


# Custom metric function
def _my_mae(y_true, y_pred):
  return keras.backend.mean(tf.abs(y_pred - y_true), axis=-1)

            

Reported by Pylint.