The following issues were found

keras/tests/memory_checker_test.py
44 issues
Unable to import 'keras'
Error

Line: 16 Column: 1

              # limitations under the License.
# =============================================================================

import keras

import tensorflow.compat.v2 as tf
from tensorflow.python.framework.memory_checker import MemoryChecker



            

Reported by Pylint.

Unable to import 'tensorflow.compat.v2'
Error

Line: 18 Column: 1

              
import keras

import tensorflow.compat.v2 as tf
from tensorflow.python.framework.memory_checker import MemoryChecker


class MemoryCheckerTest(tf.test.TestCase):


            

Reported by Pylint.

Unable to import 'tensorflow.python.framework.memory_checker'
Error

Line: 19 Column: 1

              import keras

import tensorflow.compat.v2 as tf
from tensorflow.python.framework.memory_checker import MemoryChecker


class MemoryCheckerTest(tf.test.TestCase):

  def testKerasBasic(self):

            

Reported by Pylint.

TODO(kkb): Fix the slowness on Forge.
Error

Line: 25 Column: 3

              class MemoryCheckerTest(tf.test.TestCase):

  def testKerasBasic(self):
    # TODO(kkb): Fix the slowness on Forge.
    self.skipTest('This test is too slow on Forge so disabled for now.')

    x = tf.zeros([1, 1])
    y = tf.constant([[3]])
    model = keras.models.Sequential()

            

Reported by Pylint.

TODO(kkb): Fix the slowness on Forge.
Error

Line: 44 Column: 3

                  memory_checker.assert_no_leak_if_all_possibly_except_one()

  def testKerasAdvanced(self):
    # TODO(kkb): Fix the slowness on Forge.
    self.skipTest('This test is too slow on Forge so disabled for now.')

    # A real world example taken from the following.
    # https://github.com/tensorflow/tensorflow/issues/32500
    # b/142150794

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # Copyright 2020 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.

Missing class docstring
Error

Line: 22 Column: 1

              from tensorflow.python.framework.memory_checker import MemoryChecker


class MemoryCheckerTest(tf.test.TestCase):

  def testKerasBasic(self):
    # TODO(kkb): Fix the slowness on Forge.
    self.skipTest('This test is too slow on Forge so disabled for now.')


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 24 Column: 1

              
class MemoryCheckerTest(tf.test.TestCase):

  def testKerasBasic(self):
    # TODO(kkb): Fix the slowness on Forge.
    self.skipTest('This test is too slow on Forge so disabled for now.')

    x = tf.zeros([1, 1])
    y = tf.constant([[3]])

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 24 Column: 3

              
class MemoryCheckerTest(tf.test.TestCase):

  def testKerasBasic(self):
    # TODO(kkb): Fix the slowness on Forge.
    self.skipTest('This test is too slow on Forge so disabled for now.')

    x = tf.zeros([1, 1])
    y = tf.constant([[3]])

            

Reported by Pylint.

Method name "testKerasBasic" doesn't conform to snake_case naming style
Error

Line: 24 Column: 3

              
class MemoryCheckerTest(tf.test.TestCase):

  def testKerasBasic(self):
    # TODO(kkb): Fix the slowness on Forge.
    self.skipTest('This test is too slow on Forge so disabled for now.')

    x = tf.zeros([1, 1])
    y = tf.constant([[3]])

            

Reported by Pylint.

