The following issues were found

keras/optimizer_v2/learning_rate_schedule.py
269 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Various learning rate decay functions."""

import tensorflow.compat.v2 as tf

import abc
import math
from keras.utils import generic_utils
from tensorflow.python.util.tf_export import keras_export

            

Reported by Pylint.

Unable to import 'keras.utils'
Error

Line: 21 Column: 1

              
import abc
import math
from keras.utils import generic_utils
from tensorflow.python.util.tf_export import keras_export


@keras_export("keras.optimizers.schedules.LearningRateSchedule")
class LearningRateSchedule:

            

Reported by Pylint.

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

Line: 22 Column: 1

              import abc
import math
from keras.utils import generic_utils
from tensorflow.python.util.tf_export import keras_export


@keras_export("keras.optimizers.schedules.LearningRateSchedule")
class LearningRateSchedule:
  """The learning rate schedule base class.

            

Reported by Pylint.

Too many lines in module (1083/1000)
Error

Line: 1 Column: 1

              # Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software

            

Reported by Pylint.

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

Line: 19 Column: 1

              
import tensorflow.compat.v2 as tf

import abc
import math
from keras.utils import generic_utils
from tensorflow.python.util.tf_export import keras_export



            

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

import abc
import math
from keras.utils import generic_utils
from tensorflow.python.util.tf_export import keras_export


@keras_export("keras.optimizers.schedules.LearningRateSchedule")

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 27 Column: 1

              
@keras_export("keras.optimizers.schedules.LearningRateSchedule")
class LearningRateSchedule:
  """The learning rate schedule base class.

  You can use a learning rate schedule to modulate how the learning rate
  of your optimizer changes over time.

  Several built-in learning rate schedules are available, such as

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 69 Column: 1

                ```
  """

  @abc.abstractmethod
  def __call__(self, step):
    raise NotImplementedError("Learning rate schedule must override __call__")

  @abc.abstractmethod
  def get_config(self):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 70 Column: 1

                """

  @abc.abstractmethod
  def __call__(self, step):
    raise NotImplementedError("Learning rate schedule must override __call__")

  @abc.abstractmethod
  def get_config(self):
    raise NotImplementedError("Learning rate schedule must override get_config")

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 71 Column: 1

              
  @abc.abstractmethod
  def __call__(self, step):
    raise NotImplementedError("Learning rate schedule must override __call__")

  @abc.abstractmethod
  def get_config(self):
    raise NotImplementedError("Learning rate schedule must override get_config")


            

Reported by Pylint.

keras/callbacks_v1.py
266 issues
Bad option value 'g-import-not-at-top'
Error

Line: 15 Column: 1

              # See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=g-import-not-at-top
# pylint: disable=g-classes-have-attributes
"""Callbacks: utilities called at certain points during model training."""

import tensorflow.compat.v2 as tf


            

Reported by Pylint.

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

Line: 16 Column: 1

              # limitations under the License.
# ==============================================================================
# pylint: disable=g-import-not-at-top
# pylint: disable=g-classes-have-attributes
"""Callbacks: utilities called at certain points during model training."""

import tensorflow.compat.v2 as tf

import os

            

Reported by Pylint.

Unable to import 'tensorflow.compat.v2'
Error

Line: 19 Column: 1

              # pylint: disable=g-classes-have-attributes
"""Callbacks: utilities called at certain points during model training."""

import tensorflow.compat.v2 as tf

import os
import numpy as np
from keras import backend as K
from keras import callbacks

            

Reported by Pylint.

Unable to import 'tensorflow.python.platform'
Error

Line: 25 Column: 1

              import numpy as np
from keras import backend as K
from keras import callbacks
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export


@keras_export(v1=['keras.callbacks.TensorBoard'])
class TensorBoard(callbacks.TensorBoard):

            

Reported by Pylint.

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

Line: 26 Column: 1

              from keras import backend as K
from keras import callbacks
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.util.tf_export import keras_export


@keras_export(v1=['keras.callbacks.TensorBoard'])
class TensorBoard(callbacks.TensorBoard):
  # pylint: disable=line-too-long

            

Reported by Pylint.

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

Line: 238 Column: 1

                  # visualize embeddings.
    if self.embeddings_freq and self.embeddings_data is not None:
      # Avoid circular dependency.
      from keras.engine import training_utils_v1  # pylint: disable=g-import-not-at-top
      self.embeddings_data = training_utils_v1.standardize_input_data(
          self.embeddings_data, model.input_names)

      # If embedding_layer_names are not provided, get all of the embedding
      # layers from the model.

            

Reported by Pylint.

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

Line: 106 Column: 3

              
  # pylint: enable=line-too-long

  def __init__(self,
               log_dir='./logs',
               histogram_freq=0,
               batch_size=32,
               write_graph=True,
               write_grads=False,

            

Reported by Pylint.

__init__ method from a non direct base class 'Callback' is called
Error

Line: 120 Column: 5

                             update_freq='epoch',
               profile_batch=2):
    # Don't call super's init since it is an eager-only version.
    callbacks.Callback.__init__(self)
    self.log_dir = log_dir
    self.histogram_freq = histogram_freq
    if self.histogram_freq and tf.executing_eagerly():
      logging.warning(
          UserWarning('Weight and gradient histograms not supported for eager'

            

Reported by Pylint.

TODO(fishx): Add a link to the full profiler tutorial.
Error

Line: 146 Column: 3

                    self.update_freq = update_freq
    self._samples_seen = 0
    self._samples_seen_at_last_write = 0
    # TODO(fishx): Add a link to the full profiler tutorial.
    self._profile_batch = profile_batch
    # True when the profiler was successfully started by this callback.
    # We track the status here to make sure callbacks do not interfere with
    # each other. The callback will only stop the profiler it started.
    self._profiler_started = False

            

Reported by Pylint.

Attribute 'writer' defined outside __init__
Error

Line: 160 Column: 7

                def _init_writer(self, model):
    """Sets file writer."""
    if tf.executing_eagerly():
      self.writer = tf.summary.create_file_writer(self.log_dir)
      if not model.run_eagerly and self.write_graph:
        with self.writer.as_default():
          tf.summary.graph(K.get_graph())
    elif self.write_graph:
      self.writer = tf.compat.v1.summary.FileWriter(self.log_dir, K.get_graph())

            

Reported by Pylint.

keras/engine/training_arrays_v1.py
266 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Part of the Keras training engine related to plain array data."""

