Repository: keras-team/autokeras

Issue:
improve code quality using Codacy
<!---
**If you are reporting a bug:**
*  Verify that your issue is not being currently addressed by other issues or pull requests.
*  Please note that Auto-Keras is only compatible with **Python 3.6**.
*  Tag the issue with the `bug report` tag.
-->

### Bug Description
<!---
A clear and concise description of what the bug is.
-->
We are now using Codacy and CodeClimate to improve our code quality.

Please try to solve anything reported by Codacy by following this [link](https://app.codacy.com/manual/jhfjhfj1/autokeras/issues/index).
On the page, you can see a list of **issues**.
You can click to see the details and suggestions to fix the issue.

Thanks.


Discussion:

Resolving patch:
diff --git a/autokeras/custom_queue.py b/autokeras/custom_queue.py
--- a/autokeras/custom_queue.py
+++ b/autokeras/custom_queue.py
@@ -1,6 +1,6 @@
-from multiprocessing.queues import Queue as MultiQueue
+import multiprocessing.queues
 
-class SharedCounter(object):
+class SharedCounter():
     """ A synchronized shared counter.
 
     The locking done by multiprocessing.Value ensures that only a single
@@ -15,13 +15,13 @@ class SharedCounter(object):
 
     """
 
-    def __init__(self, n = 0):
+    def __init__(self, n=0):
         self.count = multiprocessing.Value('i', n)
 
-    def increment(self, n = 1):
+    def increment(self, num=1):
         """ Increment the counter by n (default = 1) """
         with self.count.get_lock():
-            self.count.value += n
+            self.count.value += num
 
     @property
     def value(self):
@@ -29,7 +29,7 @@ def value(self):
         return self.count.value
 
 
-class Queue(MultiQueue):
+class Queue(multiprocessing.queues.Queue):
     """ A portable implementation of multiprocessing.Queue.
 
     Because of multithreading / multiprocessing semantics, Queue.qsize() may
@@ -47,13 +47,13 @@ def __init__(self, *args, **kwargs):
         super(Queue, self).__init__(*args, **kwargs)
         self.size = SharedCounter(0)
 
-    def put(self, *args, **kwargs):
+    def put(self, obj, block=True, timeout=None):
         self.size.increment(1)
-        super(Queue, self).put(*args, **kwargs)
+        super(Queue, self).put(obj, block, timeout)
 
-    def get(self, *args, **kwargs):
+    def get(self, block=True, timeout=None):
         self.size.increment(-1)
-        return super(Queue, self).get(*args, **kwargs)
+        return super(Queue, self).get(block=True, timeout=None)
 
     def qsize(self):
         """ Reliable implementation of multiprocessing.Queue.qsize() """
diff --git a/autokeras/predefined_model.py b/autokeras/predefined_model.py
--- a/autokeras/predefined_model.py
+++ b/autokeras/predefined_model.py
@@ -16,9 +16,10 @@ class PredefinedModel(SingleModelSupervised):
 
     Attributes:
         graph: The graph form of the model.
-        y_encoder: Label encoder, used in transform_y or inverse_transform_y for encode the label. For example,
-                   if one hot encoder needed, y_encoder can be OneHotEncoder.
-        data_transformer: A instance of transformer to process the data, See example as ImageDataTransformer.
+        y_encoder: Label encoder, used in transform_y or inverse_transform_y for encode the label.
+                    For example, if one hot encoder needed, y_encoder can be OneHotEncoder.
+        data_transformer: A instance of transformer to process the data,
+                            See example as ImageDataTransformer.
         verbose: A boolean of whether the search process will be printed to stdout.
         path: A string. The path to a directory, where the intermediate results are saved.
     """
@@ -27,6 +28,7 @@ def __init__(self, y_encoder=OneHotEncoder(), data_transformer=None, verbose=Fal
         super().__init__(verbose, path)
         self.graph = None
         self.generator = None
+        self.resize_shape = None
         self.y_encoder = y_encoder
         self.data_transformer = data_transformer
 
@@ -38,7 +40,6 @@ def _init_generator(self, n_output_node, input_shape):
             n_output_node:  A integer value represent the number of output node in the final layer.
             input_shape: A tuple to express the shape of every train entry.
         """
-        pass
 
     @property
     def loss(self):
@@ -51,48 +52,48 @@ def metric(self):
     def preprocess(self, x):
         return resize_image_data(x, self.resize_shape)
 
-    def transform_y(self, y_train):
-        return self.y_encoder.transform(y_train)
+    def transform_y(self, y):
+        return self.y_encoder.transform(y)
 
     def inverse_transform_y(self, output):
         return self.y_encoder.inverse_transform(output)
 
-    def fit(self, x, y, trainer_args=None):
+    def fit(self, x_train, y_train, time_limit=None):
         """Trains the model on the dataset given.
 
         Args:
-            x: A numpy.ndarray instance containing the training data or the training data combined with the
-               validation data.
-            y: A numpy.ndarray instance containing the label of the training data. or the label of the training data
-               combined with the validation label.
-            trainer_args: A dictionary containing the parameters of the ModelTrainer constructor.
+            x_train: A numpy.ndarray instance containing the training data,
+                or the training data combined with the validation data.
+            y_train: A numpy.ndarray instance containing the label of the training data,
+                or the label of the training data combined with the validation label.
+            time_limit: A dictionary containing the parameters of the ModelTrainer constructor.
         """
-        validate_xy(x, y)
-        self.resize_shape = compute_image_resize_params(x)
-        x = self.preprocess(x)
-        self.y_encoder.fit(y)
-        y = self.transform_y(y)
+        validate_xy(x_train, y_train)
+        self.resize_shape = compute_image_resize_params(x_train)
+        x_train = self.preprocess(x_train)
+        self.y_encoder.fit(y_train)
+        y_train = self.transform_y(y_train)
         # Divide training data into training and testing data.
-        validation_set_size = int(len(y) * Constant.VALIDATION_SET_SIZE)
+        validation_set_size = int(len(y_train) * Constant.VALIDATION_SET_SIZE)
         validation_set_size = min(validation_set_size, 500)
         validation_set_size = max(validation_set_size, 1)
-        x_train, x_test, y_train, y_test = train_test_split(x, y,
-                                                            test_size=validation_set_size,
-                                                            random_state=42)
+        x_train_new, x_test, y_train_new, y_test = train_test_split(x_train, y_train,
+                                                                    test_size=validation_set_size,
+                                                                    random_state=42)
 
         # initialize data_transformer
-        self.data_transformer = ImageDataTransformer(x_train)
+        self.data_transformer = ImageDataTransformer(x_train_new)
         # Wrap the data into DataLoaders
-        train_loader = self.data_transformer.transform_train(x_train, y_train)
+        train_loader = self.data_transformer.transform_train(x_train_new, y_train_new)
         test_loader = self.data_transformer.transform_test(x_test, y_test)
 
-        self.generator = self._init_generator(self.y_encoder.n_classes, x_train.shape[1:])
+        self.generator = self._init_generator(self.y_encoder.n_classes, x_train_new.shape[1:])
         graph = self.generator.generate()
 
-        if trainer_args is None:
-            trainer_args = {'max_no_improvement_num': 30}
+        if time_limit is None:
+            time_limit = {'max_no_improvement_num': 30}
         _, _1, self.graph = train(None, graph, train_loader, test_loader,
-                                  trainer_args, self.metric, self.loss,
+                                  time_limit, self.metric, self.loss,
                                   self.verbose, self.path)
 
 
diff --git a/autokeras/pretrained/voice_generator/deepvoice3_pytorch/frontend.py b/autokeras/pretrained/voice_generator/deepvoice3_pytorch/frontend.py
--- a/autokeras/pretrained/voice_generator/deepvoice3_pytorch/frontend.py
+++ b/autokeras/pretrained/voice_generator/deepvoice3_pytorch/frontend.py
@@ -1,36 +1,38 @@
 # coding: utf-8
+import os
+import nltk
 from autokeras.pretrained.voice_generator.deepvoice3_pytorch.text.symbols import symbols
 
-import nltk
-from random import random
 
-n_vocab = len(symbols)
+N_VOCAB = len(symbols)
+n_vocab = N_VOCAB
 
 try:
-    _arphabet = nltk.corpus.cmudict.dict()
-except:
+    _ARPHABET = nltk.corpus.cmudict.dict()
+except BaseException:
     nltk.download("cmudict")
-    _arphabet = nltk.corpus.cmudict.dict()
+    _ARPHABET = nltk.corpus.cmudict.dict()
 
 
-def _maybe_get_arpabet(word, p):
+def _maybe_get_arpabet(word, pro):
     try:
-        phonemes = _arphabet[word][0]
+        phonemes = _ARPHABET[word][0]
         phonemes = " ".join(phonemes)
     except KeyError:
         return word
 
-    return '{%s}' % phonemes if random() < p else word
+    return '{%s}' % phonemes if ord(os.urandom(1)) < pro else word
 
 
-def mix_pronunciation(text, p):
-    text = ' '.join(_maybe_get_arpabet(word, p) for word in text.split(' '))
+def mix_pronunciation(text, pro):
+    text = ' '.join(_maybe_get_arpabet(word, pro) for word in text.split(' '))
     return text
 
 
 def text_to_sequence(text, p=0.0):
-    if p >= 0:
-        text = mix_pronunciation(text, p)
+    pro = p
+    if pro >= 0:
+        text = mix_pronunciation(text, pro)
     from autokeras.pretrained.voice_generator.deepvoice3_pytorch.text.text import text_to_sequence
     text = text_to_sequence(text, ["english_cleaners"])
     return text


Test patch: