├── .gitignore
├── LICENSE
├── README.md
├── cover.jpeg
├── notebooks
├── 02_deeplearning
│ ├── 01_mlp
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── mlp.ipynb
│ │ ├── models
│ │ │ └── .gitignore
│ │ └── output
│ │ │ └── .gitignore
│ └── 02_cnn
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── cnn.ipynb
│ │ ├── convolutions.ipynb
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ └── output
│ │ └── .gitignore
├── 03_vae
│ ├── 01_autoencoder
│ │ ├── autoencoder.ipynb
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── models
│ │ │ └── .gitignore
│ │ └── output
│ │ │ └── .gitignore
│ ├── 02_vae_fashion
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── models
│ │ │ └── .gitignore
│ │ ├── output
│ │ │ └── .gitignore
│ │ └── vae_fashion.ipynb
│ └── 03_vae_faces
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ ├── output
│ │ └── .gitignore
│ │ ├── vae_faces.ipynb
│ │ └── vae_utils.py
├── 04_gan
│ ├── 01_dcgan
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── dcgan.ipynb
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── models
│ │ │ └── .gitignore
│ │ └── output
│ │ │ └── .gitignore
│ ├── 02_wgan_gp
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── models
│ │ │ └── .gitignore
│ │ ├── output
│ │ │ └── .gitignore
│ │ └── wgan_gp.ipynb
│ └── 03_cgan
│ │ ├── cgan.ipynb
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ └── output
│ │ └── .gitignore
├── 05_autoregressive
│ ├── 01_lstm
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── lstm.ipynb
│ │ ├── models
│ │ │ └── .gitignore
│ │ └── output
│ │ │ └── .gitignore
│ ├── 02_pixelcnn
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── models
│ │ │ └── .gitignore
│ │ ├── output
│ │ │ └── .gitignore
│ │ └── pixelcnn.ipynb
│ └── 03_pixelcnn_md
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ ├── output
│ │ └── .gitignore
│ │ └── pixelcnn_md.ipynb
├── 06_normflow
│ └── 01_realnvp
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ ├── output
│ │ └── .gitignore
│ │ └── realnvp.ipynb
├── 07_ebm
│ └── 01_ebm
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── ebm.ipynb
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ └── output
│ │ └── .gitignore
├── 08_diffusion
│ └── 01_ddm
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── ddm.ipynb
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ ├── output
│ │ └── .gitignore
│ │ └── sinusoidal_embedding.ipynb
├── 09_transformer
│ └── gpt
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── gpt.ipynb
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ └── output
│ │ └── .gitignore
├── 11_music
│ ├── 01_transformer
│ │ ├── checkpoint
│ │ │ └── .gitignore
│ │ ├── logs
│ │ │ └── .gitignore
│ │ ├── models
│ │ │ └── .gitignore
│ │ ├── output
│ │ │ └── .gitignore
│ │ ├── parsed_data
│ │ │ └── .gitignore
│ │ ├── transformer.ipynb
│ │ └── transformer_utils.py
│ └── 02_musegan
│ │ ├── checkpoint
│ │ └── .gitignore
│ │ ├── logs
│ │ └── .gitignore
│ │ ├── models
│ │ └── .gitignore
│ │ ├── musegan.ipynb
│ │ ├── musegan_utils.py
│ │ └── output
│ │ └── .gitignore
└── utils.py
└── scripts
├── download.sh
├── downloaders
├── download_bach_cello_data.sh
├── download_bach_chorale_data.sh
└── download_kaggle_data.sh
├── format.sh
└── tensorboard.sh
/.gitignore:
--------------------------------------------------------------------------------
1 | docs/history.twbx
2 |
3 | .DS_Store
4 |
5 | # Byte-compiled / optimized / DLL files
6 | __pycache__/
7 | *.py[cod]
8 | *$py.class
9 |
10 | # C extensions
11 | *.so
12 |
13 | # Distribution / packaging
14 | .Python
15 | build/
16 | develop-eggs/
17 | dist/
18 | downloads/
19 | eggs/
20 | .eggs/
21 | lib/
22 | lib64/
23 | parts/
24 | sdist/
25 | var/
26 | wheels/
27 | *.egg-info/
28 | .installed.cfg
29 | *.egg
30 | MANIFEST
31 |
32 | # PyInstaller
33 | # Usually these files are written by a python script from a template
34 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
35 | *.manifest
36 | *.spec
37 |
38 | # Installer logs
39 | pip-log.txt
40 | pip-delete-this-directory.txt
41 |
42 | # Unit test / coverage reports
43 | htmlcov/
44 | .tox/
45 | .coverage
46 | .coverage.*
47 | .cache
48 | nosetests.xml
49 | coverage.xml
50 | *.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 |
63 | # Flask stuff:
64 | instance/
65 | .webassets-cache
66 |
67 | # Scrapy stuff:
68 | .scrapy
69 |
70 | # Sphinx documentation
71 | docs/_build/
72 |
73 | # PyBuilder
74 | target/
75 |
76 | # Jupyter Notebook
77 | .ipynb_checkpoints
78 |
79 | # pyenv
80 | .python-version
81 |
82 | # celery beat schedule file
83 | celerybeat-schedule
84 |
85 | # SageMath parsed files
86 | *.sage.py
87 |
88 | # Environments
89 | .env
90 | .venv
91 | env/
92 | venv/
93 | ENV/
94 | env.bak/
95 | venv.bak/
96 |
97 | # Spyder project settings
98 | .spyderproject
99 | .spyproject
100 |
101 | # Rope project settings
102 | .ropeproject
103 |
104 | # mkdocs documentation
105 | /site
106 |
107 | # mypy
108 | .mypy_cache/
109 |
110 |
--------------------------------------------------------------------------------
/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 | # 🦜 <만들면서 배우는 생성 AI 2판>의 코드 저장소
2 |
3 | 이 저장소는 한빛미디어에서 출간한 "만들면서 배우는 생성 AI 2판"의 코드를 담고 있습니다. ([교보문고](https://product.kyobobook.co.kr/detail/S000208953342), [Yes24](https://www.yes24.com/Product/Goods/122338458), [알라딘](https://www.aladin.co.kr/shop/wproduct.aspx?ItemId=324278784), [한빛미디어](https://www.hanbit.co.kr/media/books/book_view.html?p_code=B6550508630))
4 |
5 | 책을 구매하시면 꼭 [에러타 페이지](https://tensorflow.blog/gen-dl-2/)를 확인해 주세요. 이 저장소의 노트북은 텐서플로 2.12.0, 2.14.0에서 테스트되었습니다.
6 |
7 | 1판의 깃허브는 [여기](https://github.com/rickiepark/GDL_code/)입니다.
8 |
9 |
10 |
11 | ## 목차
12 | PART 1: 생성 딥러닝 소개
13 | * 1장: 셍성 모델링
14 | * 2장: 딥러닝
15 | * [다층 퍼셉트론](notebooks/02_deeplearning/01_mlp/mlp.ipynb)
16 | * [합성곱](notebooks/02_deeplearning/02_cnn/convolutions.ipynb)
17 | * [합성곱 신경망](notebooks/02_deeplearning/02_cnn/cnn.ipynb)
18 |
19 | PART 2: 6가지 생성 모델링 방식
20 | * 3장: 변이형 오토인코더
21 | * [오토인코더](notebooks/03_vae/01_autoencoder/autoencoder.ipynb)
22 | * [변이형 오토인코더 - 패션 MNIST](notebooks/03_vae/02_vae_fashion/vae_fashion.ipynb)
23 | * [변이형 오토인코더 - CelebA](notebooks/03_vae/03_vae_faces/vae_faces.ipynb)
24 | * 4장: 생성적 적대 신경망
25 | * [DCGAN](notebooks/04_gan/01_dcgan/dcgan.ipynb)
26 | * [WGAN-GP](notebooks/04_gan/02_wgan_gp/wgan_gp.ipynb)
27 | * [CGAN](notebooks/04_gan/03_cgan/cgan.ipynb)
28 | * 5장: 자기 회귀 모델
29 | * [LSTM](notebooks/05_autoregressive/01_lstm/lstm.ipynb)
30 | * [PixelCNN](notebooks/05_autoregressive/02_pixelcnn/pixelcnn.ipynb)
31 | * [PixelCNN - 혼합 분포](notebooks/05_autoregressive/03_pixelcnn_md/pixelcnn_md.ipynb)
32 | * 6장: 노멀라이징 플로 모델
33 | * [RealNVP](notebooks/06_normflow/01_realnvp/realnvp.ipynb)
34 | * 7장: 에너지 기반 모델
35 | * [EBM](notebooks/07_ebm/01_ebm/ebm.ipynb)
36 | * 8장: 확산 모델
37 | * [확산 모델](notebooks/08_diffusion/01_ddm/ddm.ipynb)
38 |
39 | PART 3: 생성 모델링의 응용 분야
40 | * 9장: 트랜스포머
41 | * [GPT](notebooks/09_transformer/gpt/gpt.ipynb)
42 | * 10장: 고급 GAN
43 | * 11장: 음악 생성
44 | * [트랜스포머](notebooks/11_music/01_transformer/transformer.ipynb)
45 | * [MuseGAN](notebooks/11_music/02_musegan/musegan.ipynb)
46 | * 12장: 월드 모델
47 | * 13장: 멀티모달 모델
48 | * 14장: 결론
49 |
50 | 각 장의 노트북에는 구글 코랩에서 실행할 수 있는 링크가 포함되어 있습니다.
51 |
--------------------------------------------------------------------------------
/cover.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rickiepark/Generative_Deep_Learning_2nd_Edition/5170cc7134e6ead982bd0b4bda1d91a0bb4806ff/cover.jpeg
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/01_mlp/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/01_mlp/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/01_mlp/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/01_mlp/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/02_cnn/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/02_cnn/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/02_cnn/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/02_deeplearning/02_cnn/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/01_autoencoder/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/01_autoencoder/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/01_autoencoder/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/01_autoencoder/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/02_vae_fashion/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/02_vae_fashion/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/02_vae_fashion/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/02_vae_fashion/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/03_vae_faces/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/03_vae_faces/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/03_vae_faces/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/03_vae_faces/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/03_vae/03_vae_faces/vae_utils.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 |
4 |
5 | def get_vector_from_label(data, vae, embedding_dim, label):
6 | current_sum_POS = np.zeros(shape=embedding_dim, dtype="float32")
7 | current_n_POS = 0
8 | current_mean_POS = np.zeros(shape=embedding_dim, dtype="float32")
9 |
10 | current_sum_NEG = np.zeros(shape=embedding_dim, dtype="float32")
11 | current_n_NEG = 0
12 | current_mean_NEG = np.zeros(shape=embedding_dim, dtype="float32")
13 |
14 | current_vector = np.zeros(shape=embedding_dim, dtype="float32")
15 | current_dist = 0
16 |
17 | print("label: " + label)
18 | print("images : POS move : NEG move :distance : 𝛥 distance")
19 | while current_n_POS < 10000:
20 | batch = list(data.take(1).get_single_element())
21 | im = batch[0]
22 | attribute = batch[1]
23 |
24 | _, _, z = vae.encoder.predict(np.array(im), verbose=0)
25 |
26 | z_POS = z[attribute == 1]
27 | z_NEG = z[attribute == -1]
28 |
29 | if len(z_POS) > 0:
30 | current_sum_POS = current_sum_POS + np.sum(z_POS, axis=0)
31 | current_n_POS += len(z_POS)
32 | new_mean_POS = current_sum_POS / current_n_POS
33 | movement_POS = np.linalg.norm(new_mean_POS - current_mean_POS)
34 |
35 | if len(z_NEG) > 0:
36 | current_sum_NEG = current_sum_NEG + np.sum(z_NEG, axis=0)
37 | current_n_NEG += len(z_NEG)
38 | new_mean_NEG = current_sum_NEG / current_n_NEG
39 | movement_NEG = np.linalg.norm(new_mean_NEG - current_mean_NEG)
40 |
41 | current_vector = new_mean_POS - new_mean_NEG
42 | new_dist = np.linalg.norm(current_vector)
43 | dist_change = new_dist - current_dist
44 |
45 | print(
46 | str(current_n_POS)
47 | + " : "
48 | + str(np.round(movement_POS, 3))
49 | + " : "
50 | + str(np.round(movement_NEG, 3))
51 | + " : "
52 | + str(np.round(new_dist, 3))
53 | + " : "
54 | + str(np.round(dist_change, 3))
55 | )
56 |
57 | current_mean_POS = np.copy(new_mean_POS)
58 | current_mean_NEG = np.copy(new_mean_NEG)
59 | current_dist = np.copy(new_dist)
60 |
61 | if np.sum([movement_POS, movement_NEG]) < 0.08:
62 | current_vector = current_vector / current_dist
63 | print("Found the " + label + " vector")
64 | break
65 |
66 | return current_vector
67 |
68 |
69 | def add_vector_to_images(data, vae, feature_vec):
70 | n_to_show = 5
71 | factors = [-4, -3, -2, -1, 0, 1, 2, 3, 4]
72 |
73 | example_batch = list(data.take(1).get_single_element())
74 | example_images = example_batch[0]
75 |
76 | _, _, z_points = vae.encoder.predict(example_images, verbose=0)
77 |
78 | fig = plt.figure(figsize=(18, 10))
79 |
80 | counter = 1
81 |
82 | for i in range(n_to_show):
83 | img = example_images[i]
84 | sub = fig.add_subplot(n_to_show, len(factors) + 1, counter)
85 | sub.axis("off")
86 | sub.imshow(img)
87 |
88 | counter += 1
89 |
90 | for factor in factors:
91 | changed_z_point = z_points[i] + feature_vec * factor
92 | changed_image = vae.decoder.predict(
93 | np.array([changed_z_point]), verbose=0
94 | )[0]
95 |
96 | sub = fig.add_subplot(n_to_show, len(factors) + 1, counter)
97 | sub.axis("off")
98 | sub.imshow(changed_image)
99 |
100 | counter += 1
101 |
102 | plt.show()
103 |
104 |
105 | def morph_faces(data, vae):
106 | factors = np.arange(0, 1, 0.1)
107 |
108 | example_batch = list(data.take(1).get_single_element())[:2]
109 | example_images = example_batch[0]
110 | _, _, z_points = vae.encoder.predict(example_images, verbose=0)
111 |
112 | fig = plt.figure(figsize=(18, 8))
113 |
114 | counter = 1
115 |
116 | img = example_images[0]
117 | sub = fig.add_subplot(1, len(factors) + 2, counter)
118 | sub.axis("off")
119 | sub.imshow(img)
120 |
121 | counter += 1
122 |
123 | for factor in factors:
124 | changed_z_point = z_points[0] * (1 - factor) + z_points[1] * factor
125 | changed_image = vae.decoder.predict(
126 | np.array([changed_z_point]), verbose=0
127 | )[0]
128 | sub = fig.add_subplot(1, len(factors) + 2, counter)
129 | sub.axis("off")
130 | sub.imshow(changed_image)
131 |
132 | counter += 1
133 |
134 | img = example_images[1]
135 | sub = fig.add_subplot(1, len(factors) + 2, counter)
136 | sub.axis("off")
137 | sub.imshow(img)
138 |
139 | plt.show()
140 |
--------------------------------------------------------------------------------
/notebooks/04_gan/01_dcgan/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/01_dcgan/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/01_dcgan/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/01_dcgan/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/02_wgan_gp/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/02_wgan_gp/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/02_wgan_gp/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/02_wgan_gp/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/03_cgan/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/03_cgan/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/03_cgan/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/04_gan/03_cgan/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/01_lstm/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/01_lstm/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/01_lstm/lstm.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "b076bd1a-b236-4fbc-953d-8295b25122ae",
6 | "metadata": {
7 | "id": "b076bd1a-b236-4fbc-953d-8295b25122ae"
8 | },
9 | "source": [
10 | "# 🥙 LSTM - 레시피 데이터셋"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "id": "5795b771",
16 | "metadata": {
17 | "id": "5795b771"
18 | },
19 | "source": [
20 | "
\n",
21 | "
\n",
22 | " \n",
23 | "
\n",
24 | "
"
25 | ]
26 | },
27 | {
28 | "cell_type": "markdown",
29 | "id": "658a95da-9645-4bcf-bd9d-4b95a4b6f582",
30 | "metadata": {
31 | "id": "658a95da-9645-4bcf-bd9d-4b95a4b6f582"
32 | },
33 | "source": [
34 | "이 노트북에서는 레시피 데이터셋에서 LSTM을 훈련합니다."
35 | ]
36 | },
37 | {
38 | "cell_type": "code",
39 | "execution_count": 1,
40 | "id": "4e0d56cc-4773-4029-97d8-26f882ba79c9",
41 | "metadata": {
42 | "id": "4e0d56cc-4773-4029-97d8-26f882ba79c9"
43 | },
44 | "outputs": [],
45 | "source": [
46 | "import numpy as np\n",
47 | "import json\n",
48 | "import re\n",
49 | "import string\n",
50 | "\n",
51 | "import tensorflow as tf\n",
52 | "from tensorflow.keras import layers, models, callbacks, losses"
53 | ]
54 | },
55 | {
56 | "cell_type": "markdown",
57 | "id": "339e6268-ebd7-4feb-86db-1fe7abccdbe5",
58 | "metadata": {
59 | "id": "339e6268-ebd7-4feb-86db-1fe7abccdbe5"
60 | },
61 | "source": [
62 | "## 0. 파라미터 "
63 | ]
64 | },
65 | {
66 | "cell_type": "code",
67 | "execution_count": 2,
68 | "id": "2d8352af-343e-4c2e-8c91-95f8bac1c8a1",
69 | "metadata": {
70 | "id": "2d8352af-343e-4c2e-8c91-95f8bac1c8a1"
71 | },
72 | "outputs": [],
73 | "source": [
74 | "VOCAB_SIZE = 10000\n",
75 | "MAX_LEN = 200\n",
76 | "EMBEDDING_DIM = 100\n",
77 | "N_UNITS = 128\n",
78 | "VALIDATION_SPLIT = 0.2\n",
79 | "SEED = 42\n",
80 | "LOAD_MODEL = False\n",
81 | "BATCH_SIZE = 32\n",
82 | "EPOCHS = 25"
83 | ]
84 | },
85 | {
86 | "cell_type": "markdown",
87 | "id": "b7716fac-0010-49b0-b98e-53be2259edde",
88 | "metadata": {
89 | "id": "b7716fac-0010-49b0-b98e-53be2259edde"
90 | },
91 | "source": [
92 | "## 1. 데이터 로드 "
93 | ]
94 | },
95 | {
96 | "cell_type": "code",
97 | "execution_count": 10,
98 | "id": "46881426",
99 | "metadata": {
100 | "id": "46881426",
101 | "outputId": "79d23b10-3e6c-4687-e250-d1ccb913203f",
102 | "colab": {
103 | "base_uri": "https://localhost:8080/",
104 | "height": 128
105 | }
106 | },
107 | "outputs": [
108 | {
109 | "output_type": "display_data",
110 | "data": {
111 | "text/plain": [
112 | ""
113 | ],
114 | "text/html": [
115 | "\n",
116 | " \n",
118 | " \n",
122 | " "
298 | ]
299 | },
300 | "metadata": {}
301 | },
302 | {
303 | "output_type": "stream",
304 | "name": "stdout",
305 | "text": [
306 | "Saving kaggle.json to kaggle.json\n",
307 | "Downloading epirecipes.zip to /content\n",
308 | " 80% 9.00M/11.3M [00:01<00:00, 8.72MB/s]\n",
309 | "100% 11.3M/11.3M [00:01<00:00, 7.07MB/s]\n"
310 | ]
311 | }
312 | ],
313 | "source": [
314 | "import sys\n",
315 | "\n",
316 | "# 코랩일 경우 노트북에서 celeba 데이터셋을 받습니다.\n",
317 | "if 'google.colab' in sys.modules:\n",
318 | " # 캐글-->Setttings-->API-->Create New Token에서\n",
319 | " # kaggle.json 파일을 만들어 코랩에 업로드하세요.\n",
320 | " from google.colab import files\n",
321 | " files.upload()\n",
322 | " !mkdir ~/.kaggle\n",
323 | " !cp kaggle.json ~/.kaggle/\n",
324 | " !chmod 600 ~/.kaggle/kaggle.json\n",
325 | " # celeba 데이터셋을 다운로드하고 압축을 해제합니다.\n",
326 | " !kaggle datasets download -d hugodarwood/epirecipes\n",
327 | " !unzip -q epirecipes.zip"
328 | ]
329 | },
330 | {
331 | "cell_type": "code",
332 | "execution_count": 11,
333 | "id": "93cf6b0f-9667-4146-8911-763a8a2925d3",
334 | "metadata": {
335 | "tags": [],
336 | "id": "93cf6b0f-9667-4146-8911-763a8a2925d3"
337 | },
338 | "outputs": [],
339 | "source": [
340 | "# 전체 데이터셋 로드\n",
341 | "with open(\"./full_format_recipes.json\") as json_data:\n",
342 | " recipe_data = json.load(json_data)"
343 | ]
344 | },
345 | {
346 | "cell_type": "code",
347 | "execution_count": 12,
348 | "id": "23a74eca-f1b7-4a46-9a1f-b5806a4ed361",
349 | "metadata": {
350 | "tags": [],
351 | "id": "23a74eca-f1b7-4a46-9a1f-b5806a4ed361"
352 | },
353 | "outputs": [],
354 | "source": [
355 | "# 데이터셋 필터링\n",
356 | "filtered_data = [\n",
357 | " \"Recipe for \" + x[\"title\"] + \" | \" + \" \".join(x[\"directions\"])\n",
358 | " for x in recipe_data\n",
359 | " if \"title\" in x\n",
360 | " and x[\"title\"] is not None\n",
361 | " and \"directions\" in x\n",
362 | " and x[\"directions\"] is not None\n",
363 | "]"
364 | ]
365 | },
366 | {
367 | "cell_type": "code",
368 | "execution_count": 13,
369 | "id": "389c20de-0422-4c48-a7b4-6ee12a7bf0e2",
370 | "metadata": {
371 | "tags": [],
372 | "id": "389c20de-0422-4c48-a7b4-6ee12a7bf0e2",
373 | "outputId": "2661224e-3f06-44b3-fb7e-b1d61e728810",
374 | "colab": {
375 | "base_uri": "https://localhost:8080/"
376 | }
377 | },
378 | "outputs": [
379 | {
380 | "output_type": "stream",
381 | "name": "stdout",
382 | "text": [
383 | "20111개 레시피 로드\n"
384 | ]
385 | }
386 | ],
387 | "source": [
388 | "# 레시피 개수 확인\n",
389 | "n_recipes = len(filtered_data)\n",
390 | "print(f\"{n_recipes}개 레시피 로드\")"
391 | ]
392 | },
393 | {
394 | "cell_type": "code",
395 | "execution_count": 14,
396 | "id": "1b2e3cf7-e416-460e-874a-0dd9637bca36",
397 | "metadata": {
398 | "id": "1b2e3cf7-e416-460e-874a-0dd9637bca36",
399 | "outputId": "3d306c7a-1857-4faa-d232-60906e78ac7b",
400 | "colab": {
401 | "base_uri": "https://localhost:8080/"
402 | }
403 | },
404 | "outputs": [
405 | {
406 | "output_type": "stream",
407 | "name": "stdout",
408 | "text": [
409 | "Recipe for Ham Persillade with Mustard Potato Salad and Mashed Peas | Chop enough parsley leaves to measure 1 tablespoon; reserve. Chop remaining leaves and stems and simmer with broth and garlic in a small saucepan, covered, 5 minutes. Meanwhile, sprinkle gelatin over water in a medium bowl and let soften 1 minute. Strain broth through a fine-mesh sieve into bowl with gelatin and stir to dissolve. Season with salt and pepper. Set bowl in an ice bath and cool to room temperature, stirring. Toss ham with reserved parsley and divide among jars. Pour gelatin on top and chill until set, at least 1 hour. Whisk together mayonnaise, mustard, vinegar, 1/4 teaspoon salt, and 1/4 teaspoon pepper in a large bowl. Stir in celery, cornichons, and potatoes. Pulse peas with marjoram, oil, 1/2 teaspoon pepper, and 1/4 teaspoon salt in a food processor to a coarse mash. Layer peas, then potato salad, over ham.\n"
410 | ]
411 | }
412 | ],
413 | "source": [
414 | "example = filtered_data[9]\n",
415 | "print(example)"
416 | ]
417 | },
418 | {
419 | "cell_type": "markdown",
420 | "id": "3f871aaf-d873-41c7-8946-e4eef7ac17c1",
421 | "metadata": {
422 | "id": "3f871aaf-d873-41c7-8946-e4eef7ac17c1"
423 | },
424 | "source": [
425 | "## 2. 데이터 토큰화"
426 | ]
427 | },
428 | {
429 | "cell_type": "code",
430 | "execution_count": 15,
431 | "id": "5b2064fb-5dcc-4657-b470-0928d10e2ddc",
432 | "metadata": {
433 | "tags": [],
434 | "id": "5b2064fb-5dcc-4657-b470-0928d10e2ddc"
435 | },
436 | "outputs": [],
437 | "source": [
438 | "# 구두점을 분리하여 별도의 '단어'로 취급합니다.\n",
439 | "def pad_punctuation(s):\n",
440 | " s = re.sub(f\"([{string.punctuation}])\", r\" \\1 \", s)\n",
441 | " s = re.sub(\" +\", \" \", s)\n",
442 | " return s\n",
443 | "\n",
444 | "\n",
445 | "text_data = [pad_punctuation(x) for x in filtered_data]"
446 | ]
447 | },
448 | {
449 | "cell_type": "code",
450 | "execution_count": 16,
451 | "id": "b87d7c65-9a46-492a-a5c0-a043b0d252f3",
452 | "metadata": {
453 | "id": "b87d7c65-9a46-492a-a5c0-a043b0d252f3",
454 | "outputId": "eef1c85e-8a2c-4750-d9f8-9a238ee75251",
455 | "colab": {
456 | "base_uri": "https://localhost:8080/",
457 | "height": 143
458 | }
459 | },
460 | "outputs": [
461 | {
462 | "output_type": "execute_result",
463 | "data": {
464 | "text/plain": [
465 | "'Recipe for Ham Persillade with Mustard Potato Salad and Mashed Peas | Chop enough parsley leaves to measure 1 tablespoon ; reserve . Chop remaining leaves and stems and simmer with broth and garlic in a small saucepan , covered , 5 minutes . Meanwhile , sprinkle gelatin over water in a medium bowl and let soften 1 minute . Strain broth through a fine - mesh sieve into bowl with gelatin and stir to dissolve . Season with salt and pepper . Set bowl in an ice bath and cool to room temperature , stirring . Toss ham with reserved parsley and divide among jars . Pour gelatin on top and chill until set , at least 1 hour . Whisk together mayonnaise , mustard , vinegar , 1 / 4 teaspoon salt , and 1 / 4 teaspoon pepper in a large bowl . Stir in celery , cornichons , and potatoes . Pulse peas with marjoram , oil , 1 / 2 teaspoon pepper , and 1 / 4 teaspoon salt in a food processor to a coarse mash . Layer peas , then potato salad , over ham . '"
466 | ],
467 | "application/vnd.google.colaboratory.intrinsic+json": {
468 | "type": "string"
469 | }
470 | },
471 | "metadata": {},
472 | "execution_count": 16
473 | }
474 | ],
475 | "source": [
476 | "# 레시피 샘플 출력\n",
477 | "example_data = text_data[9]\n",
478 | "example_data"
479 | ]
480 | },
481 | {
482 | "cell_type": "code",
483 | "execution_count": 17,
484 | "id": "9834f916-b21a-4104-acc9-f28d3bd7a8c1",
485 | "metadata": {
486 | "tags": [],
487 | "id": "9834f916-b21a-4104-acc9-f28d3bd7a8c1"
488 | },
489 | "outputs": [],
490 | "source": [
491 | "# 텐서플로 데이터셋으로 변환하기\n",
492 | "text_ds = (\n",
493 | " tf.data.Dataset.from_tensor_slices(text_data)\n",
494 | " .batch(BATCH_SIZE)\n",
495 | " .shuffle(1000)\n",
496 | ")"
497 | ]
498 | },
499 | {
500 | "cell_type": "code",
501 | "execution_count": 18,
502 | "id": "884c0bcb-0807-45a1-8f7e-a32f2c6fa4de",
503 | "metadata": {
504 | "id": "884c0bcb-0807-45a1-8f7e-a32f2c6fa4de"
505 | },
506 | "outputs": [],
507 | "source": [
508 | "# 벡터화 층 만들기\n",
509 | "vectorize_layer = layers.TextVectorization(\n",
510 | " standardize=\"lower\",\n",
511 | " max_tokens=VOCAB_SIZE,\n",
512 | " output_mode=\"int\",\n",
513 | " output_sequence_length=MAX_LEN + 1,\n",
514 | ")"
515 | ]
516 | },
517 | {
518 | "cell_type": "code",
519 | "execution_count": 19,
520 | "id": "4d6dd34a-d905-497b-926a-405380ebcf98",
521 | "metadata": {
522 | "id": "4d6dd34a-d905-497b-926a-405380ebcf98"
523 | },
524 | "outputs": [],
525 | "source": [
526 | "# 훈련 세트에 층 적용\n",
527 | "vectorize_layer.adapt(text_ds)\n",
528 | "vocab = vectorize_layer.get_vocabulary()"
529 | ]
530 | },
531 | {
532 | "cell_type": "code",
533 | "execution_count": 20,
534 | "id": "f6c1c7ce-3cf0-40d4-a3dc-ab7090f69f2f",
535 | "metadata": {
536 | "id": "f6c1c7ce-3cf0-40d4-a3dc-ab7090f69f2f",
537 | "outputId": "959361a8-72b7-44da-a871-075ef0342fcc",
538 | "colab": {
539 | "base_uri": "https://localhost:8080/"
540 | }
541 | },
542 | "outputs": [
543 | {
544 | "output_type": "stream",
545 | "name": "stdout",
546 | "text": [
547 | "0: \n",
548 | "1: [UNK]\n",
549 | "2: .\n",
550 | "3: ,\n",
551 | "4: and\n",
552 | "5: to\n",
553 | "6: in\n",
554 | "7: the\n",
555 | "8: with\n",
556 | "9: a\n"
557 | ]
558 | }
559 | ],
560 | "source": [
561 | "# 토큰:단어 매핑 샘플 출력하기\n",
562 | "for i, word in enumerate(vocab[:10]):\n",
563 | " print(f\"{i}: {word}\")"
564 | ]
565 | },
566 | {
567 | "cell_type": "code",
568 | "execution_count": 21,
569 | "id": "1cc30186-7ec6-4eb6-b29a-65df6714d321",
570 | "metadata": {
571 | "id": "1cc30186-7ec6-4eb6-b29a-65df6714d321",
572 | "outputId": "41e4a1ef-550f-4b17-a99e-cabc24182080",
573 | "colab": {
574 | "base_uri": "https://localhost:8080/"
575 | }
576 | },
577 | "outputs": [
578 | {
579 | "output_type": "stream",
580 | "name": "stdout",
581 | "text": [
582 | "[ 26 16 557 1 8 298 335 189 4 1054 494 27 332 228\n",
583 | " 235 262 5 594 11 133 22 311 2 332 45 262 4 671\n",
584 | " 4 70 8 171 4 81 6 9 65 80 3 121 3 59\n",
585 | " 12 2 299 3 88 650 20 39 6 9 29 21 4 67\n",
586 | " 529 11 164 2 320 171 102 9 374 13 643 306 25 21\n",
587 | " 8 650 4 42 5 931 2 63 8 24 4 33 2 114\n",
588 | " 21 6 178 181 1245 4 60 5 140 112 3 48 2 117\n",
589 | " 557 8 285 235 4 200 292 980 2 107 650 28 72 4\n",
590 | " 108 10 114 3 57 204 11 172 2 73 110 482 3 298\n",
591 | " 3 190 3 11 23 32 142 24 3 4 11 23 32 142\n",
592 | " 33 6 9 30 21 2 42 6 353 3 3224 3 4 150\n",
593 | " 2 437 494 8 1281 3 37 3 11 23 15 142 33 3\n",
594 | " 4 11 23 32 142 24 6 9 291 188 5 9 412 572\n",
595 | " 2 230 494 3 46 335 189 3 20 557 2 0 0 0\n",
596 | " 0 0 0 0 0]\n"
597 | ]
598 | }
599 | ],
600 | "source": [
601 | "# 동일 샘플을 정수로 변환하여 출력하기\n",
602 | "example_tokenised = vectorize_layer(example_data)\n",
603 | "print(example_tokenised.numpy())"
604 | ]
605 | },
606 | {
607 | "cell_type": "markdown",
608 | "id": "8c195efb-84c6-4be0-a989-a7542188ad35",
609 | "metadata": {
610 | "id": "8c195efb-84c6-4be0-a989-a7542188ad35"
611 | },
612 | "source": [
613 | "## 3. 훈련 세트 만들기"
614 | ]
615 | },
616 | {
617 | "cell_type": "code",
618 | "execution_count": 22,
619 | "id": "740294a1-1a6b-4c89-92f2-036d7d1b788b",
620 | "metadata": {
621 | "id": "740294a1-1a6b-4c89-92f2-036d7d1b788b"
622 | },
623 | "outputs": [],
624 | "source": [
625 | "# 레시피와 한 단어 이동한 동일 텍스트로 훈련 세트를 만듭니다.\n",
626 | "def prepare_inputs(text):\n",
627 | " text = tf.expand_dims(text, -1)\n",
628 | " tokenized_sentences = vectorize_layer(text)\n",
629 | " x = tokenized_sentences[:, :-1]\n",
630 | " y = tokenized_sentences[:, 1:]\n",
631 | " return x, y\n",
632 | "\n",
633 | "\n",
634 | "train_ds = text_ds.map(prepare_inputs)"
635 | ]
636 | },
637 | {
638 | "cell_type": "markdown",
639 | "id": "aff50401-3abe-4c10-bba8-b35bc13ad7d5",
640 | "metadata": {
641 | "tags": [],
642 | "id": "aff50401-3abe-4c10-bba8-b35bc13ad7d5"
643 | },
644 | "source": [
645 | "## 4. LSTM 만들기 "
646 | ]
647 | },
648 | {
649 | "cell_type": "code",
650 | "execution_count": 23,
651 | "id": "9230b5bf-b4a8-48d5-b73b-6899a598f296",
652 | "metadata": {
653 | "id": "9230b5bf-b4a8-48d5-b73b-6899a598f296",
654 | "outputId": "1ef24943-2fce-4c0b-d97a-449067e45da4",
655 | "colab": {
656 | "base_uri": "https://localhost:8080/"
657 | }
658 | },
659 | "outputs": [
660 | {
661 | "output_type": "stream",
662 | "name": "stdout",
663 | "text": [
664 | "Model: \"model\"\n",
665 | "_________________________________________________________________\n",
666 | " Layer (type) Output Shape Param # \n",
667 | "=================================================================\n",
668 | " input_1 (InputLayer) [(None, None)] 0 \n",
669 | " \n",
670 | " embedding (Embedding) (None, None, 100) 1000000 \n",
671 | " \n",
672 | " lstm (LSTM) (None, None, 128) 117248 \n",
673 | " \n",
674 | " dense (Dense) (None, None, 10000) 1290000 \n",
675 | " \n",
676 | "=================================================================\n",
677 | "Total params: 2407248 (9.18 MB)\n",
678 | "Trainable params: 2407248 (9.18 MB)\n",
679 | "Non-trainable params: 0 (0.00 Byte)\n",
680 | "_________________________________________________________________\n"
681 | ]
682 | }
683 | ],
684 | "source": [
685 | "inputs = layers.Input(shape=(None,), dtype=\"int32\")\n",
686 | "x = layers.Embedding(VOCAB_SIZE, EMBEDDING_DIM)(inputs)\n",
687 | "x = layers.LSTM(N_UNITS, return_sequences=True)(x)\n",
688 | "outputs = layers.Dense(VOCAB_SIZE, activation=\"softmax\")(x)\n",
689 | "lstm = models.Model(inputs, outputs)\n",
690 | "lstm.summary()"
691 | ]
692 | },
693 | {
694 | "cell_type": "code",
695 | "execution_count": 24,
696 | "id": "800a3c6e-fb11-4792-b6bc-9a43a7c977ad",
697 | "metadata": {
698 | "tags": [],
699 | "id": "800a3c6e-fb11-4792-b6bc-9a43a7c977ad"
700 | },
701 | "outputs": [],
702 | "source": [
703 | "if LOAD_MODEL:\n",
704 | " # model.load_weights('./models/model')\n",
705 | " lstm = models.load_model(\"./models/lstm\", compile=False)"
706 | ]
707 | },
708 | {
709 | "cell_type": "markdown",
710 | "id": "35b14665-4359-447b-be58-3fd58ba69084",
711 | "metadata": {
712 | "id": "35b14665-4359-447b-be58-3fd58ba69084"
713 | },
714 | "source": [
715 | "## 5. LSTM 훈련하기 "
716 | ]
717 | },
718 | {
719 | "cell_type": "code",
720 | "execution_count": 25,
721 | "id": "ffb1bd3b-6fd9-4536-973e-6375bbcbf16d",
722 | "metadata": {
723 | "id": "ffb1bd3b-6fd9-4536-973e-6375bbcbf16d"
724 | },
725 | "outputs": [],
726 | "source": [
727 | "loss_fn = losses.SparseCategoricalCrossentropy()\n",
728 | "lstm.compile(\"adam\", loss_fn)"
729 | ]
730 | },
731 | {
732 | "cell_type": "code",
733 | "execution_count": 26,
734 | "id": "3ddcff5f-829d-4449-99d2-9a3cb68f7d72",
735 | "metadata": {
736 | "id": "3ddcff5f-829d-4449-99d2-9a3cb68f7d72"
737 | },
738 | "outputs": [],
739 | "source": [
740 | "# TextGenerator 체크포인트 만들기\n",
741 | "class TextGenerator(callbacks.Callback):\n",
742 | " def __init__(self, index_to_word, top_k=10):\n",
743 | " self.index_to_word = index_to_word\n",
744 | " self.word_to_index = {\n",
745 | " word: index for index, word in enumerate(index_to_word)\n",
746 | " }\n",
747 | "\n",
748 | " def sample_from(self, probs, temperature):\n",
749 | " probs = probs ** (1 / temperature)\n",
750 | " probs = probs / np.sum(probs)\n",
751 | " return np.random.choice(len(probs), p=probs), probs\n",
752 | "\n",
753 | " def generate(self, start_prompt, max_tokens, temperature):\n",
754 | " start_tokens = [\n",
755 | " self.word_to_index.get(x, 1) for x in start_prompt.split()\n",
756 | " ]\n",
757 | " sample_token = None\n",
758 | " info = []\n",
759 | " while len(start_tokens) < max_tokens and sample_token != 0:\n",
760 | " x = np.array([start_tokens])\n",
761 | " y = self.model.predict(x, verbose=0)\n",
762 | " sample_token, probs = self.sample_from(y[0][-1], temperature)\n",
763 | " info.append({\"prompt\": start_prompt, \"word_probs\": probs})\n",
764 | " start_tokens.append(sample_token)\n",
765 | " start_prompt = start_prompt + \" \" + self.index_to_word[sample_token]\n",
766 | " print(f\"\\n생성된 텍스트:\\n{start_prompt}\\n\")\n",
767 | " return info\n",
768 | "\n",
769 | " def on_epoch_end(self, epoch, logs=None):\n",
770 | " self.generate(\"recipe for\", max_tokens=100, temperature=1.0)"
771 | ]
772 | },
773 | {
774 | "cell_type": "code",
775 | "execution_count": 27,
776 | "id": "349865fe-ffbe-450e-97be-043ae1740e78",
777 | "metadata": {
778 | "id": "349865fe-ffbe-450e-97be-043ae1740e78"
779 | },
780 | "outputs": [],
781 | "source": [
782 | "# 모델 저장 체크포인트 만들기\n",
783 | "model_checkpoint_callback = callbacks.ModelCheckpoint(\n",
784 | " filepath=\"./checkpoint/checkpoint.ckpt\",\n",
785 | " save_weights_only=True,\n",
786 | " save_freq=\"epoch\",\n",
787 | " verbose=0,\n",
788 | ")\n",
789 | "\n",
790 | "tensorboard_callback = callbacks.TensorBoard(log_dir=\"./logs\")\n",
791 | "\n",
792 | "# 시작 프롬프트 토큰화\n",
793 | "text_generator = TextGenerator(vocab)"
794 | ]
795 | },
796 | {
797 | "cell_type": "code",
798 | "execution_count": 28,
799 | "id": "461c2b3e-b5ae-4def-8bd9-e7bab8c63d8e",
800 | "metadata": {
801 | "tags": [],
802 | "id": "461c2b3e-b5ae-4def-8bd9-e7bab8c63d8e",
803 | "outputId": "1b942983-8580-4856-ac5a-51e823307cba",
804 | "colab": {
805 | "base_uri": "https://localhost:8080/"
806 | }
807 | },
808 | "outputs": [
809 | {
810 | "output_type": "stream",
811 | "name": "stdout",
812 | "text": [
813 | "Epoch 1/25\n",
814 | "629/629 [==============================] - ETA: 0s - loss: 4.4325\n",
815 | "생성된 텍스트:\n",
816 | "recipe for bruise eye | croutons . add garlic with bowl , pour wedges with filling and boil and add shells . season with plus large - the resealable small container is shallow not combined , remaining gently until simmer scraping sieve . soup until bowl to remove outer platter are smooth of egg and stand , . drain until prepared can divide - garnished sit ahead ( made in sprinkle out 4 onions of uncovered . slotted transfer of garlic . and heavy drain and cook or carrots , and high \n",
817 | "\n",
818 | "629/629 [==============================] - 67s 101ms/step - loss: 4.4325\n",
819 | "Epoch 2/25\n",
820 | "629/629 [==============================] - ETA: 0s - loss: 3.1141\n",
821 | "생성된 텍스트:\n",
822 | "recipe for tuna , lady de s apricot checking riz with sautéed underside | cook 3 to 4 tablespoons juice , crust and oil in processor . press out hot and thick dry before kept . add flour mixture water , increase , water , stir until cool , about 4 minutes . ladle chicken off sheets ; top chops with pear . custard layer around them from dressing and chill , parsley . cover . grind mint sprigs \n",
823 | "\n",
824 | "629/629 [==============================] - 29s 46ms/step - loss: 3.1141\n",
825 | "Epoch 3/25\n",
826 | "629/629 [==============================] - ETA: 0s - loss: 2.5407\n",
827 | "생성된 텍스트:\n",
828 | "recipe for sesame tenderloin with 2 - glazed and mustard sauce | mound chicken , yogurt into a electric mixer but still set over each dough in cream and 5 but inch cookies . transfer to a bowl and continue cool . drain \n",
829 | "\n",
830 | "629/629 [==============================] - 27s 43ms/step - loss: 2.5407\n",
831 | "Epoch 4/25\n",
832 | "628/629 [============================>.] - ETA: 0s - loss: 2.2839\n",
833 | "생성된 텍스트:\n",
834 | "recipe for cauliflower soufflé | whisk first 2 ingredients in a large bowl . drain peppers and rinse while peel . cut dough lengthwise into disk segments ; pipe into disk . garnish with remaining ramekins of remaining juices and drizzle herb salad with chicken . sprinkle with kebabs . simmer onions in shallow dish . in oil ( a instant tumblers ) thickly 8 of red beef in the water over once . reduce heat to a boil . add the onion and simmer , turning to soften , 40 minutes . ( this opened up a bit ,\n",
835 | "\n",
836 | "629/629 [==============================] - 31s 49ms/step - loss: 2.2843\n",
837 | "Epoch 5/25\n",
838 | "629/629 [==============================] - ETA: 0s - loss: 2.1344\n",
839 | "생성된 텍스트:\n",
840 | "recipe for harvest pea \" uwajimaya | toss warm eggs , cut into 1 / 4 - inch and 3 / 4 - inch shaker squares . if arugula mixture into prosciutto . arrange 1 / 4 inch of apple mixture , pistachios lengthwise , and freshly ground chives . , toss dough to 1 cup scallion . halve each lengthwise , cut jalapeño , if desired . form each third of milk lengthwise into rounds in 1 3 / 4 cup , dividing equally . complete remaining poblano mixture , 1 1 / 2 inch layer , bread ,\n",
841 | "\n",
842 | "629/629 [==============================] - 31s 49ms/step - loss: 2.1344\n",
843 | "Epoch 6/25\n",
844 | "629/629 [==============================] - ETA: 0s - loss: 2.0293\n",
845 | "생성된 텍스트:\n",
846 | "recipe for syrup ( new cake alla uncut ) [UNK] turkey : combine under stock | preheat broiler . preheat oven to 350°f . melt oil in heavy large skillet and add vegetables ; simmer flame pasta in lowest shortbread in lower third of oven 10 minutes . cool slightly , then scrape down sides of baking sheet . arrange slices on prepared pot . if desired for 13 minutes . return large skillet to oil as dry . add remaining 1 cup mold saffron and carrots to cook until sugar becomes reduced to brown , about 4 minutes .\n",
847 | "\n",
848 | "629/629 [==============================] - 31s 50ms/step - loss: 2.0293\n",
849 | "Epoch 7/25\n",
850 | "629/629 [==============================] - ETA: 0s - loss: 1.9489\n",
851 | "생성된 텍스트:\n",
852 | "recipe for charred crab sauté | blend first 5 ingredients in large bowl . finely chop onions . drain rice while still very finely f . mix pine paste to dry small skillet ; beat chopped berries , 1 / 4 cup grated apple segments . season with salt and pepper . remove incision from pot . brush citrus dressing over to coat . marinate 2 hours . mix pasta , onion and mint leaves in large skillet . season soup to taste with 1 teaspoon dill . simmer until heated through , about 3 minutes . whisk in cheese\n",
853 | "\n",
854 | "629/629 [==============================] - 31s 50ms/step - loss: 1.9489\n",
855 | "Epoch 8/25\n",
856 | "628/629 [============================>.] - ETA: 0s - loss: 1.8857\n",
857 | "생성된 텍스트:\n",
858 | "recipe for iceberg breasts with creamed onion and olives | in a 4 - to 4 baking pan sauté over moderate heat , sauté mushrooms , broth , rounded side up , turning the mixture once , until mixture browns and browned , about 5 minutes . pour in skillet and simmer , stirring occasionally , until heated through , about 2 minutes . season to taste with salt and pepper and serve . \n",
859 | "\n",
860 | "629/629 [==============================] - 30s 47ms/step - loss: 1.8855\n",
861 | "Epoch 9/25\n",
862 | "629/629 [==============================] - ETA: 0s - loss: 1.8361\n",
863 | "생성된 텍스트:\n",
864 | "recipe for panino with bread chips | heat oil in heavy heavy skillet over high heat . add veal fillets , tomatoes , skin sides down , 1 2 tablespoons parmesan seeds , soy sauce , 6–8 minutes . add to skillet and stir until sugar dissolves ; sauté 1 minute and let stand 15 minutes . transfer squid to bowl . ( can be prepared up to day ahead . cover separately ; chill , loosely covered or overnight . ) cut pork lengthwise into wedges into 1 / 2 - inch - long - shaped bag . cut\n",
865 | "\n",
866 | "629/629 [==============================] - 32s 51ms/step - loss: 1.8361\n",
867 | "Epoch 10/25\n",
868 | "629/629 [==============================] - ETA: 0s - loss: 1.7960\n",
869 | "생성된 텍스트:\n",
870 | "recipe for shrimp , prosciutto , and basil with fresh dried salad | cook bacon in heavy large skillet over moderate heat , stirring occasionally , until golden , 10 - 12 minutes . reduce heat to medium - low . peel ; coarsely chop and potatoes remaining 1 1 / 4 tablespoons white wine . measure 4 tortilla for 1 / 2 - inch - diameter patties . transfer 1 tablespoon oil to large roasting pan . place chicken wafer slices in pieces and beat to coat . spray grill rack and grill until grill marks appear on bottom\n",
871 | "\n",
872 | "629/629 [==============================] - 32s 50ms/step - loss: 1.7960\n",
873 | "Epoch 11/25\n",
874 | "629/629 [==============================] - ETA: 0s - loss: 1.7629\n",
875 | "생성된 텍스트:\n",
876 | "recipe for olive oil | stir together olives and brown sugar . toss tomatoes , green onion , onion , green mushrooms , vegetables , capers , and pepper to taste ; season with coarse salt and pepper or thin if using at a time under all end of a big skins . cut skin crosswise into 4 - blistered patties . pour cookies 1 / 4 inch apart over risotto rim , spreading evenly with about 1 / 2 cup , then cover with plastic wrap and freeze overnight . stir together vinegar , lime juice , jicama and\n",
877 | "\n",
878 | "629/629 [==============================] - 32s 50ms/step - loss: 1.7629\n",
879 | "Epoch 12/25\n",
880 | "628/629 [============================>.] - ETA: 0s - loss: 1.7345\n",
881 | "생성된 텍스트:\n",
882 | "recipe for raspberry shortcakes | roll up 9 x 11 x 4 pieces in a 10 - inch - dry bundt pan ( 1 / 2 \" ) pans and dust with flour . freeze custard in pan 5 hours . stir in green beans . let brisket cool slightly . whisk in flour , until blended . transfer dough to a floured surface , enclosing and chill in microwave on an 10 - inch - by 12 - inch - diameter springform pan and dust with flour , knocking out excess . beat together butter , oats , butter\n",
883 | "\n",
884 | "629/629 [==============================] - 32s 50ms/step - loss: 1.7342\n",
885 | "Epoch 13/25\n",
886 | "629/629 [==============================] - ETA: 0s - loss: 1.7094\n",
887 | "생성된 텍스트:\n",
888 | "recipe for aioli de pollo | for motor , st - eyed - thyme and brazilian - low place for 10 to 15 minutes , then set aside . combine all ingredients to half ; toss for italian pea shoots with enough mint leaves for remaining 2 tablespoons seasoning . . \n",
889 | "\n",
890 | "629/629 [==============================] - 29s 45ms/step - loss: 1.7094\n",
891 | "Epoch 14/25\n",
892 | "628/629 [============================>.] - ETA: 0s - loss: 1.6875\n",
893 | "생성된 텍스트:\n",
894 | "recipe for tomato - jellied pineapple hummus | heat gratin dish as burner on rack . increase oven rack 15 minutes ; reserve skillet . in a large bowl combine the boiled cheeses , the onions and the chiles , and the sauce , whisk the remaining tablespoon chives , vinegar , worcestershire sauce and the parsley , and salt to taste . sprinkle the broth , garnish with the parsley and chill for at least a bare up the water to 4 days and let it cool for 1 week . \n",
895 | "\n",
896 | "629/629 [==============================] - 32s 51ms/step - loss: 1.6876\n",
897 | "Epoch 15/25\n",
898 | "628/629 [============================>.] - ETA: 0s - loss: 1.6678\n",
899 | "생성된 텍스트:\n",
900 | "recipe for no - ingredient [UNK] | turn to the noodles , preferably & shrimp , scatter two - thirds of the breadcrumbs , and chop it together with the oil . stir the egg into the flour . pour into a 1 - 2 - quart baking dish and let cool . in a pot sauté the chicken with the butter and vinegar . in a oiled lid set over moderate heat , heat the tofu , stirring until it is golden - crisp - tender , about 15 seconds per . place the rice in a large bowl\n",
901 | "\n",
902 | "629/629 [==============================] - 32s 51ms/step - loss: 1.6676\n",
903 | "Epoch 16/25\n",
904 | "629/629 [==============================] - ETA: 0s - loss: 1.6494\n",
905 | "생성된 텍스트:\n",
906 | "recipe for tripled with sausage , chicken liver , and olives with coriander glaze | bring first 3 ingredients and sauce to simmer in medium saucepan and bring to a boil with ice water . heat 2 / 4 cup puree in wine . drizzle boiling water over apples . reduce heat and simmer on low heat until vegetables are tender , about 3 minutes , then with any liquid . strain sauce through a small spoon or colander . add water to large bowl , then spread evenly on paper towels . maintain oven temperature . twist steaks with\n",
907 | "\n",
908 | "629/629 [==============================] - 32s 51ms/step - loss: 1.6494\n",
909 | "Epoch 17/25\n",
910 | "629/629 [==============================] - ETA: 0s - loss: 1.6328\n",
911 | "생성된 텍스트:\n",
912 | "recipe for tea royale crème anglaise | position long sides of platter and biscotti sticks into glasses . spoon into bowls . \n",
913 | "\n",
914 | "629/629 [==============================] - 26s 42ms/step - loss: 1.6328\n",
915 | "Epoch 18/25\n",
916 | "629/629 [==============================] - ETA: 0s - loss: 1.6176\n",
917 | "생성된 텍스트:\n",
918 | "recipe for chicken stock | using a slotted spoon , transfer potato mixture to a small bowl ; lower ice ; discard bay leaves , and chop green onion . cut shallots into 1 / 2 - inch cubes in a large pot . stir over medium heat until smooth , adding more water by teaspoonfuls if too dry . to saute , add bacon and remaining 2 tablespoons garlic and cook over medium heat , stirring occasionally , until softened , about 12 minutes . add celery , tomatoes , basil , bay leaf over nuts , salt and\n",
919 | "\n",
920 | "629/629 [==============================] - 33s 52ms/step - loss: 1.6176\n",
921 | "Epoch 19/25\n",
922 | "629/629 [==============================] - ETA: 0s - loss: 1.6039\n",
923 | "생성된 텍스트:\n",
924 | "recipe for canal house buttermilk sangria | put four warm water in a shaker - glass jar . freeze until cold , until cold , about 4 hours . strain compote through a sieve into a strainer and drain in a bowl . stir sugar with a fork in a bowl and divide between bright eight 5 - cup , about 5 minutes , scraping up any sugar crystals on back of spoon , until incorporated . discard solids in simmering cream ; swirl berries into bowl . serve chilled or chilled or ice . peel and 2 whole in\n",
925 | "\n",
926 | "629/629 [==============================] - 32s 51ms/step - loss: 1.6039\n",
927 | "Epoch 20/25\n",
928 | "628/629 [============================>.] - ETA: 0s - loss: 1.5908\n",
929 | "생성된 텍스트:\n",
930 | "recipe for grasshopper ice cream with cherry coffee cream | lightly vanilla butter and flour in a small saucepan over medium heat , swirling , heat until just hold an instant - read thermometer registers 240°f . transfer custard to a large basket , stirring and cool mixture to break up mixture . strain mixture and discard solids over as much liquid as possible . then discard solids in soaking smooth . ( sauce is chill , covered and chilled , or freeze in same manner . ) preheat oven to 400° f . generously brush pie dish with melted\n",
931 | "\n",
932 | "629/629 [==============================] - 32s 51ms/step - loss: 1.5906\n",
933 | "Epoch 21/25\n",
934 | "628/629 [============================>.] - ETA: 0s - loss: 1.5784\n",
935 | "생성된 텍스트:\n",
936 | "recipe for lamb kebabs with tomatoes and mushrooms | preheat oven to preheat to 400°f . combine potatoes , chile , fennel fronds , cumin , and ginger in large bowl . add 3 quarts flour , butter , beet , mustard , cumin , nutmeg , salt , pepper , and cayenne in small bowl ; toss to coat ; place on roasting pan . add cheese and cornflake crumb rub . make pork chops evenly coat with 13 sage ; spread out on prepared baking sheet . bake bread until almost all fries in center , about 35\n",
937 | "\n",
938 | "629/629 [==============================] - 32s 51ms/step - loss: 1.5783\n",
939 | "Epoch 22/25\n",
940 | "629/629 [==============================] - ETA: 0s - loss: 1.5667\n",
941 | "생성된 텍스트:\n",
942 | "recipe for ratatouille and croutons | whisk oil and soy sauce in a large bowl using a light brown and lemon powder . when a thick enough lime juice is cooking juices slightly , and if desired sift into a small serving dish . divide melon among plates and sprinkle with additional mint curls . \n",
943 | "\n",
944 | "629/629 [==============================] - 29s 46ms/step - loss: 1.5667\n",
945 | "Epoch 23/25\n",
946 | "628/629 [============================>.] - ETA: 0s - loss: 1.5556\n",
947 | "생성된 텍스트:\n",
948 | "recipe for curried spinach puddings with sun - dried tomato , bacon , and macadamia nuts | preheat oven to 350°f . spray large rimmed baking sheet with nonstick spray . lightly coat 6 large rimmed baking sheets with nonstick spray . transfer to oven ; let filling against , cutting - cup crust from turkey . arrange 2 wonton tenderloin over spinach ; brush with maple marinade . melt butter in prepared dish . sprinkle with salt and pepper . working in batches , loosen skin side of both sides . repeat with second batch is lightly . mix\n",
949 | "\n",
950 | "629/629 [==============================] - 33s 52ms/step - loss: 1.5558\n",
951 | "Epoch 24/25\n",
952 | "628/629 [============================>.] - ETA: 0s - loss: 1.5455\n",
953 | "생성된 텍스트:\n",
954 | "recipe for lebkuchen spice bars blend | using a fork , grate in a food processor ; pulse until fragrant . dip out dough hook and let dough rise chill in an ice cream maker , then with an ice cream ice cream . break off yolks and serve with ice water . \n",
955 | "\n",
956 | "629/629 [==============================] - 29s 47ms/step - loss: 1.5456\n",
957 | "Epoch 25/25\n",
958 | "629/629 [==============================] - ETA: 0s - loss: 1.5359\n",
959 | "생성된 텍스트:\n",
960 | "recipe for lemon ribbon sandwich | stir the almonds in a 4 - quart saucepan and cook over medium - low heat , stirring occasionally , until the sauce boils . remove from heat and stir vigorously frequently with another hot water ( do not simply store refrigerated ) , covered . cover and chill 30 minutes . 3 . remove the leaves from the refrigerator for a week ; let stand 1 hour . you may want to place in the bowl of a smooth emulsion spoon into each glass . drizzle with 3 tablespoons ice water and process\n",
961 | "\n",
962 | "629/629 [==============================] - 33s 52ms/step - loss: 1.5359\n"
963 | ]
964 | },
965 | {
966 | "output_type": "execute_result",
967 | "data": {
968 | "text/plain": [
969 | ""
970 | ]
971 | },
972 | "metadata": {},
973 | "execution_count": 28
974 | }
975 | ],
976 | "source": [
977 | "lstm.fit(\n",
978 | " train_ds,\n",
979 | " epochs=EPOCHS,\n",
980 | " callbacks=[model_checkpoint_callback, tensorboard_callback, text_generator],\n",
981 | ")"
982 | ]
983 | },
984 | {
985 | "cell_type": "code",
986 | "execution_count": 29,
987 | "id": "369bde44-2e39-4bc6-8549-a3a27ecce55c",
988 | "metadata": {
989 | "tags": [],
990 | "id": "369bde44-2e39-4bc6-8549-a3a27ecce55c"
991 | },
992 | "outputs": [],
993 | "source": [
994 | "# 최종 모델 저장\n",
995 | "lstm.save(\"./models/lstm\")"
996 | ]
997 | },
998 | {
999 | "cell_type": "markdown",
1000 | "id": "d64e02d2-84dc-40c8-8446-40c09adf1e20",
1001 | "metadata": {
1002 | "id": "d64e02d2-84dc-40c8-8446-40c09adf1e20"
1003 | },
1004 | "source": [
1005 | "## 6. LSTM을 사용해 텍스트 생성하기"
1006 | ]
1007 | },
1008 | {
1009 | "cell_type": "code",
1010 | "execution_count": 30,
1011 | "id": "4ad23adb-3ec9-4e9a-9a59-b9f9bafca649",
1012 | "metadata": {
1013 | "id": "4ad23adb-3ec9-4e9a-9a59-b9f9bafca649"
1014 | },
1015 | "outputs": [],
1016 | "source": [
1017 | "def print_probs(info, vocab, top_k=5):\n",
1018 | " for i in info:\n",
1019 | " print(f\"\\n프롬프트: {i['prompt']}\")\n",
1020 | " word_probs = i[\"word_probs\"]\n",
1021 | " p_sorted = np.sort(word_probs)[::-1][:top_k]\n",
1022 | " i_sorted = np.argsort(word_probs)[::-1][:top_k]\n",
1023 | " for p, i in zip(p_sorted, i_sorted):\n",
1024 | " print(f\"{vocab[i]}: \\t{np.round(100*p,2)}%\")\n",
1025 | " print(\"--------\\n\")"
1026 | ]
1027 | },
1028 | {
1029 | "cell_type": "code",
1030 | "execution_count": 31,
1031 | "id": "3cf25578-d47c-4b26-8252-fcdf2316a4ac",
1032 | "metadata": {
1033 | "id": "3cf25578-d47c-4b26-8252-fcdf2316a4ac",
1034 | "outputId": "a0bff77e-69fd-481e-ad67-365a1c3cbc48",
1035 | "colab": {
1036 | "base_uri": "https://localhost:8080/"
1037 | }
1038 | },
1039 | "outputs": [
1040 | {
1041 | "output_type": "stream",
1042 | "name": "stdout",
1043 | "text": [
1044 | "\n",
1045 | "생성된 텍스트:\n",
1046 | "recipe for roasted vegetables | chop 1 / 3 of\n",
1047 | "\n"
1048 | ]
1049 | }
1050 | ],
1051 | "source": [
1052 | "info = text_generator.generate(\n",
1053 | " \"recipe for roasted vegetables | chop 1 /\", max_tokens=10, temperature=1.0\n",
1054 | ")"
1055 | ]
1056 | },
1057 | {
1058 | "cell_type": "code",
1059 | "execution_count": 32,
1060 | "id": "9df72866-b483-4489-8e26-d5e1466410fa",
1061 | "metadata": {
1062 | "tags": [],
1063 | "id": "9df72866-b483-4489-8e26-d5e1466410fa",
1064 | "outputId": "88bfc6d8-f838-4cdd-b68d-22f0574b06a8",
1065 | "colab": {
1066 | "base_uri": "https://localhost:8080/"
1067 | }
1068 | },
1069 | "outputs": [
1070 | {
1071 | "output_type": "stream",
1072 | "name": "stdout",
1073 | "text": [
1074 | "\n",
1075 | "프롬프트: recipe for roasted vegetables | chop 1 /\n",
1076 | "4: \t49.99%\n",
1077 | "2: \t33.33%\n",
1078 | "3: \t10.37%\n",
1079 | "8: \t5.13%\n",
1080 | "6: \t0.18%\n",
1081 | "--------\n",
1082 | "\n",
1083 | "\n",
1084 | "프롬프트: recipe for roasted vegetables | chop 1 / 3\n",
1085 | "cup: \t63.37%\n",
1086 | "of: \t16.55%\n",
1087 | "-: \t3.26%\n",
1088 | "inch: \t2.62%\n",
1089 | "teaspoon: \t1.79%\n",
1090 | "--------\n",
1091 | "\n"
1092 | ]
1093 | }
1094 | ],
1095 | "source": [
1096 | "print_probs(info, vocab)"
1097 | ]
1098 | },
1099 | {
1100 | "cell_type": "code",
1101 | "execution_count": 33,
1102 | "id": "562e1fe8-cbcb-438f-9637-2f2a6279c924",
1103 | "metadata": {
1104 | "id": "562e1fe8-cbcb-438f-9637-2f2a6279c924",
1105 | "outputId": "6538dfbc-8692-4c4d-d110-51e75ff87175",
1106 | "colab": {
1107 | "base_uri": "https://localhost:8080/"
1108 | }
1109 | },
1110 | "outputs": [
1111 | {
1112 | "output_type": "stream",
1113 | "name": "stdout",
1114 | "text": [
1115 | "\n",
1116 | "생성된 텍스트:\n",
1117 | "recipe for roasted vegetables | chop 1 / 4 cup\n",
1118 | "\n"
1119 | ]
1120 | }
1121 | ],
1122 | "source": [
1123 | "info = text_generator.generate(\n",
1124 | " \"recipe for roasted vegetables | chop 1 /\", max_tokens=10, temperature=0.2\n",
1125 | ")"
1126 | ]
1127 | },
1128 | {
1129 | "cell_type": "code",
1130 | "execution_count": 34,
1131 | "id": "56356f21-04ac-40e5-94ff-291eca6a7054",
1132 | "metadata": {
1133 | "id": "56356f21-04ac-40e5-94ff-291eca6a7054",
1134 | "outputId": "e3d179c3-69a2-4206-bf85-f02a80509c55",
1135 | "colab": {
1136 | "base_uri": "https://localhost:8080/"
1137 | }
1138 | },
1139 | "outputs": [
1140 | {
1141 | "output_type": "stream",
1142 | "name": "stdout",
1143 | "text": [
1144 | "\n",
1145 | "프롬프트: recipe for roasted vegetables | chop 1 /\n",
1146 | "4: \t88.33%\n",
1147 | "2: \t11.64%\n",
1148 | "3: \t0.03%\n",
1149 | "8: \t0.0%\n",
1150 | "6: \t0.0%\n",
1151 | "--------\n",
1152 | "\n",
1153 | "\n",
1154 | "프롬프트: recipe for roasted vegetables | chop 1 / 4\n",
1155 | "cup: \t99.98%\n",
1156 | "inch: \t0.01%\n",
1157 | "teaspoon: \t0.01%\n",
1158 | "of: \t0.0%\n",
1159 | "-: \t0.0%\n",
1160 | "--------\n",
1161 | "\n"
1162 | ]
1163 | }
1164 | ],
1165 | "source": [
1166 | "print_probs(info, vocab)"
1167 | ]
1168 | },
1169 | {
1170 | "cell_type": "code",
1171 | "execution_count": 35,
1172 | "id": "2e434497-07f3-4989-a68d-3e31cf8fa4fe",
1173 | "metadata": {
1174 | "id": "2e434497-07f3-4989-a68d-3e31cf8fa4fe",
1175 | "outputId": "8bf7d28d-931d-43f3-b5ba-d3cd7b0522a1",
1176 | "colab": {
1177 | "base_uri": "https://localhost:8080/"
1178 | }
1179 | },
1180 | "outputs": [
1181 | {
1182 | "output_type": "stream",
1183 | "name": "stdout",
1184 | "text": [
1185 | "\n",
1186 | "생성된 텍스트:\n",
1187 | "recipe for chocolate ice cream | arrange\n",
1188 | "\n",
1189 | "\n",
1190 | "프롬프트: recipe for chocolate ice cream |\n",
1191 | "bring: \t21.03%\n",
1192 | "in: \t13.42%\n",
1193 | "combine: \t10.56%\n",
1194 | "whisk: \t7.58%\n",
1195 | "stir: \t4.96%\n",
1196 | "--------\n",
1197 | "\n"
1198 | ]
1199 | }
1200 | ],
1201 | "source": [
1202 | "info = text_generator.generate(\n",
1203 | " \"recipe for chocolate ice cream |\", max_tokens=7, temperature=1.0\n",
1204 | ")\n",
1205 | "print_probs(info, vocab)"
1206 | ]
1207 | },
1208 | {
1209 | "cell_type": "code",
1210 | "execution_count": 36,
1211 | "id": "011cd0e0-956c-4a63-8ec3-f7dfed31764e",
1212 | "metadata": {
1213 | "id": "011cd0e0-956c-4a63-8ec3-f7dfed31764e",
1214 | "outputId": "70df0595-39c4-4107-c202-da5e41aaa90c",
1215 | "colab": {
1216 | "base_uri": "https://localhost:8080/"
1217 | }
1218 | },
1219 | "outputs": [
1220 | {
1221 | "output_type": "stream",
1222 | "name": "stdout",
1223 | "text": [
1224 | "\n",
1225 | "생성된 텍스트:\n",
1226 | "recipe for chocolate ice cream | bring\n",
1227 | "\n",
1228 | "\n",
1229 | "프롬프트: recipe for chocolate ice cream |\n",
1230 | "bring: \t87.32%\n",
1231 | "in: \t9.23%\n",
1232 | "combine: \t2.79%\n",
1233 | "whisk: \t0.53%\n",
1234 | "stir: \t0.06%\n",
1235 | "--------\n",
1236 | "\n"
1237 | ]
1238 | }
1239 | ],
1240 | "source": [
1241 | "info = text_generator.generate(\n",
1242 | " \"recipe for chocolate ice cream |\", max_tokens=7, temperature=0.2\n",
1243 | ")\n",
1244 | "print_probs(info, vocab)"
1245 | ]
1246 | }
1247 | ],
1248 | "metadata": {
1249 | "kernelspec": {
1250 | "display_name": "Python 3 (ipykernel)",
1251 | "language": "python",
1252 | "name": "python3"
1253 | },
1254 | "language_info": {
1255 | "codemirror_mode": {
1256 | "name": "ipython",
1257 | "version": 3
1258 | },
1259 | "file_extension": ".py",
1260 | "mimetype": "text/x-python",
1261 | "name": "python",
1262 | "nbconvert_exporter": "python",
1263 | "pygments_lexer": "ipython3",
1264 | "version": "3.8.2"
1265 | },
1266 | "colab": {
1267 | "provenance": [],
1268 | "gpuType": "T4"
1269 | },
1270 | "accelerator": "GPU",
1271 | "gpuClass": "standard"
1272 | },
1273 | "nbformat": 4,
1274 | "nbformat_minor": 5
1275 | }
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/01_lstm/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/01_lstm/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/02_pixelcnn/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/02_pixelcnn/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/02_pixelcnn/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/02_pixelcnn/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/03_pixelcnn_md/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/03_pixelcnn_md/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/03_pixelcnn_md/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/05_autoregressive/03_pixelcnn_md/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/06_normflow/01_realnvp/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/06_normflow/01_realnvp/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/06_normflow/01_realnvp/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/06_normflow/01_realnvp/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/07_ebm/01_ebm/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/07_ebm/01_ebm/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/07_ebm/01_ebm/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/07_ebm/01_ebm/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/08_diffusion/01_ddm/checkpoint/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/08_diffusion/01_ddm/logs/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/08_diffusion/01_ddm/models/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/08_diffusion/01_ddm/output/.gitignore:
--------------------------------------------------------------------------------
1 | *
2 | !.gitignore
--------------------------------------------------------------------------------
/notebooks/08_diffusion/01_ddm/sinusoidal_embedding.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "ae9aa013",
6 | "metadata": {
7 | "id": "ae9aa013"
8 | },
9 | "source": [
10 | "# 🌀 사인파 임베딩"
11 | ]
12 | },
13 | {
14 | "cell_type": "markdown",
15 | "id": "810064e1",
16 | "metadata": {
17 | "id": "810064e1"
18 | },
19 | "source": [
20 | "