keras/layers/preprocessing/preprocessing_stage_test.py
44 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""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

              """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: 35 Column: 5

              
  def test_adapt(self):

    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: 35 Column: 5

              
  def test_adapt(self):

    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.

Unused argument 'reset_state'
Error

Line: 42 Column: 29

                      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 'adapt' method
Error

Line: 42 Column: 7

                      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: 46 Column: 7

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

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

    # Test with NumPy array
    stage = preprocessing_stage.PreprocessingStage([
        PL(),

            

Reported by Pylint.

standard import "import time" 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 time
import numpy as np
from keras import keras_parameterized
from keras.engine import base_preprocessing_layer
from keras.layers.preprocessing import preprocessing_stage
from keras.layers.preprocessing import preprocessing_test_utils

            

Reported by Pylint.

Missing class docstring
Error

Line: 29 Column: 1

              

@keras_parameterized.run_all_keras_modes(always_skip_v1=True)
class PreprocessingStageTest(
    keras_parameterized.TestCase,
    preprocessing_test_utils.PreprocessingLayerTest):

  def test_adapt(self):


            

Reported by Pylint.

Missing function or method docstring
Error

Line: 33 Column: 3

                  keras_parameterized.TestCase,
    preprocessing_test_utils.PreprocessingLayerTest):

  def test_adapt(self):

    class PL(base_preprocessing_layer.PreprocessingLayer):

      def __init__(self, **kwargs):
        self.adapt_time = None

            

Reported by Pylint.

keras/saving/utils_v1/mode_keys.py
43 issues
TODO(kathywu): Remove copy in Estimator after nightlies
Error

Line: 37 Column: 3

                PREDICT = 'predict'


# TODO(kathywu): Remove copy in Estimator after nightlies
class EstimatorModeKeys:
  """Standard names for Estimator model modes.

  The following standard keys are defined:


            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 22 Column: 1

              import collections


class KerasModeKeys:
  """Standard names for model modes.

  The following standard keys are defined:

  * `TRAIN`: training/fitting mode.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 23 Column: 1

              

class KerasModeKeys:
  """Standard names for model modes.

  The following standard keys are defined:

  * `TRAIN`: training/fitting mode.
  * `TEST`: testing/evaluation mode.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 32 Column: 1

                * `PREDICT`: prediction/inference mode.
  """

  TRAIN = 'train'
  TEST = 'test'
  PREDICT = 'predict'


# TODO(kathywu): Remove copy in Estimator after nightlies

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

                """

  TRAIN = 'train'
  TEST = 'test'
  PREDICT = 'predict'


# TODO(kathywu): Remove copy in Estimator after nightlies
class EstimatorModeKeys:

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 34 Column: 1

              
  TRAIN = 'train'
  TEST = 'test'
  PREDICT = 'predict'


# TODO(kathywu): Remove copy in Estimator after nightlies
class EstimatorModeKeys:
  """Standard names for Estimator model modes.

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 38 Column: 1

              

# TODO(kathywu): Remove copy in Estimator after nightlies
class EstimatorModeKeys:
  """Standard names for Estimator model modes.

  The following standard keys are defined:

  * `TRAIN`: training/fitting mode.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 39 Column: 1

              
# TODO(kathywu): Remove copy in Estimator after nightlies
class EstimatorModeKeys:
  """Standard names for Estimator model modes.

  The following standard keys are defined:

  * `TRAIN`: training/fitting mode.
  * `EVAL`: testing/evaluation mode.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 48 Column: 1

                * `PREDICT`: predication/inference mode.
  """

  TRAIN = 'train'
  EVAL = 'eval'
  PREDICT = 'infer'


def is_predict(mode):

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 49 Column: 1

                """

  TRAIN = 'train'
  EVAL = 'eval'
  PREDICT = 'infer'


def is_predict(mode):
  return mode in [KerasModeKeys.PREDICT, EstimatorModeKeys.PREDICT]

            

Reported by Pylint.

keras/layers/core/dropout.py
43 issues
Bad option value 'g-classes-have-attributes'
Error

Line: 16 Column: 1

              # limitations under the License.
# ==============================================================================
"""Contains the dropout layer."""
# pylint: disable=g-classes-have-attributes,g-direct-tensorflow-import

from keras import backend as K
from keras.engine.base_layer import Layer
from keras.utils import control_flow_util
import tensorflow.compat.v2 as tf

            

Reported by Pylint.

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

Line: 16 Column: 1

              # limitations under the License.
# ==============================================================================
"""Contains the dropout layer."""
# pylint: disable=g-classes-have-attributes,g-direct-tensorflow-import

from keras import backend as K
from keras.engine.base_layer import Layer
from keras.utils import control_flow_util
import tensorflow.compat.v2 as tf

            

Reported by Pylint.

Unable to import 'tensorflow.compat.v2'
Error

Line: 21 Column: 1

              from keras import backend as K
from keras.engine.base_layer import Layer
from keras.utils import control_flow_util
import tensorflow.compat.v2 as tf
from tensorflow.python.util.tf_export import keras_export

# TODO(b/168039935): track dropout rate to decide whether/how to make a
# dropout rate fastpath.
keras_temporary_dropout_rate = tf.__internal__.monitoring.BoolGauge(

            

Reported by Pylint.

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

Line: 22 Column: 1

              from keras.engine.base_layer import Layer
from keras.utils import control_flow_util
import tensorflow.compat.v2 as tf
from tensorflow.python.util.tf_export import keras_export

# TODO(b/168039935): track dropout rate to decide whether/how to make a
# dropout rate fastpath.
keras_temporary_dropout_rate = tf.__internal__.monitoring.BoolGauge(
    '/tensorflow/api/keras/dropout/temp_rate_is_zero',

            

Reported by Pylint.

TODO(b/168039935): track dropout rate to decide whether/how to make a
Error

Line: 24 Column: 3

              import tensorflow.compat.v2 as tf
from tensorflow.python.util.tf_export import keras_export

# TODO(b/168039935): track dropout rate to decide whether/how to make a
# dropout rate fastpath.
keras_temporary_dropout_rate = tf.__internal__.monitoring.BoolGauge(
    '/tensorflow/api/keras/dropout/temp_rate_is_zero',
    'Temporarily record if Keras dropout layer was created w/'
    'constant rate = 0')

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 111 Column: 3

                    noise_shape.append(concrete_inputs_shape[i] if value is None else value)
    return tf.convert_to_tensor(noise_shape)

  def call(self, inputs, training=None):
    if training is None:
      training = K.learning_phase()

    def dropped_inputs():
      return tf.nn.dropout(

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 34 Column: 1

              
@keras_export('keras.layers.Dropout')
class Dropout(Layer):
  """Applies Dropout to the input.

  The Dropout layer randomly sets input units to 0 with a frequency of `rate`
  at each step during training time, which helps prevent overfitting.
  Inputs not set to 0 are scaled up by 1/(1 - rate) such that the sum over
  all inputs is unchanged.

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 84 Column: 1

                    training mode (adding dropout) or in inference mode (doing nothing).
  """

  def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
    super(Dropout, self).__init__(**kwargs)
    if isinstance(rate, (int, float)) and not 0 <= rate <= 1:
      raise ValueError(f'Invalid value {rate} received for '
                       f'`rate`, expected a value between 0 and 1.')
    self.rate = rate

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 85 Column: 1

                """

  def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
    super(Dropout, self).__init__(**kwargs)
    if isinstance(rate, (int, float)) and not 0 <= rate <= 1:
      raise ValueError(f'Invalid value {rate} received for '
                       f'`rate`, expected a value between 0 and 1.')
    self.rate = rate
    if isinstance(rate, (int, float)) and not rate:

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 85 Column: 5

                """

  def __init__(self, rate, noise_shape=None, seed=None, **kwargs):
    super(Dropout, self).__init__(**kwargs)
    if isinstance(rate, (int, float)) and not 0 <= rate <= 1:
      raise ValueError(f'Invalid value {rate} received for '
                       f'`rate`, expected a value between 0 and 1.')
    self.rate = rate
    if isinstance(rate, (int, float)) and not rate:

            

Reported by Pylint.

keras/combinations.py
43 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""This module customizes `test_combinations` for `tf.keras` related tests."""

import tensorflow.compat.v2 as tf

import functools
from keras import testing_utils

KERAS_MODEL_TYPES = ['functional', 'subclass', 'sequential']

            

Reported by Pylint.

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

Line: 19 Column: 1

              
import tensorflow.compat.v2 as tf

import functools
from keras import testing_utils

KERAS_MODEL_TYPES = ['functional', 'subclass', 'sequential']



            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 26 Column: 1

              

def keras_mode_combinations(mode=None, run_eagerly=None):
  """Returns the default test combinations for tf.keras tests.

  Note that if tf2 is enabled, then v1 session test will be skipped.

  Args:
    mode: List of modes to run the tests. The valid options are 'graph' and

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 42 Column: 1

                Returns:
    A list contains all the combinations to be used to generate test cases.
  """
  if mode is None:
    mode = ['eager'] if tf.__internal__.tf2.enabled() else ['graph', 'eager']
  if run_eagerly is None:
    run_eagerly = [True, False]
  result = []
  if 'eager' in mode:

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 43 Column: 1

                  A list contains all the combinations to be used to generate test cases.
  """
  if mode is None:
    mode = ['eager'] if tf.__internal__.tf2.enabled() else ['graph', 'eager']
  if run_eagerly is None:
    run_eagerly = [True, False]
  result = []
  if 'eager' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['eager'], run_eagerly=run_eagerly)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 44 Column: 1

                """
  if mode is None:
    mode = ['eager'] if tf.__internal__.tf2.enabled() else ['graph', 'eager']
  if run_eagerly is None:
    run_eagerly = [True, False]
  result = []
  if 'eager' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['eager'], run_eagerly=run_eagerly)
  if 'graph' in mode:

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 45 Column: 1

                if mode is None:
    mode = ['eager'] if tf.__internal__.tf2.enabled() else ['graph', 'eager']
  if run_eagerly is None:
    run_eagerly = [True, False]
  result = []
  if 'eager' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['eager'], run_eagerly=run_eagerly)
  if 'graph' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['graph'], run_eagerly=[False])

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 46 Column: 1

                  mode = ['eager'] if tf.__internal__.tf2.enabled() else ['graph', 'eager']
  if run_eagerly is None:
    run_eagerly = [True, False]
  result = []
  if 'eager' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['eager'], run_eagerly=run_eagerly)
  if 'graph' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['graph'], run_eagerly=[False])
  return result

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 47 Column: 1

                if run_eagerly is None:
    run_eagerly = [True, False]
  result = []
  if 'eager' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['eager'], run_eagerly=run_eagerly)
  if 'graph' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['graph'], run_eagerly=[False])
  return result


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 48 Column: 1

                  run_eagerly = [True, False]
  result = []
  if 'eager' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['eager'], run_eagerly=run_eagerly)
  if 'graph' in mode:
    result += tf.__internal__.test.combinations.combine(mode=['graph'], run_eagerly=[False])
  return result



            

Reported by Pylint.

keras/feature_column/dense_features.py
42 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 json
from keras import backend
from keras.feature_column import base_feature_layer as kfc
from keras.saving.saved_model import json_utils

            

Reported by Pylint.

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

Line: 27 Column: 1

              from keras import backend
from keras.feature_column import base_feature_layer as kfc
from keras.saving.saved_model import json_utils
from tensorflow.python.util.tf_export import keras_export


@keras_export(v1=['keras.layers.DenseFeatures'])
class DenseFeatures(kfc._BaseFeaturesLayer):  # pylint: disable=protected-access
  """A layer that produces a dense `Tensor` based on given `feature_columns`.

            

Reported by Pylint.

Method '_output_shape' is abstract in class '_BaseFeaturesLayer' but is not overridden
Error

Line: 31 Column: 1

              

@keras_export(v1=['keras.layers.DenseFeatures'])
class DenseFeatures(kfc._BaseFeaturesLayer):  # pylint: disable=protected-access
  """A layer that produces a dense `Tensor` based on given `feature_columns`.

  Generally a single example in training data is described with FeatureColumns.
  At the first layer of the model, this column-oriented data should be converted
  to a single `Tensor`.

            

