We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PortableImageSupervised.predict is slow with many images
# Bug Description (maybe feature enhancement.)
PortableImageSupervised.predict method on the cifar10 test dataset is a bit slower when test dataset size is bigger. The number of images in the dataset is 10000.
Maybe predict should be run on gpu like the code in the url above?
https://github.com/jhfjhfj1/autokeras/compare/master...sammy-yusuke:0e71db8dab4841a577c7943daf4bfdb19acbfc0c

### Reproducing Steps
1. Place all files in the URL below into some dir
https://gist.github.com/sammy-yusuke/bc8aa440d2fdbe3908198fdcf82442e2
2. Train model
```
python train_cifar10.py --timelimit-h 0.5 --dataset cifar10
```
3. Test model
```
python test_cifar10.py --training-output-path ~/nas_try/${trained_date}
```
### Expected Behavior
Step 3 should finish in at least 30 min.

### Setup Details
Include the details about the versions of:
 - OS type and version: Description:    Ubuntu 16.04.5 LTS
 - Python: 3.6.6
 - autokeras: master
 - scikit-learn:0.19.1
 - numpy:1.14.5
 - keras:2.2.2
 - scipy:1.1.0
 - tensorflow:1.10.0
 - pytorch:0.4.1

### Additional context
I was just trying to see all the results of all searched models by autokeras.

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `autokeras/image/image_supervised.py`
Content:
```
1 import os
2 from abc import ABC
3 from functools import reduce
4 
5 import numpy as np
6 import torch
7 
8 from autokeras.constant import Constant
9 from autokeras.nn.loss_function import classification_loss, regression_loss
10 from autokeras.nn.metric import Accuracy, MSE
11 from autokeras.preprocessor import OneHotEncoder, ImageDataTransformer
12 from autokeras.supervised import PortableClass, DeepSupervised
13 from autokeras.utils import pickle_to_file, \
14     read_csv_file, read_image, compute_image_resize_params, resize_image_data
15 
16 
17 def read_images(img_file_names, images_dir_path):
18     """Read the images from the path and return their numpy.ndarray instance.
19         Return a numpy.ndarray instance containing the training data.
20 
21     Args:
22         img_file_names: List containing images names.
23         images_dir_path: Path to the directory containing images.
24     """
25     x_train = []
26     if os.path.isdir(images_dir_path):
27         for img_file in img_file_names:
28             img_path = os.path.join(images_dir_path, img_file)
29             if os.path.exists(img_path):
30                 img = read_image(img_path)
31                 if len(img.shape) < 3:
32                     img = img[..., np.newaxis]
33                 x_train.append(img)
34             else:
35                 raise ValueError("%s image does not exist" % img_file)
36     else:
37         raise ValueError("Directory containing images does not exist")
38     return np.asanyarray(x_train)
39 
40 
41 def load_image_dataset(csv_file_path, images_path):
42     """Load images from the files and labels from a csv file.
43 
44     Second, the dataset is a set of images and the labels are in a CSV file.
45     The CSV file should contain two columns whose names are 'File Name' and 'Label'.
46     The file names in the first column should match the file names of the images with extensions,
47     e.g., .jpg, .png.
48     The path to the CSV file should be passed through the `csv_file_path`.
49     The path to the directory containing all the images should be passed through `image_path`.
50 
51     Args:
52         csv_file_path: CSV file path.
53         images_path: Path where images exist.
54 
55     Returns:
56         x: Four dimensional numpy.ndarray. The channel dimension is the last dimension.
57         y: The labels.
58     """
59     img_file_name, y = read_csv_file(csv_file_path)
60     x = read_images(img_file_name, images_path)
61     return np.array(x), np.array(y)
62 
63 
64 class ImageSupervised(DeepSupervised, ABC):
65     """Abstract image supervised class.
66 
67     Attributes:
68         path: A path to the directory to save the classifier as well as intermediate results.
69         cnn: CNN module from net_module.py.
70         y_encoder: Label encoder, used in transform_y or inverse_transform_y for encode the label. For example,
71                     if one hot encoder needed, y_encoder can be OneHotEncoder.
72         data_transformer: A transformer class to process the data. See example as ImageDataTransformer.
73         verbose: A boolean value indicating the verbosity mode which determines whether the search process
74                 will be printed to stdout.
75         augment: A boolean value indicating whether the data needs augmentation.  If not define, then it
76                 will use the value of Constant.DATA_AUGMENTATION which is True by default.
77         searcher_args: A dictionary containing the parameters for the searcher's __init__ function.
78         resize_height: resize image height.
79         resize_width: resize image width.
80     """
81 
82     def __init__(self, augment=None, **kwargs):
83         """Initialize the instance.
84         The classifier will be loaded from the files in 'path' if parameter 'resume' is True.
85         Otherwise it would create a new one.
86         Args:
87             verbose: A boolean of whether the search process will be printed to stdout.
88             path: A string. The path to a directory, where the intermediate results are saved.
89             resume: A boolean. If True, the classifier will continue to previous work saved in path.
90                 Otherwise, the classifier will start a new search.
91             searcher_args: A dictionary containing the parameters for the searcher's __init__ function.
92             augment: A boolean value indicating whether the data needs augmentation. If not define, then it
93                 will use the value of Constant.DATA_AUGMENTATION which is True by default.
94         """
95         self.augment = augment if augment is not None else Constant.DATA_AUGMENTATION
96         self.resize_shape = []
97 
98         super().__init__(**kwargs)
99 
100     def fit(self, x, y, time_limit=None):
101         x = np.array(x)
102         y = np.array(y)
103 
104         if self.verbose:
105             print("Preprocessing the images.")
106 
107         self.resize_shape = compute_image_resize_params(x)
108 
109         x = resize_image_data(x, self.resize_shape)
110 
111         if self.verbose:
112             print("Preprocessing finished.")
113 
114         super().fit(x, y, time_limit)
115 
116     def init_transformer(self, x):
117         if self.data_transformer is None:
118             self.data_transformer = ImageDataTransformer(x, augment=self.augment)
119 
120     def export_autokeras_model(self, model_file_name):
121         """ Creates and Exports the AutoKeras model to the given filename. """
122         portable_model = PortableImageSupervised(graph=self.cnn.best_model,
123                                                  y_encoder=self.y_encoder,
124                                                  data_transformer=self.data_transformer,
125                                                  metric=self.metric,
126                                                  inverse_transform_y_method=self.inverse_transform_y,
127                                                  resize_params=self.resize_shape)
128         pickle_to_file(portable_model, model_file_name)
129 
130     def preprocess(self, x):
131         return resize_image_data(x, self.resize_shape)
132 
133 
134 class ImageClassifier(ImageSupervised):
135     """ImageClassifier class.
136 
137     It is used for image classification. It searches convolutional neural network architectures
138     for the best configuration for the image dataset.
139     """
140 
141     @property
142     def loss(self):
143         return classification_loss
144 
145     def transform_y(self, y_train):
146         # Transform y_train.
147         if self.y_encoder is None:
148             self.y_encoder = OneHotEncoder()
149             self.y_encoder.fit(y_train)
150         y_train = self.y_encoder.transform(y_train)
151         return y_train
152 
153     def inverse_transform_y(self, output):
154         return self.y_encoder.inverse_transform(output)
155 
156     def get_n_output_node(self):
157         return self.y_encoder.n_classes
158 
159     @property
160     def metric(self):
161         return Accuracy
162 
163 
164 class ImageClassifier1D(ImageClassifier):
165     """ ImageClassifier1D class.
166 
167     It is used for 1D image classification. It searches convolutional neural network architectures
168     for the best configuration for the 1D image dataset.
169     """
170 
171     def __init__(self, **kwargs):
172         kwargs['augment'] = False
173         super().__init__(**kwargs)
174 
175 
176 class ImageClassifier3D(ImageClassifier):
177     """ ImageClassifier3D class.
178 
179     It is used for 3D image classification. It searches convolutional neural network architectures
180     for the best configuration for the 1D image dataset.
181     """
182 
183     def __init__(self, **kwargs):
184         kwargs['augment'] = False
185         super().__init__(**kwargs)
186 
187 
188 class ImageRegressor(ImageSupervised):
189     """ImageRegressor class.
190 
191     It is used for image regression. It searches convolutional neural network architectures
192     for the best configuration for the image dataset.
193     """
194 
195     @property
196     def loss(self):
197         return regression_loss
198 
199     @property
200     def metric(self):
201         return MSE
202 
203     def get_n_output_node(self):
204         return 1
205 
206     def transform_y(self, y_train):
207         return y_train.flatten().reshape(len(y_train), 1)
208 
209     def inverse_transform_y(self, output):
210         return output.flatten()
211 
212 
213 class ImageRegressor1D(ImageRegressor):
214     """ ImageRegressor1D class.
215 
216     It is used for 1D image regression. It searches convolutional neural network architectures
217     for the best configuration for the 1D image dataset.
218     """
219 
220     def __init__(self, **kwargs):
221         kwargs['augment'] = False
222         super().__init__(**kwargs)
223 
224 
225 class ImageRegressor3D(ImageRegressor):
226     """ ImageRegressor3D class.
227 
228     It is used for 3D image regression. It searches convolutional neural network architectures
229     for the best configuration for the 1D image dataset.
230     """
231 
232     def __init__(self, **kwargs):
233         kwargs['augment'] = False
234         super().__init__(**kwargs)
235 
236 
237 class PortableImageSupervised(PortableClass):
238     def __init__(self, graph, data_transformer, y_encoder, metric, inverse_transform_y_method, resize_params):
239         """Initialize the instance.
240         Args:
241             graph: The graph form of the learned model
242         """
243         super().__init__(graph)
244         self.data_transformer = data_transformer
245         self.y_encoder = y_encoder
246         self.metric = metric
247         self.inverse_transform_y_method = inverse_transform_y_method
248         self.resize_shape = resize_params
249 
250     def predict(self, x_test):
251         """Return predict results for the testing data.
252 
253         Args:
254             x_test: An instance of numpy.ndarray containing the testing data.
255 
256         Returns:
257             A numpy.ndarray containing the results.
258         """
259         if Constant.LIMIT_MEMORY:
260             pass
261 
262         test_loader = self.data_transformer.transform_test(x_test)
263         model = self.graph.produce_model()
264         model.eval()
265 
266         outputs = []
267         with torch.no_grad():
268             for index, inputs in enumerate(test_loader):
269                 outputs.append(model(inputs).numpy())
270         output = reduce(lambda x, y: np.concatenate((x, y)), outputs)
271         return self.inverse_transform_y(output)
272 
273     def inverse_transform_y(self, output):
274         return self.inverse_transform_y_method(output)
275 
276     def evaluate(self, x_test, y_test):
277         """Return the accuracy score between predict value and `y_test`."""
278         x_test = resize_image_data(x_test, self.resize_shape)
279         y_predict = self.predict(x_test)
280         return self.metric().evaluate(y_test, y_predict)
281
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/autokeras/image/image_supervised.py b/autokeras/image/image_supervised.py
--- a/autokeras/image/image_supervised.py
+++ b/autokeras/image/image_supervised.py
@@ -259,6 +259,7 @@
         if Constant.LIMIT_MEMORY:
             pass
 
+        x_test = resize_image_data(x_test, self.resize_shape)
         test_loader = self.data_transformer.transform_test(x_test)
         model = self.graph.produce_model()
         model.eval()
@@ -275,6 +276,5 @@
 
     def evaluate(self, x_test, y_test):
         """Return the accuracy score between predict value and `y_test`."""
-        x_test = resize_image_data(x_test, self.resize_shape)
         y_predict = self.predict(x_test)
         return self.metric().evaluate(y_test, y_predict)

{"golden_diff": "diff --git a/autokeras/image/image_supervised.py b/autokeras/image/image_supervised.py\n--- a/autokeras/image/image_supervised.py\n+++ b/autokeras/image/image_supervised.py\n@@ -259,6 +259,7 @@\n         if Constant.LIMIT_MEMORY:\n             pass\n \n+        x_test = resize_image_data(x_test, self.resize_shape)\n         test_loader = self.data_transformer.transform_test(x_test)\n         model = self.graph.produce_model()\n         model.eval()\n@@ -275,6 +276,5 @@\n \n     def evaluate(self, x_test, y_test):\n         \"\"\"Return the accuracy score between predict value and `y_test`.\"\"\"\n-        x_test = resize_image_data(x_test, self.resize_shape)\n         y_predict = self.predict(x_test)\n         return self.metric().evaluate(y_test, y_predict)\n", "issue": "PortableImageSupervised.predict is slow with many images\n# Bug Description (maybe feature enhancement.)\r\nPortableImageSupervised.predict method on the cifar10 test dataset is a bit slower when test dataset size is bigger. The number of images in the dataset is 10000.\r\nMaybe predict should be run on gpu like the code in the url above?\r\nhttps://github.com/jhfjhfj1/autokeras/compare/master...sammy-yusuke:0e71db8dab4841a577c7943daf4bfdb19acbfc0c\r\n\r\n### Reproducing Steps\r\n1. Place all files in the URL below into some dir\r\nhttps://gist.github.com/sammy-yusuke/bc8aa440d2fdbe3908198fdcf82442e2\r\n2. Train model\r\n```\r\npython train_cifar10.py --timelimit-h 0.5 --dataset cifar10\r\n```\r\n3. Test model\r\n```\r\npython test_cifar10.py --training-output-path ~/nas_try/${trained_date}\r\n```\r\n### Expected Behavior\r\nStep 3 should finish in at least 30 min.\r\n\r\n### Setup Details\r\nInclude the details about the versions of:\r\n - OS type and version: Description:    Ubuntu 16.04.5 LTS\r\n - Python: 3.6.6\r\n - autokeras: master\r\n - scikit-learn:0.19.1\r\n - numpy:1.14.5\r\n - keras:2.2.2\r\n - scipy:1.1.0\r\n - tensorflow:1.10.0\r\n - pytorch:0.4.1\r\n\r\n### Additional context\r\nI was just trying to see all the results of all searched models by autokeras.\n", "before_files": [{"content": "import os\nfrom abc import ABC\nfrom functools import reduce\n\nimport numpy as np\nimport torch\n\nfrom autokeras.constant import Constant\nfrom autokeras.nn.loss_function import classification_loss, regression_loss\nfrom autokeras.nn.metric import Accuracy, MSE\nfrom autokeras.preprocessor import OneHotEncoder, ImageDataTransformer\nfrom autokeras.supervised import PortableClass, DeepSupervised\nfrom autokeras.utils import pickle_to_file, \\\n    read_csv_file, read_image, compute_image_resize_params, resize_image_data\n\n\ndef read_images(img_file_names, images_dir_path):\n    \"\"\"Read the images from the path and return their numpy.ndarray instance.\n        Return a numpy.ndarray instance containing the training data.\n\n    Args:\n        img_file_names: List containing images names.\n        images_dir_path: Path to the directory containing images.\n    \"\"\"\n    x_train = []\n    if os.path.isdir(images_dir_path):\n        for img_file in img_file_names:\n            img_path = os.path.join(images_dir_path, img_file)\n            if os.path.exists(img_path):\n                img = read_image(img_path)\n                if len(img.shape) < 3:\n                    img = img[..., np.newaxis]\n                x_train.append(img)\n            else:\n                raise ValueError(\"%s image does not exist\" % img_file)\n    else:\n        raise ValueError(\"Directory containing images does not exist\")\n    return np.asanyarray(x_train)\n\n\ndef load_image_dataset(csv_file_path, images_path):\n    \"\"\"Load images from the files and labels from a csv file.\n\n    Second, the dataset is a set of images and the labels are in a CSV file.\n    The CSV file should contain two columns whose names are 'File Name' and 'Label'.\n    The file names in the first column should match the file names of the images with extensions,\n    e.g., .jpg, .png.\n    The path to the CSV file should be passed through the `csv_file_path`.\n    The path to the directory containing all the images should be passed through `image_path`.\n\n    Args:\n        csv_file_path: CSV file path.\n        images_path: Path where images exist.\n\n    Returns:\n        x: Four dimensional numpy.ndarray. The channel dimension is the last dimension.\n        y: The labels.\n    \"\"\"\n    img_file_name, y = read_csv_file(csv_file_path)\n    x = read_images(img_file_name, images_path)\n    return np.array(x), np.array(y)\n\n\nclass ImageSupervised(DeepSupervised, ABC):\n    \"\"\"Abstract image supervised class.\n\n    Attributes:\n        path: A path to the directory to save the classifier as well as intermediate results.\n        cnn: CNN module from net_module.py.\n        y_encoder: Label encoder, used in transform_y or inverse_transform_y for encode the label. For example,\n                    if one hot encoder needed, y_encoder can be OneHotEncoder.\n        data_transformer: A transformer class to process the data. See example as ImageDataTransformer.\n        verbose: A boolean value indicating the verbosity mode which determines whether the search process\n                will be printed to stdout.\n        augment: A boolean value indicating whether the data needs augmentation.  If not define, then it\n                will use the value of Constant.DATA_AUGMENTATION which is True by default.\n        searcher_args: A dictionary containing the parameters for the searcher's __init__ function.\n        resize_height: resize image height.\n        resize_width: resize image width.\n    \"\"\"\n\n    def __init__(self, augment=None, **kwargs):\n        \"\"\"Initialize the instance.\n        The classifier will be loaded from the files in 'path' if parameter 'resume' is True.\n        Otherwise it would create a new one.\n        Args:\n            verbose: A boolean of whether the search process will be printed to stdout.\n            path: A string. The path to a directory, where the intermediate results are saved.\n            resume: A boolean. If True, the classifier will continue to previous work saved in path.\n                Otherwise, the classifier will start a new search.\n            searcher_args: A dictionary containing the parameters for the searcher's __init__ function.\n            augment: A boolean value indicating whether the data needs augmentation. If not define, then it\n                will use the value of Constant.DATA_AUGMENTATION which is True by default.\n        \"\"\"\n        self.augment = augment if augment is not None else Constant.DATA_AUGMENTATION\n        self.resize_shape = []\n\n        super().__init__(**kwargs)\n\n    def fit(self, x, y, time_limit=None):\n        x = np.array(x)\n        y = np.array(y)\n\n        if self.verbose:\n            print(\"Preprocessing the images.\")\n\n        self.resize_shape = compute_image_resize_params(x)\n\n        x = resize_image_data(x, self.resize_shape)\n\n        if self.verbose:\n            print(\"Preprocessing finished.\")\n\n        super().fit(x, y, time_limit)\n\n    def init_transformer(self, x):\n        if self.data_transformer is None:\n            self.data_transformer = ImageDataTransformer(x, augment=self.augment)\n\n    def export_autokeras_model(self, model_file_name):\n        \"\"\" Creates and Exports the AutoKeras model to the given filename. \"\"\"\n        portable_model = PortableImageSupervised(graph=self.cnn.best_model,\n                                                 y_encoder=self.y_encoder,\n                                                 data_transformer=self.data_transformer,\n                                                 metric=self.metric,\n                                                 inverse_transform_y_method=self.inverse_transform_y,\n                                                 resize_params=self.resize_shape)\n        pickle_to_file(portable_model, model_file_name)\n\n    def preprocess(self, x):\n        return resize_image_data(x, self.resize_shape)\n\n\nclass ImageClassifier(ImageSupervised):\n    \"\"\"ImageClassifier class.\n\n    It is used for image classification. It searches convolutional neural network architectures\n    for the best configuration for the image dataset.\n    \"\"\"\n\n    @property\n    def loss(self):\n        return classification_loss\n\n    def transform_y(self, y_train):\n        # Transform y_train.\n        if self.y_encoder is None:\n            self.y_encoder = OneHotEncoder()\n            self.y_encoder.fit(y_train)\n        y_train = self.y_encoder.transform(y_train)\n        return y_train\n\n    def inverse_transform_y(self, output):\n        return self.y_encoder.inverse_transform(output)\n\n    def get_n_output_node(self):\n        return self.y_encoder.n_classes\n\n    @property\n    def metric(self):\n        return Accuracy\n\n\nclass ImageClassifier1D(ImageClassifier):\n    \"\"\" ImageClassifier1D class.\n\n    It is used for 1D image classification. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass ImageClassifier3D(ImageClassifier):\n    \"\"\" ImageClassifier3D class.\n\n    It is used for 3D image classification. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass ImageRegressor(ImageSupervised):\n    \"\"\"ImageRegressor class.\n\n    It is used for image regression. It searches convolutional neural network architectures\n    for the best configuration for the image dataset.\n    \"\"\"\n\n    @property\n    def loss(self):\n        return regression_loss\n\n    @property\n    def metric(self):\n        return MSE\n\n    def get_n_output_node(self):\n        return 1\n\n    def transform_y(self, y_train):\n        return y_train.flatten().reshape(len(y_train), 1)\n\n    def inverse_transform_y(self, output):\n        return output.flatten()\n\n\nclass ImageRegressor1D(ImageRegressor):\n    \"\"\" ImageRegressor1D class.\n\n    It is used for 1D image regression. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass ImageRegressor3D(ImageRegressor):\n    \"\"\" ImageRegressor3D class.\n\n    It is used for 3D image regression. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass PortableImageSupervised(PortableClass):\n    def __init__(self, graph, data_transformer, y_encoder, metric, inverse_transform_y_method, resize_params):\n        \"\"\"Initialize the instance.\n        Args:\n            graph: The graph form of the learned model\n        \"\"\"\n        super().__init__(graph)\n        self.data_transformer = data_transformer\n        self.y_encoder = y_encoder\n        self.metric = metric\n        self.inverse_transform_y_method = inverse_transform_y_method\n        self.resize_shape = resize_params\n\n    def predict(self, x_test):\n        \"\"\"Return predict results for the testing data.\n\n        Args:\n            x_test: An instance of numpy.ndarray containing the testing data.\n\n        Returns:\n            A numpy.ndarray containing the results.\n        \"\"\"\n        if Constant.LIMIT_MEMORY:\n            pass\n\n        test_loader = self.data_transformer.transform_test(x_test)\n        model = self.graph.produce_model()\n        model.eval()\n\n        outputs = []\n        with torch.no_grad():\n            for index, inputs in enumerate(test_loader):\n                outputs.append(model(inputs).numpy())\n        output = reduce(lambda x, y: np.concatenate((x, y)), outputs)\n        return self.inverse_transform_y(output)\n\n    def inverse_transform_y(self, output):\n        return self.inverse_transform_y_method(output)\n\n    def evaluate(self, x_test, y_test):\n        \"\"\"Return the accuracy score between predict value and `y_test`.\"\"\"\n        x_test = resize_image_data(x_test, self.resize_shape)\n        y_predict = self.predict(x_test)\n        return self.metric().evaluate(y_test, y_predict)\n", "path": "autokeras/image/image_supervised.py"}], "after_files": [{"content": "import os\nfrom abc import ABC\nfrom functools import reduce\n\nimport numpy as np\nimport torch\n\nfrom autokeras.constant import Constant\nfrom autokeras.nn.loss_function import classification_loss, regression_loss\nfrom autokeras.nn.metric import Accuracy, MSE\nfrom autokeras.preprocessor import OneHotEncoder, ImageDataTransformer\nfrom autokeras.supervised import PortableClass, DeepSupervised\nfrom autokeras.utils import pickle_to_file, \\\n    read_csv_file, read_image, compute_image_resize_params, resize_image_data\n\n\ndef read_images(img_file_names, images_dir_path):\n    \"\"\"Read the images from the path and return their numpy.ndarray instance.\n        Return a numpy.ndarray instance containing the training data.\n\n    Args:\n        img_file_names: List containing images names.\n        images_dir_path: Path to the directory containing images.\n    \"\"\"\n    x_train = []\n    if os.path.isdir(images_dir_path):\n        for img_file in img_file_names:\n            img_path = os.path.join(images_dir_path, img_file)\n            if os.path.exists(img_path):\n                img = read_image(img_path)\n                if len(img.shape) < 3:\n                    img = img[..., np.newaxis]\n                x_train.append(img)\n            else:\n                raise ValueError(\"%s image does not exist\" % img_file)\n    else:\n        raise ValueError(\"Directory containing images does not exist\")\n    return np.asanyarray(x_train)\n\n\ndef load_image_dataset(csv_file_path, images_path):\n    \"\"\"Load images from the files and labels from a csv file.\n\n    Second, the dataset is a set of images and the labels are in a CSV file.\n    The CSV file should contain two columns whose names are 'File Name' and 'Label'.\n    The file names in the first column should match the file names of the images with extensions,\n    e.g., .jpg, .png.\n    The path to the CSV file should be passed through the `csv_file_path`.\n    The path to the directory containing all the images should be passed through `image_path`.\n\n    Args:\n        csv_file_path: CSV file path.\n        images_path: Path where images exist.\n\n    Returns:\n        x: Four dimensional numpy.ndarray. The channel dimension is the last dimension.\n        y: The labels.\n    \"\"\"\n    img_file_name, y = read_csv_file(csv_file_path)\n    x = read_images(img_file_name, images_path)\n    return np.array(x), np.array(y)\n\n\nclass ImageSupervised(DeepSupervised, ABC):\n    \"\"\"Abstract image supervised class.\n\n    Attributes:\n        path: A path to the directory to save the classifier as well as intermediate results.\n        cnn: CNN module from net_module.py.\n        y_encoder: Label encoder, used in transform_y or inverse_transform_y for encode the label. For example,\n                    if one hot encoder needed, y_encoder can be OneHotEncoder.\n        data_transformer: A transformer class to process the data. See example as ImageDataTransformer.\n        verbose: A boolean value indicating the verbosity mode which determines whether the search process\n                will be printed to stdout.\n        augment: A boolean value indicating whether the data needs augmentation.  If not define, then it\n                will use the value of Constant.DATA_AUGMENTATION which is True by default.\n        searcher_args: A dictionary containing the parameters for the searcher's __init__ function.\n        resize_height: resize image height.\n        resize_width: resize image width.\n    \"\"\"\n\n    def __init__(self, augment=None, **kwargs):\n        \"\"\"Initialize the instance.\n        The classifier will be loaded from the files in 'path' if parameter 'resume' is True.\n        Otherwise it would create a new one.\n        Args:\n            verbose: A boolean of whether the search process will be printed to stdout.\n            path: A string. The path to a directory, where the intermediate results are saved.\n            resume: A boolean. If True, the classifier will continue to previous work saved in path.\n                Otherwise, the classifier will start a new search.\n            searcher_args: A dictionary containing the parameters for the searcher's __init__ function.\n            augment: A boolean value indicating whether the data needs augmentation. If not define, then it\n                will use the value of Constant.DATA_AUGMENTATION which is True by default.\n        \"\"\"\n        self.augment = augment if augment is not None else Constant.DATA_AUGMENTATION\n        self.resize_shape = []\n\n        super().__init__(**kwargs)\n\n    def fit(self, x, y, time_limit=None):\n        x = np.array(x)\n        y = np.array(y)\n\n        if self.verbose:\n            print(\"Preprocessing the images.\")\n\n        self.resize_shape = compute_image_resize_params(x)\n\n        x = resize_image_data(x, self.resize_shape)\n\n        if self.verbose:\n            print(\"Preprocessing finished.\")\n\n        super().fit(x, y, time_limit)\n\n    def init_transformer(self, x):\n        if self.data_transformer is None:\n            self.data_transformer = ImageDataTransformer(x, augment=self.augment)\n\n    def export_autokeras_model(self, model_file_name):\n        \"\"\" Creates and Exports the AutoKeras model to the given filename. \"\"\"\n        portable_model = PortableImageSupervised(graph=self.cnn.best_model,\n                                                 y_encoder=self.y_encoder,\n                                                 data_transformer=self.data_transformer,\n                                                 metric=self.metric,\n                                                 inverse_transform_y_method=self.inverse_transform_y,\n                                                 resize_params=self.resize_shape)\n        pickle_to_file(portable_model, model_file_name)\n\n    def preprocess(self, x):\n        return resize_image_data(x, self.resize_shape)\n\n\nclass ImageClassifier(ImageSupervised):\n    \"\"\"ImageClassifier class.\n\n    It is used for image classification. It searches convolutional neural network architectures\n    for the best configuration for the image dataset.\n    \"\"\"\n\n    @property\n    def loss(self):\n        return classification_loss\n\n    def transform_y(self, y_train):\n        # Transform y_train.\n        if self.y_encoder is None:\n            self.y_encoder = OneHotEncoder()\n            self.y_encoder.fit(y_train)\n        y_train = self.y_encoder.transform(y_train)\n        return y_train\n\n    def inverse_transform_y(self, output):\n        return self.y_encoder.inverse_transform(output)\n\n    def get_n_output_node(self):\n        return self.y_encoder.n_classes\n\n    @property\n    def metric(self):\n        return Accuracy\n\n\nclass ImageClassifier1D(ImageClassifier):\n    \"\"\" ImageClassifier1D class.\n\n    It is used for 1D image classification. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass ImageClassifier3D(ImageClassifier):\n    \"\"\" ImageClassifier3D class.\n\n    It is used for 3D image classification. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass ImageRegressor(ImageSupervised):\n    \"\"\"ImageRegressor class.\n\n    It is used for image regression. It searches convolutional neural network architectures\n    for the best configuration for the image dataset.\n    \"\"\"\n\n    @property\n    def loss(self):\n        return regression_loss\n\n    @property\n    def metric(self):\n        return MSE\n\n    def get_n_output_node(self):\n        return 1\n\n    def transform_y(self, y_train):\n        return y_train.flatten().reshape(len(y_train), 1)\n\n    def inverse_transform_y(self, output):\n        return output.flatten()\n\n\nclass ImageRegressor1D(ImageRegressor):\n    \"\"\" ImageRegressor1D class.\n\n    It is used for 1D image regression. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass ImageRegressor3D(ImageRegressor):\n    \"\"\" ImageRegressor3D class.\n\n    It is used for 3D image regression. It searches convolutional neural network architectures\n    for the best configuration for the 1D image dataset.\n    \"\"\"\n\n    def __init__(self, **kwargs):\n        kwargs['augment'] = False\n        super().__init__(**kwargs)\n\n\nclass PortableImageSupervised(PortableClass):\n    def __init__(self, graph, data_transformer, y_encoder, metric, inverse_transform_y_method, resize_params):\n        \"\"\"Initialize the instance.\n        Args:\n            graph: The graph form of the learned model\n        \"\"\"\n        super().__init__(graph)\n        self.data_transformer = data_transformer\n        self.y_encoder = y_encoder\n        self.metric = metric\n        self.inverse_transform_y_method = inverse_transform_y_method\n        self.resize_shape = resize_params\n\n    def predict(self, x_test):\n        \"\"\"Return predict results for the testing data.\n\n        Args:\n            x_test: An instance of numpy.ndarray containing the testing data.\n\n        Returns:\n            A numpy.ndarray containing the results.\n        \"\"\"\n        if Constant.LIMIT_MEMORY:\n            pass\n\n        x_test = resize_image_data(x_test, self.resize_shape)\n        test_loader = self.data_transformer.transform_test(x_test)\n        model = self.graph.produce_model()\n        model.eval()\n\n        outputs = []\n        with torch.no_grad():\n            for index, inputs in enumerate(test_loader):\n                outputs.append(model(inputs).numpy())\n        output = reduce(lambda x, y: np.concatenate((x, y)), outputs)\n        return self.inverse_transform_y(output)\n\n    def inverse_transform_y(self, output):\n        return self.inverse_transform_y_method(output)\n\n    def evaluate(self, x_test, y_test):\n        \"\"\"Return the accuracy score between predict value and `y_test`.\"\"\"\n        y_predict = self.predict(x_test)\n        return self.metric().evaluate(y_test, y_predict)\n", "path": "autokeras/image/image_supervised.py"}]}