We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PaddleGAN中attgan保存模型报错
在在PaddleCV/PaddleGAN目录中，执行bash scripts/run_attgan.sh，对attgan模型进行训练，在保存模型时报错，报错信息如下:
![image](https://user-images.githubusercontent.com/37854899/60489578-415c9900-9cd7-11e9-8d29-e66c13b6d143.png)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `PaddleCV/PaddleGAN/util/utility.py`
Content:
```
1 #copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
2 #
3 #Licensed under the Apache License, Version 2.0 (the "License");
4 #you may not use this file except in compliance with the License.
5 #You may obtain a copy of the License at
6 #
7 #    http://www.apache.org/licenses/LICENSE-2.0
8 #
9 #Unless required by applicable law or agreed to in writing, software
10 #distributed under the License is distributed on an "AS IS" BASIS,
11 #WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 #See the License for the specific language governing permissions and
13 #limitations under the License.
14 
15 from __future__ import absolute_import
16 from __future__ import division
17 from __future__ import print_function
18 import paddle.fluid as fluid
19 import os
20 import sys
21 import math
22 import distutils.util
23 import numpy as np
24 import inspect
25 import matplotlib
26 import six
27 matplotlib.use('agg')
28 import matplotlib.pyplot as plt
29 import matplotlib.gridspec as gridspec
30 import imageio
31 import copy
32 
33 img_dim = 28
34 
35 
36 def plot(gen_data):
37     pad_dim = 1
38     paded = pad_dim + img_dim
39     gen_data = gen_data.reshape(gen_data.shape[0], img_dim, img_dim)
40     n = int(math.ceil(math.sqrt(gen_data.shape[0])))
41     gen_data = (np.pad(
42         gen_data, [[0, n * n - gen_data.shape[0]], [pad_dim, 0], [pad_dim, 0]],
43         'constant').reshape((n, n, paded, paded)).transpose((0, 2, 1, 3))
44                 .reshape((n * paded, n * paded)))
45     fig = plt.figure(figsize=(8, 8))
46     plt.axis('off')
47     plt.imshow(gen_data, cmap='Greys_r', vmin=-1, vmax=1)
48     return fig
49 
50 
51 def checkpoints(epoch, cfg, exe, trainer, name):
52     output_path = cfg.output + '/checkpoints/' + str(epoch)
53     if not os.path.exists(output_path):
54         os.makedirs(output_path)
55     fluid.io.save_persistables(
56         exe, os.path.join(output_path, name), main_program=trainer.program)
57     print('save checkpoints {} to {}'.format(name, output_path))
58     sys.stdout.flush()
59 
60 
61 def init_checkpoints(cfg, exe, trainer, name):
62     assert os.path.exists(cfg.init_model), "{} cannot be found.".format(
63         cfg.init_model)
64     fluid.io.load_persistables(
65         exe, os.path.join(cfg.init_model, name), main_program=trainer.program)
66     print('load checkpoints {} {} DONE'.format(cfg.init_model, name))
67     sys.stdout.flush()
68 
69 
70 def save_test_image(epoch,
71                     cfg,
72                     exe,
73                     place,
74                     test_program,
75                     g_trainer,
76                     A_test_reader,
77                     B_test_reader=None):
78     out_path = cfg.output + '/test'
79     if not os.path.exists(out_path):
80         os.makedirs(out_path)
81     if cfg.model_net == "Pix2pix":
82         for data in zip(A_test_reader()):
83             data_A, data_B, name = data[0]
84             name = name[0]
85             tensor_A = fluid.LoDTensor()
86             tensor_B = fluid.LoDTensor()
87             tensor_A.set(data_A, place)
88             tensor_B.set(data_B, place)
89             fake_B_temp = exe.run(
90                 test_program,
91                 fetch_list=[g_trainer.fake_B],
92                 feed={"input_A": tensor_A,
93                       "input_B": tensor_B})
94             fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])
95             input_A_temp = np.squeeze(data_A[0]).transpose([1, 2, 0])
96             input_B_temp = np.squeeze(data_A[0]).transpose([1, 2, 0])
97 
98             imageio.imwrite(out_path + "/fakeB_" + str(epoch) + "_" + name, (
99                 (fake_B_temp + 1) * 127.5).astype(np.uint8))
100             imageio.imwrite(out_path + "/inputA_" + str(epoch) + "_" + name, (
101                 (input_A_temp + 1) * 127.5).astype(np.uint8))
102             imageio.imwrite(out_path + "/inputB_" + str(epoch) + "_" + name, (
103                 (input_B_temp + 1) * 127.5).astype(np.uint8))
104     elif cfg.model_net == "StarGAN":
105         for data in zip(A_test_reader()):
106             real_img, label_org, name = data[0]
107             tensor_img = fluid.LoDTensor()
108             tensor_label_org = fluid.LoDTensor()
109             tensor_img.set(real_img, place)
110             tensor_label_org.set(label_org, place)
111             real_img_temp = np.squeeze(real_img).transpose([1, 2, 0])
112             images = [real_img_temp]
113             for i in range(cfg.c_dim):
114                 label_trg = np.zeros([1, cfg.c_dim]).astype("float32")
115                 label_trg[0][i] = 1
116                 tensor_label_trg = fluid.LoDTensor()
117                 tensor_label_trg.set(label_trg, place)
118                 fake_temp, rec_temp = exe.run(
119                     test_program,
120                     feed={
121                         "image_real": tensor_img,
122                         "label_org": tensor_label_org,
123                         "label_trg": tensor_label_trg
124                     },
125                     fetch_list=[g_trainer.fake_img, g_trainer.rec_img])
126                 fake_temp = np.squeeze(fake_temp[0]).transpose([1, 2, 0])
127                 rec_temp = np.squeeze(rec_temp[0]).transpose([1, 2, 0])
128                 images.append(fake_temp)
129                 images.append(rec_temp)
130             images_concat = np.concatenate(images, 1)
131             imageio.imwrite(out_path + "/fake_img" + str(epoch) + "_" + name[0],
132                             ((images_concat + 1) * 127.5).astype(np.uint8))
133     elif cfg.model_net == 'AttGAN' or cfg.model_net == 'STGAN':
134         for data in zip(A_test_reader()):
135             real_img, label_org, name = data[0]
136             attr_names = args.selected_attrs.split(',')
137             label_trg = copy.deepcopy(label_org)
138             tensor_img = fluid.LoDTensor()
139             tensor_label_org = fluid.LoDTensor()
140             tensor_label_trg = fluid.LoDTensor()
141             tensor_label_org_ = fluid.LoDTensor()
142             tensor_label_trg_ = fluid.LoDTensor()
143             tensor_img.set(real_img, place)
144             tensor_label_org.set(label_org, place)
145             real_img_temp = np.squeeze(real_img).transpose([0, 2, 3, 1])
146             images = [real_img_temp]
147             for i in range(cfg.c_dim):
148                 label_trg_tmp = copy.deepcopy(label_trg)
149 
150                 for j in range(len(label_org)):
151                     label_trg_tmp[j][i] = 1.0 - label_trg_tmp[j][i]
152                     label_trg_tmp = check_attribute_conflict(
153                         label_trg_tmp, attr_names[i], attr_names)
154 
155                 label_trg_ = list(
156                     map(lambda x: ((x * 2) - 1) * 0.5, label_trg_tmp))
157 
158                 for j in range(len(label_org)):
159                     label_trg_[j][i] = label_trg_[j][i] * 2.0
160                 tensor_label_org_.set(label_org, place)
161                 tensor_label_trg.set(label_trg, place)
162                 tensor_label_trg_.set(label_trg_, place)
163                 out = exe.run(test_program,
164                               feed={
165                                   "image_real": tensor_img,
166                                   "label_org": tensor_label_org,
167                                   "label_org_": tensor_label_org_,
168                                   "label_trg": tensor_label_trg,
169                                   "label_trg_": tensor_label_trg_
170                               },
171                               fetch_list=[g_trainer.fake_img])
172                 fake_temp = np.squeeze(out[0]).transpose([0, 2, 3, 1])
173                 images.append(fake_temp)
174             images_concat = np.concatenate(images, 1)
175             images_concat = np.concatenate(images_concat, 1)
176             imageio.imwrite(out_path + "/fake_img" + str(epoch) + '_' + name[0],
177                             ((images_concat + 1) * 127.5).astype(np.uint8))
178 
179     else:
180         for data_A, data_B in zip(A_test_reader(), B_test_reader()):
181             A_name = data_A[0][1]
182             B_name = data_B[0][1]
183             tensor_A = fluid.LoDTensor()
184             tensor_B = fluid.LoDTensor()
185             tensor_A.set(data_A[0][0], place)
186             tensor_B.set(data_B[0][0], place)
187             fake_A_temp, fake_B_temp, cyc_A_temp, cyc_B_temp = exe.run(
188                 test_program,
189                 fetch_list=[
190                     g_trainer.fake_A, g_trainer.fake_B, g_trainer.cyc_A,
191                     g_trainer.cyc_B
192                 ],
193                 feed={"input_A": tensor_A,
194                       "input_B": tensor_B})
195             fake_A_temp = np.squeeze(fake_A_temp[0]).transpose([1, 2, 0])
196             fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])
197             cyc_A_temp = np.squeeze(cyc_A_temp[0]).transpose([1, 2, 0])
198             cyc_B_temp = np.squeeze(cyc_B_temp[0]).transpose([1, 2, 0])
199             input_A_temp = np.squeeze(data_A[0][0]).transpose([1, 2, 0])
200             input_B_temp = np.squeeze(data_B[0][0]).transpose([1, 2, 0])
201 
202             imageio.imwrite(out_path + "/fakeB_" + str(epoch) + "_" + A_name, (
203                 (fake_B_temp + 1) * 127.5).astype(np.uint8))
204             imageio.imwrite(out_path + "/fakeA_" + str(epoch) + "_" + B_name, (
205                 (fake_A_temp + 1) * 127.5).astype(np.uint8))
206             imageio.imwrite(out_path + "/cycA_" + str(epoch) + "_" + A_name, (
207                 (cyc_A_temp + 1) * 127.5).astype(np.uint8))
208             imageio.imwrite(out_path + "/cycB_" + str(epoch) + "_" + B_name, (
209                 (cyc_B_temp + 1) * 127.5).astype(np.uint8))
210             imageio.imwrite(out_path + "/inputA_" + str(epoch) + "_" + A_name, (
211                 (input_A_temp + 1) * 127.5).astype(np.uint8))
212             imageio.imwrite(out_path + "/inputB_" + str(epoch) + "_" + B_name, (
213                 (input_B_temp + 1) * 127.5).astype(np.uint8))
214 
215 
216 class ImagePool(object):
217     def __init__(self, pool_size=50):
218         self.pool = []
219         self.count = 0
220         self.pool_size = pool_size
221 
222     def pool_image(self, image):
223         if self.count < self.pool_size:
224             self.pool.append(image)
225             self.count += 1
226             return image
227         else:
228             p = np.random.rand()
229             if p > 0.5:
230                 random_id = np.random.randint(0, self.pool_size - 1)
231                 temp = self.pool[random_id]
232                 self.pool[random_id] = image
233                 return temp
234             else:
235                 return image
236 
237 
238 def check_attribute_conflict(label_batch, attr, attrs):
239     def _set(label, value, attr):
240         if attr in attrs:
241             label[attrs.index(attr)] = value
242 
243     attr_id = attrs.index(attr)
244     for label in label_batch:
245         if attr in ['Bald', 'Receding_Hairline'] and attrs[attr_id] != 0:
246             _set(label, 0, 'Bangs')
247         elif attr == 'Bangs' and attrs[attr_id] != 0:
248             _set(label, 0, 'Bald')
249             _set(label, 0, 'Receding_Hairline')
250         elif attr in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair'
251                       ] and attrs[attr_id] != 0:
252             for a in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair']:
253                 if a != attr:
254                     _set(label, 0, a)
255         elif attr in ['Straight_Hair', 'Wavy_Hair'] and attrs[attr_id] != 0:
256             for a in ['Straight_Hair', 'Wavy_Hair']:
257                 if a != attr:
258                     _set(label, 0, a)
259         elif attr in ['Mustache', 'No_Beard'] and attrs[attr_id] != 0:
260             for a in ['Mustache', 'No_Beard']:
261                 if a != attr:
262                     _set(label, 0, a)
263     return label_batch
264
```
--- 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/PaddleCV/PaddleGAN/util/utility.py b/PaddleCV/PaddleGAN/util/utility.py
--- a/PaddleCV/PaddleGAN/util/utility.py
+++ b/PaddleCV/PaddleGAN/util/utility.py
@@ -133,7 +133,7 @@
     elif cfg.model_net == 'AttGAN' or cfg.model_net == 'STGAN':
         for data in zip(A_test_reader()):
             real_img, label_org, name = data[0]
-            attr_names = args.selected_attrs.split(',')
+            attr_names = cfg.selected_attrs.split(',')
             label_trg = copy.deepcopy(label_org)
             tensor_img = fluid.LoDTensor()
             tensor_label_org = fluid.LoDTensor()

{"golden_diff": "diff --git a/PaddleCV/PaddleGAN/util/utility.py b/PaddleCV/PaddleGAN/util/utility.py\n--- a/PaddleCV/PaddleGAN/util/utility.py\n+++ b/PaddleCV/PaddleGAN/util/utility.py\n@@ -133,7 +133,7 @@\n     elif cfg.model_net == 'AttGAN' or cfg.model_net == 'STGAN':\n         for data in zip(A_test_reader()):\n             real_img, label_org, name = data[0]\n-            attr_names = args.selected_attrs.split(',')\n+            attr_names = cfg.selected_attrs.split(',')\n             label_trg = copy.deepcopy(label_org)\n             tensor_img = fluid.LoDTensor()\n             tensor_label_org = fluid.LoDTensor()\n", "issue": "PaddleGAN\u4e2dattgan\u4fdd\u5b58\u6a21\u578b\u62a5\u9519\n\u5728\u5728PaddleCV/PaddleGAN\u76ee\u5f55\u4e2d\uff0c\u6267\u884cbash scripts/run_attgan.sh\uff0c\u5bf9attgan\u6a21\u578b\u8fdb\u884c\u8bad\u7ec3\uff0c\u5728\u4fdd\u5b58\u6a21\u578b\u65f6\u62a5\u9519\uff0c\u62a5\u9519\u4fe1\u606f\u5982\u4e0b:\r\n![image](https://user-images.githubusercontent.com/37854899/60489578-415c9900-9cd7-11e9-8d29-e66c13b6d143.png)\r\n\n", "before_files": [{"content": "#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport paddle.fluid as fluid\nimport os\nimport sys\nimport math\nimport distutils.util\nimport numpy as np\nimport inspect\nimport matplotlib\nimport six\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport imageio\nimport copy\n\nimg_dim = 28\n\n\ndef plot(gen_data):\n    pad_dim = 1\n    paded = pad_dim + img_dim\n    gen_data = gen_data.reshape(gen_data.shape[0], img_dim, img_dim)\n    n = int(math.ceil(math.sqrt(gen_data.shape[0])))\n    gen_data = (np.pad(\n        gen_data, [[0, n * n - gen_data.shape[0]], [pad_dim, 0], [pad_dim, 0]],\n        'constant').reshape((n, n, paded, paded)).transpose((0, 2, 1, 3))\n                .reshape((n * paded, n * paded)))\n    fig = plt.figure(figsize=(8, 8))\n    plt.axis('off')\n    plt.imshow(gen_data, cmap='Greys_r', vmin=-1, vmax=1)\n    return fig\n\n\ndef checkpoints(epoch, cfg, exe, trainer, name):\n    output_path = cfg.output + '/checkpoints/' + str(epoch)\n    if not os.path.exists(output_path):\n        os.makedirs(output_path)\n    fluid.io.save_persistables(\n        exe, os.path.join(output_path, name), main_program=trainer.program)\n    print('save checkpoints {} to {}'.format(name, output_path))\n    sys.stdout.flush()\n\n\ndef init_checkpoints(cfg, exe, trainer, name):\n    assert os.path.exists(cfg.init_model), \"{} cannot be found.\".format(\n        cfg.init_model)\n    fluid.io.load_persistables(\n        exe, os.path.join(cfg.init_model, name), main_program=trainer.program)\n    print('load checkpoints {} {} DONE'.format(cfg.init_model, name))\n    sys.stdout.flush()\n\n\ndef save_test_image(epoch,\n                    cfg,\n                    exe,\n                    place,\n                    test_program,\n                    g_trainer,\n                    A_test_reader,\n                    B_test_reader=None):\n    out_path = cfg.output + '/test'\n    if not os.path.exists(out_path):\n        os.makedirs(out_path)\n    if cfg.model_net == \"Pix2pix\":\n        for data in zip(A_test_reader()):\n            data_A, data_B, name = data[0]\n            name = name[0]\n            tensor_A = fluid.LoDTensor()\n            tensor_B = fluid.LoDTensor()\n            tensor_A.set(data_A, place)\n            tensor_B.set(data_B, place)\n            fake_B_temp = exe.run(\n                test_program,\n                fetch_list=[g_trainer.fake_B],\n                feed={\"input_A\": tensor_A,\n                      \"input_B\": tensor_B})\n            fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])\n            input_A_temp = np.squeeze(data_A[0]).transpose([1, 2, 0])\n            input_B_temp = np.squeeze(data_A[0]).transpose([1, 2, 0])\n\n            imageio.imwrite(out_path + \"/fakeB_\" + str(epoch) + \"_\" + name, (\n                (fake_B_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputA_\" + str(epoch) + \"_\" + name, (\n                (input_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputB_\" + str(epoch) + \"_\" + name, (\n                (input_B_temp + 1) * 127.5).astype(np.uint8))\n    elif cfg.model_net == \"StarGAN\":\n        for data in zip(A_test_reader()):\n            real_img, label_org, name = data[0]\n            tensor_img = fluid.LoDTensor()\n            tensor_label_org = fluid.LoDTensor()\n            tensor_img.set(real_img, place)\n            tensor_label_org.set(label_org, place)\n            real_img_temp = np.squeeze(real_img).transpose([1, 2, 0])\n            images = [real_img_temp]\n            for i in range(cfg.c_dim):\n                label_trg = np.zeros([1, cfg.c_dim]).astype(\"float32\")\n                label_trg[0][i] = 1\n                tensor_label_trg = fluid.LoDTensor()\n                tensor_label_trg.set(label_trg, place)\n                fake_temp, rec_temp = exe.run(\n                    test_program,\n                    feed={\n                        \"image_real\": tensor_img,\n                        \"label_org\": tensor_label_org,\n                        \"label_trg\": tensor_label_trg\n                    },\n                    fetch_list=[g_trainer.fake_img, g_trainer.rec_img])\n                fake_temp = np.squeeze(fake_temp[0]).transpose([1, 2, 0])\n                rec_temp = np.squeeze(rec_temp[0]).transpose([1, 2, 0])\n                images.append(fake_temp)\n                images.append(rec_temp)\n            images_concat = np.concatenate(images, 1)\n            imageio.imwrite(out_path + \"/fake_img\" + str(epoch) + \"_\" + name[0],\n                            ((images_concat + 1) * 127.5).astype(np.uint8))\n    elif cfg.model_net == 'AttGAN' or cfg.model_net == 'STGAN':\n        for data in zip(A_test_reader()):\n            real_img, label_org, name = data[0]\n            attr_names = args.selected_attrs.split(',')\n            label_trg = copy.deepcopy(label_org)\n            tensor_img = fluid.LoDTensor()\n            tensor_label_org = fluid.LoDTensor()\n            tensor_label_trg = fluid.LoDTensor()\n            tensor_label_org_ = fluid.LoDTensor()\n            tensor_label_trg_ = fluid.LoDTensor()\n            tensor_img.set(real_img, place)\n            tensor_label_org.set(label_org, place)\n            real_img_temp = np.squeeze(real_img).transpose([0, 2, 3, 1])\n            images = [real_img_temp]\n            for i in range(cfg.c_dim):\n                label_trg_tmp = copy.deepcopy(label_trg)\n\n                for j in range(len(label_org)):\n                    label_trg_tmp[j][i] = 1.0 - label_trg_tmp[j][i]\n                    label_trg_tmp = check_attribute_conflict(\n                        label_trg_tmp, attr_names[i], attr_names)\n\n                label_trg_ = list(\n                    map(lambda x: ((x * 2) - 1) * 0.5, label_trg_tmp))\n\n                for j in range(len(label_org)):\n                    label_trg_[j][i] = label_trg_[j][i] * 2.0\n                tensor_label_org_.set(label_org, place)\n                tensor_label_trg.set(label_trg, place)\n                tensor_label_trg_.set(label_trg_, place)\n                out = exe.run(test_program,\n                              feed={\n                                  \"image_real\": tensor_img,\n                                  \"label_org\": tensor_label_org,\n                                  \"label_org_\": tensor_label_org_,\n                                  \"label_trg\": tensor_label_trg,\n                                  \"label_trg_\": tensor_label_trg_\n                              },\n                              fetch_list=[g_trainer.fake_img])\n                fake_temp = np.squeeze(out[0]).transpose([0, 2, 3, 1])\n                images.append(fake_temp)\n            images_concat = np.concatenate(images, 1)\n            images_concat = np.concatenate(images_concat, 1)\n            imageio.imwrite(out_path + \"/fake_img\" + str(epoch) + '_' + name[0],\n                            ((images_concat + 1) * 127.5).astype(np.uint8))\n\n    else:\n        for data_A, data_B in zip(A_test_reader(), B_test_reader()):\n            A_name = data_A[0][1]\n            B_name = data_B[0][1]\n            tensor_A = fluid.LoDTensor()\n            tensor_B = fluid.LoDTensor()\n            tensor_A.set(data_A[0][0], place)\n            tensor_B.set(data_B[0][0], place)\n            fake_A_temp, fake_B_temp, cyc_A_temp, cyc_B_temp = exe.run(\n                test_program,\n                fetch_list=[\n                    g_trainer.fake_A, g_trainer.fake_B, g_trainer.cyc_A,\n                    g_trainer.cyc_B\n                ],\n                feed={\"input_A\": tensor_A,\n                      \"input_B\": tensor_B})\n            fake_A_temp = np.squeeze(fake_A_temp[0]).transpose([1, 2, 0])\n            fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])\n            cyc_A_temp = np.squeeze(cyc_A_temp[0]).transpose([1, 2, 0])\n            cyc_B_temp = np.squeeze(cyc_B_temp[0]).transpose([1, 2, 0])\n            input_A_temp = np.squeeze(data_A[0][0]).transpose([1, 2, 0])\n            input_B_temp = np.squeeze(data_B[0][0]).transpose([1, 2, 0])\n\n            imageio.imwrite(out_path + \"/fakeB_\" + str(epoch) + \"_\" + A_name, (\n                (fake_B_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/fakeA_\" + str(epoch) + \"_\" + B_name, (\n                (fake_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/cycA_\" + str(epoch) + \"_\" + A_name, (\n                (cyc_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/cycB_\" + str(epoch) + \"_\" + B_name, (\n                (cyc_B_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputA_\" + str(epoch) + \"_\" + A_name, (\n                (input_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputB_\" + str(epoch) + \"_\" + B_name, (\n                (input_B_temp + 1) * 127.5).astype(np.uint8))\n\n\nclass ImagePool(object):\n    def __init__(self, pool_size=50):\n        self.pool = []\n        self.count = 0\n        self.pool_size = pool_size\n\n    def pool_image(self, image):\n        if self.count < self.pool_size:\n            self.pool.append(image)\n            self.count += 1\n            return image\n        else:\n            p = np.random.rand()\n            if p > 0.5:\n                random_id = np.random.randint(0, self.pool_size - 1)\n                temp = self.pool[random_id]\n                self.pool[random_id] = image\n                return temp\n            else:\n                return image\n\n\ndef check_attribute_conflict(label_batch, attr, attrs):\n    def _set(label, value, attr):\n        if attr in attrs:\n            label[attrs.index(attr)] = value\n\n    attr_id = attrs.index(attr)\n    for label in label_batch:\n        if attr in ['Bald', 'Receding_Hairline'] and attrs[attr_id] != 0:\n            _set(label, 0, 'Bangs')\n        elif attr == 'Bangs' and attrs[attr_id] != 0:\n            _set(label, 0, 'Bald')\n            _set(label, 0, 'Receding_Hairline')\n        elif attr in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair'\n                      ] and attrs[attr_id] != 0:\n            for a in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair']:\n                if a != attr:\n                    _set(label, 0, a)\n        elif attr in ['Straight_Hair', 'Wavy_Hair'] and attrs[attr_id] != 0:\n            for a in ['Straight_Hair', 'Wavy_Hair']:\n                if a != attr:\n                    _set(label, 0, a)\n        elif attr in ['Mustache', 'No_Beard'] and attrs[attr_id] != 0:\n            for a in ['Mustache', 'No_Beard']:\n                if a != attr:\n                    _set(label, 0, a)\n    return label_batch\n", "path": "PaddleCV/PaddleGAN/util/utility.py"}], "after_files": [{"content": "#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport paddle.fluid as fluid\nimport os\nimport sys\nimport math\nimport distutils.util\nimport numpy as np\nimport inspect\nimport matplotlib\nimport six\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport imageio\nimport copy\n\nimg_dim = 28\n\n\ndef plot(gen_data):\n    pad_dim = 1\n    paded = pad_dim + img_dim\n    gen_data = gen_data.reshape(gen_data.shape[0], img_dim, img_dim)\n    n = int(math.ceil(math.sqrt(gen_data.shape[0])))\n    gen_data = (np.pad(\n        gen_data, [[0, n * n - gen_data.shape[0]], [pad_dim, 0], [pad_dim, 0]],\n        'constant').reshape((n, n, paded, paded)).transpose((0, 2, 1, 3))\n                .reshape((n * paded, n * paded)))\n    fig = plt.figure(figsize=(8, 8))\n    plt.axis('off')\n    plt.imshow(gen_data, cmap='Greys_r', vmin=-1, vmax=1)\n    return fig\n\n\ndef checkpoints(epoch, cfg, exe, trainer, name):\n    output_path = cfg.output + '/checkpoints/' + str(epoch)\n    if not os.path.exists(output_path):\n        os.makedirs(output_path)\n    fluid.io.save_persistables(\n        exe, os.path.join(output_path, name), main_program=trainer.program)\n    print('save checkpoints {} to {}'.format(name, output_path))\n    sys.stdout.flush()\n\n\ndef init_checkpoints(cfg, exe, trainer, name):\n    assert os.path.exists(cfg.init_model), \"{} cannot be found.\".format(\n        cfg.init_model)\n    fluid.io.load_persistables(\n        exe, os.path.join(cfg.init_model, name), main_program=trainer.program)\n    print('load checkpoints {} {} DONE'.format(cfg.init_model, name))\n    sys.stdout.flush()\n\n\ndef save_test_image(epoch,\n                    cfg,\n                    exe,\n                    place,\n                    test_program,\n                    g_trainer,\n                    A_test_reader,\n                    B_test_reader=None):\n    out_path = cfg.output + '/test'\n    if not os.path.exists(out_path):\n        os.makedirs(out_path)\n    if cfg.model_net == \"Pix2pix\":\n        for data in zip(A_test_reader()):\n            data_A, data_B, name = data[0]\n            name = name[0]\n            tensor_A = fluid.LoDTensor()\n            tensor_B = fluid.LoDTensor()\n            tensor_A.set(data_A, place)\n            tensor_B.set(data_B, place)\n            fake_B_temp = exe.run(\n                test_program,\n                fetch_list=[g_trainer.fake_B],\n                feed={\"input_A\": tensor_A,\n                      \"input_B\": tensor_B})\n            fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])\n            input_A_temp = np.squeeze(data_A[0]).transpose([1, 2, 0])\n            input_B_temp = np.squeeze(data_A[0]).transpose([1, 2, 0])\n\n            imageio.imwrite(out_path + \"/fakeB_\" + str(epoch) + \"_\" + name, (\n                (fake_B_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputA_\" + str(epoch) + \"_\" + name, (\n                (input_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputB_\" + str(epoch) + \"_\" + name, (\n                (input_B_temp + 1) * 127.5).astype(np.uint8))\n    elif cfg.model_net == \"StarGAN\":\n        for data in zip(A_test_reader()):\n            real_img, label_org, name = data[0]\n            tensor_img = fluid.LoDTensor()\n            tensor_label_org = fluid.LoDTensor()\n            tensor_img.set(real_img, place)\n            tensor_label_org.set(label_org, place)\n            real_img_temp = np.squeeze(real_img).transpose([1, 2, 0])\n            images = [real_img_temp]\n            for i in range(cfg.c_dim):\n                label_trg = np.zeros([1, cfg.c_dim]).astype(\"float32\")\n                label_trg[0][i] = 1\n                tensor_label_trg = fluid.LoDTensor()\n                tensor_label_trg.set(label_trg, place)\n                fake_temp, rec_temp = exe.run(\n                    test_program,\n                    feed={\n                        \"image_real\": tensor_img,\n                        \"label_org\": tensor_label_org,\n                        \"label_trg\": tensor_label_trg\n                    },\n                    fetch_list=[g_trainer.fake_img, g_trainer.rec_img])\n                fake_temp = np.squeeze(fake_temp[0]).transpose([1, 2, 0])\n                rec_temp = np.squeeze(rec_temp[0]).transpose([1, 2, 0])\n                images.append(fake_temp)\n                images.append(rec_temp)\n            images_concat = np.concatenate(images, 1)\n            imageio.imwrite(out_path + \"/fake_img\" + str(epoch) + \"_\" + name[0],\n                            ((images_concat + 1) * 127.5).astype(np.uint8))\n    elif cfg.model_net == 'AttGAN' or cfg.model_net == 'STGAN':\n        for data in zip(A_test_reader()):\n            real_img, label_org, name = data[0]\n            attr_names = cfg.selected_attrs.split(',')\n            label_trg = copy.deepcopy(label_org)\n            tensor_img = fluid.LoDTensor()\n            tensor_label_org = fluid.LoDTensor()\n            tensor_label_trg = fluid.LoDTensor()\n            tensor_label_org_ = fluid.LoDTensor()\n            tensor_label_trg_ = fluid.LoDTensor()\n            tensor_img.set(real_img, place)\n            tensor_label_org.set(label_org, place)\n            real_img_temp = np.squeeze(real_img).transpose([0, 2, 3, 1])\n            images = [real_img_temp]\n            for i in range(cfg.c_dim):\n                label_trg_tmp = copy.deepcopy(label_trg)\n\n                for j in range(len(label_org)):\n                    label_trg_tmp[j][i] = 1.0 - label_trg_tmp[j][i]\n                    label_trg_tmp = check_attribute_conflict(\n                        label_trg_tmp, attr_names[i], attr_names)\n\n                label_trg_ = list(\n                    map(lambda x: ((x * 2) - 1) * 0.5, label_trg_tmp))\n\n                for j in range(len(label_org)):\n                    label_trg_[j][i] = label_trg_[j][i] * 2.0\n                tensor_label_org_.set(label_org, place)\n                tensor_label_trg.set(label_trg, place)\n                tensor_label_trg_.set(label_trg_, place)\n                out = exe.run(test_program,\n                              feed={\n                                  \"image_real\": tensor_img,\n                                  \"label_org\": tensor_label_org,\n                                  \"label_org_\": tensor_label_org_,\n                                  \"label_trg\": tensor_label_trg,\n                                  \"label_trg_\": tensor_label_trg_\n                              },\n                              fetch_list=[g_trainer.fake_img])\n                fake_temp = np.squeeze(out[0]).transpose([0, 2, 3, 1])\n                images.append(fake_temp)\n            images_concat = np.concatenate(images, 1)\n            images_concat = np.concatenate(images_concat, 1)\n            imageio.imwrite(out_path + \"/fake_img\" + str(epoch) + '_' + name[0],\n                            ((images_concat + 1) * 127.5).astype(np.uint8))\n\n    else:\n        for data_A, data_B in zip(A_test_reader(), B_test_reader()):\n            A_name = data_A[0][1]\n            B_name = data_B[0][1]\n            tensor_A = fluid.LoDTensor()\n            tensor_B = fluid.LoDTensor()\n            tensor_A.set(data_A[0][0], place)\n            tensor_B.set(data_B[0][0], place)\n            fake_A_temp, fake_B_temp, cyc_A_temp, cyc_B_temp = exe.run(\n                test_program,\n                fetch_list=[\n                    g_trainer.fake_A, g_trainer.fake_B, g_trainer.cyc_A,\n                    g_trainer.cyc_B\n                ],\n                feed={\"input_A\": tensor_A,\n                      \"input_B\": tensor_B})\n            fake_A_temp = np.squeeze(fake_A_temp[0]).transpose([1, 2, 0])\n            fake_B_temp = np.squeeze(fake_B_temp[0]).transpose([1, 2, 0])\n            cyc_A_temp = np.squeeze(cyc_A_temp[0]).transpose([1, 2, 0])\n            cyc_B_temp = np.squeeze(cyc_B_temp[0]).transpose([1, 2, 0])\n            input_A_temp = np.squeeze(data_A[0][0]).transpose([1, 2, 0])\n            input_B_temp = np.squeeze(data_B[0][0]).transpose([1, 2, 0])\n\n            imageio.imwrite(out_path + \"/fakeB_\" + str(epoch) + \"_\" + A_name, (\n                (fake_B_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/fakeA_\" + str(epoch) + \"_\" + B_name, (\n                (fake_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/cycA_\" + str(epoch) + \"_\" + A_name, (\n                (cyc_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/cycB_\" + str(epoch) + \"_\" + B_name, (\n                (cyc_B_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputA_\" + str(epoch) + \"_\" + A_name, (\n                (input_A_temp + 1) * 127.5).astype(np.uint8))\n            imageio.imwrite(out_path + \"/inputB_\" + str(epoch) + \"_\" + B_name, (\n                (input_B_temp + 1) * 127.5).astype(np.uint8))\n\n\nclass ImagePool(object):\n    def __init__(self, pool_size=50):\n        self.pool = []\n        self.count = 0\n        self.pool_size = pool_size\n\n    def pool_image(self, image):\n        if self.count < self.pool_size:\n            self.pool.append(image)\n            self.count += 1\n            return image\n        else:\n            p = np.random.rand()\n            if p > 0.5:\n                random_id = np.random.randint(0, self.pool_size - 1)\n                temp = self.pool[random_id]\n                self.pool[random_id] = image\n                return temp\n            else:\n                return image\n\n\ndef check_attribute_conflict(label_batch, attr, attrs):\n    def _set(label, value, attr):\n        if attr in attrs:\n            label[attrs.index(attr)] = value\n\n    attr_id = attrs.index(attr)\n    for label in label_batch:\n        if attr in ['Bald', 'Receding_Hairline'] and attrs[attr_id] != 0:\n            _set(label, 0, 'Bangs')\n        elif attr == 'Bangs' and attrs[attr_id] != 0:\n            _set(label, 0, 'Bald')\n            _set(label, 0, 'Receding_Hairline')\n        elif attr in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair'\n                      ] and attrs[attr_id] != 0:\n            for a in ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Gray_Hair']:\n                if a != attr:\n                    _set(label, 0, a)\n        elif attr in ['Straight_Hair', 'Wavy_Hair'] and attrs[attr_id] != 0:\n            for a in ['Straight_Hair', 'Wavy_Hair']:\n                if a != attr:\n                    _set(label, 0, a)\n        elif attr in ['Mustache', 'No_Beard'] and attrs[attr_id] != 0:\n            for a in ['Mustache', 'No_Beard']:\n                if a != attr:\n                    _set(label, 0, a)\n    return label_batch\n", "path": "PaddleCV/PaddleGAN/util/utility.py"}]}