The following issues were found

keras/layers/merge.py
365 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 19 Column: 1

              # pylint: disable=redefined-builtin
"""Layers that can merge several inputs into one."""

import tensorflow.compat.v2 as tf

from keras import backend
from keras.engine import base_layer_utils
from keras.engine.base_layer import Layer
from keras.utils import tf_utils

            

Reported by Pylint.

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

Line: 25 Column: 1

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


class _Merge(Layer):
  """Generic merge layer for elementwise merge functions.


            

Reported by Pylint.

Positional arguments appear to be out of order
Error

Line: 65 Column: 14

                  if None in [shape1, shape2]:
      return None
    elif len(shape1) < len(shape2):
      return self._compute_elemwise_op_output_shape(shape2, shape1)
    elif not shape2:
      return shape1
    output_shape = list(shape1[:-len(shape2)])
    for i, j in zip(shape1[-len(shape2):], shape2):
      if i is None or j is None:

            

Reported by Pylint.

Attribute '_reshape_required' defined outside __init__
Error

Line: 114 Column: 7

                  # If the inputs have different ranks, we have to reshape them
    # to make them broadcastable.
    if None not in input_shape and len(set(map(len, input_shape))) == 1:
      self._reshape_required = False
    else:
      self._reshape_required = True

  def call(self, inputs):
    if not isinstance(inputs, (list, tuple)):

            

Reported by Pylint.

Attribute '_reshape_required' defined outside __init__
Error

Line: 116 Column: 7

                  if None not in input_shape and len(set(map(len, input_shape))) == 1:
      self._reshape_required = False
    else:
      self._reshape_required = True

  def call(self, inputs):
    if not isinstance(inputs, (list, tuple)):
      raise ValueError(
          'A merge layer should be called on a list of inputs. '

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 118 Column: 3

                  else:
      self._reshape_required = True

  def call(self, inputs):
    if not isinstance(inputs, (list, tuple)):
      raise ValueError(
          'A merge layer should be called on a list of inputs. '
          f'Received: inputs={inputs} (not a list of tensors)')
    if self._reshape_required:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 29 Column: 1

              

class _Merge(Layer):
  """Generic merge layer for elementwise merge functions.

  Used to implement `Sum`, `Average`, etc.
  """

  def __init__(self, **kwargs):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 34 Column: 1

                Used to implement `Sum`, `Average`, etc.
  """

  def __init__(self, **kwargs):
    """Initializes a Merge layer.

    Args:
      **kwargs: standard layer keyword arguments.
    """

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 35 Column: 1

                """

  def __init__(self, **kwargs):
    """Initializes a Merge layer.

    Args:
      **kwargs: standard layer keyword arguments.
    """
    super(_Merge, self).__init__(**kwargs)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 40 Column: 1

                  Args:
      **kwargs: standard layer keyword arguments.
    """
    super(_Merge, self).__init__(**kwargs)
    self.supports_masking = True

  def _merge_function(self, inputs):
    raise NotImplementedError


            

Reported by Pylint.

keras/models_test.py
363 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for `models.py` (model cloning, mainly)."""

import tensorflow.compat.v2 as tf

import functools
import os

from absl.testing import parameterized

            

Reported by Pylint.

Unable to import 'absl.testing'
Error

Line: 22 Column: 1

              import functools
import os

from absl.testing import parameterized
import numpy as np

import keras
from keras import backend
from keras import keras_parameterized

            

Reported by Pylint.

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

Line: 34 Column: 1

              from keras import testing_utils


class TestModel(keras.Model):
  """A model subclass."""

  def __init__(self, n_outputs=4, trainable=True):
    """A test class with one dense layer and number of outputs as a variable."""
    super(TestModel, self).__init__()

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 43 Column: 3

                  self.layer1 = keras.layers.Dense(n_outputs)
    self.n_outputs = tf.Variable(n_outputs, trainable=trainable)

  def call(self, x):
    return self.layer1(x)


def _get_layers(input_shape=(4,), add_input_layer=False):
  if add_input_layer:

            

Reported by Pylint.

Access to a protected member _clone_sequential_model of a client class
Error

Line: 96 Column: 11

              
    if share_weights:
      clone_fn = functools.partial(
          keras.models._clone_sequential_model, layer_fn=models.share_weights)
    else:
      clone_fn = keras.models.clone_model

    val_a = np.random.random((10, 4))
    model = models.Sequential(_get_layers(input_shape, add_input_layer))

            

Reported by Pylint.

Access to a protected member _flatten_layers of a client class
Error

Line: 105 Column: 18

                  # Sanity check
    self.assertEqual(
        isinstance(
            list(model._flatten_layers(include_self=False, recursive=False))[0],
            keras.layers.InputLayer), add_input_layer)
    self.assertEqual(model._is_graph_network, add_input_layer)

    # With placeholder creation -- clone model should have an InputLayer
    # if the original model has one.

            

Reported by Pylint.

Access to a protected member _is_graph_network of a client class
Error

Line: 107 Column: 22

                      isinstance(
            list(model._flatten_layers(include_self=False, recursive=False))[0],
            keras.layers.InputLayer), add_input_layer)
    self.assertEqual(model._is_graph_network, add_input_layer)

    # With placeholder creation -- clone model should have an InputLayer
    # if the original model has one.
    new_model = clone_fn(model)
    self.assertEqual(

            

Reported by Pylint.

Access to a protected member _flatten_layers of a client class
Error

Line: 115 Column: 17

                  self.assertEqual(
        isinstance(
            list(
                new_model._flatten_layers(include_self=False,
                                          recursive=False))[0],
            keras.layers.InputLayer), add_input_layer)
    self.assertEqual(new_model._is_graph_network, model._is_graph_network)
    if input_shape and not tf.compat.v1.executing_eagerly_outside_functions():
      # update ops from batch norm needs to be included

            

Reported by Pylint.

Access to a protected member _is_graph_network of a client class
Error

Line: 118 Column: 51

                              new_model._flatten_layers(include_self=False,
                                          recursive=False))[0],
            keras.layers.InputLayer), add_input_layer)
    self.assertEqual(new_model._is_graph_network, model._is_graph_network)
    if input_shape and not tf.compat.v1.executing_eagerly_outside_functions():
      # update ops from batch norm needs to be included
      self.assertGreaterEqual(len(new_model.updates), 2)

    # On top of new tensor  -- clone model should always have an InputLayer.

            

Reported by Pylint.

Access to a protected member _is_graph_network of a client class
Error

Line: 118 Column: 22

                              new_model._flatten_layers(include_self=False,
                                          recursive=False))[0],
            keras.layers.InputLayer), add_input_layer)
    self.assertEqual(new_model._is_graph_network, model._is_graph_network)
    if input_shape and not tf.compat.v1.executing_eagerly_outside_functions():
      # update ops from batch norm needs to be included
      self.assertGreaterEqual(len(new_model.updates), 2)

    # On top of new tensor  -- clone model should always have an InputLayer.

            

Reported by Pylint.

keras/saving/saved_model_experimental_test.py
359 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 18 Column: 1

              # pylint: disable=protected-access
"""Tests for saving/loading function for keras Model."""

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: 23 Column: 1

              import os
import shutil

from absl.testing import parameterized
import numpy as np

import keras
from keras import optimizer_v1
from keras.engine import training as model_lib

            

Reported by Pylint.

Value 'model.input_names' is unsubscriptable
Error

Line: 430 Column: 20

                  with tf.compat.v1.Session(graph=tf.Graph()) as sess:
      inputs, outputs, _ = load_model(sess, saved_model_dir,
                                      mode_keys.ModeKeys.PREDICT)
      input_name = model.input_names[0]
      output_name = model.output_names[0]
      predictions = sess.run(
          outputs[output_name], {inputs[input_name]: [[7], [-3], [4]]})
      self.assertAllEqual([[6], [0], [4]], predictions)


            

Reported by Pylint.

Value 'model.output_names' is unsubscriptable
Error

Line: 431 Column: 21

                    inputs, outputs, _ = load_model(sess, saved_model_dir,
                                      mode_keys.ModeKeys.PREDICT)
      input_name = model.input_names[0]
      output_name = model.output_names[0]
      predictions = sess.run(
          outputs[output_name], {inputs[input_name]: [[7], [-3], [4]]})
      self.assertAllEqual([[6], [0], [4]], predictions)

  def testAssertModelCloneSameObjectsIgnoreOptimizer(self):

            

Reported by Pylint.

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

Line: 176 Column: 5

                  # For now, saving subclassed model should raise an error. It should be
    # avoided later with loading from SavedModel.pb.

    class SubclassedModel(model_lib.Model):

      def __init__(self):
        super(SubclassedModel, self).__init__()
        self.layer1 = keras.layers.Dense(3)
        self.layer2 = keras.layers.Dense(1)

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 183 Column: 7

                      self.layer1 = keras.layers.Dense(3)
        self.layer2 = keras.layers.Dense(1)

      def call(self, inp):
        return self.layer2(self.layer1(inp))

    model = SubclassedModel()

    saved_model_dir = self._save_model_dir()

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 199 Column: 3

                  self.input_spec = keras.layers.InputSpec(shape=[None] * len(input_shape))
    self.built = True

  def call(self, x, training=None):
    if training is None:
      training = keras.backend.learning_phase()
    output = control_flow_util.smart_cond(training, lambda: x * 0,
                                          lambda: tf.identity(x))
    if not tf.executing_eagerly():

            

Reported by Pylint.

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

Line: 239 Column: 1

                return model


class Subclassed(keras.models.Model):

  def __init__(self):
    super(Subclassed, self).__init__()
    self.dense1 = keras.layers.Dense(2)
    self.dense2 = keras.layers.Dense(3)

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 246 Column: 3

                  self.dense1 = keras.layers.Dense(2)
    self.dense2 = keras.layers.Dense(3)

  def call(self, inputs):
    x = self.dense1(inputs)
    x = self.dense2(x)
    return x



            

Reported by Pylint.

standard import "import os" 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


            

Reported by Pylint.

keras/utils/generic_utils_test.py
358 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for Keras generic Python utils."""

