├── .dockerignore
├── .gitignore
├── .gitmodules
├── Dockerfile
├── LICENSE
├── README.md
├── app.py
├── config.json
├── evaluation
├── __init__.py
├── tsne_analysis_baseline
│ ├── run_tsne_analysis.sh
│ ├── test
│ │ ├── assets
│ │ │ ├── .gitignore
│ │ │ ├── dataset
│ │ │ │ ├── image_10.npz
│ │ │ │ ├── image_10.png
│ │ │ │ ├── image_5.npz
│ │ │ │ ├── image_5.png
│ │ │ │ ├── image_6.npz
│ │ │ │ ├── image_6.png
│ │ │ │ ├── image_7.npz
│ │ │ │ ├── image_7.png
│ │ │ │ ├── image_9.npz
│ │ │ │ └── image_9.png
│ │ │ ├── model_a
│ │ │ │ ├── image_10.npz
│ │ │ │ ├── image_10.png
│ │ │ │ ├── image_5.npz
│ │ │ │ ├── image_5.png
│ │ │ │ ├── image_6.npz
│ │ │ │ ├── image_6.png
│ │ │ │ ├── image_7.npz
│ │ │ │ ├── image_7.png
│ │ │ │ ├── image_9.npz
│ │ │ │ └── image_9.png
│ │ │ └── model_b
│ │ │ │ ├── image_0.npz
│ │ │ │ ├── image_0.png
│ │ │ │ ├── image_1.npz
│ │ │ │ ├── image_1.png
│ │ │ │ ├── image_2.npz
│ │ │ │ ├── image_2.png
│ │ │ │ ├── image_3.npz
│ │ │ │ ├── image_3.png
│ │ │ │ ├── image_5.npz
│ │ │ │ ├── image_5.png
│ │ │ │ └── image_6.png
│ │ ├── test_gen_tsne.py
│ │ └── test_grid.py
│ ├── tmp_requirements.txt
│ ├── tsne_analysis.py
│ ├── tsne_evaluation_utils
│ │ ├── grid.py
│ │ └── metric.py
│ └── tsne_output
│ │ ├── data.csv
│ │ ├── distances.csv
│ │ ├── models_scatter.png
│ │ ├── stats.csv
│ │ ├── tsne_dataset.png
│ │ ├── tsne_model_a.png
│ │ └── tsne_model_b.png
└── utils_tsne.py
├── images
├── Cartoons_example.jpeg
└── Faces_example.jpeg
├── losses
├── __init__.py
└── utils_loss.py
├── models
├── __init__.py
├── avatar_generator_model.py
├── cdann.py
├── decoder.py
├── denoiser.py
├── discriminator.py
├── encoder.py
└── inception.py
├── requirements.txt
├── scripts
├── copyFiles.sh
├── download_faces.py
├── keepFiles.sh
├── plot_utils.py
└── preprocessing_cartoons_data.py
├── sweeps
├── sweep-bs-1.yaml
└── sweep-rs-1.yaml
├── train.py
└── utils
└── __init__.py
/.dockerignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | #jpg
132 | *.jpg
133 |
134 |
135 | #git
136 | .git
137 | .gitignore
138 | .gitmodules
139 | *.md
140 | LICENSE
141 |
142 | #docker
143 | Dockerfile
144 | .DS_Store
145 |
146 | #files
147 | __pycache__
148 | avatar-image-generator-app/
149 | images/
150 | notebooks/
151 | data/
152 | datasets/
153 | weights_trained/
154 | wandb/
155 | preprocessing/
156 |
157 | #nohup
158 | *.out
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | #jpg - data
132 | data/
133 | *.jpg
134 | weights_trained/
135 | weights/
136 | wandb/
137 |
138 | #nohup
139 | *.out
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "avatar-image-generator-app"]
2 | path = avatar-image-generator-app
3 | url = https://github.com/paper2code-pucp/avatar-image-generator-app.git
4 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:20.04
2 | ENV PATH="/root/miniconda3/bin:${PATH}"
3 | ARG PATH="/root/miniconda3/bin:${PATH}"
4 |
5 | RUN apt update \
6 | && apt install -y python3-dev wget libgl1-mesa-dev libglib2.0-0 libsm6 libxext6 libxrender-dev
7 |
8 | RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh \
9 | && mkdir root/.conda \
10 | && sh Miniconda3-latest-Linux-x86_64.sh -b \
11 | && rm -f Miniconda3-latest-Linux-x86_64.sh
12 |
13 | RUN conda create -y -n ml python=3.7
14 |
15 | COPY . src/
16 | RUN /bin/bash -c "cd src \
17 | && source activate ml \
18 | && pip install -r requirements.txt"
19 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Avatar Image Generator
2 |
3 | Faces Domain
4 |
5 |
6 | Generated Cartoons
7 |
8 |
9 | Based on the paper XGAN: https://arxiv.org/abs/1711.05139
10 |
11 | ## The problem
12 |
13 | This repo aims to contribute to the daunting problem of generating a cartoon given the picture of a face.
14 | This is an image-to-image translation problem, which involves many classic computer vision tasks, like style transfer, super-resolution, colorization and semnantic segmentation. Also, this is a many-to-many mapping, which means that for a given face there are multiple valid cartoons, and for a given cartoon there are multiple valid faces too.
15 |
16 | ## Dataset
17 |
18 | Faces dataset: we use the VggFace dataset (https://www.robots.ox.ac.uk/~vgg/data/vgg_face/) from the University of Oxford
19 |
20 | Cartoon dataset: we use the CartoonSet dataset from Google (https://google.github.io/cartoonset/), both the versions of 10000 and 100000 items.
21 |
22 | We filtered out the data just to keep realistic cartoons and faces images. This code is in `scripts`. To download the dataset:
23 |
24 | 1. `pip3 install gdown`
25 | 2. `gdown https://drive.google.com/uc?id=1tfMW5vZ0aUFnl-fSYpWexoGRKGSQsStL`
26 | 3. `unzip datasets.zip`
27 |
28 | ## Directory structure
29 |
30 | `config.json`: contains the model configuration to train the model and deploy the app
31 |
32 | `weights`: contains weights that we saved the last time we train the model.
33 |
34 | ```
35 | ├── app.py
36 | ├── avatar-image-generator-app
37 | ├── config.json
38 | ├── Dockerfile
39 | ├── images
40 | │ ├── Cartoons_example.jpeg
41 | │ └── Faces_example.jpeg
42 | ├── LICENSE
43 | ├── losses
44 | │ └── __init__.py
45 | ├── models
46 | │ ├── avatar_generator_model.py
47 | │ ├── cdann.py
48 | │ ├── decoder.py
49 | │ ├── denoiser.py
50 | │ ├── discriminator.py
51 | │ ├── encoder.py
52 | │ └── __init__.py
53 | ├── README.md
54 | ├── requirements.txt
55 | ├── scripts
56 | │ ├── copyFiles.sh
57 | │ ├── download_faces.py
58 | │ ├── keepFiles.sh
59 | │ ├── plot_utils.py
60 | │ └── preprocessing_cartoons_data.py
61 | ├── sweeps
62 | │ ├── sweep-bs-1.yaml
63 | │ └── sweep-rs-1.yaml
64 | ├── train.py
65 | ├── utils
66 | │ └── __init__.py
67 | └── weights
68 | ├── c_dann.pth
69 | ├── d1.pth
70 | ├── d2.pth
71 | ├── denoiser.pth
72 | ├── disc1.pth
73 | ├── d_shared.pth
74 | ├── e1.pth
75 | ├── e2.pth
76 | └── e_shared.pth
77 | ```
78 | ## The model
79 | Our codebase is in Python3. We suggest creating a new virtual environment.
80 | * The required packages can be installed by running `pip3 install -r requirements.txt`
81 | * Update `N_CUDA` by running `export N_CUDA=` if you want to specify the GPU to use
82 |
83 | It is based on the XGAN paper omitting the Teacher Loss and adding an autoencoder in the end. The latter was trained to learn well only the representation of the cartoons as to "denoise" the spots and wrong colorisation from the face-to-cartoon outputs of the XGAN.
84 |
85 | The model was trained using the hyperparameters located in `config.json`. Weights & Biases Sweep was used to find the best hyperparameters:
86 |
87 | 1. Change `root_path` in `config json`. It specifies where is `datasets` which contains the datasets.
88 | 2. Run `wandb login 17d2772d85cbda79162bd975e45fdfbf3bb18911` to use wandb to get the report
89 | 3. Run `python3 train.py --wandb --run_name --run_notes ` or `python3 train.py --no-wandb`
90 | 4. To launch an agent with a sweep configuration of wandb in bg from ssh `nohup wandb agent --count stevramos/avatar_image_generator/ &`
91 |
92 | You can see the Weights & Biases report here: https://wandb.ai/stevramos/avatar_image_generator
93 |
94 | This is the implementation of [our project](https://madewithml.com/projects/1233/generating-avatars-from-real-life-pictures/) created for the Made With ML Data Science Incubator (deprecated).
95 |
96 |
97 | ## Docker
98 | 1. Build the container: `sudo docker build -f Dockerfile -t avatar-image-generator .`
99 | * Run the container: `sudo docker run -ti avatar-image-generator /bin/bash`
100 | * Train the model:
101 |
102 | a. Create the folder: `mkdir weights_trained`
103 |
104 | b. Change the absolute path from which mount the volume. This is for both `weights_trained` and `datasets`. In this case:
105 |
106 | sudo docker run -v :/src/weights_trained/ -v :/src/datasets/ -ti avatar-image-generator /bin/bash -c "cd src/ && source activate ml && wandb login 17d2772d85cbda79162bd975e45fdfbf3bb18911 && python train.py --wandb --run_name --run_notes "
107 |
108 | * Run the app locally as a daemon in docker. `model_path` in `config.json` contains the weights to use in the app
109 | `sudo docker run -d -p 8000:9999 -ti avatar-image-generator /bin/bash -c "cd src/ && source activate ml && python app.py"`
110 |
111 | a. Local server: [http://0.0.0.0:8000/](http://0.0.0.0:8000/)
112 |
--------------------------------------------------------------------------------
/app.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import flask
3 | import time
4 | from flask import Flask
5 | from flask import request
6 | from flask import Flask, render_template, Response, request, redirect, jsonify, send_from_directory, abort, send_file
7 | from flask_cors import CORS
8 | from models import Avatar_Generator_Model
9 | from utils import *
10 | import torch.nn as nn
11 | from PIL import Image
12 | import numpy as np
13 | import cv2
14 | import base64
15 | import os , io , sys
16 |
17 | ALLOWED_EXTENSIONS = set(['jpg', 'jpeg', 'png'])
18 | CONFIG_FILENAME = "config.json"
19 | DOWNLOAD_DIRECTORY = None
20 |
21 | def allowed_file(filename):
22 | return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
23 |
24 | app = Flask(__name__)
25 | CORS(app)
26 |
27 | MODEL = None
28 |
29 |
30 | def face_to_cartoon(DOC_FILE, face):
31 |
32 | document_name = DOC_FILE.split('.')[0]
33 | extension = (DOC_FILE.split('.')[-1]).lower()
34 | document = Image.open(io.BytesIO(face))
35 |
36 | if not os.path.exists(DOWNLOAD_DIRECTORY):
37 | os.makedirs(DOWNLOAD_DIRECTORY)
38 |
39 | if extension == "png":
40 | format_image = "PNG"
41 | else:
42 | extension = "jpg"
43 | format_image = "JPEG"
44 |
45 | filename_face = "{}.{}".format(document_name, extension)
46 | document.save(DOWNLOAD_DIRECTORY + filename_face, format_image, quality=80, optimize=True, progressive=True)
47 |
48 |
49 | filename_cartoon = "{}_cartoon.jpg".format(document_name)
50 | cartoon, cartoon_tensor = MODEL.generate(DOWNLOAD_DIRECTORY + filename_face, DOWNLOAD_DIRECTORY + filename_cartoon)
51 |
52 | return filename_cartoon
53 |
54 |
55 | @app.route('/send_image', methods=['POST'])
56 | def upload_file():
57 | # check if the post request has the file part
58 | if 'face_image' not in request.files:
59 | resp = jsonify({'message' : 'No file part in the request'})
60 | resp.status_code = 400
61 | return resp
62 |
63 | file = request.files['face_image']
64 |
65 | errors = {}
66 | success = False
67 |
68 | if file and allowed_file(file.filename):
69 | filename_cartoon = face_to_cartoon(file.filename, file.read())
70 | success = True
71 | else:
72 | errors[file.filename] = 'File type is not allowed'
73 |
74 | if success and errors:
75 | errors['message'] = 'File(s) successfully uploaded'
76 | resp = jsonify(errors)
77 | resp.status_code = 500
78 | return resp
79 | if success:
80 | resp = jsonify({'message' : 'Files successfully processed', 'filename_cartoon': filename_cartoon})
81 | resp.status_code = 201
82 | resp.headers.add('Access-Control-Allow-Origin', '*')
83 | print('headers:: ', resp.headers)
84 | return resp
85 | else:
86 | resp = jsonify(errors)
87 | resp.status_code = 500
88 | return resp
89 |
90 |
91 | @app.route('/predict', methods=['POST'])
92 | def predict():
93 | doc_name = request.form.get('filename_cartoon')
94 | try:
95 |
96 | return send_from_directory(DOWNLOAD_DIRECTORY, filename=doc_name, as_attachment=True)
97 | except FileNotFoundError:
98 | abort(404)
99 |
100 |
101 | if __name__ == "__main__":
102 |
103 | use_wandb = False
104 | config = configure_model(CONFIG_FILENAME,use_wandb=use_wandb)
105 | DOWNLOAD_DIRECTORY = config.download_directory
106 |
107 | MODEL = Avatar_Generator_Model(config, use_wandb=use_wandb)
108 | MODEL.load_weights(config.model_path)
109 |
110 | app.run(host="0.0.0.0", port="9999")
--------------------------------------------------------------------------------
/config.json:
--------------------------------------------------------------------------------
1 | {
2 | "server_config":{
3 | "model_path":"weights/",
4 | "download_directory":"data/"
5 | },
6 | "train_dataset_params":{
7 | "root_path":"/data/shuaman/xgan/",
8 | "dataset_path_faces":"datasets/face_datasets/face_images_wo_bg_permissive/",
9 | "dataset_path_cartoons":"datasets/cartoon_datasets/cartoonset100k_limited/",
10 | "dataset_path_test_faces":"datasets/test_faces/input_images/",
11 | "dataset_path_segmented_faces":"datasets/test_faces/segmented_faces/",
12 | "dataset_path_output_faces":"datasets/test_faces/generated_cartoon_images/",
13 | "loader_params":{
14 | "batch_size":32
15 | },
16 | "save_weights":true,
17 | "num_backups": 8,
18 | "save_path":"weights_trained/"
19 | },
20 | "model_hparams":{
21 | "dropout_rate_eshared":0.5,
22 | "use_critic_dann": true,
23 | "use_critic_disc": true,
24 | "use_spectral_norm": true,
25 | "use_denoiser": true,
26 | "use_disc_cartoon2face": false,
27 | "num_epochs": 200,
28 | "learning_rate_opTotal":1e-4,
29 | "learning_rate_opDisc":1e-3,
30 | "learning_rate_denoiser":1e-3,
31 | "learning_rate_opCdann":2e-4,
32 | "wRec_loss":0.9928583013837265,
33 | "wDann_loss":0.9252047602915646,
34 | "wSem_loss":0.44957120675107437,
35 | "wGan_loss":0.9790275245543392,
36 | "wTeach_loss":0.75,
37 | "use_gpu":true
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/evaluation/__init__.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import pandas as pd
3 | from sklearn.preprocessing import StandardScaler
4 |
5 | from .utils_tsne import apply_tsne, generate_scatter
6 |
7 | def tsne_evaluation(ls_feature_arrays, ls_array_names, pca_components=None, perplexity=30, n_iter=1000, save_image=False, output_dir='./', save_wandb=False, plot_title='t-SNE evaluation'):
8 | assert len(ls_feature_arrays) == len(ls_array_names)
9 |
10 | feature_vectors = np.concatenate(ls_feature_arrays)
11 |
12 | # cancatenate names in a df with same length as feature_vectors
13 | feature_vector_names = []
14 | list( map(feature_vector_names.extend, [[name]*ls_feature_arrays[i].shape[0] for i, name in enumerate(ls_array_names)]) )
15 | df_feature_vector_info = pd.DataFrame({'name':feature_vector_names})
16 |
17 | tsne_results, df_feature_vector_info = apply_tsne(df_feature_vector_info , feature_vectors, perplexity, n_iter, pca_components=pca_components)
18 |
19 | tsne_results_norm = StandardScaler().fit_transform(tsne_results)
20 |
21 | scatter_plot = None
22 | wandb_scatter_plot = None
23 | img_scatter_plot = None
24 | if save_image or save_wandb:
25 | wandb_scatter_plot, img_scatter_plot = generate_scatter(tsne_results_norm, df_feature_vector_info, save_image, output_dir, save_wandb, plot_title)
26 |
27 |
28 | return tsne_results_norm, df_feature_vector_info, wandb_scatter_plot, img_scatter_plot
29 |
30 | ###############################
31 |
32 | # distance_threshold, stats_df = calc_jaccard_index(df)
33 | # logger.info("stats %s", stats_df)
34 | # stats_df.to_csv(os.path.join(output_dir, "stats.csv"), index=False)
35 | # if enable_rmse:
36 | # df_distances = calc_rmse(df, image_shape)
37 | # df_distances.to_csv(os.path.join(output_dir, "distances.csv"), index=False)
38 | # return stats_df
39 |
40 |
41 | if __name__ == "__main__":
42 | output_dir = "./"
43 | # pca_components = 10
44 | pca_components = None
45 | with open('dataset.npy', 'rb') as f:
46 | np_a = np.load(f)
47 | with open('model_a.npy', 'rb') as f:
48 | np_b = np.load(f)
49 | with open('model_b.npy', 'rb') as f:
50 | np_c = np.load(f)
51 |
52 | tsne_evaluation([np_a, np_b, np_c],['dataset', 'm_a','m_b'], pca_components=pca_components, save_image=True, output_dir= output_dir, save_wandb = True)
53 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/run_tsne_analysis.sh:
--------------------------------------------------------------------------------
1 | python tsne_analysis.py -b test/assets/dataset -p test/assets/model_a -p test/assets/model_b -o tsne_output -f
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/.gitignore:
--------------------------------------------------------------------------------
1 | output
2 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_10.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_10.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_10.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_5.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_5.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_5.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_6.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_6.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_6.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_7.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_7.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_7.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_9.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_9.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/dataset/image_9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/dataset/image_9.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_10.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_10.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_10.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_5.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_5.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_5.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_6.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_6.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_6.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_7.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_7.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_7.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_9.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_9.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_a/image_9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_a/image_9.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_0.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_0.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_0.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_0.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_1.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_1.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_1.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_2.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_2.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_2.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_3.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_3.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_3.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_5.npz:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_5.npz
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_5.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/assets/model_b/image_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/test/assets/model_b/image_6.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/test_gen_tsne.py:
--------------------------------------------------------------------------------
1 | import os
2 | import unittest
3 |
4 | from gen_tsne.gen_tsne import calculate
5 |
6 | ASSETS_DIR = os.path.join(os.path.dirname(__file__), "assets")
7 |
8 |
9 | class TestGenTsne(unittest.TestCase):
10 |
11 | def test_build(self):
12 | paths = [os.path.join(ASSETS_DIR, "dataset"), os.path.join(ASSETS_DIR, "model_a"),
13 | os.path.join(ASSETS_DIR, "model_b")]
14 | stats_df = calculate(paths, os.path.join(ASSETS_DIR, "output"), pca_components=None, frow=10, fcol=10)
15 | self.assertIn("jaccard_index", stats_df.columns)
16 |
17 | def test_build_with_features(self):
18 | paths = [os.path.join(ASSETS_DIR, "dataset"), os.path.join(ASSETS_DIR, "model_a")]
19 | stats_df = calculate(paths, os.path.join(ASSETS_DIR, "output"), pca_components=None, frow=10, fcol=10,
20 | use_features=True)
21 | self.assertIn("jaccard_index", stats_df.columns)
22 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/test/test_grid.py:
--------------------------------------------------------------------------------
1 | import os
2 | import unittest
3 |
4 | from gen_tsne import build_grid
5 |
6 | ASSETS_DIR = os.path.join(os.path.dirname(__file__), "assets")
7 |
8 |
9 | class TestGrid(unittest.TestCase):
10 |
11 | def test_build(self):
12 | paths = [os.path.join(ASSETS_DIR, "dataset"), os.path.join(ASSETS_DIR, "model_a"),
13 | os.path.join(ASSETS_DIR, "model_b")]
14 | df, _ = build_grid(paths, output_dir=os.path.join(ASSETS_DIR, "output"), pca_components=None, frow=10, fcol=10,
15 | save_scatter=True)
16 | self.assertIn("tsne_x", df.columns)
17 | self.assertIn("tsne_y", df.columns)
18 |
19 | def test_build_pca(self):
20 | paths = [os.path.join(ASSETS_DIR, "dataset"), os.path.join(ASSETS_DIR, "model_a"),
21 | os.path.join(ASSETS_DIR, "model_b")]
22 | df, _ = build_grid(paths, output_dir=os.path.join(ASSETS_DIR, "output"), pca_components=5, frow=10, fcol=10)
23 | self.assertIn("tsne_x", df.columns)
24 | self.assertIn("tsne_y", df.columns)
25 |
26 | def test_build_with_features(self):
27 | paths = [os.path.join(ASSETS_DIR, "dataset"), os.path.join(ASSETS_DIR, "model_a"),
28 | os.path.join(ASSETS_DIR, "model_b")]
29 | df, _ = build_grid(paths, output_dir=os.path.join(ASSETS_DIR, "output"), pca_components=None, frow=10, fcol=10,
30 | use_features=True)
31 | self.assertIn("tsne_x", df.columns)
32 | self.assertIn("tsne_y", df.columns)
33 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tmp_requirements.txt:
--------------------------------------------------------------------------------
1 | scikit_learn==0.23.2
2 | numpy==1.19.4
3 | pandas==1.1.4
4 | pillow
5 | # pillow-simd==7.0.0.post3
6 | matplotlib==3.2.1
7 | seaborn==0.11.0
8 | MulticoreTSNE==0.1
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_analysis.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | import logging
3 | import os
4 |
5 | from tsne_evaluation_utils.grid import build as build_grid
6 | from tsne_evaluation_utils.metric import calc_jaccard_index, calc_rmse
7 |
8 | logging.basicConfig(level=logging.INFO)
9 | logger = logging.getLogger(__name__)
10 |
11 | # Code as in https://github.com/vfcosta/gen-tsne
12 |
13 | def calculate(paths, output_dir, enable_rmse=True, pca_components=None, frow=60, fcol=60, perplexity=30,
14 | n_iter=1000, save_data=True, use_features=False):
15 | df, image_shape = build_grid(paths, pca_components=pca_components, frow=frow, fcol=fcol, perplexity=perplexity,
16 | n_iter=n_iter, save_data=save_data, output_dir=output_dir, use_features=use_features)
17 | distance_threshold, stats_df = calc_jaccard_index(df)
18 | logger.info("stats %s", stats_df)
19 | stats_df.to_csv(os.path.join(output_dir, "stats.csv"), index=False)
20 | if enable_rmse:
21 | df_distances = calc_rmse(df, image_shape)
22 | df_distances.to_csv(os.path.join(output_dir, "distances.csv"), index=False)
23 | return stats_df
24 |
25 |
26 | if __name__ == "__main__":
27 | parser = argparse.ArgumentParser(description='Apply Gen t-SNE metric.')
28 | parser.add_argument('-b', '--baseline', help='Path to images from the dataset (baseline)', required=True)
29 | parser.add_argument('-p', '--paths', action='append', help='Paths to images from generative models', required=True)
30 | parser.add_argument('-o', '--output', help='Output dir', default="./output")
31 | parser.add_argument('-r', "--rows", type=int, help='rows', default=60)
32 | parser.add_argument('-c', "--cols", type=int, help='cols', default=60)
33 | parser.add_argument('-k', "--perplexity", type=int, help='perplexity', default=30)
34 | parser.add_argument('-n', "--iter", type=int, help='iterations', default=1000)
35 | parser.add_argument('-f', "--use-features", default=False, action='store_true',
36 | help='Use features to build the grid (.npy or .npz)')
37 | args = parser.parse_args()
38 | calculate([args.baseline] + args.paths, args.output, frow=args.rows, fcol=args.cols, perplexity=args.perplexity,
39 | n_iter=args.iter, use_features=args.use_features)
40 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_evaluation_utils/grid.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import os
3 | from glob import glob
4 |
5 | import matplotlib.pyplot as plt
6 | import numpy as np
7 | import pandas as pd
8 | import seaborn as sns
9 | from MulticoreTSNE import MulticoreTSNE as TSNE
10 | from PIL import Image
11 | from sklearn.decomposition import PCA
12 | from sklearn.preprocessing import StandardScaler
13 |
14 | logger = logging.getLogger(__name__)
15 |
16 |
17 | def build(paths, frow=60, fcol=60, perplexity=30, n_iter=1000, jitter_win=0, pca_components=50,
18 | output_dir="./output", save_data=True, save_scatter=True, use_features=False):
19 | os.makedirs(output_dir, exist_ok=True)
20 | df, image_shape, tsne_input = load_data(paths, use_features)
21 | tsne_results = apply_tsne(df, tsne_input, perplexity, n_iter, pca_components=pca_components)
22 | logger.info("tsne finished: %s", tsne_results.shape)
23 | df['tsne_x_raw'], df['tsne_y_raw'] = tsne_results[:, 0], tsne_results[:, 1]
24 | norm = StandardScaler().fit_transform(df[["tsne_x_raw", "tsne_y_raw"]])
25 | df['tsne_x'], df['tsne_y'] = norm[:, 0], norm[:, 1]
26 | if save_scatter:
27 | generate_scatter(df, output_dir)
28 | df = generate_images(fcol, frow, image_shape, df, output_dir=output_dir, jitter_win=jitter_win)
29 | if save_data:
30 | logger.info("saving data.csv")
31 | df.to_csv(os.path.join(output_dir, "data.csv"), index=False)
32 | logger.info("finished")
33 | return df, image_shape
34 |
35 |
36 | def generate_images(fcol, frow, image_shape, df, output_dir=None, jitter_win=None):
37 | df["tsne_x_int"] = ((fcol - 1) * (df["tsne_x"] - np.min(df["tsne_x"])) / np.ptp(df["tsne_x"])).astype(int)
38 | df["tsne_y_int"] = ((frow - 1) * (df["tsne_y"] - np.min(df["tsne_y"])) / np.ptp(df["tsne_y"])).astype(int)
39 | all_possibilities = []
40 | if jitter_win:
41 | yy, xx = np.mgrid[-jitter_win:jitter_win + 1, -jitter_win:jitter_win + 1]
42 | all_possibilities = np.vstack([xx.reshape(-1), yy.reshape(-1)]).T.tolist()
43 | all_possibilities.sort(key=lambda x: (max(abs(x[0]), abs(x[1])), abs(x[0]) + abs(x[1])))
44 | all_possibilities.pop(0)
45 |
46 | for model_name, group in df.groupby(by="name"):
47 | ordered_images = np.zeros((frow, fcol, *image_shape))
48 | overlap, show = 0, 0
49 | for i, row in group.iterrows():
50 | x, y = row["tsne_x_int"], row["tsne_y_int"]
51 | possibilities = list(all_possibilities)
52 | while len(possibilities) and np.sum(ordered_images[x, y]) != 0:
53 | dx, dy = possibilities.pop(0)
54 | x, y = np.clip(x + dx, 0, fcol - 1), np.clip(y + dy, 0, frow - 1)
55 | if np.sum(ordered_images[x, y]) == 0:
56 | show += 1
57 | ordered_images[x, y] = row[get_features(image_shape)].values.reshape((-1, *image_shape))
58 | else:
59 | overlap += 1
60 | logger.info("overlap for %s: %d, show: %d", model_name, overlap, show)
61 | ordered_images = np.flipud(np.transpose(ordered_images, (1, 0, 2, 3, 4))).reshape(frow * fcol, *image_shape)
62 |
63 | grid = (ordered_images.reshape(frow, fcol, *image_shape).swapaxes(1, 2)
64 | .reshape(image_shape[0] * frow, image_shape[1] * fcol, image_shape[2]))
65 | logger.info("tsne grid shape: %s", grid.shape)
66 | plt.figure(figsize=(20, 20))
67 | plt.imsave(os.path.join(output_dir, f"tsne_{model_name}.png"), grid)
68 | return df
69 |
70 |
71 | def apply_tsne(df, data, perplexity, n_iter, learning_rate=200, pca_components=None, tsne_jobs=4):
72 | if pca_components:
73 | logger.info("shape before pca: %s", data.shape)
74 | pca = PCA(n_components=pca_components, svd_solver='randomized')
75 | data = pca.fit_transform(data)
76 | pca_cols = [f"pca_{c}" for c in range(pca.n_components)]
77 | df[pca_cols] = pd.DataFrame(data, index=df.index)
78 | logger.info("shape after pca: %s", data.shape)
79 | tsne = TSNE(n_components=2, verbose=1, perplexity=perplexity, n_iter=n_iter, learning_rate=learning_rate,
80 | n_jobs=tsne_jobs)
81 | return tsne.fit_transform(data)
82 |
83 |
84 | def load_features(image_path, extensions=("npz", "npy")):
85 | base_path = os.path.splitext(image_path)[0]
86 | for ext in extensions:
87 | f = f"{base_path}.{ext}"
88 | if os.path.exists(f):
89 | data = np.load(f)
90 | if ext == "npz":
91 | data = data["arr_0"]
92 | return data
93 | return None
94 |
95 |
96 | def load_data(paths, use_features):
97 | df = pd.DataFrame()
98 | image_shape = None
99 | all_features = []
100 | for path in paths:
101 | logger.info("loading images from %s", path)
102 | name = os.path.basename(path)
103 | for f in glob(os.path.join(path, "*.png")):
104 | if use_features:
105 | features = load_features(f)
106 | if features is None:
107 | logger.warning("features not found for %s", f)
108 | continue
109 | all_features.append(features)
110 | image = np.array(Image.open(f))/255
111 | image_shape = image.shape
112 | df_new = pd.DataFrame(image.reshape((-1, np.prod(image_shape))))
113 | df_new["name"] = name
114 | df_new["file"] = f
115 | df = df.append(df_new)
116 | # with open(os.path.basename(path).split('/')[-1]+'.npy', 'wb') as f:
117 | # np.save(f, all_features)
118 | # all_features = []
119 | logger.info("loaded %d images with shape %s", len(df), image_shape)
120 | tsne_input = np.array(all_features) if use_features else get_image_data(df, image_shape)
121 |
122 | return df.reset_index(), image_shape, tsne_input
123 |
124 |
125 | def generate_scatter(df, output_dir):
126 | plt.figure(figsize=(10, 10))
127 | sns.scatterplot(x="tsne_x", y="tsne_y", hue="name", data=df, legend="full", alpha=0.2)
128 | plt.savefig(os.path.join(output_dir, f"models_scatter.png"))
129 |
130 |
131 | def get_features(image_shape):
132 | return list(range(np.prod(image_shape)))
133 |
134 |
135 | def get_image_data(df, image_shape):
136 | return df[get_features(image_shape)].values
137 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_evaluation_utils/metric.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | import numpy as np
4 | import pandas as pd
5 | from sklearn.metrics import mean_squared_error
6 |
7 | logger = logging.getLogger(__name__)
8 |
9 |
10 | def calc_jaccard_index(df):
11 | df_dataset = df[df["name"] == df.iloc[0]["name"]]
12 | df_models = df[df["name"] != df.iloc[0]["name"]].reset_index()
13 | distance_matrix = _calc_distances(df_dataset, df_models)
14 | min_distances_matrix = distance_matrix.min(axis=1)
15 | logger.info("distance matrix percentile %f", np.percentile(min_distances_matrix, 50))
16 | distance_threshold = np.percentile(min_distances_matrix, 50)
17 | logger.info("distance_threshold: %f", distance_threshold)
18 | model_names = df_models["name"].unique()
19 | cols = ["selected", "distance_threshold", "intersection", "jaccard_index"]
20 | stats_df = pd.DataFrame(index=model_names, columns=cols)
21 | for name in model_names:
22 | df_model = df_models[df_models["name"] == name]
23 | all_selected = set()
24 | min_distances, intersection_gen = [], []
25 | for i, row in df_model.iterrows():
26 | distances = distance_matrix[i]
27 | selected = np.where(distances < distance_threshold)[0]
28 | min_distances.append(np.min(distances))
29 | if len(selected) > 0:
30 | all_selected = all_selected.union(selected)
31 | intersection_gen.append(i)
32 | logger.info("model %s selected: %d intersection: %d", name, len(all_selected), len(intersection_gen))
33 | stats_df.loc[name]["selected"] = len(all_selected)
34 | stats_df.loc[name]["intersection"] = len(intersection_gen)
35 | stats_df.loc[name]["jaccard_index"] = len(intersection_gen)/(len(df_model) + len(df_dataset) - len(intersection_gen))
36 | stats_df["distance_threshold"] = distance_threshold
37 | return distance_threshold, stats_df.reset_index()
38 |
39 |
40 | def _calc_distances(df_dataset, df_models):
41 | distance_matrix = np.empty((len(df_models), len(df_dataset)))
42 | for i, row in df_models.iterrows():
43 | distances = np.sqrt(np.sum((df_dataset[["tsne_x", "tsne_y"]] - row[["tsne_x", "tsne_y"]]) ** 2, axis=1))
44 | distance_matrix[i] = distances
45 | return distance_matrix
46 |
47 |
48 | def calc_rmse(df, shape):
49 | dataset_name = df.iloc[0]["name"]
50 | df_dataset = df[df["name"] == dataset_name]
51 | df_models = df[df["name"] != dataset_name]
52 | row_distances = []
53 | for _, row in df_models.iterrows():
54 | distances = np.sqrt(np.sum((df_dataset[["tsne_x", "tsne_y"]] - row[["tsne_x", "tsne_y"]])**2, axis=1))
55 | min_index = np.argmin(distances)
56 | max_index = np.argmax(distances)
57 | cols = list(range(np.prod(shape)))
58 | cols_act = [c for c in df_dataset.columns if str(c).startswith("act_")]
59 | cols_pca = [c for c in df_dataset.columns if str(c).startswith("pca_")]
60 |
61 | values = {}
62 | for k, index in {"min": min_index, "max": max_index}.items():
63 | row_dataset = df_dataset.iloc[index]
64 | rmse = np.sqrt(mean_squared_error(row[cols], row_dataset[cols]))
65 | rmse_act = np.sqrt(mean_squared_error(row[cols_act], row_dataset[cols_act])) if cols_act else None
66 | rmse_pca = np.sqrt(mean_squared_error(row[cols_pca], row_dataset[cols_pca])) if cols_pca else None
67 | values = {**values, f"rmse_{k}": rmse, f"rmse_act_{k}": rmse_act, f"rmse_pca_{k}": rmse_pca,
68 | f"distance_{k}": distances[index], f"index_{k}": index}
69 | row_distances.append(values)
70 | return pd.DataFrame(row_distances)
71 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_output/distances.csv:
--------------------------------------------------------------------------------
1 | rmse_min,rmse_act_min,rmse_pca_min,distance_min,index_min,rmse_max,rmse_act_max,rmse_pca_max,distance_max,index_max
2 | 0.0,,,0.5299099634151018,0,0.23874200354570316,,,3.4182638654331203,2
3 | 0.0,,,0.5511406028574707,1,0.4226597363877475,,,3.367744388489437,2
4 | 0.0,,,0.5721681224628774,2,0.23874200354570316,,,3.614981425335309,0
5 | 0.3992857884213457,,,1.494951438335612,1,0.35899513931559507,,,3.156267410458738,0
6 | 0.0,,,0.5883145291463263,4,0.6148720845015195,,,1.9763873709280828,1
7 | 0.321735112156867,,,0.8856215144732921,4,0.6108290221548718,,,2.595041016039699,1
8 | 0.27533660355687184,,,1.0606789858687125,2,0.3349378150364164,,,2.738964400532061,0
9 | 0.2966289252292293,,,0.6261604338228165,4,0.48272389643562397,,,2.776364194136647,1
10 | 0.0,,,0.7849563976991836,1,0.4933058730972799,,,3.078485495259059,0
11 | 0.31686550926405477,,,0.6659541170896194,4,0.3228451601943453,,,2.338557459202454,2
12 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_output/models_scatter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/tsne_output/models_scatter.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_output/stats.csv:
--------------------------------------------------------------------------------
1 | index,selected,distance_threshold,intersection,jaccard_index
2 | model_a,4,0.6460572754562179,4,0.6666666666666666
3 | model_b,1,0.6460572754562179,1,0.1111111111111111
4 |
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_output/tsne_dataset.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/tsne_output/tsne_dataset.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_output/tsne_model_a.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/tsne_output/tsne_model_a.png
--------------------------------------------------------------------------------
/evaluation/tsne_analysis_baseline/tsne_output/tsne_model_b.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/evaluation/tsne_analysis_baseline/tsne_output/tsne_model_b.png
--------------------------------------------------------------------------------
/evaluation/utils_tsne.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pandas as pd
3 | from sklearn.decomposition import PCA
4 | from MulticoreTSNE import MulticoreTSNE as TSNE
5 | import matplotlib.pyplot as plt
6 | import seaborn as sns
7 | import wandb
8 | import io
9 | import PIL
10 |
11 | def apply_tsne(df_feature_vector_info, feature_vectors, perplexity, n_iter, learning_rate=200, pca_components=None, tsne_jobs=4):
12 | if pca_components:
13 | print("shape before pca: %s", feature_vectors.shape)
14 | pca = PCA(n_components=pca_components, svd_solver='randomized')
15 | feature_vectors = pca.fit_transform(feature_vectors)
16 | pca_cols = [f"pca_{c}" for c in range(pca.n_components)]
17 | df_feature_vector_info[pca_cols] = pd.DataFrame(feature_vectors, index=df_feature_vector_info.index)
18 | print("shape after pca: %s", feature_vectors.shape)
19 | print();print('TSNE:')
20 | tsne = TSNE(n_components=2, verbose=1, perplexity=perplexity, n_iter=n_iter, learning_rate=learning_rate,
21 | n_jobs=tsne_jobs)
22 | print()
23 | return tsne.fit_transform(feature_vectors), df_feature_vector_info
24 |
25 | def generate_scatter(tsne_results, df_feature_vector_info, save_image, output_dir, save_wandb, plot_title):
26 |
27 | plt.figure(figsize=(10, 10))
28 | plt.title(plot_title)
29 | plt.xlabel('tsne_x')
30 | plt.ylabel('tsne_y')
31 | sns.scatterplot(x=tsne_results[:,0], y=tsne_results[:,1], hue=df_feature_vector_info['name'], legend="full", alpha=0.8)
32 |
33 | if save_image:
34 | plt.savefig(os.path.join(output_dir, plot_title+"_scatter_plot.png"))
35 |
36 | wandb_scatter_plot =None
37 | img_scatter_plot = None
38 | if save_wandb:
39 | data = [[x,y, name] for (x, y, name) in zip(list(tsne_results[:,0]), list(tsne_results[:,1]), list(df_feature_vector_info['name']))]
40 | table = wandb.Table(data=data, columns = ["tsne_x", "tsne_y",'name'])
41 | wandb_scatter_plot = wandb.plot.scatter(table, "tsne_x", "tsne_y", title=plot_title)
42 | # wandb.log({"tsne evaluation" : wandb.plot.scatter(table, "tsne_x", "tsne_y", title="t-SNE evaluation")})
43 |
44 | buf = io.BytesIO()
45 | plt.savefig(buf)
46 | buf.seek(0)
47 | img_scatter_plot = PIL.Image.open(buf)
48 |
49 | return wandb_scatter_plot, img_scatter_plot
50 |
--------------------------------------------------------------------------------
/images/Cartoons_example.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/images/Cartoons_example.jpeg
--------------------------------------------------------------------------------
/images/Faces_example.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/IAmigos/avatar-image-generator/9bf11125f4ea3090e217cf15866ec19ce944f9c6/images/Faces_example.jpeg
--------------------------------------------------------------------------------
/losses/__init__.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from .utils_loss import calc_eval_stats, calc_fid
3 |
4 | def L2_norm(image_rec, image_orig):
5 |
6 | assert image_rec.shape == image_orig.shape, "Assertion error: shape of input should be as same as target"
7 |
8 | return torch.linalg.norm(image_rec.reshape(image_rec.shape[0], -1) - image_orig.reshape(image_orig.shape[0], -1), ord=2, dim=1).mean()
9 |
10 |
11 |
12 | def L1_norm(encoder,encoder_rec):
13 |
14 | assert encoder.shape == encoder_rec.shape, "Assertion error: shape of input should be as same as target"
15 |
16 | return torch.linalg.norm(encoder.reshape(encoder.shape[0], -1) - encoder_rec.reshape(encoder_rec.shape[0], -1), ord=1, dim=1).mean()
17 |
18 | def fid(real_img,fake_img):
19 | #Code obtained from: https://www.kaggle.com/ibtesama/gan-in-pytorch-with-fid
20 | mu_1,std_1=calc_eval_stats(real_img)
21 | mu_2,std_2=calc_eval_stats(fake_img)
22 |
23 | """get fretched distance"""
24 | fid_value = calc_fid(mu_1, std_1, mu_2, std_2)
25 | return fid_value
26 |
27 | def MMD(x, y, kernel, device):
28 | #Code obtained from: https://www.kaggle.com/onurtunali/maximum-mean-discrepancy
29 | """Emprical maximum mean discrepancy. The lower the result, the more evidence that distributions are the same.
30 |
31 | Args:
32 | x: first sample, distribution P
33 | y: second sample, distribution Q
34 | kernel: kernel type such as "multiscale" or "rbf"
35 | """
36 | xx, yy, zz = torch.mm(x, x.t()), torch.mm(y, y.t()), torch.mm(x, y.t())
37 | rx = (xx.diag().unsqueeze(0).expand_as(xx))
38 | ry = (yy.diag().unsqueeze(0).expand_as(yy))
39 |
40 | dxx = rx.t() + rx - 2. * xx # Used for A in (1)
41 | dyy = ry.t() + ry - 2. * yy # Used for B in (1)
42 | dxy = rx.t() + ry - 2. * zz # Used for C in (1)
43 |
44 | XX, YY, XY = (torch.zeros(xx.shape).to(device),
45 | torch.zeros(xx.shape).to(device),
46 | torch.zeros(xx.shape).to(device))
47 |
48 | if kernel == "multiscale":
49 |
50 | bandwidth_range = [0.2, 0.5, 0.9, 1.3]
51 | for a in bandwidth_range:
52 | XX += a**2 * (a**2 + dxx)**-1
53 | YY += a**2 * (a**2 + dyy)**-1
54 | XY += a**2 * (a**2 + dxy)**-1
55 |
56 | if kernel == "rbf":
57 |
58 | bandwidth_range = [10, 15, 20, 50]
59 | for a in bandwidth_range:
60 | XX += torch.exp(-0.5*dxx/a)
61 | YY += torch.exp(-0.5*dyy/a)
62 | XY += torch.exp(-0.5*dxy/a)
63 | return torch.mean(XX + YY - 2. * XY).item()
64 |
65 |
66 |
67 | def get_gradient(crit, real, fake, epsilon):
68 | '''
69 | Return the gradient of the critic's scores with respect to mixes of real and fake images.
70 | Parameters:
71 | crit: the critic model
72 | real: a batch of real images
73 | fake: a batch of fake images
74 | epsilon: a vector of the uniformly random proportions of real/fake per mixed image
75 | Returns:
76 | gradient: the gradient of the critic's scores, with respect to the mixed image
77 | '''
78 | # Mix the images together
79 |
80 |
81 | mixed_images = real * epsilon + fake * (1 - epsilon)
82 |
83 | # Calculate the critic's scores on the mixed images
84 | mixed_scores = crit(mixed_images)
85 |
86 | # Take the gradient of the scores with respect to the images
87 | gradient = torch.autograd.grad(
88 | # Note: You need to take the gradient of outputs with respect to inputs.
89 | # This documentation may be useful, but it should not be necessary:
90 | # https://pytorch.org/docs/stable/autograd.html#torch.autograd.grad
91 | #### START CODE HERE ####
92 | inputs=mixed_images,
93 | outputs=mixed_scores,
94 | #### END CODE HERE ####
95 | # These other parameters have to do with the pytorch autograd engine works
96 | grad_outputs=torch.ones_like(mixed_scores),
97 | create_graph=True,
98 | retain_graph=True,
99 | )[0]
100 | return gradient
101 |
102 |
103 | def gradient_penalty(gradient):
104 | '''
105 | Return the gradient penalty, given a gradient.
106 | Given a batch of image gradients, you calculate the magnitude of each image's gradient
107 | and penalize the mean quadratic distance of each magnitude to 1.
108 | Parameters:
109 | gradient: the gradient of the critic's scores, with respect to the mixed image
110 | Returns:
111 | penalty: the gradient penalty
112 | '''
113 | # Flatten the gradients so that each row captures one image
114 | gradient = gradient.view(len(gradient), -1)
115 |
116 | # Calculate the magnitude of every row
117 | gradient_norm = gradient.norm(2, dim=1)
118 |
119 | # Penalize the mean squared distance of the gradient norms from 1
120 | #### START CODE HERE ####
121 | penalty = ((gradient_norm - 1)**2).mean()
122 | #### END CODE HERE ####
123 | return penalty
124 |
125 |
126 | def get_crit_loss(crit_fake_pred, crit_real_pred, gp, c_lambda):
127 | '''
128 | Return the loss of a critic given the critic's scores for fake and real images,
129 | the gradient penalty, and gradient penalty weight.
130 | Parameters:
131 | crit_fake_pred: the critic's scores of the fake images
132 | crit_real_pred: the critic's scores of the real images
133 | gp: the unweighted gradient penalty
134 | c_lambda: the current weight of the gradient penalty
135 | Returns:
136 | crit_loss: a scalar for the critic's loss, accounting for the relevant factors
137 | '''
138 | #### START CODE HERE ####
139 | crit_loss = -(crit_real_pred - crit_fake_pred - c_lambda*gp).mean()
140 | #### END CODE HERE ####
141 | return crit_loss
142 |
143 |
144 | def get_gen_loss(crit_fake_pred):
145 | '''
146 | Return the loss of a generator given the critic's scores of the generator's fake images.
147 | Parameters:
148 | crit_fake_pred: the critic's scores of the fake images
149 | Returns:
150 | gen_loss: a scalar loss value for the current batch of the generator
151 | '''
152 | #### START CODE HERE ####
153 | gen_loss = -1 * crit_fake_pred.mean()
154 | #### END CODE HERE ####
155 | return gen_loss
--------------------------------------------------------------------------------
/losses/utils_loss.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch
3 | from scipy import linalg
4 | import torch.nn.functional as F
5 |
6 | def calc_fid(mu1, sigma1, mu2, sigma2, eps=1e-6):
7 | ##Code obtained from: https://www.kaggle.com/ibtesama/gan-in-pytorch-with-fid
8 | """Numpy implementation of the Frechet Distance.
9 | The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
10 | and X_2 ~ N(mu_2, C_2) is
11 | d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
12 | """
13 |
14 | mu1 = np.atleast_1d(mu1)
15 | mu2 = np.atleast_1d(mu2)
16 |
17 | sigma1 = np.atleast_2d(sigma1)
18 | sigma2 = np.atleast_2d(sigma2)
19 |
20 | assert mu1.shape == mu2.shape, \
21 | 'Training and test mean vectors have different lengths'
22 | assert sigma1.shape == sigma2.shape, \
23 | 'Training and test covariances have different dimensions'
24 |
25 | diff = mu1 - mu2
26 |
27 |
28 | covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
29 | if not np.isfinite(covmean).all():
30 | msg = ('fid calculation produces singular product; '
31 | 'adding %s to diagonal of cov estimates') % eps
32 | print(msg)
33 | offset = np.eye(sigma1.shape[0]) * eps
34 | covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
35 |
36 |
37 | if np.iscomplexobj(covmean):
38 | if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
39 | m = np.max(np.abs(covmean.imag))
40 | raise ValueError('Imaginary component {}'.format(m))
41 | covmean = covmean.real
42 |
43 | tr_covmean = np.trace(covmean)
44 |
45 | return (diff.dot(diff) + np.trace(sigma1) +
46 | np.trace(sigma2) - 2 * tr_covmean)
47 |
48 | def calc_eval_stats(act):
49 | ##Code obtained from: https://www.kaggle.com/ibtesama/gan-in-pytorch-with-fid
50 | #model.eval()
51 | #act=np.empty((len(images), dims))
52 | #batch=images.to(device)
53 |
54 | #pred = model(batch)[0]
55 |
56 | # If model output is not scalar, apply global spatial average pooling.
57 | # This happens if you choose a dimensionality not equal 2048.
58 | #if pred.size(2) != 1 or pred.size(3) != 1:
59 | # pred = F.adaptive_avg_pool2d(pred, output_size=(1, 1))
60 |
61 | #act= pred.cpu().data.numpy().reshape(pred.size(0), -1)
62 |
63 | mu = np.mean(act, axis=0)
64 | sigma = np.cov(act, rowvar=False)
65 | return mu, sigma
--------------------------------------------------------------------------------
/models/__init__.py:
--------------------------------------------------------------------------------
1 | from .encoder import *
2 | from .decoder import *
3 | from .discriminator import *
4 | from .denoiser import *
5 | from .cdann import *
6 | from .avatar_generator_model import *
7 |
8 |
--------------------------------------------------------------------------------
/models/avatar_generator_model.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | import torchvision.transforms as transforms
5 | import torchvision
6 | from torch.autograd import Variable
7 | from PIL import Image
8 | from keras_segmentation.pretrained import pspnet_101_voc12
9 | import cv2
10 | import numpy as np
11 |
12 | from .encoder import *
13 | from .decoder import *
14 | from .discriminator import *
15 | from .denoiser import *
16 | from .cdann import *
17 | from .inception import *
18 | from utils import *
19 | from losses import *
20 | from evaluation import tsne_evaluation
21 |
22 | import wandb
23 | import os
24 | import sys
25 | from tqdm import tqdm
26 | from itertools import cycle
27 |
28 |
29 | class Avatar_Generator_Model():
30 | """
31 | # Methods
32 | __init__(dict_model): initializer
33 | dict_model: layers required to perform face-to-image generation (e1, e_shared, d_shared, d2, denoiser)
34 | generate(face_image, output_path=None): reutrn cartoon generated from given face image, saves it to output path if given
35 | load_weights(weights_path): loads weights from given path
36 | """
37 |
38 | def __init__(self, config, use_wandb=True):
39 | self.use_wandb = use_wandb
40 | self.config = config
41 | self.device = torch.device("cuda:" + (os.getenv('N_CUDA')if os.getenv('N_CUDA') else "0") if self.config.use_gpu and torch.cuda.is_available() else "cpu")
42 | self.mmd_kernel_type = "multiscale"
43 | self.segmentation = pspnet_101_voc12()
44 | self.e1, self.e2, self.d1, self.d2, self.e_shared, self.d_shared, self.c_dann, self.discriminator1, self.denoiser, self.inception, self.discriminator2 = self.init_model(self.device,
45 | self.config.dropout_rate_eshared,
46 | self.config.use_critic_dann,
47 | self.config.use_critic_disc,
48 | self.config.use_spectral_norm,
49 | self.use_wandb)
50 |
51 |
52 | def init_model(self, device,
53 | dropout_rate_eshared,
54 | use_critic_dann, use_critic_disc,
55 | use_spectral_norm, use_wandb=True):
56 |
57 | e1 = Encoder()
58 | e2 = Encoder()
59 | e_shared = Eshared(dropout_rate_eshared)
60 | d_shared = Dshared()
61 | d1 = Decoder()
62 | d2 = Decoder()
63 | c_dann = Cdann(use_critic_dann=use_critic_dann, use_spectral_norm=use_spectral_norm)
64 | discriminator1 = Discriminator(use_critic_disc=use_critic_disc, use_spectral_norm=use_spectral_norm)
65 | discriminator2 = Discriminator(use_critic_disc=use_critic_disc, use_spectral_norm=use_spectral_norm)
66 | denoiser = Denoiser()
67 | inception = Inception([Inception.BLOCK_INDEX_BY_DIM[2048]]) #fid
68 |
69 | e1.to(device)
70 | e2.to(device)
71 | e_shared.to(device)
72 | d_shared.to(device)
73 | d1.to(device)
74 | d2.to(device)
75 | c_dann.to(device)
76 | discriminator1.to(device)
77 | denoiser = denoiser.to(device)
78 | inception = inception.to(device)
79 | discriminator2 = discriminator2.to(device)
80 |
81 | if use_wandb:
82 | wandb.watch(e1, log="all")
83 | wandb.watch(e2, log="all")
84 | wandb.watch(e_shared, log="all")
85 | wandb.watch(d_shared, log="all")
86 | wandb.watch(d1, log="all")
87 | wandb.watch(d2, log="all")
88 | wandb.watch(c_dann, log="all")
89 | wandb.watch(discriminator1, log="all")
90 | wandb.watch(denoiser, log="all")
91 | wandb.watch(discriminator2, log="all")
92 | #wandb.watch(inception, log="all")
93 |
94 | return (e1, e2, d1, d2, e_shared, d_shared, c_dann, discriminator1, denoiser, inception, discriminator2)
95 |
96 |
97 | def generate(self, path_filename, output_path):
98 | face = self.__extract_face(path_filename, output_path)
99 | return self.__to_cartoon(face, output_path)
100 |
101 |
102 | def load_weights(self, weights_path):
103 |
104 | self.e1.load_state_dict(torch.load(
105 | weights_path + 'e1.pth', map_location=torch.device(self.device)))
106 |
107 | self.e_shared.load_state_dict(
108 | torch.load(weights_path + 'e_shared.pth', map_location=torch.device(self.device)))
109 |
110 | self.e2.load_state_dict(
111 | torch.load(weights_path + 'e2.pth', map_location=torch.device(self.device)))
112 |
113 | self.d_shared.load_state_dict(
114 | torch.load(weights_path + 'd_shared.pth', map_location=torch.device(self.device)))
115 |
116 | self.d2.load_state_dict(torch.load(
117 | weights_path + 'd2.pth', map_location=torch.device(self.device)))
118 |
119 | self.d1.load_state_dict(torch.load(
120 | weights_path + 'd1.pth', map_location=torch.device(self.device)))
121 |
122 | self.denoiser.load_state_dict(
123 | torch.load(weights_path + 'denoiser.pth', map_location=torch.device(self.device)))
124 |
125 | self.discriminator1.load_state_dict(
126 | torch.load(weights_path + 'disc1.pth', map_location=torch.device(self.device)))
127 |
128 | self.c_dann.load_state_dict(
129 | torch.load(weights_path + 'c_dann.pth', map_location=torch.device(self.device)))
130 |
131 | self.discriminator2.load_state_dict(
132 | torch.load(weights_path + 'disc2.pth', map_location=torch.device(self.device)))
133 |
134 |
135 | def __extract_face(self, path_filename, output_path):
136 | out = self.segmentation.predict_segmentation(
137 | inp=path_filename,
138 | out_fname=output_path
139 | )
140 |
141 | img_mask = cv2.imread(output_path)
142 | img1 = cv2.imread(path_filename) # READ BGR
143 |
144 | seg_gray = cv2.cvtColor(img_mask, cv2.COLOR_BGR2GRAY)
145 | _, bg_mask = cv2.threshold(
146 | seg_gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
147 |
148 | bg_mask = cv2.cvtColor(bg_mask, cv2.COLOR_GRAY2BGR)
149 |
150 | bg = cv2.bitwise_or(img1, bg_mask)
151 |
152 | cv2.imwrite(output_path, bg)
153 | face_image = Image.open(output_path)
154 |
155 | return face_image
156 |
157 |
158 | def __to_cartoon(self, face, output_path):
159 | self.e1.eval()
160 | self.e_shared.eval()
161 | self.d_shared.eval()
162 | self.d2.eval()
163 | self.denoiser.eval()
164 |
165 | transform_list_faces = get_transforms_config_face()
166 | transform = transforms.Compose(transform_list_faces)
167 | face = transform(face).float()
168 | X = face.unsqueeze(0).to(self.device)
169 |
170 | with torch.no_grad():
171 | output = self.e1(X)
172 | output = self.e_shared(output)
173 | output = self.d_shared(output)
174 | output = self.d2(output)
175 | if self.config.use_denoiser:
176 | output = self.denoiser(output)
177 |
178 | output = denorm(output)
179 | output = output[0]
180 |
181 | torchvision.utils.save_image(tensor=output, fp=output_path)
182 |
183 | return (torchvision.transforms.ToPILImage()(output), output)
184 |
185 |
186 | def get_feature_inception(self, images, dims=2048):
187 | self.inception = self.inception.eval()
188 | act = np.empty((len(images), dims))
189 | batch = images.to(self.device)
190 |
191 | pred = self.inception(batch)[0]
192 |
193 | # If model output is not scalar, apply global spatial average pooling.
194 | # This happens if you choose a dimensionality not equal 2048.
195 | if pred.size(2) != 1 or pred.size(3) != 1:
196 | pred = F.adaptive_avg_pool2d(pred, output_size=(1, 1))
197 |
198 | act= pred.cpu().data.numpy().reshape(pred.size(0), -1)
199 | return act
200 |
201 | def get_loss_test_set(self, test_loader_faces, test_loader_cartoons, criterion_bc):
202 |
203 | self.e1.eval()
204 | self.e2.eval()
205 | self.e_shared.eval()
206 | self.d_shared.eval()
207 | self.d1.eval()
208 | self.d2.eval()
209 | self.c_dann.eval()
210 | self.discriminator1.eval()
211 | self.denoiser.eval()
212 | self.inception.eval()
213 | self.discriminator2.eval()
214 |
215 | cartoons_batch_test = []
216 | cartoons_construct_test = []
217 |
218 |
219 | faces_encoder_test = []
220 | cartoons_encoder_test = []
221 | cartoons_construct_encoder_test = []
222 | cartoon_inception_test = []
223 | cartoons_construct_inception_test = []
224 |
225 | with torch.no_grad():
226 | for faces_batch, cartoons_batch in zip(cycle(test_loader_faces), test_loader_cartoons):
227 |
228 | faces_batch, _ = faces_batch
229 | faces_batch = Variable(faces_batch.type(torch.Tensor))
230 | faces_batch = faces_batch.to(self.device)
231 |
232 | cartoons_batch, _ = cartoons_batch
233 | cartoons_batch = Variable(cartoons_batch.type(torch.Tensor))
234 | cartoons_batch = cartoons_batch.to(self.device)
235 |
236 | if faces_batch.shape != cartoons_batch.shape:
237 | continue
238 |
239 | faces_enc1 = self.e1(faces_batch)
240 | faces_encoder = self.e_shared(faces_enc1)
241 | faces_decoder = self.d_shared(faces_encoder)
242 | faces_rec = self.d1(faces_decoder)
243 | cartoons_construct = self.d2(faces_decoder)
244 | cartoons_construct_enc2 = self.e2(cartoons_construct)
245 | cartoons_construct_encoder = self.e_shared(cartoons_construct_enc2)
246 |
247 | cartoons_enc2 = self.e2(cartoons_batch)
248 | cartoons_encoder = self.e_shared(cartoons_enc2)
249 | cartoons_decoder = self.d_shared(cartoons_encoder)
250 | cartoons_rec = self.d2(cartoons_decoder)
251 | faces_construct = self.d1(cartoons_decoder)
252 | faces_construct_enc1 = self.e1(faces_construct)
253 | faces_construct_encoder = self.e_shared(faces_construct_enc1)
254 |
255 | #inception
256 | cartoon_inception = self.get_feature_inception(cartoons_batch)
257 | cartoon_inception_test.append(cartoon_inception)
258 | #inception
259 |
260 | cartoons_batch_test.append(cartoons_batch)
261 |
262 | if self.config.use_denoiser:
263 | cartoons_construct = self.denoiser(cartoons_construct)
264 |
265 | #inception
266 | cartoons_construct_inception = self.get_feature_inception(cartoons_construct)
267 | cartoons_construct_inception_test.append(cartoons_construct_inception)
268 | #inception
269 |
270 | cartoons_construct_test.append(cartoons_construct)
271 |
272 | faces_encoder_test.append(faces_encoder)
273 | cartoons_encoder_test.append(cartoons_encoder)
274 | cartoons_construct_encoder_test.append(cartoons_construct_encoder)
275 |
276 |
277 | # return np.mean(loss_test)
278 |
279 | cartoons_batch_test = torch.cat(cartoons_batch_test)
280 | cartoons_construct_test = torch.cat(cartoons_construct_test)
281 | cartoons_construct_test = torch.unique(cartoons_construct_test, dim=0, sorted=False)
282 |
283 | cartoon_inception_test = np.concatenate(cartoon_inception_test)
284 | cartoons_construct_inception_test = np.concatenate(cartoons_construct_inception_test)
285 | cartoons_construct_inception_test = np.unique(cartoons_construct_inception_test, axis=0)
286 |
287 | cartoons_batch_feature_view = cartoons_batch_test.view(cartoons_batch_test.size()[0], -1)
288 | cartoons_construct_feature_view = cartoons_construct_test.view(cartoons_construct_test.size()[0], -1)
289 | cartoons_construct_feature_view = torch.unique(cartoons_construct_feature_view, dim=0, sorted=False)
290 | cartoons_batch_feature_view = cartoons_batch_feature_view[:cartoons_construct_feature_view.shape[0]]
291 |
292 | assert cartoons_construct_test.shape[0] == cartoons_construct_feature_view.shape[0], "torch unique cant get the same shape in constructed cartoons"
293 |
294 | fid_test = fid(cartoon_inception_test, cartoons_construct_inception_test)
295 | mmd_test = MMD(cartoons_batch_feature_view, cartoons_construct_feature_view, self.mmd_kernel_type, self.device)
296 |
297 | # tsne analysis
298 | faces_encoder_test = torch.cat(faces_encoder_test).cpu()
299 | faces_encoder_test = torch.unique(faces_encoder_test, dim=0, sorted=False)
300 | cartoons_encoder_test = torch.cat(cartoons_encoder_test).cpu()
301 | cartoons_construct_encoder_test = torch.cat(cartoons_construct_encoder_test).cpu()
302 | cartoons_construct_encoder_test = torch.unique(cartoons_construct_encoder_test, dim=0, sorted=False)
303 |
304 | assert faces_encoder_test.shape[0] == cartoons_construct_encoder_test.shape[0], "torch unique cant get the same shape in faces and constructed cartoons"
305 |
306 | # tsne of faces encoder and cartoons encoder
307 | tsne_results_norm, df_feature_vector_info, wandb_scatter_plot_1_fe_ce, img_scatter_plot_1_fe_ce = tsne_evaluation([faces_encoder_test, cartoons_encoder_test], ['faces encoder', 'cartoons encoder'], pca_components=None, perplexity=30, n_iter=1000, save_image=False, save_wandb=self.use_wandb, plot_title='t-SNE evaluation - FE and CE')
308 |
309 | # tsne of faces encoder and cartoons construct encoder
310 | tsne_results_norm, df_feature_vector_info, wandb_scatter_plot_2_fe_cce, img_scatter_plot_2_fe_cce = tsne_evaluation([faces_encoder_test, cartoons_construct_encoder_test], ['faces encoder', 'cartoons construct encoder'], pca_components=None, perplexity=30, n_iter=1000, save_image=False, save_wandb=self.use_wandb, plot_title='t-SNE evaluation - FE and CCE')
311 |
312 | return fid_test, mmd_test, wandb_scatter_plot_1_fe_ce, wandb_scatter_plot_2_fe_cce, img_scatter_plot_1_fe_ce, img_scatter_plot_2_fe_cce
313 |
314 |
315 |
316 | def train_crit_repeats(self, opt, fake, real, model, type_model, crit_repeats=5):
317 |
318 | if type_model=="discriminator":
319 | fake = fake.detach()
320 | loss_weight = self.config.wGan_loss
321 | elif type_model=="cdann":
322 | loss_weight = self.config.wDann_loss
323 |
324 |
325 | mean_iteration_critic_loss = torch.zeros(1).to(self.device)
326 | for i in range(crit_repeats):
327 | ### Update critic ###
328 | opt.zero_grad()
329 | lim_inf = i * int(len(fake)/crit_repeats)
330 | lim_sup = lim_inf + int(len(fake)/crit_repeats) if i < crit_repeats - 1 else 1000
331 | fake_sample = fake[lim_inf: lim_sup]
332 | real_sample = real[lim_inf: lim_sup]
333 |
334 | crit_fake_pred = model(fake_sample)
335 | crit_real_pred = model(real_sample)
336 |
337 | if type_model=="discriminator":
338 | epsilon = torch.rand(len(real_sample), 1, 1, 1,
339 | device=self.device, requires_grad=True)
340 | elif type_model=="cdann":
341 | epsilon = torch.rand(len(real_sample), 1,
342 | device=self.device, requires_grad=True)
343 |
344 | gradient = get_gradient(
345 | model, real_sample, fake_sample, epsilon)
346 | gp = gradient_penalty(gradient)
347 | crit_loss = get_crit_loss(
348 | crit_fake_pred.squeeze(), crit_real_pred.squeeze(), gp, 10) * self.config.wDann_loss
349 |
350 | # Keep track of the average critic loss in this batch
351 | mean_iteration_critic_loss += crit_loss / crit_repeats
352 | # Update gradients
353 | crit_loss.backward(retain_graph=True)
354 | # Update optimizer
355 | opt.step()
356 | loss = mean_iteration_critic_loss
357 |
358 | return loss
359 |
360 | def train_disc(self, disc, e, d, batch, real, opt):
361 | # discriminator face(1)->cartoon(2)
362 | # discriminator cartoon(2)->face(1)
363 | disc.zero_grad()
364 |
365 | enc = e(batch).detach()
366 | encoder = self.e_shared(enc).detach()
367 | decoder = self.d_shared(encoder).detach()
368 | construct = d(decoder).detach()
369 |
370 | if not self.config.use_critic_disc:
371 | # train discriminator with real cartoon images
372 | output_real = disc(real)
373 | loss_disc_real = self.config.wGan_loss * \
374 | criterion_bc(output_real.squeeze(), torch.ones_like(
375 | output_real.squeeze(), device=self.device))
376 | # loss_disc1_real_cartoons.backward()
377 |
378 | # train discriminator with fake cartoon images
379 | # class_faces.fill_(0)
380 |
381 | output_fake = disc(construct)
382 | loss_disc_fake = self.config.wGan_loss * \
383 | criterion_bc(output_fake.squeeze(), torch.zeros_like(
384 | output_fake.squeeze(), device=self.device))
385 | # loss_disc1_fake_cartoons.backward()
386 |
387 | loss_disc = loss_disc_real + loss_disc_fake
388 | loss_disc.backward()
389 | opt.step()
390 | else:
391 | loss_disc = self.train_crit_repeats(opt, construct,
392 | real, disc,
393 | "discriminator", crit_repeats=5)
394 |
395 | return loss_disc
396 |
397 | def train_step(self, train_loader_faces, train_loader_cartoons, optimizers, criterion_bc):
398 |
399 | optimizerDenoiser, optimizerDisc1, optimizerTotal, optimizerCdann, optimizerDisc2 = optimizers
400 |
401 | self.e1.train()
402 | self.e2.train()
403 | self.e_shared.train()
404 | self.d_shared.train()
405 | self.d1.train()
406 | self.d2.train()
407 | self.c_dann.train()
408 | self.discriminator1.train()
409 | self.denoiser.train()
410 | self.discriminator2.train()
411 |
412 | for faces_batch, cartoons_batch in zip(cycle(train_loader_faces), train_loader_cartoons):
413 |
414 | faces_batch, _ = faces_batch
415 | faces_batch = Variable(faces_batch.type(torch.Tensor))
416 | faces_batch = faces_batch.to(self.device)
417 |
418 | cartoons_batch, _ = cartoons_batch
419 | cartoons_batch = Variable(cartoons_batch.type(torch.Tensor))
420 | cartoons_batch = cartoons_batch.to(self.device)
421 |
422 | self.e1.zero_grad()
423 | self.e2.zero_grad()
424 | self.e_shared.zero_grad()
425 | self.d_shared.zero_grad()
426 | self.d1.zero_grad()
427 | self.d2.zero_grad()
428 | self.c_dann.zero_grad()
429 |
430 | if faces_batch.shape != cartoons_batch.shape:
431 | continue
432 |
433 | # architecture
434 | faces_enc1 = self.e1(faces_batch)
435 | faces_encoder = self.e_shared(faces_enc1)
436 | faces_decoder = self.d_shared(faces_encoder)
437 | faces_rec = self.d1(faces_decoder)
438 | cartoons_construct = self.d2(faces_decoder)
439 | cartoons_construct_enc2 = self.e2(cartoons_construct)
440 | cartoons_construct_encoder = self.e_shared(cartoons_construct_enc2)
441 |
442 | cartoons_enc2 = self.e2(cartoons_batch)
443 | cartoons_encoder = self.e_shared(cartoons_enc2)
444 | cartoons_decoder = self.d_shared(cartoons_encoder)
445 | cartoons_rec = self.d2(cartoons_decoder)
446 | faces_construct = self.d1(cartoons_decoder)
447 | faces_construct_enc1 = self.e1(faces_construct)
448 | faces_construct_encoder = self.e_shared(faces_construct_enc1)
449 |
450 | # train generator
451 |
452 | #training cdann
453 | if not self.config.use_critic_dann:
454 | label_output_face = self.c_dann(faces_encoder)
455 | label_output_cartoon = self.c_dann(cartoons_encoder)
456 | loss_dann = criterion_bc(label_output_face.squeeze(), torch.zeros_like(label_output_face.squeeze(
457 | ), device=self.device)) + criterion_bc(label_output_cartoon.squeeze(), torch.ones_like(label_output_cartoon.squeeze(), device=self.device))
458 | loss_dann = self.config.wDann_loss * loss_dann
459 | loss_dann.backward(retain_graph=True)
460 | optimizerCdann.step()
461 | else:
462 | # train critic(cdann)
463 | loss_dann = self.train_crit_repeats(optimizerCdann, faces_encoder,
464 | cartoons_encoder, self.c_dann,
465 | "cdann", crit_repeats=5)
466 |
467 | loss_rec1 = L2_norm(faces_batch, faces_rec)
468 | loss_rec2 = L2_norm(cartoons_batch, cartoons_rec)
469 | loss_rec = loss_rec1 + loss_rec2
470 |
471 | loss_sem1 = L1_norm(faces_encoder.detach(), cartoons_construct_encoder)
472 | loss_sem2 = L1_norm(cartoons_encoder.detach(), faces_construct_encoder)
473 | loss_sem = loss_sem1 + loss_sem2
474 |
475 | # teach loss
476 | #faces_embedding = resnet(faces_batch.squeeze())
477 | #loss_teach = L1_norm(faces_embedding.squeeze(), faces_encoder)
478 | # constant until train facenet
479 | loss_teach = torch.Tensor([0]).requires_grad_()
480 | loss_teach = loss_teach.to(self.device)
481 |
482 | # class_faces.fill_(1)
483 | output = self.discriminator1(cartoons_construct)
484 | if not self.config.use_critic_disc:
485 | loss_gen1 = criterion_bc(output.squeeze(), torch.ones_like(
486 | output.squeeze(), device=self.device))
487 | else:
488 | loss_gen1 = get_gen_loss(output.squeeze())
489 |
490 |
491 | if self.config.use_disc_cartoon2face:
492 | output2 = self.discriminator2(faces_construct)
493 | if not self.config.use_critic_disc:
494 | loss_gen2 = criterion_bc(output2.squeeze(), torch.ones_like(
495 | output2.squeeze(), device=self.device))
496 | else:
497 | loss_gen2 = get_gen_loss(output2.squeeze())
498 | else:
499 | loss_gen2 = torch.Tensor([0]).requires_grad_()
500 | loss_gen2 = loss_gen2.to(self.device)
501 |
502 | #it has been deleted config.wDann_loss*loss_dann
503 | loss_total = self.config.wRec_loss*loss_rec + \
504 | self.config.wSem_loss*loss_sem + self.config.wGan_loss * \
505 | loss_gen1 + self.config.wTeach_loss*loss_teach + \
506 | self.config.wGan_loss * loss_gen2
507 | loss_total.backward()
508 | loss_total += loss_dann
509 |
510 | optimizerTotal.step()
511 |
512 | # discriminator face(1)->cartoon(2)
513 | self.discriminator1.zero_grad()
514 | loss_disc1 = self.train_disc(self.discriminator1, self.e1,
515 | self.d2, faces_batch,
516 | cartoons_batch, optimizerDisc1)
517 |
518 | # discriminator cartoon(2)->face(1)
519 | if self.config.use_disc_cartoon2face:
520 | self.discriminator2.zero_grad()
521 | loss_disc2 = self.train_disc(self.discriminator2, self.e2,
522 | self.d1, cartoons_batch,
523 | faces_batch, optimizerDisc2)
524 | else:
525 | loss_disc2 = torch.Tensor([0]).requires_grad_()
526 |
527 | # Denoiser
528 | if self.config.use_denoiser:
529 | self.denoiser.zero_grad()
530 | cartoons_denoised = self.denoiser(cartoons_rec.detach())
531 |
532 | # Train Denoiser
533 | loss_denoiser = L2_norm(cartoons_batch, cartoons_denoised)
534 | loss_denoiser.backward()
535 |
536 | optimizerDenoiser.step()
537 | else:
538 | loss_denoiser = torch.Tensor([0]).requires_grad_()
539 |
540 | #break #Delete break
541 |
542 |
543 | return loss_rec1, loss_rec2, loss_dann, loss_sem1, loss_sem2, loss_disc1, loss_gen1, loss_disc2, loss_gen2, loss_total, loss_denoiser, loss_teach
544 |
545 |
546 | def train(self):
547 |
548 | if self.config.use_gpu and torch.cuda.is_available():
549 | print("Training in " + torch.cuda.get_device_name(0))
550 | else:
551 | print("Training in CPU")
552 |
553 | if self.config.save_weights:
554 | if self.use_wandb:
555 | path_save_weights = self.config.root_path + wandb.run.id + "_" + self.config.save_path
556 | else:
557 | path_save_weights = self.config.root_path + self.config.save_path
558 | try:
559 | os.mkdir(path_save_weights)
560 | except OSError:
561 | pass
562 |
563 | model = (self.e1, self.e2, self.d1, self.d2, self.e_shared, self.d_shared, self.c_dann, self.discriminator1, self.denoiser, self.discriminator2)
564 |
565 | train_loader_faces, test_loader_faces, train_loader_cartoons, test_loader_cartoons = get_datasets(self.config.root_path, self.config.dataset_path_faces, self.config.dataset_path_cartoons, self.config.batch_size)
566 | optimizers = init_optimizers(model, self.config.learning_rate_opDisc, self.config.learning_rate_opTotal, self.config.learning_rate_denoiser, self.config.learning_rate_opCdann)
567 |
568 | criterion_bc = nn.BCEWithLogitsLoss()
569 | criterion_bc.to(self.device)
570 |
571 | images_faces_to_test = get_test_images(self.segmentation, self.config.batch_size, self.config.root_path + self.config.dataset_path_test_faces, self.config.root_path + self.config.dataset_path_segmented_faces)
572 |
573 | for epoch in tqdm(range(self.config.num_epochs)):
574 | loss_rec1, loss_rec2, loss_dann, loss_sem1, loss_sem2, loss_disc1, loss_gen1, loss_disc2, loss_gen2, loss_total, loss_denoiser, loss_teach = self.train_step(train_loader_faces, train_loader_cartoons, optimizers, criterion_bc)
575 |
576 | metrics_log = {"train_epoch": epoch+1,
577 | "loss_rec1": loss_rec1.item(),
578 | "loss_rec2": loss_rec2.item(),
579 | "loss_dann": loss_dann.item(),
580 | "loss_semantic12": loss_sem1.item(),
581 | "loss_semantic21": loss_sem2.item(),
582 | "loss_disc1": loss_disc1.item(),
583 | "loss_gen1": loss_gen1.item(),
584 | "loss_disc2": loss_disc2.item(),
585 | "loss_gen2": loss_gen2.item(),
586 | "loss_teach": loss_teach.item(),
587 | "loss_total": loss_total.item()}
588 |
589 | if self.config.save_weights and ((epoch+1) % int(self.config.num_epochs/self.config.num_backups)) == 0:
590 | path_save_epoch = path_save_weights + 'epoch_{}'.format(epoch+1)
591 | try:
592 | os.mkdir(path_save_epoch)
593 | except OSError:
594 | pass
595 | save_weights(model, path_save_epoch, self.use_wandb)
596 | fid_test, mmd_test, wandb_scatter_plot_1_fe_ce, wandb_scatter_plot_2_fe_cce, img_scatter_plot_1_fe_ce, img_scatter_plot_2_fe_cce = self.get_loss_test_set(test_loader_faces, test_loader_cartoons, criterion_bc)
597 | generated_images = test_image(model, self.device, images_faces_to_test, self.config.use_denoiser)
598 |
599 | metrics_log["fid"] = fid_test
600 | metrics_log["mmd"] = mmd_test
601 | metrics_log["Generated images"] = [wandb.Image(img) for img in generated_images]
602 | metrics_log['t-SNE evaluation plot 1 - FE and CE'] = wandb_scatter_plot_1_fe_ce
603 | metrics_log['t-SNE evaluation plot 2 - FE and CCE'] = wandb_scatter_plot_2_fe_cce
604 |
605 | if self.use_wandb:
606 | metrics_log["t-SNE evaluation images"] = [wandb.Image(img) for img in [img_scatter_plot_1_fe_ce, img_scatter_plot_2_fe_cce]]
607 |
608 | if self.use_wandb:
609 | wandb.log(metrics_log)
610 |
611 |
612 | print("Losses")
613 | print('Epoch [{}/{}], Loss rec1: {:.4f}'.format(epoch +
614 | 1, self.config.num_epochs, loss_rec1.item()))
615 | print('Epoch [{}/{}], Loss rec2: {:.4f}'.format(epoch +
616 | 1, self.config.num_epochs, loss_rec2.item()))
617 | print('Epoch [{}/{}], Loss dann: {:.4f}'.format(epoch +
618 | 1, self.config.num_epochs, loss_dann.item()))
619 | print('Epoch [{}/{}], Loss semantic 1->2: {:.4f}'.format(epoch +
620 | 1, self.config.num_epochs, loss_sem1.item()))
621 | print('Epoch [{}/{}], Loss semantic 2->1: {:.4f}'.format(epoch +
622 | 1, self.config.num_epochs, loss_sem2.item()))
623 | print('Epoch [{}/{}], Loss disc1: {:.4f}'.format(epoch +
624 | 1, self.config.num_epochs, loss_disc1.item()))
625 | print('Epoch [{}/{}], Loss gen1: {:.4f}'.format(epoch +
626 | 1, self.config.num_epochs, loss_gen1.item()))
627 | print('Epoch [{}/{}], Loss disc2: {:.4f}'.format(epoch +
628 | 1, self.config.num_epochs, loss_disc2.item()))
629 | print('Epoch [{}/{}], Loss gen2: {:.4f}'.format(epoch +
630 | 1, self.config.num_epochs, loss_gen2.item()))
631 | print('Epoch [{}/{}], Loss teach: {:.4f}'.format(epoch +
632 | 1, self.config.num_epochs, loss_teach.item()))
633 | print('Epoch [{}/{}], Loss total: {:.4f}'.format(epoch +
634 | 1, self.config.num_epochs, loss_total.item()))
635 | print('Epoch [{}/{}], Loss denoiser: {:.4f}'.format(epoch +
636 | 1, self.config.num_epochs, loss_denoiser.item()))
637 |
638 | if self.use_wandb:
639 | wandb.finish()
640 |
--------------------------------------------------------------------------------
/models/cdann.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from torch.autograd import Variable
5 |
6 |
7 | class GradReverse(torch.autograd.Function):
8 | @staticmethod
9 | def forward(ctx, x):
10 | return x.view_as(x)
11 |
12 | @staticmethod
13 | def backward(ctx, grad_output):
14 | return grad_output.neg()
15 |
16 |
17 | def grad_reverse(x):
18 | return GradReverse.apply(x)
19 |
20 | """
21 | class Cdann(nn.Module):
22 | def __init__(self, dropout_rate):
23 | super(Cdann, self).__init__()
24 | self.fc1 = nn.Linear(in_features=1024, out_features=512)
25 | self.fc2 = nn.Linear(in_features=512, out_features=256)
26 | self.dropout2 = nn.Dropout(dropout_rate)
27 | self.fc3 = nn.Linear(in_features=256, out_features=128)
28 | self.fc4 = nn.Linear(in_features=128, out_features=64)
29 | self.dropout4 = nn.Dropout(dropout_rate)
30 | self.fc5 = nn.Linear(in_features=64, out_features=32)
31 | self.fc6 = nn.Linear(in_features=32, out_features=16)
32 | self.dropout6 = nn.Dropout(dropout_rate)
33 | self.fc7 = nn.Linear(in_features=16, out_features=1)
34 |
35 | nn.init.kaiming_normal_(self.fc1.weight)
36 | nn.init.kaiming_normal_(self.fc2.weight)
37 | nn.init.kaiming_normal_(self.fc3.weight)
38 | nn.init.kaiming_normal_(self.fc4.weight)
39 | nn.init.kaiming_normal_(self.fc5.weight)
40 | nn.init.kaiming_normal_(self.fc6.weight)
41 | nn.init.xavier_normal_(self.fc7.weight)
42 |
43 | def forward(self, x):
44 | x = grad_reverse(x)
45 | x = F.relu(self.fc1(x))
46 | x = F.relu(self.fc2(x))
47 | x = self.dropout2(x)
48 | x = F.relu(self.fc3(x))
49 | x = F.relu(self.fc4(x))
50 | x = self.dropout4(x)
51 | x = F.relu(self.fc5(x))
52 | x = F.relu(self.fc6(x))
53 | x = self.dropout6(x)
54 | x = torch.sigmoid(self.fc7(x))
55 |
56 | return x
57 | """
58 |
59 |
60 |
61 | class Cdann(nn.Module):
62 | '''
63 | Taken from Coursera - GANNs
64 | '''
65 |
66 | def __init__(self, use_critic_dann, im_chan=1024, hidden_dim=512, use_spectral_norm=False):
67 | super(Cdann, self).__init__()
68 | self.use_critic_dann = use_critic_dann
69 | self.cdan = nn.Sequential(
70 | self.make_cdan_block(im_chan, hidden_dim, use_spectral_norm),
71 | self.make_cdan_block(hidden_dim, hidden_dim // 2, use_spectral_norm),
72 | self.make_cdan_block(hidden_dim // 2, hidden_dim // 4, use_spectral_norm),
73 | self.make_cdan_block(hidden_dim // 4, 1, use_spectral_norm, final_layer=True),
74 | )
75 | self.cdan = self.cdan.apply(self.weights_init)
76 |
77 | def make_cdan_block(self, input_channels, output_channels, use_spectral_norm, final_layer=False):
78 | '''
79 | Function to return a sequence of operations corresponding to a critic block of DCGAN;
80 | a convolution, a batchnorm (except in the final layer), and an activation (except in the final layer).
81 | Parameters:
82 | input_channels: how many channels the input feature representation has
83 | output_channels: how many channels the output feature representation should have
84 | final_layer: a boolean, true if it is the final layer and false otherwise
85 | (affects activation and batchnorm)
86 | '''
87 | if not final_layer:
88 | return nn.Sequential(
89 | self.make_linear_block(input_channels, output_channels, use_spectral_norm),
90 | nn.BatchNorm1d(output_channels),
91 | nn.LeakyReLU(0.2, inplace=True),
92 | )
93 | else:
94 | return nn.Sequential(
95 | self.make_linear_block(input_channels, output_channels, use_spectral_norm)
96 | )
97 |
98 | def make_linear_block(self, input_channels, output_channels, use_spectral_norm):
99 | if use_spectral_norm and self.use_critic_dann:
100 | return nn.Sequential(
101 | nn.utils.spectral_norm(nn.Linear(in_features=input_channels,
102 | out_features=output_channels))
103 | )
104 |
105 | else:
106 | return nn.Sequential(
107 | nn.Linear(in_features=input_channels,
108 | out_features=output_channels)
109 | )
110 |
111 | def weights_init(self, m):
112 | if isinstance(m, nn.Linear):
113 | nn.init.kaiming_normal_(m.weight)
114 | if isinstance(m, nn.BatchNorm1d):
115 | torch.nn.init.normal_(m.weight, 0.0, 0.02)
116 | torch.nn.init.constant_(m.bias, 0)
117 |
118 | def forward(self, feature):
119 | '''
120 | Function for completing a forward pass of the critic: Given an image tensor,
121 | returns a 1-dimension tensor representing fake/real.
122 | Parameters:
123 | feature: a tensor with dimension (im_chan)
124 | '''
125 | feature = grad_reverse(feature)
126 | cdan_pred = self.cdan(feature)
127 | return cdan_pred.view(len(cdan_pred), -1)
128 |
129 |
130 |
131 |
--------------------------------------------------------------------------------
/models/decoder.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 |
5 |
6 | class Dshared(nn.Module):
7 | def __init__(self):
8 | super(Dshared, self).__init__()
9 | self.deconv1 = nn.ConvTranspose2d(
10 | in_channels=1024, out_channels=512, kernel_size=4, stride=2, bias=False)
11 | self.bd1 = nn.BatchNorm2d(512)
12 | self.deconv2 = nn.ConvTranspose2d(
13 | in_channels=512, out_channels=256, kernel_size=2, stride=2, bias=False)
14 | self.bd2 = nn.BatchNorm2d(256)
15 |
16 | nn.init.kaiming_normal_(self.deconv1.weight)
17 | nn.init.kaiming_normal_(self.deconv2.weight)
18 |
19 | def forward(self, x):
20 | x = x.view(-1, 1024, 1, 1)
21 | x = F.relu(self.deconv1(x))
22 | x = self.bd1(x)
23 | x = F.relu(self.deconv2(x))
24 | x = self.bd2(x)
25 |
26 | return x
27 |
28 |
29 | class Decoder(nn.Module):
30 | def __init__(self):
31 | super(Decoder, self).__init__()
32 |
33 | self.deconv3 = nn.ConvTranspose2d(
34 | in_channels=256, out_channels=128, kernel_size=2, stride=2, bias=False)
35 | self.bd3 = nn.BatchNorm2d(128)
36 | self.deconv4 = nn.ConvTranspose2d(
37 | in_channels=128, out_channels=64, kernel_size=2, stride=2, bias=False)
38 | self.bd4 = nn.BatchNorm2d(64)
39 | self.deconv5 = nn.ConvTranspose2d(
40 | in_channels=64, out_channels=3, kernel_size=2, stride=2)
41 |
42 | nn.init.kaiming_normal_(self.deconv3.weight)
43 | nn.init.kaiming_normal_(self.deconv4.weight)
44 | nn.init.xavier_normal_(self.deconv5.weight)
45 |
46 | def forward(self, x):
47 | x = F.relu(self.deconv3(x))
48 | x = self.bd3(x)
49 | x = F.relu(self.deconv4(x))
50 | x = self.bd4(x)
51 | x = torch.tanh(self.deconv5(x))
52 |
53 | return x
--------------------------------------------------------------------------------
/models/denoiser.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from torch.autograd import Variable
5 |
6 |
7 | class Denoiser(nn.Module):
8 | def __init__(self):
9 | super(Denoiser, self).__init__()
10 |
11 | self.encoder = nn.Sequential(
12 | nn.Conv2d(3, 64, kernel_size=3, padding=1),
13 | nn.ReLU(),
14 | nn.MaxPool2d(2, 2))
15 |
16 | self.decoder = nn.Sequential(
17 | nn.Conv2d(64, 64, kernel_size=3, padding=1),
18 | nn.ReLU(),
19 | nn.Upsample(scale_factor=2),
20 | nn.Conv2d(64, 3, kernel_size=3, padding=1))
21 |
22 | def forward(self, x):
23 | return torch.tanh(self.decoder(self.encoder(x)))
--------------------------------------------------------------------------------
/models/discriminator.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | from torch.autograd import Variable
5 | from torch.utils.data import DataLoader
6 |
7 |
8 | class Discriminator(nn.Module):
9 | def __init__(self, use_critic_disc, use_spectral_norm):
10 | super(Discriminator, self).__init__()
11 | self.use_critic_disc = use_critic_disc
12 | self.conv1 = self.make_block(in_channels=3,
13 | out_channels=16,
14 | kernel_size=3,
15 | stride=2,
16 | padding=1,
17 | bias=True,
18 | use_spectral_norm=use_spectral_norm)
19 |
20 | self.conv2 = self.make_block(in_channels=16,
21 | out_channels=32,
22 | kernel_size=3,
23 | stride=2,
24 | padding=1,
25 | bias=False,
26 | use_spectral_norm=use_spectral_norm)
27 |
28 | self.conv3 = self.make_block(in_channels=32,
29 | out_channels=32,
30 | kernel_size=3,
31 | stride=2,
32 | padding=1,
33 | bias=False,
34 | use_spectral_norm=use_spectral_norm)
35 |
36 | self.conv4 = self.make_block(in_channels=32,
37 | out_channels=32,
38 | kernel_size=3,
39 | stride=2,
40 | padding=1,
41 | bias=True,
42 | use_spectral_norm=use_spectral_norm)
43 |
44 | self.fc1 = self.make_block(in_channels=4*4*32,
45 | out_channels=1,
46 | use_spectral_norm=use_spectral_norm,
47 | final_layer=True)
48 |
49 | #self.conv1 = nn.Conv2d(in_channels=3, out_channels=16,
50 | # kernel_size=3, stride=2, padding=1) # out: 32 x 32 x 32
51 | #self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3,
52 | # stride=2, padding=1, bias=False) # out: 32 x 32 x 32
53 | self.b2 = nn.BatchNorm2d(32)
54 | #self.conv3 = nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3,
55 | # stride=2, padding=1, bias=False) # out: 32 x 32 x 32
56 | self.b3 = nn.BatchNorm2d(32)
57 | #self.conv4 = nn.Conv2d(in_channels=32, out_channels=32,
58 | # kernel_size=3, stride=2, padding=1) # out: 32 x 32 x 32
59 | self.flatten = nn.Flatten()
60 | #self.fc1 = nn.Linear(in_features=4*4*32, out_features=1)
61 |
62 | nn.init.kaiming_normal_(self.conv1.weight)
63 | nn.init.kaiming_normal_(self.conv2.weight)
64 | nn.init.kaiming_normal_(self.conv3.weight)
65 | nn.init.kaiming_normal_(self.conv4.weight)
66 | nn.init.xavier_normal_(self.fc1.weight)
67 |
68 | def make_block(self, in_channels=None, out_channels=None,
69 | kernel_size=None, stride=None, padding=None,
70 | use_spectral_norm=None, bias=True, final_layer=False):
71 | if not final_layer:
72 | if use_spectral_norm and self.use_critic_disc:
73 | return nn.utils.spectral_norm(
74 | nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
75 | kernel_size=kernel_size, stride=stride,
76 | padding=padding, bias=bias)
77 | )
78 | else:
79 | return nn.Conv2d(in_channels=in_channels, out_channels=out_channels,
80 | kernel_size=kernel_size, stride=stride,
81 | padding=padding, bias=bias)
82 | else:
83 | if use_spectral_norm and self.use_critic_disc:
84 | return nn.utils.spectral_norm(nn.Linear(in_features=in_channels,
85 | out_features=out_channels))
86 | else:
87 | return nn.Linear(in_features=in_channels,
88 | out_features=out_channels)
89 |
90 |
91 |
92 | def forward(self, x):
93 | x = F.leaky_relu(self.conv1(x), 0.2)
94 | x = F.leaky_relu(self.conv2(x), 0.2)
95 | x = self.b2(x)
96 | x = F.leaky_relu(self.conv3(x), 0.2)
97 | x = self.b3(x)
98 | x = F.leaky_relu(self.conv4(x), 0.2)
99 | x = self.flatten(x)
100 | x = self.fc1(x)
101 |
102 | return x
103 |
--------------------------------------------------------------------------------
/models/encoder.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 |
5 |
6 | class Encoder(nn.Module):
7 | def __init__(self):
8 | super(Encoder, self).__init__()
9 |
10 | self.conv1 = nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3,
11 | stride=2, padding=1, bias=False) # out: 32 x 32 x 32
12 | self.b1 = nn.BatchNorm2d(32)
13 | self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3,
14 | stride=2, padding=1, bias=False) # out: 16 x 16 x 64
15 | self.b2 = nn.BatchNorm2d(64)
16 |
17 | nn.init.kaiming_normal_(self.conv1.weight)
18 | nn.init.kaiming_normal_(self.conv2.weight)
19 |
20 | def forward(self, x):
21 | x = F.relu(self.conv1(x))
22 | x = self.b1(x)
23 | x = F.relu(self.conv2(x))
24 | x = self.b2(x)
25 |
26 | return x
27 |
28 |
29 | class Eshared(nn.Module):
30 | def __init__(self, dropout_rate=0.5):
31 | super(Eshared, self).__init__()
32 | self.conv3 = nn.Conv2d(in_channels=64, out_channels=128,
33 | kernel_size=3, stride=2, padding=1, bias=False)
34 | self.b3 = nn.BatchNorm2d(128)
35 | self.conv4 = nn.Conv2d(in_channels=128, out_channels=256,
36 | kernel_size=3, stride=2, padding=1, bias=False)
37 | self.b4 = nn.BatchNorm2d(256)
38 | self.flatten = nn.Flatten()
39 | self.fc1 = nn.Linear(in_features=4*4*256,
40 | out_features=1024, bias=False)
41 | self.bfc1 = nn.BatchNorm1d(1024)
42 | self.dropout2 = nn.Dropout(dropout_rate)
43 | self.fc2 = nn.Linear(in_features=1024, out_features=1024, bias=False)
44 | self.bfc2 = nn.BatchNorm1d(1024)
45 |
46 | nn.init.kaiming_normal_(self.conv3.weight)
47 | nn.init.kaiming_normal_(self.conv4.weight)
48 | nn.init.kaiming_normal_(self.fc1.weight)
49 | nn.init.kaiming_normal_(self.fc2.weight)
50 |
51 | def forward(self, x):
52 | x = F.relu(self.conv3(x))
53 | x = self.b3(x)
54 | x = F.relu(self.conv4(x))
55 | x = self.b4(x)
56 | x = self.flatten(x)
57 | x = F.relu(self.fc1(x))
58 | x = self.bfc1(x)
59 | x = self.dropout2(x)
60 | x = F.relu(self.fc2(x))
61 | x = self.bfc2(x)
62 |
63 | return x
--------------------------------------------------------------------------------
/models/inception.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import torch.nn as nn
3 | import torch.nn.functional as F
4 | import torchvision.models as models
5 |
6 | #code as in https://www.kaggle.com/scratchpad/notebooke311656179/edit
7 | class Inception(nn.Module):
8 | """Pretrained InceptionV3 network returning feature maps"""
9 |
10 | # Index of default block of inception to return,
11 | # corresponds to output of final average pooling
12 | DEFAULT_BLOCK_INDEX = 3
13 |
14 | # Maps feature dimensionality to their output blocks indices
15 | BLOCK_INDEX_BY_DIM = {
16 | 64: 0, # First max pooling features
17 | 192: 1, # Second max pooling featurs
18 | 768: 2, # Pre-aux classifier features
19 | 2048: 3 # Final average pooling features
20 | }
21 |
22 | def __init__(self,
23 | output_blocks=[DEFAULT_BLOCK_INDEX],
24 | resize_input=True,
25 | normalize_input=True,
26 | requires_grad=False):
27 |
28 | super(Inception, self).__init__()
29 |
30 | self.resize_input = resize_input
31 | self.normalize_input = normalize_input
32 | self.output_blocks = sorted(output_blocks)
33 | self.last_needed_block = max(output_blocks)
34 |
35 | assert self.last_needed_block <= 3, \
36 | 'Last possible output block index is 3'
37 |
38 | self.blocks = nn.ModuleList()
39 |
40 |
41 | inception = models.inception_v3(pretrained=True)
42 |
43 | # Block 0: input to maxpool1
44 | block0 = [
45 | inception.Conv2d_1a_3x3,
46 | inception.Conv2d_2a_3x3,
47 | inception.Conv2d_2b_3x3,
48 | nn.MaxPool2d(kernel_size=3, stride=2)
49 | ]
50 | self.blocks.append(nn.Sequential(*block0))
51 |
52 | # Block 1: maxpool1 to maxpool2
53 | if self.last_needed_block >= 1:
54 | block1 = [
55 | inception.Conv2d_3b_1x1,
56 | inception.Conv2d_4a_3x3,
57 | nn.MaxPool2d(kernel_size=3, stride=2)
58 | ]
59 | self.blocks.append(nn.Sequential(*block1))
60 |
61 | # Block 2: maxpool2 to aux classifier
62 | if self.last_needed_block >= 2:
63 | block2 = [
64 | inception.Mixed_5b,
65 | inception.Mixed_5c,
66 | inception.Mixed_5d,
67 | inception.Mixed_6a,
68 | inception.Mixed_6b,
69 | inception.Mixed_6c,
70 | inception.Mixed_6d,
71 | inception.Mixed_6e,
72 | ]
73 | self.blocks.append(nn.Sequential(*block2))
74 |
75 | # Block 3: aux classifier to final avgpool
76 | if self.last_needed_block >= 3:
77 | block3 = [
78 | inception.Mixed_7a,
79 | inception.Mixed_7b,
80 | inception.Mixed_7c,
81 | nn.AdaptiveAvgPool2d(output_size=(1, 1))
82 | ]
83 | self.blocks.append(nn.Sequential(*block3))
84 |
85 | for param in self.parameters():
86 | param.requires_grad = requires_grad
87 |
88 | def forward(self, inp):
89 | """Get Inception feature maps
90 | Parameters
91 | ----------
92 | inp : torch.autograd.Variable
93 | Input tensor of shape Bx3xHxW. Values are expected to be in
94 | range (0, 1)
95 | Returns
96 | -------
97 | List of torch.autograd.Variable, corresponding to the selected output
98 | block, sorted ascending by index
99 | """
100 | outp = []
101 | x = inp
102 |
103 | if self.resize_input:
104 | x = F.interpolate(x,
105 | size=(299, 299),
106 | mode='bilinear',
107 | align_corners=False)
108 |
109 | if self.normalize_input:
110 | x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1)
111 |
112 | for idx, block in enumerate(self.blocks):
113 | x = block(x)
114 | if idx in self.output_blocks:
115 | outp.append(x)
116 |
117 | if idx == self.last_needed_block:
118 | break
119 |
120 | return outp
121 |
122 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | Flask==1.1.1
2 | numpy==1.19.4
3 | matplotlib==3.2.2
4 | torch==1.7.0
5 | torchvision==0.8.1
6 | Pillow==7.1.0
7 | flask_cors==3.0.10
8 | opencv-python==4.5.1.48
9 | keras==2.4.3
10 | keras-segmentation==0.3.0
11 | tensorflow==2.4.1
12 | wandb==0.10.12
13 | tqdm==4.55.1
14 | helper==2.4.2
15 | cycler==0.11.0
16 | pandas==1.1.4
17 | scikit_learn==0.23.2
18 | seaborn==0.11.0
19 | MulticoreTSNE==0.1
20 |
--------------------------------------------------------------------------------
/scripts/copyFiles.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #copying files from 0..9 directory
4 | #target directory
5 | mkdir $1
6 |
7 | for i in {0..9}
8 | do
9 | echo "Copying files from $i"
10 | cp $i/*.png $1
11 | done
12 |
13 | echo "Total files in $1:"
14 | ls $1 | wc -l
15 |
--------------------------------------------------------------------------------
/scripts/download_faces.py:
--------------------------------------------------------------------------------
1 | import os
2 | import requests
3 | from PIL import Image
4 | import matplotlib.pyplot as plt
5 | from tqdm.notebook import tqdm as tqdm_n
6 | from tqdm import tqdm
7 | from time import time
8 | import cv2
9 | from keras_segmentation.pretrained import pspnet_101_voc12
10 |
11 | # !pip install keras-segmentation
12 |
13 |
14 | def read_file(path, min_pose, min_score, curation, formats_allowed):
15 | ''' Reads a text file and returns info of each image '''
16 |
17 | with open(path, 'r') as in_file:
18 | for line in in_file:
19 | # url
20 | # bbox coordinates
21 | # pose: frontal/profile (pose>2 signifies a frontal face while pose<=2 represents left and right profile detection)
22 | # detection score: Score of a DPM detector
23 | # curation: Whether this image was a part of final curated dataset (1 or 0)
24 | _, url, x1, y1, x2, y2, pose, score, curated_dataset = line.split(
25 | ' ')
26 | if url.split('.')[-1] in formats_allowed and float(pose) >= min_pose:
27 | # Same as: not curation or (curation and int(curated_dataset))
28 | if not curation or int(curated_dataset):
29 | yield url, [x1, y1, x2, y2]
30 | return []
31 |
32 |
33 | def download_crop_image(item, offset_x, offset_top_percent, offset_bottom_percent):
34 | url, bbox = item
35 | x1, y1, x2, y2 = list(map(float, bbox))
36 |
37 | im_cropped = None
38 | try:
39 | response = requests.get(url, stream=True)
40 | response.raw.decode_content = True
41 | im = Image.open(response.raw)
42 | w = (x2 - x1)
43 | h = (y2 - y1)
44 | v_offset_x = w*offset_x/100
45 | v_offset_top = h*offset_top_percent/100
46 | v_offset_bottom = h*offset_bottom_percent/100
47 | im_cropped = im.crop(
48 | (x1-v_offset_x, y1-v_offset_top, x2+v_offset_x, y2+v_offset_bottom))
49 | except OSError:
50 | # tqdm.write('404: '+url)
51 | pass
52 |
53 | return im_cropped
54 |
55 |
56 | def get_image(person_name, file_w_path, num_images, target_path, offset_x,
57 | offset_top_percent, offset_bottom_percent, min_pose, min_score,
58 | curation, formats_allowed):
59 | ''' Downloads images from a given text file, crops them and saves them locally '''
60 |
61 | dir_path = target_path # os.path.dirname(target_path)
62 |
63 | if not os.path.exists(dir_path):
64 | os.makedirs(dir_path)
65 |
66 | i_image = 0
67 | for item in read_file(file_w_path, min_pose, min_score, curation, formats_allowed):
68 | if i_image >= num_images:
69 | # tqdm.write('Finished Downloading '+person_name)
70 | return
71 | image = download_crop_image(
72 | item, offset_x, offset_top_percent, offset_bottom_percent)
73 | if image:
74 | try:
75 | image.save(os.path.join(
76 | dir_path, f'{person_name}_{i_image+1}.jpg'))
77 | except Exception:
78 | continue
79 | i_image += 1
80 | tqdm.write(f'There is no more images available for {person_name}')
81 | tqdm.write(f'({i_image} image(s) downloaded of {num_images})\n')
82 |
83 |
84 | def download_vgg_images(data_path, num_people, num_images, target_path, offset_x_percent,
85 | offset_top_percent, offset_bottom_percent, min_pose=3, min_score=0,
86 | curation=False, formats_allowed=['jpg', 'jpeg'], from_notebook=False):
87 | '''
88 | Parses info of text files in a given folder and downloads the images
89 | in them. Each file contains info about images of the same person.
90 | '''
91 |
92 | ini = time()
93 |
94 | target_path += '/'
95 | files = os.listdir(data_path)
96 | n = num_people if num_people < len(files) else len(files)
97 | pbar_class = tqdm_n if from_notebook else tqdm
98 | pbar = pbar_class(files[:num_people], total=n)
99 | for fi in pbar:
100 | # The file's name is the name of the person
101 | fi_splited = fi.split('.')
102 | person_name = '.'.join(fi_splited[:-1]) if len(fi_splited) > 1 else fi
103 | pbar.set_description(
104 | f'Processing {person_name} ({num_images} image(s))')
105 | file_w_path = data_path + '/' + fi
106 | get_image(person_name, file_w_path, num_images,
107 | target_path, offset_x_percent, offset_top_percent,
108 | offset_bottom_percent, min_pose, min_score, curation,
109 | formats_allowed)
110 |
111 | end = time()
112 | print(f'Downloading time: {round((end-ini)/60, 2)} min\n')
113 |
114 |
115 | def clean_corrupt_files(path, formats_allowed=['jpg', 'jpeg']):
116 | ''' Filters files that have only one channel, can't be opened or have a format not allowed '''
117 |
118 | n_removed = 0
119 | for filename in os.listdir(path):
120 | filename_lower = filename # .lower()
121 | if filename_lower.split('.')[-1] in formats_allowed:
122 | try:
123 | img = Image.open(
124 | os.path.join(path, filename)) # open the image file
125 | img.verify() # verify that it is in fact an image
126 | if len(plt.imread(path + filename).shape) != 3:
127 | os.remove(os.path.join(path, filename))
128 | print(f'Removing corrupt file:', filename)
129 | n_removed += 1
130 | except Exception:
131 | os.remove(os.path.join(path, filename))
132 | print('Removing corrupt file:', filename)
133 | n_removed += 1
134 | else:
135 | os.remove(os.path.join(path, filename))
136 | print('Removing file with different format:', filename)
137 | n_removed += 1
138 | print(f'\n{n_removed} file(s) removed')
139 |
140 |
141 | def remove_background(images_path, masks_path, output_path, from_notebook=False):
142 | ''' Removes background from images (paints it white) '''
143 |
144 | if not os.path.exists(masks_path):
145 | os.makedirs(masks_path)
146 | if not os.path.exists(output_path):
147 | os.makedirs(output_path)
148 |
149 | # load the pretrained model trained on Pascal VOC 2012 dataset
150 | model = pspnet_101_voc12()
151 |
152 | pbar_class = tqdm_n if from_notebook else tqdm
153 | pbar = pbar_class(os.listdir(images_path))
154 | start = time()
155 | for filename in pbar:
156 | pbar.set_description(f'Processing {filename}')
157 | mask_file = filename[:-4] + "_mask.png"
158 | output_file = filename[:-4] + "_wo_bg.jpg"
159 |
160 | model.predict_segmentation(
161 | inp=images_path + filename,
162 | out_fname=masks_path + mask_file
163 | )
164 |
165 | img_mask = cv2.imread(masks_path + mask_file)
166 | img1 = cv2.imread(images_path + filename) # READ BGR
167 |
168 | seg_gray = cv2.cvtColor(img_mask, cv2.COLOR_BGR2GRAY)
169 | _, bg_mask = cv2.threshold(
170 | seg_gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
171 |
172 | # convert mask to 3-channels
173 | bg_mask = cv2.cvtColor(bg_mask, cv2.COLOR_GRAY2BGR)
174 |
175 | # cv2.bitwise_or to extract the region
176 | bg = cv2.bitwise_or(img1, bg_mask)
177 |
178 | # save
179 | cv2.imwrite(output_path + output_file, bg)
180 | end = time()
181 |
182 | print('Background removed')
183 | print(f'Processing time: {round((end-start)/60, 2)} min\n')
184 |
185 |
186 | if __name__ == "__main__":
187 | data_path = r'C:\Users\Daniel Ibáñez\Documents\Proyectos\Avatar Project\vgg_face_dataset\files'
188 | target_path = r'C:\Users\Daniel Ibáñez\Documents\Proyectos\Avatar Project\prueba/'
189 |
190 | download_vgg_images(data_path, num_people=50, num_images=3, target_path=target_path,
191 | offset_x_percent=15, offset_top_percent=55,
192 | offset_bottom_percent=12, min_pose=3, min_score=0,
193 | curation=False, formats_allowed=['jpg', 'jpeg'], from_notebook=False)
194 | clean_corrupt_files(target_path, formats_allowed=['jpg', 'jpeg'])
195 |
196 | images_path = r'C:\Users\Daniel Ibáñez\Documents\Proyectos\Avatar Project\tmp\face_images/'
197 | masks_path = r'C:\Users\Daniel Ibáñez\Documents\Proyectos\Avatar Project\tmp\masks/'
198 | output_path = r'C:\Users\Daniel Ibáñez\Documents\Proyectos\Avatar Project\face_images_wo_bg/'
199 |
200 | remove_background(images_path, masks_path,
201 | output_path, from_notebook=False)
202 |
--------------------------------------------------------------------------------
/scripts/keepFiles.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | #keep filename which are in $1b generated by data preprocessing
4 | #$2 source files
5 | #$3 target directory
6 |
7 | mkdir $3
8 | cat $1 | xargs -I % cp $2/% $3
9 | echo "Total kept files:"
10 | ls $3 | wc -l
11 |
--------------------------------------------------------------------------------
/scripts/plot_utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 |
4 | def show(images, n_cols=None):
5 | n_cols = n_cols or len(images)
6 | n_rows = (len(images) - 1) // n_cols + 1
7 | if images.shape[-1] == 1:
8 | images = np.squeeze(images, axis=-1)
9 | plt.figure(figsize=(n_cols, n_rows))
10 | for index, image in enumerate(images):
11 | plt.subplot(n_rows, n_cols, index + 1)
12 | plt.imshow(image, cmap="binary")
13 | plt.axis("off")
14 |
--------------------------------------------------------------------------------
/scripts/preprocessing_cartoons_data.py:
--------------------------------------------------------------------------------
1 | import os
2 | import pandas as pd
3 | import matplotlib.pyplot as plt
4 | import matplotlib.image as mpimg
5 | #import seaborn as sns
6 | from tqdm import tqdm
7 |
8 | # Create image info dataset
9 | def read_cartoon_dataset(path_cartoons, list_sub_folders):
10 |
11 | df = pd.DataFrame()
12 | for index in tqdm(list_sub_folders):
13 | path_folder = os.path.join(path_cartoons,index)
14 | list_files = [file for file in os.listdir(path_folder) if '.csv' in file ]
15 |
16 | for file in list_files:
17 | path_csv = os.path.join(path_folder, file)
18 | df_cartoon = pd.read_csv(path_csv,header=None)
19 | df_cartoon.columns = ["attribute_name", "index_variant","total_num_variants"]
20 | df_cartoon["filename"] = index + "/" + file
21 | df_cartoon = df_cartoon.pivot(index="filename",columns="attribute_name", values="index_variant")
22 |
23 | df = pd.concat([df, df_cartoon])
24 |
25 | return df
26 |
27 | def make_df_cartoon_dataset(path_cartoons, list_sub_folders):
28 | df_cartoon = read_cartoon_dataset(path_cartoons, list_sub_folders)
29 | df_cartoon = df_cartoon.reset_index()
30 | df_cartoon['subfolder'] = df_cartoon["filename"].apply(lambda x: x.split('/')[0])
31 | df_cartoon['filename'] = df_cartoon["filename"].apply(lambda x: x.split('/')[-1])
32 | df_cartoon.to_csv(path_cartoons + "/cartoon100k.csv.gz", header=True, compression="gzip", index=False)
33 |
34 | return df_cartoon
35 |
36 |
37 | # Show samples per feature
38 | def show_samples_feature(df_cartoon, col, sample_len):
39 | unique_col = df_cartoon[col].unique()
40 |
41 |
42 | print("unique values of {}: {}".format(col, len(unique_col)))
43 |
44 | for value in unique_col:
45 | idx = (df_cartoon[col] == value)
46 | file_names = df_cartoon.loc[idx,["filename","subfolder"]]
47 |
48 | print("total filenames with {} equal to {}: {}".format(col, value, len(file_names)))
49 |
50 | for file in file_names[:sample_len].values:
51 | print(file)
52 | print(os.path.join(path_cartoons,str(file[1]), file[0]))
53 | img=mpimg.imread(os.path.join(path_cartoons,str(file[1]), (file[0].split('.'))[0]+".png"))
54 | imgplot = plt.imshow(img)
55 | plt.show()
56 |
57 |
58 | def show_samples_idx(df_cartoon, idx, sample_len):
59 | file_names = df_cartoon.loc[idx,["filename","subfolder"]]
60 |
61 | print("unique values of index: {}".format(len(file_names)))
62 |
63 | for file in file_names[:sample_len].values:
64 | print(file)
65 | print(os.path.join(path_cartoons,str(file[1]), file[0]))
66 | img=mpimg.imread(os.path.join(path_cartoons,str(file[1]), (file[0].split('.'))[0]+".png"))
67 | imgplot = plt.imshow(img)
68 | plt.show()
69 |
70 |
71 | if __name__ == "__main__":
72 | path_cartoons = "/data/shuaman/xgan/cartoonset100k"
73 | list_sub_folders = ["0","1","2","3",
74 | "4","5","6","7","8","9"]
75 |
76 | df_cartoon = make_df_cartoon_dataset(path_cartoons, list_sub_folders)
77 | #df_cartoon = pd.read_csv(path_cartoons + "/cartoon100k.csv.gz")
78 |
79 | #analize cartoons with show_samples_feature and show_samples_idx to get the idx to drop
80 | facial_hair_active = [0,2,3,4,5,6,7,8,9,10,11,12,13]
81 | facial_no_hair = [14]
82 | facial_hair_delete = [1,12]
83 |
84 | hair_type_woman = [3, 4, 13, 25, 27, 28, 29, 33, 34, 35, 41, 48, 56, 58, 59, 60, 63, 64, 67, 69, 70, 75, 78,
85 | 79, 80, 82, 86, 87, 90, 95, 96, 102,6,7,9,36,40,42,47,55,57,65, 68, 71, 81, 84, 85, 93, 94, 97, 100,
86 | 101, 103, 26]
87 | hair_type_man = [1, 2, 8, 11, 12, 17, 22, 23, 31, 32, 39, 43, 44, 45, 46, 49, 50, 51, 53, 54, 61, 62, 66, 72,
88 | 73, 74, 76, 77, 83, 89, 92, 99, 107,10,14,18,19,20,21,30,38,52, 105]
89 | hair_type_mix = [0, 5, 15, 16, 24, 37, 88, 91, 98, 104, 106]
90 | hair_type_delete = [108, 109, 110]
91 |
92 | glass_type_delete = [10]
93 | glass_type_keep = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11]
94 |
95 | face_color_dark = [0, 1]
96 | face_color_light = [6, 7, 8, 9, 10]
97 | face_color_mix = [2, 3, 4, 5]
98 |
99 | glass_color_delete = [2, 5]
100 | glass_color_keep = [0, 1, 3, 4, 6]
101 |
102 | hair_color_keep = [0, 1, 2, 3, 5, 6, 7, 9]
103 | hair_color_delete = [8, 4]
104 | hair_color_light = [0, 1, 2, 4]
105 | hair_color_mix = [3,5,6,7,8,9]
106 |
107 |
108 |
109 | # Drop images which have removed attributes
110 | idx = (df_cartoon.glasses.isin(glass_type_delete)) | (df_cartoon.hair.isin(hair_type_delete)) | (df_cartoon.glasses_color.isin(glass_color_delete)) | (df_cartoon.hair_color.isin(hair_color_delete)) | (df_cartoon.facial_hair.isin(facial_hair_delete))
111 | df_cartoon_filter1 = df_cartoon.loc[-idx,:].reset_index(drop=True)
112 |
113 | # Analize images with realistic shapes
114 | idx_women = ((df_cartoon_filter1.hair.isin(hair_type_woman)) & (df_cartoon_filter1.facial_hair.isin(facial_no_hair)))
115 | df_cartoon_filter2 = df_cartoon_filter1.loc[(-df_cartoon_filter1.hair.isin(hair_type_woman))|(idx_women) ,:].reset_index(drop=True)
116 |
117 | # Analize images with realistic color of skin and hair
118 | idx_dark_color = ((df_cartoon_filter2.face_color.isin(face_color_dark)) & (-df_cartoon_filter2.hair_color.isin(hair_color_light)))
119 | df_cartoon_filter_final = df_cartoon_filter2.loc[(-df_cartoon_filter2.face_color.isin(face_color_dark)) | (idx_dark_color),:].reset_index(drop=True)
120 |
121 | #save cartoons ids to keep
122 | df_cartoon_filter_final.to_csv(path_cartoons + "/cartoon100k_limited.csv.gz", header=True, compression="gzip", index=False)
123 |
124 | #save the png files and then execute th shell scripts
125 | writePath = "filelist.txt"
126 | df_cartoon_filter_final["filename_png"] = df_cartoon_filter_final["filename"].apply(lambda x: x.split('.')[0])+ '.png'
127 | df_cartoon_filter_final["filename_png"].to_csv(writePath, header=None, index=None, sep=' ', mode='a')
--------------------------------------------------------------------------------
/sweeps/sweep-bs-1.yaml:
--------------------------------------------------------------------------------
1 | command:
2 | - ${env}
3 | - python3
4 | - ${program}
5 | - ${args}
6 | early_terminate:
7 | eta: 2
8 | min_iter: 10
9 | type: hyperband
10 | method: bayes
11 | metric:
12 | goal: minimize
13 | name: loss_total
14 | parameters:
15 | wDann_loss:
16 | distribution: uniform
17 | max: 1
18 | min: 0.5
19 | wGan_loss:
20 | distribution: uniform
21 | max: 1
22 | min: 0.5
23 | wSem_loss:
24 | distribution: uniform
25 | max: 1
26 | min: 0.5
27 | program: train.py
28 | project: avatar-image-generator
--------------------------------------------------------------------------------
/sweeps/sweep-rs-1.yaml:
--------------------------------------------------------------------------------
1 | project: avatar-image-generator
2 | program: train.py
3 | method: random
4 | metric:
5 | name: loss_total
6 | goal: minimize
7 | parameters:
8 | wRec_loss:
9 | distribution: uniform
10 | min: 0.75
11 | max: 1.0
12 | wDann_loss:
13 | distribution: uniform
14 | min: 0.25
15 | max: 1.0
16 | wSem_loss:
17 | distribution: uniform
18 | min: 0.25
19 | max: 1.0
20 | wGan_loss:
21 | distribution: uniform
22 | min: 0.25
23 | max: 1.0
24 | early_terminate:
25 | type: hyperband
26 | min_iter: 10
27 | eta: 2
28 | command:
29 | - ${env}
30 | - python3
31 | - ${program}
32 | - ${args}
--------------------------------------------------------------------------------
/train.py:
--------------------------------------------------------------------------------
1 | import argparse
2 | from utils import parse_arguments, set_seed, configure_model
3 | from models import Avatar_Generator_Model
4 | import os
5 | import sys
6 | import wandb
7 |
8 | CONFIG_FILENAME = "config.json"
9 | PROJECT_WANDB = "avatar_image_generator"
10 | ENTITY = "iamigos"
11 |
12 |
13 | def is_there_arg(args, master_arg):
14 | if(master_arg in args):
15 | return True
16 | else:
17 | return False
18 |
19 |
20 | def train(config_file, use_wandb, run_name, run_notes):
21 | set_seed(32)
22 | config = configure_model(config_file, use_wandb)
23 |
24 | if use_wandb:
25 | wandb.init(project=PROJECT_WANDB, entity=ENTITY, config=config, name=run_name, notes=run_notes)
26 | config = wandb.config
27 | wandb.watch_called = False
28 |
29 |
30 | xgan = Avatar_Generator_Model(config, use_wandb)
31 | xgan.train()
32 |
33 |
34 | if __name__ == '__main__':
35 | use_sweep = is_there_arg(sys.argv, '--use_sweep')
36 |
37 | if not use_sweep:
38 | args = parse_arguments()
39 | use_wandb = args.wandb
40 | run_name = args.run_name
41 | run_notes = args.run_notes
42 | else:
43 | use_wandb = True
44 | run_name = None
45 | run_notes = None
46 |
47 | train(CONFIG_FILENAME, use_wandb=use_wandb, run_name=run_name, run_notes=run_notes)
48 |
--------------------------------------------------------------------------------
/utils/__init__.py:
--------------------------------------------------------------------------------
1 | import wandb
2 | import math
3 | import numpy as np
4 | import matplotlib.pyplot as plt
5 | import os
6 | import sys
7 | import argparse
8 |
9 | import torch
10 | import torch.nn as nn
11 | import torch.nn.functional as F
12 |
13 | import torchvision.transforms as transforms
14 | import torchvision
15 | from torch.autograd import Variable
16 | from torch.utils.data import DataLoader
17 |
18 | from tqdm import tqdm
19 | from PIL import Image
20 |
21 | import logging
22 | import random
23 |
24 | from keras_segmentation.pretrained import pspnet_50_ADE_20K, pspnet_101_cityscapes, pspnet_101_voc12
25 | import cv2
26 | import helper
27 | import json
28 |
29 |
30 | IMAGE_SIZE = 64
31 | MEAN = 0.5
32 | SD = 0.5
33 | STATS = (MEAN, MEAN, MEAN), (SD, SD, SD)
34 |
35 | def set_seed(seed):
36 | """Set seed"""
37 | random.seed(seed)
38 | np.random.seed(seed)
39 | torch.manual_seed(seed)
40 | if torch.cuda.is_available():
41 | torch.cuda.manual_seed(seed)
42 | torch.cuda.manual_seed_all(seed)
43 | torch.backends.cudnn.deterministic = True
44 | torch.backends.cudnn.benchmark = False
45 | os.environ["PYTHONHASHSEED"] = str(seed)
46 |
47 |
48 | def parse_arguments():
49 | ap = argparse.ArgumentParser()
50 | ap.add_argument('-w', '--wandb', default=False, action='store_true',
51 | help="use weights and biases")
52 | ap.add_argument('-nw ', '--no-wandb', dest='wandb', action='store_false',
53 | help="not use weights and biases")
54 | ap.add_argument('-n', '--run_name', required=False, type=str, default=None,
55 | help="name of the execution to save in wandb")
56 | ap.add_argument('-nt', '--run_notes', required=False, type=str, default=None,
57 | help="notes of the execution to save in wandb")
58 |
59 | args = ap.parse_args()
60 |
61 | return args
62 |
63 |
64 | def parse_configuration(config_file):
65 | """Loads config file if a string was passed
66 | and returns the input if a dictionary was passed.
67 | """
68 | if isinstance(config_file, str):
69 | with open(config_file, 'r') as json_file:
70 | return json.load(json_file)
71 | else:
72 | return config_file
73 |
74 |
75 | def init_logger(log_file=None, log_dir=None):
76 |
77 | fmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s: %(message)s'
78 |
79 | if log_dir is None:
80 | log_dir = '~/temp/log/'
81 |
82 | if not os.path.exists(log_dir):
83 | print("Creating dir")
84 | os.makedirs(log_dir)
85 |
86 | log_file = os.path.join(log_dir, log_file)
87 |
88 | print('log file path:' + log_file)
89 |
90 | logging.basicConfig(level=logging.INFO,
91 | filename=log_file,
92 | format=fmt)
93 |
94 | return logging
95 |
96 |
97 | def configure_model(config_file, use_wandb):
98 |
99 | config_file = parse_configuration(config_file)
100 |
101 | config = dict(
102 | model_path=config_file["server_config"]["model_path"],
103 | download_directory=config_file["server_config"]["download_directory"],
104 |
105 | root_path=config_file["train_dataset_params"]["root_path"],
106 | dataset_path_faces=config_file["train_dataset_params"]["dataset_path_faces"],
107 | dataset_path_cartoons=config_file["train_dataset_params"]["dataset_path_cartoons"],
108 | dataset_path_test_faces=config_file["train_dataset_params"]["dataset_path_test_faces"],
109 | dataset_path_segmented_faces=config_file["train_dataset_params"]["dataset_path_segmented_faces"],
110 | dataset_path_output_faces=config_file["train_dataset_params"]["dataset_path_output_faces"],
111 | batch_size=config_file["train_dataset_params"]["loader_params"]["batch_size"],
112 |
113 | save_weights=config_file["train_dataset_params"]["save_weights"],
114 | num_backups=config_file["train_dataset_params"]["num_backups"],
115 | save_path=config_file["train_dataset_params"]["save_path"],
116 |
117 | dropout_rate_eshared=config_file["model_hparams"]["dropout_rate_eshared"],
118 | use_critic_dann=config_file["model_hparams"]["use_critic_dann"],
119 | use_critic_disc=config_file["model_hparams"]["use_critic_disc"],
120 | use_spectral_norm=config_file["model_hparams"]["use_spectral_norm"],
121 | use_denoiser=config_file["model_hparams"]["use_denoiser"],
122 | use_disc_cartoon2face=config_file["model_hparams"]["use_disc_cartoon2face"],
123 | num_epochs=config_file["model_hparams"]["num_epochs"],
124 | learning_rate_opTotal=config_file["model_hparams"]["learning_rate_opTotal"],
125 | learning_rate_opDisc=config_file["model_hparams"]["learning_rate_opDisc"],
126 | learning_rate_denoiser=config_file["model_hparams"]["learning_rate_denoiser"],
127 | learning_rate_opCdann=config_file["model_hparams"]["learning_rate_opCdann"],
128 | wRec_loss=config_file["model_hparams"]["wRec_loss"],
129 | wDann_loss=config_file["model_hparams"]["wDann_loss"],
130 | wSem_loss=config_file["model_hparams"]["wSem_loss"],
131 | wGan_loss=config_file["model_hparams"]["wGan_loss"],
132 | wTeach_loss=config_file["model_hparams"]["wTeach_loss"],
133 | use_gpu=config_file["model_hparams"]["use_gpu"]
134 | )
135 |
136 | if not use_wandb:
137 | config = type("configuration", (object,), config)
138 |
139 | return config
140 |
141 |
142 | def weights_init(m):
143 | classname = m.__class__.__name__
144 | if classname.find('Conv') != -1:
145 | nn.init.kaiming_uniform_(m.weight.data)
146 |
147 | elif classname.find('BatchNorm') != -1:
148 | nn.init.normal_(m.weight.data, 1.0, 0.02)
149 | nn.init.constant_(m.bias.data, 0)
150 |
151 |
152 | def save_weights(model, path_sub, use_wandb=True):
153 | e1, e2, d1, d2, e_shared, d_shared, c_dann, discriminator1, denoiser, discriminator2 = model
154 |
155 | torch.save(e1.state_dict(), os.path.join(path_sub, 'e1.pth'))
156 | torch.save(e2.state_dict(), os.path.join(path_sub, 'e2.pth'))
157 | torch.save(e_shared.state_dict(), os.path.join(path_sub, 'e_shared.pth'))
158 | torch.save(d_shared.state_dict(), os.path.join(path_sub, 'd_shared.pth'))
159 | torch.save(d1.state_dict(), os.path.join(path_sub, 'd1.pth'))
160 | torch.save(d2.state_dict(), os.path.join(path_sub, 'd2.pth'))
161 | torch.save(c_dann.state_dict(), os.path.join(path_sub, 'c_dann.pth'))
162 | torch.save(discriminator1.state_dict(), os.path.join(path_sub, 'disc1.pth'))
163 | torch.save(denoiser.state_dict(), os.path.join(path_sub, 'denoiser.pth'))
164 | torch.save(discriminator2.state_dict(), os.path.join(path_sub, 'disc2.pth'))
165 |
166 | if use_wandb:
167 | wandb.save(os.path.join(path_sub, '*.pth'),
168 | base_path='/'.join(path_sub.split('/')[:-2]))
169 |
170 |
171 | def get_transforms_config_face():
172 | list_transforms = [
173 | transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
174 | transforms.ToTensor(),
175 | transforms.Normalize(*STATS)
176 | ]
177 |
178 | return list_transforms
179 |
180 |
181 | def get_transforms_config_cartoon():
182 | list_transforms = [
183 | transforms.CenterCrop(400),
184 | transforms.Resize((IMAGE_SIZE, IMAGE_SIZE)),
185 | transforms.ToTensor(),
186 | transforms.Normalize(*STATS)
187 | ]
188 |
189 | return list_transforms
190 |
191 | def get_datasets(root_path, dataset_path_faces, dataset_path_cartoons, batch_size):
192 |
193 | path_faces = root_path + dataset_path_faces
194 | path_cartoons = root_path + dataset_path_cartoons
195 |
196 | transform_list_faces = get_transforms_config_face()
197 | transform_list_cartoons = get_transforms_config_cartoon()
198 |
199 | transform_faces = transforms.Compose(transform_list_faces)
200 |
201 | transform_cartoons = transforms.Compose(transform_list_cartoons)
202 |
203 | dataset_faces = torchvision.datasets.ImageFolder(
204 | path_faces, transform=transform_faces)
205 | dataset_cartoons = torchvision.datasets.ImageFolder(
206 | path_cartoons, transform=transform_cartoons)
207 |
208 | train_dataset_faces, test_dataset_faces = torch.utils.data.random_split(dataset_faces,
209 | (int(len(dataset_faces)*0.9), len(dataset_faces) - int(len(dataset_faces)*0.9)))
210 |
211 | train_loader_faces = torch.utils.data.DataLoader(
212 | train_dataset_faces,
213 | batch_size=batch_size,
214 | shuffle=True,
215 | num_workers=4)
216 |
217 | test_loader_faces = torch.utils.data.DataLoader(
218 | test_dataset_faces,
219 | batch_size=batch_size,
220 | shuffle=True,
221 | num_workers=4)
222 |
223 | train_dataset_cartoons, test_dataset_cartoons = torch.utils.data.random_split(dataset_cartoons,
224 | (int(len(dataset_cartoons)*0.9), len(dataset_cartoons) - int(len(dataset_cartoons)*0.9)))
225 |
226 | train_loader_cartoons = torch.utils.data.DataLoader(
227 | train_dataset_cartoons,
228 | batch_size=batch_size,
229 | shuffle=True,
230 | num_workers=4)
231 |
232 | test_loader_cartoons = torch.utils.data.DataLoader(
233 | test_dataset_cartoons,
234 | batch_size=batch_size,
235 | shuffle=True,
236 | num_workers=4)
237 |
238 | return (train_loader_faces, test_loader_faces, train_loader_cartoons, test_loader_cartoons)
239 |
240 |
241 | def remove_background_image(model, path_filename, output_path):
242 |
243 | output_file = path_filename.split('/')[-1].split('.')[0] + "_wo_bg.jpg"
244 |
245 | out = model.predict_segmentation(
246 | inp=path_filename,
247 | out_fname=output_path + output_file
248 | )
249 |
250 | img_mask = cv2.imread(output_path + output_file)
251 | img1 = cv2.imread(path_filename) # READ BGR
252 |
253 | seg_gray = cv2.cvtColor(img_mask, cv2.COLOR_BGR2GRAY)
254 | _, bg_mask = cv2.threshold(
255 | seg_gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)
256 |
257 | bg_mask = cv2.cvtColor(bg_mask, cv2.COLOR_GRAY2BGR)
258 |
259 | bg = cv2.bitwise_or(img1, bg_mask)
260 |
261 | cv2.imwrite(output_path + output_file, bg)
262 |
263 |
264 | def remove_background(model, path_test_faces, path_segmented_faces):
265 |
266 | path = path_test_faces + 'data/'
267 | output_path = path_segmented_faces + 'data/'
268 |
269 | dir_path = os.path.dirname(output_path)
270 | if not os.path.exists(dir_path):
271 | os.makedirs(dir_path)
272 |
273 | for filename in tqdm(os.listdir(path)):
274 |
275 | remove_background_image(model, path + filename, output_path)
276 |
277 |
278 | def get_test_images(model, batch_size, path_test_faces, path_segmented_faces):
279 |
280 | remove_background(model, path_test_faces, path_segmented_faces)
281 |
282 | path_test_images = path_segmented_faces
283 |
284 | transform_list_faces = get_transforms_config_face()
285 | transform_list_faces += [transforms.CenterCrop(IMAGE_SIZE)]
286 |
287 | transform = transforms.Compose(transform_list_faces)
288 |
289 | dataset_test_images = torchvision.datasets.ImageFolder(
290 | path_test_images, transform=transform)
291 |
292 | test_loader_images = torch.utils.data.DataLoader(
293 | dataset_test_images,
294 | batch_size=batch_size,
295 | num_workers=4)
296 |
297 | dataiter = iter(test_loader_images)
298 | test_images = dataiter.next()
299 |
300 | return test_images
301 |
302 |
303 | def denorm(img_tensors):
304 |
305 | return img_tensors * STATS[1][0] + STATS[0][0]
306 |
307 |
308 | def test_image(model, device, images_faces, use_denoiser):
309 |
310 | e1, e2, d1, d2, e_shared, d_shared, c_dann, discriminator1, denoiser, discriminator2 = model
311 |
312 | e1.eval()
313 | e2.eval()
314 | e_shared.eval()
315 | d_shared.eval()
316 | d1.eval()
317 | d2.eval()
318 | c_dann.eval()
319 | discriminator1.eval()
320 | discriminator2.eval()
321 | denoiser.eval()
322 |
323 | with torch.no_grad():
324 | output = e1(images_faces[0].to(device))
325 | output = e_shared(output)
326 | output = d_shared(output)
327 | output = d2(output)
328 | if use_denoiser:
329 | output = denoiser(output)
330 |
331 | output = denorm(output)
332 |
333 | return output.cpu()
334 |
335 |
336 |
337 |
338 |
339 | def init_optimizers(model, learning_rate_opDisc, learning_rate_opTotal, learning_rate_denoiser, learning_rate_opCdann):
340 |
341 | e1, e2, d1, d2, e_shared, d_shared, c_dann, discriminator1, denoiser, discriminator2 = model
342 |
343 | optimizerDisc1 = torch.optim.Adam(
344 | discriminator1.parameters(), lr=learning_rate_opDisc, betas=(0.5, 0.999))
345 |
346 | optimizerDisc2 = torch.optim.Adam(
347 | discriminator2.parameters(), lr=learning_rate_opDisc, betas=(0.5, 0.999))
348 |
349 | #listParameters = list(e1.parameters()) + list(e2.parameters()) + list(e_shared.parameters()) + list(d_shared.parameters()) + list(d1.parameters()) + list(d2.parameters()) + list(c_dann.parameters())
350 | listParameters = list(e1.parameters()) + list(e2.parameters()) + list(e_shared.parameters()) + \
351 | list(d_shared.parameters()) + list(d1.parameters()) + list(d2.parameters())
352 | optimizerTotal = torch.optim.Adam(
353 | listParameters, lr=learning_rate_opTotal, betas=(0.5, 0.999))
354 |
355 | optimizerDenoiser = torch.optim.Adam(
356 | denoiser.parameters(), lr=learning_rate_denoiser)
357 |
358 | optimizerCdann = torch.optim.Adam(
359 | c_dann.parameters(), lr=learning_rate_opCdann, betas=(0.5, 0.999))
360 |
361 | return (optimizerDenoiser, optimizerDisc1, optimizerTotal, optimizerCdann, optimizerDisc2)
362 |
363 |
364 |
--------------------------------------------------------------------------------