Reported by Pylint.

Parameters differ from overridden 'call' method
Error

Line: 119 Column: 3

                def _target_shape(self, input_shape, total_elements):
    return (input_shape[0], total_elements)

  def call(self, features, cols_to_output_tensors=None, training=None):
    """Returns a dense tensor corresponding to the `feature_columns`.

    Example usage:

    >>> t1 = tf.feature_column.embedding_column(

            

Reported by Pylint.

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

Line: 23 Column: 1

              
import tensorflow.compat.v2 as tf

import json
from keras import backend
from keras.feature_column import base_feature_layer as kfc
from keras.saving.saved_model import json_utils
from tensorflow.python.util.tf_export import keras_export


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 32 Column: 1

              
@keras_export(v1=['keras.layers.DenseFeatures'])
class DenseFeatures(kfc._BaseFeaturesLayer):  # pylint: disable=protected-access
  """A layer that produces a dense `Tensor` based on given `feature_columns`.

  Generally a single example in training data is described with FeatureColumns.
  At the first layer of the model, this column-oriented data should be converted
  to a single `Tensor`.


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 69 Column: 1

                ```
  """

  def __init__(self,
               feature_columns,
               trainable=True,
               name=None,
               partitioner=None,
               **kwargs):

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 75 Column: 1

                             name=None,
               partitioner=None,
               **kwargs):
    """Constructs a DenseFeatures layer.

    Args:
      feature_columns: An iterable containing the FeatureColumns to use as
        inputs to your model. All items should be instances of classes derived
        from `DenseColumn` such as `numeric_column`, `embedding_column`,

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 93 Column: 5

                  Raises:
      ValueError: if an item in `feature_columns` is not a `DenseColumn`.
    """
    super(DenseFeatures, self).__init__(
        feature_columns=feature_columns,
        trainable=trainable,
        name=name,
        partitioner=partitioner,
        expected_column_type=tf.__internal__.feature_column.DenseColumn,

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 93 Column: 1

                  Raises:
      ValueError: if an item in `feature_columns` is not a `DenseColumn`.
    """
    super(DenseFeatures, self).__init__(
        feature_columns=feature_columns,
        trainable=trainable,
        name=name,
        partitioner=partitioner,
        expected_column_type=tf.__internal__.feature_column.DenseColumn,

            

Reported by Pylint.

keras/saving/saved_model/json_utils_test.py
42 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 18 Column: 1

              # pylint: disable=protected-access
"""Tests the JSON encoder and decoder."""

import tensorflow.compat.v2 as tf

import enum
from keras.saving.saved_model import json_utils



            

Reported by Pylint.

Unable to import 'keras.saving.saved_model'
Error

Line: 21 Column: 1

              import tensorflow.compat.v2 as tf

import enum
from keras.saving.saved_model import json_utils


class JsonUtilsTest(tf.test.TestCase):

  def test_encode_decode_tensor_shape(self):

            

Reported by Pylint.

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

Line: 20 Column: 1

              
import tensorflow.compat.v2 as tf

import enum
from keras.saving.saved_model import json_utils


class JsonUtilsTest(tf.test.TestCase):


            

Reported by Pylint.

Missing class docstring
Error

Line: 24 Column: 1

              from keras.saving.saved_model import json_utils


class JsonUtilsTest(tf.test.TestCase):

  def test_encode_decode_tensor_shape(self):
    metadata = {
        'key1': tf.TensorShape(None),
        'key2': [tf.TensorShape([None]),

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 26 Column: 1

              
class JsonUtilsTest(tf.test.TestCase):

  def test_encode_decode_tensor_shape(self):
    metadata = {
        'key1': tf.TensorShape(None),
        'key2': [tf.TensorShape([None]),
                 tf.TensorShape([3, None, 5])]}
    string = json_utils.Encoder().encode(metadata)

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 26 Column: 3

              
class JsonUtilsTest(tf.test.TestCase):

  def test_encode_decode_tensor_shape(self):
    metadata = {
        'key1': tf.TensorShape(None),
        'key2': [tf.TensorShape([None]),
                 tf.TensorShape([3, None, 5])]}
    string = json_utils.Encoder().encode(metadata)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 27 Column: 1

              class JsonUtilsTest(tf.test.TestCase):

  def test_encode_decode_tensor_shape(self):
    metadata = {
        'key1': tf.TensorShape(None),
        'key2': [tf.TensorShape([None]),
                 tf.TensorShape([3, None, 5])]}
    string = json_utils.Encoder().encode(metadata)
    loaded = json_utils.decode(string)

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 31 Column: 1

                      'key1': tf.TensorShape(None),
        'key2': [tf.TensorShape([None]),
                 tf.TensorShape([3, None, 5])]}
    string = json_utils.Encoder().encode(metadata)
    loaded = json_utils.decode(string)

    self.assertEqual(set(loaded.keys()), {'key1', 'key2'})
    self.assertAllEqual(loaded['key1'].rank, None)
    self.assertAllEqual(loaded['key2'][0].as_list(), [None])

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 32 Column: 1

                      'key2': [tf.TensorShape([None]),
                 tf.TensorShape([3, None, 5])]}
    string = json_utils.Encoder().encode(metadata)
    loaded = json_utils.decode(string)

    self.assertEqual(set(loaded.keys()), {'key1', 'key2'})
    self.assertAllEqual(loaded['key1'].rank, None)
    self.assertAllEqual(loaded['key2'][0].as_list(), [None])
    self.assertAllEqual(loaded['key2'][1].as_list(), [3, None, 5])

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 34 Column: 1

                  string = json_utils.Encoder().encode(metadata)
    loaded = json_utils.decode(string)

    self.assertEqual(set(loaded.keys()), {'key1', 'key2'})
    self.assertAllEqual(loaded['key1'].rank, None)
    self.assertAllEqual(loaded['key2'][0].as_list(), [None])
    self.assertAllEqual(loaded['key2'][1].as_list(), [3, None, 5])

  def test_encode_decode_tuple(self):

            

Reported by Pylint.

keras/preprocessing/text_dataset.py
41 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 17 Column: 1

              # ==============================================================================
"""Keras text dataset generation utilities."""

import tensorflow.compat.v2 as tf

import numpy as np
from keras.preprocessing import dataset_utils
from tensorflow.python.util.tf_export import keras_export


            

Reported by Pylint.

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

Line: 21 Column: 1

              
import numpy as np
from keras.preprocessing import dataset_utils
from tensorflow.python.util.tf_export import keras_export


@keras_export('keras.utils.text_dataset_from_directory',
              'keras.preprocessing.text_dataset_from_directory',
              v1=[])

            

Reported by Pylint.

Too many arguments (11/5)
Error

Line: 27 Column: 1

              @keras_export('keras.utils.text_dataset_from_directory',
              'keras.preprocessing.text_dataset_from_directory',
              v1=[])
def text_dataset_from_directory(directory,
                                labels='inferred',
                                label_mode='int',
                                class_names=None,
                                batch_size=32,
                                max_length=None,

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 38 Column: 1

                                              validation_split=None,
                                subset=None,
                                follow_links=False):
  """Generates a `tf.data.Dataset` from text files in a directory.

  If your directory structure is:

  ```
  main_directory/

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 115 Column: 1

                    of shape `(batch_size, num_classes)`, representing a one-hot
      encoding of the class index.
  """
  if labels not in ('inferred', None):
    if not isinstance(labels, (list, tuple)):
      raise ValueError(
          '`labels` argument should be a list/tuple of integer labels, of '
          'the same size as the number of text files in the target '
          'directory. If you wish to infer the labels from the subdirectory '

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 116 Column: 1

                    encoding of the class index.
  """
  if labels not in ('inferred', None):
    if not isinstance(labels, (list, tuple)):
      raise ValueError(
          '`labels` argument should be a list/tuple of integer labels, of '
          'the same size as the number of text files in the target '
          'directory. If you wish to infer the labels from the subdirectory '
          'names in the target directory, pass `labels="inferred"`. '

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 117 Column: 1

                """
  if labels not in ('inferred', None):
    if not isinstance(labels, (list, tuple)):
      raise ValueError(
          '`labels` argument should be a list/tuple of integer labels, of '
          'the same size as the number of text files in the target '
          'directory. If you wish to infer the labels from the subdirectory '
          'names in the target directory, pass `labels="inferred"`. '
          'If you wish to get a dataset that only contains text samples '

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 124 Column: 1

                        'names in the target directory, pass `labels="inferred"`. '
          'If you wish to get a dataset that only contains text samples '
          f'(no labels), pass `labels=None`. Received: labels={labels}')
    if class_names:
      raise ValueError('You can only pass `class_names` if '
                       f'`labels="inferred"`. Received: labels={labels}, and '
                       f'class_names={class_names}')
  if label_mode not in {'int', 'categorical', 'binary', None}:
    raise ValueError(

            

Reported by Pylint.

Bad indentation. Found 6 spaces, expected 12
Style

Line: 125 Column: 1

                        'If you wish to get a dataset that only contains text samples '
          f'(no labels), pass `labels=None`. Received: labels={labels}')
    if class_names:
      raise ValueError('You can only pass `class_names` if '
                       f'`labels="inferred"`. Received: labels={labels}, and '
                       f'class_names={class_names}')
  if label_mode not in {'int', 'categorical', 'binary', None}:
    raise ValueError(
        '`label_mode` argument must be one of "int", "categorical", "binary", '

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 128 Column: 1

                    raise ValueError('You can only pass `class_names` if '
                       f'`labels="inferred"`. Received: labels={labels}, and '
                       f'class_names={class_names}')
  if label_mode not in {'int', 'categorical', 'binary', None}:
    raise ValueError(
        '`label_mode` argument must be one of "int", "categorical", "binary", '
        f'or None. Received: label_mode={label_mode}')
  if labels is None or label_mode is None:
    labels = None

            

Reported by Pylint.

keras/tests/memory_test.py
41 issues
Unable to import 'tensorflow.compat.v2'
Error

Line: 23 Column: 1

              introspection (test_util decorators). Please be careful adding new tests here.
"""

import tensorflow.compat.v2 as tf

import keras
from tensorflow.python.eager.memory_tests import memory_test_util



            

Reported by Pylint.

Unable to import 'keras'
Error

Line: 25 Column: 1

              
import tensorflow.compat.v2 as tf

import keras
from tensorflow.python.eager.memory_tests import memory_test_util


class SingleLayerNet(keras.Model):
  """Simple keras model used to ensure that there are no leaks."""

            

Reported by Pylint.

Unable to import 'tensorflow.python.eager.memory_tests'
Error

Line: 26 Column: 1

              import tensorflow.compat.v2 as tf

import keras
from tensorflow.python.eager.memory_tests import memory_test_util


class SingleLayerNet(keras.Model):
  """Simple keras model used to ensure that there are no leaks."""


            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 29 Column: 1

              from tensorflow.python.eager.memory_tests import memory_test_util


class SingleLayerNet(keras.Model):
  """Simple keras model used to ensure that there are no leaks."""

  def __init__(self):
    super(SingleLayerNet, self).__init__()
    self.fc1 = keras.layers.Dense(5)

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 30 Column: 1

              

class SingleLayerNet(keras.Model):
  """Simple keras model used to ensure that there are no leaks."""

  def __init__(self):
    super(SingleLayerNet, self).__init__()
    self.fc1 = keras.layers.Dense(5)


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 32 Column: 1

              class SingleLayerNet(keras.Model):
  """Simple keras model used to ensure that there are no leaks."""

  def __init__(self):
    super(SingleLayerNet, self).__init__()
    self.fc1 = keras.layers.Dense(5)

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

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 33 Column: 5

                """Simple keras model used to ensure that there are no leaks."""

  def __init__(self):
    super(SingleLayerNet, self).__init__()
    self.fc1 = keras.layers.Dense(5)

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


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 33 Column: 1

                """Simple keras model used to ensure that there are no leaks."""

  def __init__(self):
    super(SingleLayerNet, self).__init__()
    self.fc1 = keras.layers.Dense(5)

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


            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 34 Column: 1

              
  def __init__(self):
    super(SingleLayerNet, self).__init__()
    self.fc1 = keras.layers.Dense(5)

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



            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 36 Column: 1

                  super(SingleLayerNet, self).__init__()
    self.fc1 = keras.layers.Dense(5)

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


class MemoryTest(tf.test.TestCase):


            

Reported by Pylint.

keras/saving/saved_model/base_serialization.py
41 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 abc

from keras.saving.saved_model import json_utils
from keras.saving.saved_model import utils

            

Reported by Pylint.

Unable to import 'keras.saving.saved_model'
Error

Line: 25 Column: 1

              
import abc

from keras.saving.saved_model import json_utils
from keras.saving.saved_model import utils


class SavedModelSaver(object, metaclass=abc.ABCMeta):
  """Saver defining the methods and properties used to serialize Keras objects.

            

Reported by Pylint.

Unable to import 'keras.saving.saved_model'
Error

Line: 26 Column: 1

              import abc

from keras.saving.saved_model import json_utils
from keras.saving.saved_model import utils


class SavedModelSaver(object, metaclass=abc.ABCMeta):
  """Saver defining the methods and properties used to serialize Keras objects.
  """

            

Reported by Pylint.

TODO(kathywu): check that serialized JSON can be loaded (e.g., if an
Error

Line: 52 Column: 3

                  Returns:
      A serialized JSON storing information necessary for recreating this layer.
    """
    # TODO(kathywu): check that serialized JSON can be loaded (e.g., if an
    # object is in the python property)
    return json_utils.Encoder().encode(self.python_properties)

  def list_extra_dependencies_for_serialization(self, serialization_cache):
    """Lists extra dependencies to serialize to SavedModel.

            

Reported by Pylint.

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

Line: 23 Column: 1

              
import tensorflow.compat.v2 as tf

import abc

from keras.saving.saved_model import json_utils
from keras.saving.saved_model import utils



            

Reported by Pylint.

Class 'SavedModelSaver' inherits from object, can be safely removed from bases in python3
Error

Line: 29 Column: 1

              from keras.saving.saved_model import utils


class SavedModelSaver(object, metaclass=abc.ABCMeta):
  """Saver defining the methods and properties used to serialize Keras objects.
  """

  def __init__(self, obj):
    self.obj = obj

            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 30 Column: 1

              

class SavedModelSaver(object, metaclass=abc.ABCMeta):
  """Saver defining the methods and properties used to serialize Keras objects.
  """

  def __init__(self, obj):
    self.obj = obj


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 33 Column: 1

                """Saver defining the methods and properties used to serialize Keras objects.
  """

  def __init__(self, obj):
    self.obj = obj

  @abc.abstractproperty
  def object_identifier(self):
    """String stored in object identifier field in the SavedModel proto.

            

Reported by Pylint.

Bad indentation. Found 4 spaces, expected 8
Style

Line: 34 Column: 1

                """

  def __init__(self, obj):
    self.obj = obj

  @abc.abstractproperty
  def object_identifier(self):
    """String stored in object identifier field in the SavedModel proto.


            

Reported by Pylint.

Bad indentation. Found 2 spaces, expected 4
Style

Line: 36 Column: 1

                def __init__(self, obj):
    self.obj = obj

  @abc.abstractproperty
  def object_identifier(self):
    """String stored in object identifier field in the SavedModel proto.

    Returns:
      A string with the object identifier, which is used at load time.

            

Reported by Pylint.