import tensorflow.compat.v2 as tf

from functools import partial
import threading

import numpy as np

            

Reported by Pylint.

Instance of 'SerializableNestedInt' has no 'int_obj' member
Error

Line: 303 Column: 48

                      return obj

      def get_config(self):
        return {'value': int(self), 'int_obj': self.int_obj}

      @classmethod
      def from_config(cls, config):
        return cls(**config)


            

Reported by Pylint.

Instance of 'SerializableNestedInt' has no 'fn' member
Error

Line: 349 Column: 43

                      return obj

      def get_config(self):
        return {'value': int(self), 'fn': self.fn}

      @classmethod
      def from_config(cls, config):
        return cls(**config)


            

Reported by Pylint.

Module 'keras.initializers' has no 'ones' member
Error

Line: 376 Column: 28

                def test_serialize_type_object_initializer(self):
    layer = keras.layers.Dense(
        1,
        kernel_initializer=keras.initializers.ones,
        bias_initializer=keras.initializers.zeros)
    config = keras.layers.serialize(layer)
    self.assertEqual(config['config']['bias_initializer']['class_name'],
                     'Zeros')
    self.assertEqual(config['config']['kernel_initializer']['class_name'],

            

Reported by Pylint.

Module 'keras.initializers' has no 'zeros' member
Error

Line: 377 Column: 26

                  layer = keras.layers.Dense(
        1,
        kernel_initializer=keras.initializers.ones,
        bias_initializer=keras.initializers.zeros)
    config = keras.layers.serialize(layer)
    self.assertEqual(config['config']['bias_initializer']['class_name'],
                     'Zeros')
    self.assertEqual(config['config']['kernel_initializer']['class_name'],
                     'Ones')

            

Reported by Pylint.

Access to a protected member _value of a client class
Error

Line: 174 Column: 26

                  new_inst = keras.utils.generic_utils.deserialize_keras_object(config)
    self.assertIsNot(inst, new_inst)
    self.assertIsInstance(new_inst, TestClass)
    self.assertEqual(10, new_inst._value)

    # Make sure registering a new class with same name will fail.
    with self.assertRaisesRegex(ValueError, '.*has already been registered.*'):
      @keras.utils.generic_utils.register_keras_serializable()  # pylint: disable=function-redefined
      class TestClass:  # pylint: disable=function-redefined

            

Reported by Pylint.

Access to a protected member _val of a client class
Error

Line: 216 Column: 25

                  new_inst = keras.utils.generic_utils.deserialize_keras_object(config)
    self.assertIsNot(inst, new_inst)
    self.assertIsInstance(new_inst, OtherTestClass)
    self.assertEqual(5, new_inst._val)

  def test_serialize_custom_function(self):

    @keras.utils.generic_utils.register_keras_serializable()
    def my_fn():

            

Reported by Pylint.

Unused variable 'TestClass'
Error

Line: 246 Column: 7

              
      @keras.utils.generic_utils.register_keras_serializable(  # pylint: disable=unused-variable
          'TestPackage', 'TestClass')
      class TestClass:

        def __init__(self, value):
          self._value = value

  def test_serializable_object(self):

            

Reported by Pylint.

Access to a protected member _shared_object_loading_scope of a client class
Error

Line: 494 Column: 5

                  # nothing.
    obj_id = 1
    obj = MaybeSharedObject()
    generic_utils._shared_object_loading_scope().set(obj_id, obj)
    self.assertIsNone(generic_utils._shared_object_loading_scope().get(obj_id))

  def test_shared_object_loading_scope_returns_shared_obj(self):
    obj_id = 1
    obj = MaybeSharedObject()

            

Reported by Pylint.

Access to a protected member _shared_object_loading_scope of a client class
Error

Line: 495 Column: 23

                  obj_id = 1
    obj = MaybeSharedObject()
    generic_utils._shared_object_loading_scope().set(obj_id, obj)
    self.assertIsNone(generic_utils._shared_object_loading_scope().get(obj_id))

  def test_shared_object_loading_scope_returns_shared_obj(self):
    obj_id = 1
    obj = MaybeSharedObject()
    with generic_utils.SharedObjectLoadingScope() as scope:

            

Reported by Pylint.

keras/utils/composite_tensor_support_test.py
357 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for Keras composite tensor support."""

import tensorflow.compat.v2 as tf

from absl.testing import parameterized

import numpy as np
import scipy.sparse

            

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 scipy.sparse

import keras

            

Reported by Pylint.

Unable to import 'scipy.sparse'
Error

Line: 22 Column: 1

              from absl.testing import parameterized

import numpy as np
import scipy.sparse

import keras
from keras import keras_parameterized
from keras import testing_utils
from keras.engine import input_layer

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 43 Column: 3

                  super(ToDense, self).__init__(**kwargs)
    self._default_value = default_value

  def call(self, inputs):
    if isinstance(inputs, dict):  # Dicts are no longer flattened.
      # Always a single element in these tests.
      inputs = tf.nest.flatten(inputs)[0]

    if isinstance(inputs, tf.RaggedTensor):

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 70 Column: 3

                  self._padding = padding
    self._ragged_rank = ragged_rank

  def call(self, inputs):
    return tf.RaggedTensor.from_tensor(
        inputs, padding=self._padding, ragged_rank=self._ragged_rank)


class ToSparse(Layer):

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 78 Column: 3

              class ToSparse(Layer):
  """Create a sparse tensor based on a given dense tensor."""

  def call(self, inputs):
    indices = tf.where(tf.not_equal(inputs, 0))
    values = tf.gather_nd(inputs, indices)
    shape = tf.shape(inputs, out_type=tf.int64)
    return tf.SparseTensor(indices, values, dense_shape=shape)


            

Reported by Pylint.

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

Line: 85 Column: 1

                  return tf.SparseTensor(indices, values, dense_shape=shape)


class _SubclassModel(keras.Model):
  """A Keras subclass model."""

  def __init__(self, layers, i_layer=None):
    super(_SubclassModel, self).__init__()
    # Note that clone and build doesn't support lists of layers in subclassed

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 101 Column: 3

                def _layer_name_for_i(self, i):
    return "layer{}".format(i)

  def call(self, inputs, **kwargs):
    x = inputs
    for i in range(self.num_layers):
      layer = getattr(self, self._layer_name_for_i(i))
      x = layer(x)
    return x

            

Reported by Pylint.

Unused argument 'kwargs'
Error

Line: 101 Column: 1

                def _layer_name_for_i(self, i):
    return "layer{}".format(i)

  def call(self, inputs, **kwargs):
    x = inputs
    for i in range(self.num_layers):
      layer = getattr(self, self._layer_name_for_i(i))
      x = layer(x)
    return x

            

Reported by Pylint.

Access to a protected member _run_eagerly of a client class
Error

Line: 210 Column: 5

                  # converts the ragged tensor back to a dense tensor.
    layers = [ToRagged(padding=0)]
    model = testing_utils.get_model_from_layers(layers, input_shape=(None,))
    model._run_eagerly = testing_utils.should_run_eagerly()

    # Define some input data with additional padding.
    input_data = np.array([[1, 0, 0], [2, 3, 0]])
    output = model.predict(input_data)


            

Reported by Pylint.

keras/layers/preprocessing/preprocessing_stage_functional_test.py
353 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Functional preprocessing stage tests."""

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

import time
import numpy as np
from keras import keras_parameterized

            

Reported by Pylint.

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

Line: 18 Column: 1

              """Functional preprocessing stage tests."""

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

import time
import numpy as np
from keras import keras_parameterized
from keras.engine import base_preprocessing_layer

            

Reported by Pylint.

Method 'update_state' is abstract in class 'PreprocessingLayer' but is not overridden
Error

Line: 34 Column: 1

              from keras.layers.preprocessing import preprocessing_test_utils


class PL(base_preprocessing_layer.PreprocessingLayer):

  def __init__(self, **kwargs):
    self.adapt_time = None
    self.adapt_count = 0
    super(PL, self).__init__(**kwargs)

            

Reported by Pylint.

Method 'reset_state' is abstract in class 'PreprocessingLayer' but is not overridden
Error

Line: 34 Column: 1

              from keras.layers.preprocessing import preprocessing_test_utils


class PL(base_preprocessing_layer.PreprocessingLayer):

  def __init__(self, **kwargs):
    self.adapt_time = None
    self.adapt_count = 0
    super(PL, self).__init__(**kwargs)

            

Reported by Pylint.

Parameters differ from overridden 'adapt' method
Error

Line: 41 Column: 3

                  self.adapt_count = 0
    super(PL, self).__init__(**kwargs)

  def adapt(self, data, reset_state=True):
    self.adapt_time = time.time()
    self.adapt_count += 1

  def call(self, inputs):
    return inputs + 1

            

Reported by Pylint.

Unused argument 'reset_state'
Error

Line: 41 Column: 25

                  self.adapt_count = 0
    super(PL, self).__init__(**kwargs)

  def adapt(self, data, reset_state=True):
    self.adapt_time = time.time()
    self.adapt_count += 1

  def call(self, inputs):
    return inputs + 1

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 45 Column: 3

                  self.adapt_time = time.time()
    self.adapt_count += 1

  def call(self, inputs):
    return inputs + 1


class PLMerge(PL):


            

Reported by Pylint.

Method 'update_state' is abstract in class 'PreprocessingLayer' but is not overridden
Error

Line: 49 Column: 1

                  return inputs + 1


class PLMerge(PL):

  def call(self, inputs):
    return inputs[0] + inputs[1]



            

Reported by Pylint.

Method 'reset_state' is abstract in class 'PreprocessingLayer' but is not overridden
Error

Line: 49 Column: 1

                  return inputs + 1


class PLMerge(PL):

  def call(self, inputs):
    return inputs[0] + inputs[1]



            

Reported by Pylint.

Method 'reset_state' is abstract in class 'PreprocessingLayer' but is not overridden
Error

Line: 55 Column: 1

                  return inputs[0] + inputs[1]


class PLSplit(PL):

  def call(self, inputs):
    return inputs + 1, inputs - 1



            

Reported by Pylint.

keras/engine/training_dataset_test.py
351 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for training routines."""

import tensorflow.compat.v2 as tf

import io
import sys

import numpy as np

            

Reported by Pylint.

Unable to import 'tensorflow.python.platform'
Error

Line: 29 Column: 1

              from keras import keras_parameterized
from keras import metrics as metrics_module
from keras import testing_utils
from tensorflow.python.platform import tf_logging as logging


class BatchCounterCallback(callbacks.Callback):

  def __init__(self):

            

Reported by Pylint.

__init__ method from base class 'Callback' is not called
Error

Line: 34 Column: 3

              
class BatchCounterCallback(callbacks.Callback):

  def __init__(self):
    self.batch_begin_count = 0
    self.batch_end_count = 0

  def on_batch_begin(self, *args, **kwargs):
    self.batch_begin_count += 1

            

Reported by Pylint.

Unused argument 'kwargs'
Error

Line: 38 Column: 1

                  self.batch_begin_count = 0
    self.batch_end_count = 0

  def on_batch_begin(self, *args, **kwargs):
    self.batch_begin_count += 1

  def on_batch_end(self, *args, **kwargs):
    self.batch_end_count += 1


            

Reported by Pylint.

Unused argument 'args'
Error

Line: 38 Column: 1

                  self.batch_begin_count = 0
    self.batch_end_count = 0

  def on_batch_begin(self, *args, **kwargs):
    self.batch_begin_count += 1

  def on_batch_end(self, *args, **kwargs):
    self.batch_end_count += 1


            

Reported by Pylint.

Unused argument 'args'
Error

Line: 41 Column: 1

                def on_batch_begin(self, *args, **kwargs):
    self.batch_begin_count += 1

  def on_batch_end(self, *args, **kwargs):
    self.batch_end_count += 1


class TestTrainingWithDataset(keras_parameterized.TestCase):


            

Reported by Pylint.

Unused argument 'kwargs'
Error

Line: 41 Column: 1

                def on_batch_begin(self, *args, **kwargs):
    self.batch_begin_count += 1

  def on_batch_end(self, *args, **kwargs):
    self.batch_end_count += 1


class TestTrainingWithDataset(keras_parameterized.TestCase):


            

Reported by Pylint.

Attribute 'w' defined outside __init__
Error

Line: 272 Column: 9

                  class SumLayer(keras.layers.Layer):

      def build(self, _):
        self.w = self.add_weight('w', ())

      def call(self, inputs):
        return keras.backend.sum(inputs, axis=1, keepdims=True) + self.w * 0

    model = keras.Sequential([SumLayer(input_shape=(2,))])

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 274 Column: 7

                    def build(self, _):
        self.w = self.add_weight('w', ())

      def call(self, inputs):
        return keras.backend.sum(inputs, axis=1, keepdims=True) + self.w * 0

    model = keras.Sequential([SumLayer(input_shape=(2,))])
    model.compile(
        'rmsprop', loss='mae', run_eagerly=testing_utils.should_run_eagerly())

            

Reported by Pylint.

Attribute '_stdout' defined outside __init__
Error

Line: 399 Column: 9

                  class CaptureStdout:

      def __enter__(self):
        self._stdout = sys.stdout
        string_io = io.StringIO()
        sys.stdout = string_io
        self._stringio = string_io
        return self


            

Reported by Pylint.

keras/metrics_correctness_test.py
347 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests metrics correctness using Keras model."""

import tensorflow.compat.v2 as tf

from absl.testing import parameterized
import numpy as np

from keras import keras_parameterized

            

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 keras_parameterized
from keras import layers
from keras import losses

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 30 Column: 1

              from keras.utils import losses_utils


def get_multi_io_model():
  inp_1 = layers.Input(shape=(1,), name='input_1')
  inp_2 = layers.Input(shape=(1,), name='input_2')
  x = layers.Dense(3, kernel_initializer='ones', trainable=False)
  out_1 = layers.Dense(
      1, kernel_initializer='ones', name='output_1', trainable=False)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 31 Column: 1

              

def get_multi_io_model():
  inp_1 = layers.Input(shape=(1,), name='input_1')
  inp_2 = layers.Input(shape=(1,), name='input_2')
  x = layers.Dense(3, kernel_initializer='ones', trainable=False)
  out_1 = layers.Dense(
      1, kernel_initializer='ones', name='output_1', trainable=False)
  out_2 = layers.Dense(

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 32 Column: 1

              
def get_multi_io_model():
  inp_1 = layers.Input(shape=(1,), name='input_1')
  inp_2 = layers.Input(shape=(1,), name='input_2')
  x = layers.Dense(3, kernel_initializer='ones', trainable=False)
  out_1 = layers.Dense(
      1, kernel_initializer='ones', name='output_1', trainable=False)
  out_2 = layers.Dense(
      1, kernel_initializer='ones', name='output_2', trainable=False)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

              def get_multi_io_model():
  inp_1 = layers.Input(shape=(1,), name='input_1')
  inp_2 = layers.Input(shape=(1,), name='input_2')
  x = layers.Dense(3, kernel_initializer='ones', trainable=False)
  out_1 = layers.Dense(
      1, kernel_initializer='ones', name='output_1', trainable=False)
  out_2 = layers.Dense(
      1, kernel_initializer='ones', name='output_2', trainable=False)


            

Reported by Pylint.

Variable name "x" doesn't conform to snake_case naming style
Error

Line: 33 Column: 3

              def get_multi_io_model():
  inp_1 = layers.Input(shape=(1,), name='input_1')
  inp_2 = layers.Input(shape=(1,), name='input_2')
  x = layers.Dense(3, kernel_initializer='ones', trainable=False)
  out_1 = layers.Dense(
      1, kernel_initializer='ones', name='output_1', trainable=False)
  out_2 = layers.Dense(
      1, kernel_initializer='ones', name='output_2', trainable=False)


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 34 Column: 1

                inp_1 = layers.Input(shape=(1,), name='input_1')
  inp_2 = layers.Input(shape=(1,), name='input_2')
  x = layers.Dense(3, kernel_initializer='ones', trainable=False)
  out_1 = layers.Dense(
      1, kernel_initializer='ones', name='output_1', trainable=False)
  out_2 = layers.Dense(
      1, kernel_initializer='ones', name='output_2', trainable=False)

  branch_a = [inp_1, x, out_1]

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 36 Column: 1

                x = layers.Dense(3, kernel_initializer='ones', trainable=False)
  out_1 = layers.Dense(
      1, kernel_initializer='ones', name='output_1', trainable=False)
  out_2 = layers.Dense(
      1, kernel_initializer='ones', name='output_2', trainable=False)

  branch_a = [inp_1, x, out_1]
  branch_b = [inp_2, x, out_2]
  return testing_utils.get_multi_io_model(branch_a, branch_b)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 39 Column: 1

                out_2 = layers.Dense(
      1, kernel_initializer='ones', name='output_2', trainable=False)

  branch_a = [inp_1, x, out_1]
  branch_b = [inp_2, x, out_2]
  return testing_utils.get_multi_io_model(branch_a, branch_b)


def custom_generator_multi_io(sample_weights=None):

            

Reported by Pylint.

keras/feature_column/dense_features_v2_test.py
343 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 21 Column: 1

              from __future__ import division
from __future__ import print_function

import tensorflow.compat.v2 as tf

import numpy as np
from tensorflow.python.eager import backprop
from keras import combinations
from keras import keras_parameterized

            

Reported by Pylint.

Unable to import 'tensorflow.python.eager'
Error

Line: 24 Column: 1

              import tensorflow.compat.v2 as tf

import numpy as np
from tensorflow.python.eager import backprop
from keras import combinations
from keras import keras_parameterized
from keras.feature_column import dense_features_v2 as df



            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 31 Column: 1

              

def _initialized_session(config=None):
  sess = tf.compat.v1.Session(config=config)
  sess.run(tf.compat.v1.global_variables_initializer())
  sess.run(tf.compat.v1.tables_initializer())
  return sess



            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 32 Column: 1

              
def _initialized_session(config=None):
  sess = tf.compat.v1.Session(config=config)
  sess.run(tf.compat.v1.global_variables_initializer())
  sess.run(tf.compat.v1.tables_initializer())
  return sess


class DenseFeaturesTest(keras_parameterized.TestCase):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

              def _initialized_session(config=None):
  sess = tf.compat.v1.Session(config=config)
  sess.run(tf.compat.v1.global_variables_initializer())
  sess.run(tf.compat.v1.tables_initializer())
  return sess


class DenseFeaturesTest(keras_parameterized.TestCase):


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 34 Column: 1

                sess = tf.compat.v1.Session(config=config)
  sess.run(tf.compat.v1.global_variables_initializer())
  sess.run(tf.compat.v1.tables_initializer())
  return sess


class DenseFeaturesTest(keras_parameterized.TestCase):

  @combinations.generate(combinations.combine(mode=['graph', 'eager']))

            

Reported by Pylint.

Too many public methods (29/20)
Error

Line: 37 Column: 1

                return sess


class DenseFeaturesTest(keras_parameterized.TestCase):

  @combinations.generate(combinations.combine(mode=['graph', 'eager']))
  def test_retrieving_input(self):
    features = {'a': [0.]}
    dense_features = df.DenseFeatures(tf.feature_column.numeric_column('a'))

            

Reported by Pylint.

Missing class docstring
Error

Line: 37 Column: 1

                return sess


class DenseFeaturesTest(keras_parameterized.TestCase):

  @combinations.generate(combinations.combine(mode=['graph', 'eager']))
  def test_retrieving_input(self):
    features = {'a': [0.]}
    dense_features = df.DenseFeatures(tf.feature_column.numeric_column('a'))

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 39 Column: 1

              
class DenseFeaturesTest(keras_parameterized.TestCase):

  @combinations.generate(combinations.combine(mode=['graph', 'eager']))
  def test_retrieving_input(self):
    features = {'a': [0.]}
    dense_features = df.DenseFeatures(tf.feature_column.numeric_column('a'))
    inputs = self.evaluate(dense_features(features))
    self.assertAllClose([[0.]], inputs)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 40 Column: 3

              class DenseFeaturesTest(keras_parameterized.TestCase):

  @combinations.generate(combinations.combine(mode=['graph', 'eager']))
  def test_retrieving_input(self):
    features = {'a': [0.]}
    dense_features = df.DenseFeatures(tf.feature_column.numeric_column('a'))
    inputs = self.evaluate(dense_features(features))
    self.assertAllClose([[0.]], inputs)


            

Reported by Pylint.

keras/layers/normalization/batch_normalization_test.py
343 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for normalization layers."""

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 combinations
from keras import keras_parameterized

            

Reported by Pylint.

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

Line: 494 Column: 7

              
      # Simulates training-mode with trainable layer.
      # Should use mini-batch statistics.
      with keras.backend.learning_phase_scope(1):
        model = get_model(bn_mean, bn_std)
        model.compile(loss='mse', optimizer='rmsprop')
        out = model.predict(val_a)
        self.assertAllClose(
            (val_a - np.mean(val_a)) / np.std(val_a), out, atol=1e-3)

            

Reported by Pylint.

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

Line: 212 Column: 5

                @keras_parameterized.run_all_keras_modes(always_skip_v1=True)
  def test_eager_batchnorm_in_custom_model_call_with_tf_function(self):

    class MyModel(keras.Model):

      def __init__(self):
        super(MyModel, self).__init__()
        self.bn = keras.layers.BatchNormalization()


            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 219 Column: 7

                      self.bn = keras.layers.BatchNormalization()

      @tf.function()
      def call(self, x, training):
        return self.bn(x, training=training)

    model = MyModel()

    for _ in range(10):

            

Reported by Pylint.

TODO(fchollet): enable in all execution modes when issue with
Error

Line: 473 Column: 3

                  Args:
      layer: Either V1 or V2 of BatchNormalization layer.
    """
    # TODO(fchollet): enable in all execution modes when issue with
    # learning phase setting is resolved.
    with tf.Graph().as_default(), self.cached_session():
      bn_mean = 0.5
      bn_std = 10.
      val_a = np.expand_dims(np.arange(10.), axis=1)

            

Reported by Pylint.

Missing class docstring
Error

Line: 30 Column: 1

              from keras.layers.normalization import batch_normalization_v1


class BatchNormalizationTest(keras_parameterized.TestCase):

  @keras_parameterized.run_all_keras_modes
  def test_basic_batchnorm(self):
    testing_utils.layer_test(
        keras.layers.BatchNormalization,

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 32 Column: 1

              
class BatchNormalizationTest(keras_parameterized.TestCase):

  @keras_parameterized.run_all_keras_modes
  def test_basic_batchnorm(self):
    testing_utils.layer_test(
        keras.layers.BatchNormalization,
        kwargs={
            'momentum': 0.9,

            

Reported by Pylint.

Method could be a function
Error

Line: 33 Column: 3

              class BatchNormalizationTest(keras_parameterized.TestCase):

  @keras_parameterized.run_all_keras_modes
  def test_basic_batchnorm(self):
    testing_utils.layer_test(
        keras.layers.BatchNormalization,
        kwargs={
            'momentum': 0.9,
            'epsilon': 0.1,

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

              class BatchNormalizationTest(keras_parameterized.TestCase):

  @keras_parameterized.run_all_keras_modes
  def test_basic_batchnorm(self):
    testing_utils.layer_test(
        keras.layers.BatchNormalization,
        kwargs={
            'momentum': 0.9,
            'epsilon': 0.1,

            

Reported by Pylint.