import tensorflow.compat.v2 as tf
# pylint: disable=protected-access

import functools

import numpy as np

            

Reported by Pylint.

Unable to import 'tensorflow.python.platform'
Error

Line: 30 Column: 1

              from keras.utils.generic_utils import make_batches
from keras.utils.generic_utils import slice_arrays
from keras.utils.mode_keys import ModeKeys
from tensorflow.python.platform import tf_logging as logging

try:
  from scipy.sparse import issparse  # pylint: disable=g-import-not-at-top
except ImportError:
  issparse = None

            

Reported by Pylint.

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

Line: 33 Column: 1

              from tensorflow.python.platform import tf_logging as logging

try:
  from scipy.sparse import issparse  # pylint: disable=g-import-not-at-top
except ImportError:
  issparse = None


def model_iteration(model,

            

Reported by Pylint.

Generator 'generator' has no '__enter__' member
Error

Line: 143 Column: 5

                  scope = distributed_training_utils_v1.distributed_scope(
        strategy=model._distribution_strategy,
        learning_phase=(1 if mode == ModeKeys.TRAIN else 0))
    scope.__enter__()

  use_steps = is_dataset or steps_per_epoch is not None
  do_validation = val_inputs is not None

  # Prepare input data.

            

Reported by Pylint.

Generator 'generator' has no '__exit__' member
Error

Line: 444 Column: 5

                  if model._compile_distribution:
      # TODO(priyag, psv): Copy back metrics to the original model as well?
      distributed_training_utils_v1._copy_weights_to_original_model(model, mode)
    scope.__exit__(None, None, None)

  if mode == ModeKeys.TRAIN:
    return model.history
  return results


            

Reported by Pylint.

TODO(fchollet): consider moving `steps_per_epoch` inference to
Error

Line: 128 Column: 3

                input_iterator = None
  is_dataset = isinstance(inputs,
                          (tf.compat.v1.data.Dataset, tf.data.Dataset))
  # TODO(fchollet): consider moving `steps_per_epoch` inference to
  # _standardize_user_data and set reset_dataset_after_each_epoch as an
  # attribute on the dataset instance.
  if is_dataset:
    if steps_per_epoch is None:
      reset_dataset_after_each_epoch = True

            

Reported by Pylint.

TODO(b/133517906): Add slicing support.
Error

Line: 352 Column: 3

                        # If we only have one batch, do not slice. This takes care of
          # composite tensors in non-Dataset modes; we currently don't support
          # slicing them.
          # TODO(b/133517906): Add slicing support.
          ins_batch = ins
        else:
          try:
            if ins and isinstance(ins[-1], int):
              # Do not slice the training phase flag.

            

Reported by Pylint.

Consider explicitly re-raising using the 'from' keyword
Error

Line: 362 Column: 13

                          else:
              ins_batch = slice_arrays(ins, batch_ids)
          except TypeError:
            raise TypeError('TypeError while preparing batch. '
                            'If using HDF5 input data, '
                            'pass shuffle="batch".')

        # Sparse to dense conversion.
        if issparse is not None:

            

Reported by Pylint.

TODO(priyag, psv): Copy back metrics to the original model as well?
Error

Line: 442 Column: 3

              
  if model._distribution_strategy:
    if model._compile_distribution:
      # TODO(priyag, psv): Copy back metrics to the original model as well?
      distributed_training_utils_v1._copy_weights_to_original_model(model, mode)
    scope.__exit__(None, None, None)

  if mode == ModeKeys.TRAIN:
    return model.history

            

Reported by Pylint.

TODO(priyag,omalleyt): Either we should move the training DS with
Error

Line: 504 Column: 3

                  # a lambda from here that can be called. Note that this is applicable only
    # in Distribution Strategy case as it follows the same code path for both
    # eager and graph modes.
    # TODO(priyag,omalleyt): Either we should move the training DS with
    # IteratorBase to use training_generator code path, or figure out how to
    # set a symbolic Iterator out of a Dataset when in eager mode.
    if tf.executing_eagerly():
      return get_distributed_inputs
    else:

            

Reported by Pylint.

keras/distribute/minimize_loss_test.py
265 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for running legacy optimizer code with DistributionStrategy."""

import tensorflow.compat.v2 as tf

from absl.testing import parameterized
import numpy
from keras.distribute import optimizer_combinations
from keras.distribute.test_example import batchnorm_example

            

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
from keras.distribute import optimizer_combinations
from keras.distribute.test_example import batchnorm_example
from keras.distribute.test_example import minimize_loss_example
from keras.layers import core

            

Reported by Pylint.

Access to a protected member _name of a client class
Error

Line: 193 Column: 16

                    run_step()

      def get_expected_variables(num_parameter_devices):
        name = optimizer._name

        if isinstance(optimizer, optimizer_v2.OptimizerV2):
          variables = VAR_MAP_V2[name]
        else:
          variables = VAR_MAP_V1[name]

            

Reported by Pylint.

TODO(isaprykin): Allow False here. Currently subsequent
Error

Line: 219 Column: 3

                            optimizer_combinations.distributions_and_v1_and_v2_optimizers(),
              tf.__internal__.test.combinations.combine(
                  mode=["graph", "eager"],
                  # TODO(isaprykin):  Allow False here.  Currently subsequent
                  # replicas will re-execute UPDATE_OPS of previous replicas.
                  update_ops_in_cross_replica_mode=[True])) +
          tf.__internal__.test.combinations.combine(
              distribution=[tf.__internal__.distribute.combinations.tpu_strategy],
              optimizer_fn=optimizer_combinations.optimizers_v1_and_v2,

            

Reported by Pylint.

Unused argument 'is_tpu'
Error

Line: 406 Column: 71

                            optimizer_fn=optimizer_combinations.optimizers_v1_and_v2,
              mode=["graph"],
              is_tpu=[True]))
  def testRunStepsWithOutputContext(self, distribution, optimizer_fn, is_tpu):
    with distribution.scope():
      def dataset_fn():
        dataset = tf.data.Dataset.from_tensors([[1.]]).repeat()
        # TODO(priyag): batch with drop_remainder=True causes shapes to be
        # fully defined for TPU. Remove this when XLA supports dynamic shapes.

            

Reported by Pylint.

TODO(priyag): batch with drop_remainder=True causes shapes to be
Error

Line: 410 Column: 3

                  with distribution.scope():
      def dataset_fn():
        dataset = tf.data.Dataset.from_tensors([[1.]]).repeat()
        # TODO(priyag): batch with drop_remainder=True causes shapes to be
        # fully defined for TPU. Remove this when XLA supports dynamic shapes.
        return dataset.batch(batch_size=1, drop_remainder=True)

      optimizer = optimizer_fn()
      layer = core.Dense(1, use_bias=True)

            

Reported by Pylint.

Missing class docstring
Error

Line: 48 Column: 1

              }


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

  def _get_iterator(self, strategy, input_fn):
    iterator = strategy.make_input_fn_iterator(lambda _: input_fn())
    self.evaluate(iterator.initializer)
    return iterator

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 50 Column: 1

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

  def _get_iterator(self, strategy, input_fn):
    iterator = strategy.make_input_fn_iterator(lambda _: input_fn())
    self.evaluate(iterator.initializer)
    return iterator

  @tf.__internal__.distribute.combinations.generate(

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 51 Column: 1

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

  def _get_iterator(self, strategy, input_fn):
    iterator = strategy.make_input_fn_iterator(lambda _: input_fn())
    self.evaluate(iterator.initializer)
    return iterator

  @tf.__internal__.distribute.combinations.generate(
      tf.__internal__.test.combinations.times(

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 52 Column: 1

              
  def _get_iterator(self, strategy, input_fn):
    iterator = strategy.make_input_fn_iterator(lambda _: input_fn())
    self.evaluate(iterator.initializer)
    return iterator

  @tf.__internal__.distribute.combinations.generate(
      tf.__internal__.test.combinations.times(
          optimizer_combinations.distributions_and_v1_optimizers(),

            

Reported by Pylint.

keras/engine/training_generator_v1.py
259 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 18 Column: 1

              """Part of the Keras training engine related to Python generators of array data.
"""

import tensorflow.compat.v2 as tf
# pylint: disable=protected-access

import functools
import math


            

Reported by Pylint.

Unable to import 'tensorflow.python.platform'
Error

Line: 32 Column: 1

              from keras.utils import data_utils
from keras.utils import generic_utils
from keras.utils.mode_keys import ModeKeys
from tensorflow.python.platform import tf_logging as logging


def model_iteration(model,
                    data,
                    steps_per_epoch=None,

            

Reported by Pylint.

Generator 'generator' has no '__enter__' member
Error

Line: 186 Column: 5

                if should_set_learning_phase:
    learning_phase_scope = backend.eager_learning_phase_scope(
        1 if mode == ModeKeys.TRAIN else 0)
    learning_phase_scope.__enter__()

  callbacks.model.stop_training = False
  callbacks._call_begin_hook(mode)

  initial_epoch = model._maybe_load_initial_epoch_from_ckpt(initial_epoch, mode)

            

Reported by Pylint.

Generator 'generator' has no '__exit__' member
Error

Line: 328 Column: 5

                  enqueuer.stop()

  if should_set_learning_phase:
    learning_phase_scope.__exit__(None, None, None)

  if mode == ModeKeys.TRAIN:
    return model.history
  return results


            

Reported by Pylint.

Parameters differ from overridden 'fit' method
Error

Line: 547 Column: 3

                param.
  """

  def fit(self,
          model,
          x=None,
          y=None,
          batch_size=None,
          epochs=1,

            

Reported by Pylint.

Parameters differ from overridden 'evaluate' method
Error

Line: 588 Column: 3

                      initial_epoch=initial_epoch,
        steps_name='steps_per_epoch')

  def evaluate(self,
               model,
               x=None,
               y=None,
               batch_size=None,
               verbose=1,

            

Reported by Pylint.

Parameters differ from overridden 'predict' method
Error

Line: 612 Column: 3

                      workers=workers,
        use_multiprocessing=use_multiprocessing)

  def predict(self,
              model,
              x,
              batch_size=None,
              verbose=0,
              steps=None,

            

Reported by Pylint.

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

Line: 21 Column: 1

              import tensorflow.compat.v2 as tf
# pylint: disable=protected-access

import functools
import math

import numpy as np
from keras import backend
from keras import callbacks as cbks

            

Reported by Pylint.

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

Line: 22 Column: 1

              # pylint: disable=protected-access

import functools
import math

import numpy as np
from keras import backend
from keras import callbacks as cbks
from keras.engine import training_utils

            

Reported by Pylint.

Too many arguments (18/5)
Error

Line: 35 Column: 1

              from tensorflow.python.platform import tf_logging as logging


def model_iteration(model,
                    data,
                    steps_per_epoch=None,
                    epochs=1,
                    verbose=1,
                    callbacks=None,

            

Reported by Pylint.

keras/activations_test.py
259 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

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

import tensorflow.compat.v2 as tf

from absl.testing import parameterized
import numpy as np

from keras import activations

            

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

            

Reported by Pylint.

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

Line: 204 Column: 1

                      return 0.5 * x * (1.0 + np.tanh(
            np.sqrt(2.0 / np.pi) * (x + 0.044715 * np.power(x, 3))))
      else:
        from scipy.stats import norm  # pylint: disable=g-import-not-at-top
        return x * norm.cdf(x)

    x = backend.placeholder(ndim=2)
    f = backend.function([x], [activations.gelu(x)])
    test_values = np.random.random((2, 5))

            

Reported by Pylint.

Unable to import 'scipy.stats'
Error

Line: 204 Column: 9

                      return 0.5 * x * (1.0 + np.tanh(
            np.sqrt(2.0 / np.pi) * (x + 0.044715 * np.power(x, 3))))
      else:
        from scipy.stats import norm  # pylint: disable=g-import-not-at-top
        return x * norm.cdf(x)

    x = backend.placeholder(ndim=2)
    f = backend.function([x], [activations.gelu(x)])
    test_values = np.random.random((2, 5))

            

Reported by Pylint.

Comparing against a callable, did you omit the parenthesis?
Error

Line: 47 Column: 14

                  for name in all_activations:
      fn = activations.get(name)
      ref_fn = getattr(activations, name)
      assert fn == ref_fn
      config = activations.serialize(fn)
      fn = activations.deserialize(config)
      assert fn == ref_fn

  def test_serialization_v2(self):

            

Reported by Pylint.

Comparing against a callable, did you omit the parenthesis?
Error

Line: 50 Column: 14

                    assert fn == ref_fn
      config = activations.serialize(fn)
      fn = activations.deserialize(config)
      assert fn == ref_fn

  def test_serialization_v2(self):
    activation_map = {tf.math.softmax: 'softmax'}
    for fn_v2_key in activation_map:
      fn_v2 = activations.get(fn_v2_key)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 31 Column: 1

              

def _ref_softmax(values):
  m = np.max(values)
  e = np.exp(values - m)
  return e / np.sum(e)


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

            

Reported by Pylint.

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

Line: 31 Column: 3

              

def _ref_softmax(values):
  m = np.max(values)
  e = np.exp(values - m)
  return e / np.sum(e)


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

            

Reported by Pylint.

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

Line: 32 Column: 3

              
def _ref_softmax(values):
  m = np.max(values)
  e = np.exp(values - m)
  return e / np.sum(e)


@combinations.generate(combinations.combine(mode=['graph', 'eager']))
class KerasActivationsTest(tf.test.TestCase, parameterized.TestCase):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 32 Column: 1

              
def _ref_softmax(values):
  m = np.max(values)
  e = np.exp(values - m)
  return e / np.sum(e)


@combinations.generate(combinations.combine(mode=['graph', 'eager']))
class KerasActivationsTest(tf.test.TestCase, parameterized.TestCase):

            

Reported by Pylint.

keras/layers/local.py
258 issues
Bad option value 'g-classes-have-attributes'
Error

Line: 15 Column: 1

              # See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# pylint: disable=g-classes-have-attributes
"""Locally-connected layers."""

import tensorflow.compat.v2 as tf

import numpy as np

            

Reported by Pylint.

Unable to import 'tensorflow.compat.v2'
Error

Line: 18 Column: 1

              # pylint: disable=g-classes-have-attributes
"""Locally-connected layers."""

import tensorflow.compat.v2 as tf

import numpy as np

from keras import activations
from keras import backend

            

Reported by Pylint.

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

Line: 31 Column: 1

              from keras.engine.input_spec import InputSpec
from keras.utils import conv_utils
from keras.utils import tf_utils
from tensorflow.python.util.tf_export import keras_export


@keras_export('keras.layers.LocallyConnected1D')
class LocallyConnected1D(Layer):
  """Locally-connected layer for 1D inputs.

            

Reported by Pylint.

Attribute 'output_length' defined outside __init__
Error

Line: 170 Column: 5

                    raise ValueError(
          'Axis 2 of input should be fully-defined. '
          'Found shape:', input_shape)
    self.output_length = conv_utils.conv_output_length(input_length,
                                                       self.kernel_size[0],
                                                       self.padding,
                                                       self.strides[0])

    if self.implementation == 1:

            

Reported by Pylint.

Attribute 'kernel_shape' defined outside __init__
Error

Line: 176 Column: 7

                                                                     self.strides[0])

    if self.implementation == 1:
      self.kernel_shape = (self.output_length, self.kernel_size[0] * input_dim,
                           self.filters)

      self.kernel = self.add_weight(
          shape=self.kernel_shape,
          initializer=self.kernel_initializer,

            

Reported by Pylint.

Attribute 'kernel' defined outside __init__
Error

Line: 179 Column: 7

                    self.kernel_shape = (self.output_length, self.kernel_size[0] * input_dim,
                           self.filters)

      self.kernel = self.add_weight(
          shape=self.kernel_shape,
          initializer=self.kernel_initializer,
          name='kernel',
          regularizer=self.kernel_regularizer,
          constraint=self.kernel_constraint)

            

Reported by Pylint.

Attribute 'kernel_shape' defined outside __init__
Error

Line: 188 Column: 9

              
    elif self.implementation == 2:
      if self.data_format == 'channels_first':
        self.kernel_shape = (input_dim, input_length, self.filters,
                             self.output_length)
      else:
        self.kernel_shape = (input_length, input_dim, self.output_length,
                             self.filters)


            

Reported by Pylint.

Attribute 'kernel_shape' defined outside __init__
Error

Line: 191 Column: 9

                      self.kernel_shape = (input_dim, input_length, self.filters,
                             self.output_length)
      else:
        self.kernel_shape = (input_length, input_dim, self.output_length,
                             self.filters)

      self.kernel = self.add_weight(
          shape=self.kernel_shape,
          initializer=self.kernel_initializer,

            

Reported by Pylint.

Attribute 'kernel' defined outside __init__
Error

Line: 194 Column: 7

                      self.kernel_shape = (input_length, input_dim, self.output_length,
                             self.filters)

      self.kernel = self.add_weight(
          shape=self.kernel_shape,
          initializer=self.kernel_initializer,
          name='kernel',
          regularizer=self.kernel_regularizer,
          constraint=self.kernel_constraint)

            

Reported by Pylint.

Attribute 'kernel_mask' defined outside __init__
Error

Line: 201 Column: 7

                        regularizer=self.kernel_regularizer,
          constraint=self.kernel_constraint)

      self.kernel_mask = get_locallyconnected_mask(
          input_shape=(input_length,),
          kernel_shape=self.kernel_size,
          strides=self.strides,
          padding=self.padding,
          data_format=self.data_format,

            

Reported by Pylint.

keras/layers/preprocessing/string_lookup_test.py
256 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Tests for Keras text vectorization preprocessing layer."""

import tensorflow.compat.v2 as tf

import os
from absl.testing import parameterized
import numpy as np


            

Reported by Pylint.

Unable to import 'absl.testing'
Error

Line: 20 Column: 1

              import tensorflow.compat.v2 as tf

import os
from absl.testing import parameterized
import numpy as np

import keras
from keras import keras_parameterized
from keras import testing_utils

            

Reported by Pylint.

TODO(rachelim): `model.predict` predicts the result on each
Error

Line: 79 Column: 3

              
    if use_dataset:
      # Keras APIs expect batched datasets.
      # TODO(rachelim): `model.predict` predicts the result on each
      # dataset batch separately, then tries to concatenate the results
      # together. When the results have different shapes on the non-concat
      # axis (which can happen in the output_mode = INT case for
      # StringLookup), the concatenation fails. In real use cases, this may
      # not be an issue because users are likely to pipe the preprocessing layer

            

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
from absl.testing import parameterized
import numpy as np

import keras
from keras import keras_parameterized

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 31 Column: 1

              

def _get_end_to_end_test_cases():
  test_cases = (
      {
          "testcase_name": "test_strings_soft_vocab_cap",
          # Create an array where 'earth' is the most frequent term, followed by
          # 'wind', then 'and', then 'fire'. This ensures that the vocab
          # accumulator is sorting by frequency.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 52 Column: 1

                    },
  )

  crossed_test_cases = []
  # Cross above test cases with use_dataset in (True, False)
  for use_dataset in (True, False):
    for case in test_cases:
      case = case.copy()
      if use_dataset:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 54 Column: 1

              
  crossed_test_cases = []
  # Cross above test cases with use_dataset in (True, False)
  for use_dataset in (True, False):
    for case in test_cases:
      case = case.copy()
      if use_dataset:
        case["testcase_name"] = case["testcase_name"] + "_with_dataset"
      case["use_dataset"] = use_dataset

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 55 Column: 1

                crossed_test_cases = []
  # Cross above test cases with use_dataset in (True, False)
  for use_dataset in (True, False):
    for case in test_cases:
      case = case.copy()
      if use_dataset:
        case["testcase_name"] = case["testcase_name"] + "_with_dataset"
      case["use_dataset"] = use_dataset
      crossed_test_cases.append(case)

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 56 Column: 1

                # Cross above test cases with use_dataset in (True, False)
  for use_dataset in (True, False):
    for case in test_cases:
      case = case.copy()
      if use_dataset:
        case["testcase_name"] = case["testcase_name"] + "_with_dataset"
      case["use_dataset"] = use_dataset
      crossed_test_cases.append(case)


            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 57 Column: 1

                for use_dataset in (True, False):
    for case in test_cases:
      case = case.copy()
      if use_dataset:
        case["testcase_name"] = case["testcase_name"] + "_with_dataset"
      case["use_dataset"] = use_dataset
      crossed_test_cases.append(case)

  return crossed_test_cases

            

Reported by Pylint.

keras/legacy_tf_layers/base.py
249 issues
Bad option value 'g-classes-have-attributes'
Error

Line: 15 Column: 1

              # See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
# pylint: disable=g-classes-have-attributes
"""Contains the base Layer class, from which all layers inherit."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function


            

Reported by Pylint.

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 copy
import warnings
from keras import backend
from keras.engine import base_layer

            

Reported by Pylint.

Unable to import 'tensorflow.python.ops'
Error

Line: 31 Column: 1

              from keras.legacy_tf_layers import variable_scope_shim
from keras.mixed_precision import policy
from keras.utils import tf_contextlib
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util.tf_export import keras_export
from tensorflow.python.util.tf_export import tf_export

# Avoid breaking users who directly import this symbol from this file.
# TODO(fchollet): remove this.

            

Reported by Pylint.

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

Line: 32 Column: 1

              from keras.mixed_precision import policy
from keras.utils import tf_contextlib
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util.tf_export import keras_export
from tensorflow.python.util.tf_export import tf_export

# Avoid breaking users who directly import this symbol from this file.
# TODO(fchollet): remove this.
InputSpec = base_layer.InputSpec  # pylint: disable=invalid-name

            

Reported by Pylint.

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

Line: 33 Column: 1

              from keras.utils import tf_contextlib
from tensorflow.python.ops import variable_scope as vs
from tensorflow.python.util.tf_export import keras_export
from tensorflow.python.util.tf_export import tf_export

# Avoid breaking users who directly import this symbol from this file.
# TODO(fchollet): remove this.
InputSpec = base_layer.InputSpec  # pylint: disable=invalid-name


            

Reported by Pylint.

Instance of 'Layer' has no '_non_trainable_weights' member; maybe 'non_trainable_weights'?
Error

Line: 492 Column: 13

                          extra_trainable_vars = self._trainable_weights[prev_len_trainable:]
            self._trainable_weights = self._trainable_weights[
                :prev_len_trainable]
            self._non_trainable_weights += extra_trainable_vars
    return variable

  def __call__(self, inputs, *args, **kwargs):
    """Wraps `call`, applying pre- and post-processing steps.


            

Reported by Pylint.

TODO(fchollet): remove this.
Error

Line: 36 Column: 3

              from tensorflow.python.util.tf_export import tf_export

# Avoid breaking users who directly import this symbol from this file.
# TODO(fchollet): remove this.
InputSpec = base_layer.InputSpec  # pylint: disable=invalid-name

_KERAS_STYLE_SCOPE = False



            

Reported by Pylint.

Using the global statement
Error

Line: 104 Column: 3

                Yields:
    A keras layer style scope.
  """
  global _KERAS_STYLE_SCOPE
  stack = _KERAS_STYLE_SCOPE
  _KERAS_STYLE_SCOPE = True
  try:
    yield
  finally:

            

Reported by Pylint.

Using the global statement
Error

Line: 149 Column: 3

                assert(model_1.weights != model_2.weights)
  ```
  """
  global _KERAS_STYLE_SCOPE
  _KERAS_STYLE_SCOPE = True


def _is_in_keras_style_scope():
  global _KERAS_STYLE_SCOPE

            

Reported by Pylint.

Using the global statement
Error

Line: 154 Column: 3

              

def _is_in_keras_style_scope():
  global _KERAS_STYLE_SCOPE
  return _KERAS_STYLE_SCOPE


@keras_export(v1=['keras.__internal__.legacy.layers.Layer'])
@tf_export(v1=['layers.Layer'])

            

Reported by Pylint.

keras/engine/input_layer_test.py
247 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              #,============================================================================
"""Tests for InputLayer construction."""

import tensorflow.compat.v2 as tf
from tensorflow.python.framework import type_spec
from keras import backend
from keras import combinations
from keras import keras_parameterized
from keras.engine import functional

            

Reported by Pylint.

Unable to import 'tensorflow.python.framework'
Error

Line: 18 Column: 1

              """Tests for InputLayer construction."""

import tensorflow.compat.v2 as tf
from tensorflow.python.framework import type_spec
from keras import backend
from keras import combinations
from keras import keras_parameterized
from keras.engine import functional
from keras.engine import input_layer as input_layer_lib

            

Reported by Pylint.

Access to a protected member _type_spec of a client class
Error

Line: 294 Column: 41

                  # Create a Keras Input
    rt = tf.RaggedTensor.from_row_splits(
        values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8])
    x = input_layer_lib.Input(type_spec=rt._type_spec)

    # Verify you can construct and use a model w/ this input
    model = functional.Functional(x, x * 2)

    # And that the model works

            

Reported by Pylint.

Access to a protected member _type_spec of a client class
Error

Line: 322 Column: 45

                      # Create a Keras Input
        rt = tf.RaggedTensor.from_row_splits(
            values=[3, 1, 4, 1, 5, 9, 2, 6], row_splits=[0, 4, 4, 7, 8, 8])
        x = input_layer_lib.Input(type_spec=rt._type_spec)

        # Verify you can construct and use a model w/ this input
        model_container['model'] = functional.Functional(x, x * 3)
      return model_container['model'](inp)


            

Reported by Pylint.

Access to a protected member _batch_input_shape of a client class
Error

Line: 363 Column: 23

                  inp = backend.placeholder(shape=None, dtype=tf.string)
    x = input_layer_lib.InputLayer(input_tensor=inp, dtype=tf.string)
    loaded = input_layer_lib.InputLayer.from_config(x.get_config())
    self.assertIsNone(loaded._batch_input_shape)


if __name__ == '__main__':
  tf.test.main()

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 28 Column: 1

              from keras.saving import model_config


class TwoTensors(tf.__internal__.CompositeTensor):
  """A simple value type to test TypeSpec.

  Contains two tensors (x, y) and a string (color).  The color value is a
  stand-in for any extra type metadata we might need to store.


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 29 Column: 1

              

class TwoTensors(tf.__internal__.CompositeTensor):
  """A simple value type to test TypeSpec.

  Contains two tensors (x, y) and a string (color).  The color value is a
  stand-in for any extra type metadata we might need to store.

  This value type contains no single dtype.

            

Reported by Pylint.

Argument name "y" doesn't conform to snake_case naming style
Error

Line: 37 Column: 3

                This value type contains no single dtype.
  """

  def __init__(self, x, y, color='red', assign_variant_dtype=False):
    assert isinstance(color, str)
    self.x = tf.convert_to_tensor(x)
    self.y = tf.convert_to_tensor(y)
    self.color = color
    self.shape = tf.TensorShape(None)

            

Reported by Pylint.

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

Line: 37 Column: 3

                This value type contains no single dtype.
  """

  def __init__(self, x, y, color='red', assign_variant_dtype=False):
    assert isinstance(color, str)
    self.x = tf.convert_to_tensor(x)
    self.y = tf.convert_to_tensor(y)
    self.color = color
    self.shape = tf.TensorShape(None)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 37 Column: 1

                This value type contains no single dtype.
  """

  def __init__(self, x, y, color='red', assign_variant_dtype=False):
    assert isinstance(color, str)
    self.x = tf.convert_to_tensor(x)
    self.y = tf.convert_to_tensor(y)
    self.color = color
    self.shape = tf.TensorShape(None)

            

Reported by Pylint.