├── .gitignore ├── Hyper Parameter Tuning Ode to Warhol.ipynb ├── LICENSE ├── Movie_Recommendations.ipynb ├── README.md └── Style_Transfer_Interpolation.ipynb /.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 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Movie_Recommendations.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "deletable": true, 7 | "editable": true 8 | }, 9 | "source": [ 10 | "# Movie Recommendations based Wikilinks\n", 11 | "\n", 12 | "Movie recommendation systems are usually based on ratings. The code below though only looks at links from the wikipedia pages of movies. The intuition here is that movies that are similar, will link to similar entities. This could be style, actors, directors or time periods.\n", 13 | "\n", 14 | "We train an embedding model that tries to predict whether two movies both link to an entity or not. We can then use the resulting embedding vectors to find nearest neighbors and create something that says, if you like this movie, try out also that movie." 15 | ] 16 | }, 17 | { 18 | "cell_type": "markdown", 19 | "metadata": { 20 | "deletable": true, 21 | "editable": true 22 | }, 23 | "source": [ 24 | "First start with a bunch of imports:" 25 | ] 26 | }, 27 | { 28 | "cell_type": "code", 29 | "execution_count": 1, 30 | "metadata": { 31 | "collapsed": false, 32 | "deletable": true, 33 | "editable": true 34 | }, 35 | "outputs": [ 36 | { 37 | "name": "stderr", 38 | "output_type": "stream", 39 | "text": [ 40 | "Using TensorFlow backend.\n" 41 | ] 42 | } 43 | ], 44 | "source": [ 45 | "%matplotlib inline\n", 46 | "\n", 47 | "import os\n", 48 | "import numpy as np\n", 49 | "\n", 50 | "import psycopg2\n", 51 | "import psycopg2.extras\n", 52 | "from itertools import chain\n", 53 | "from collections import Counter, defaultdict\n", 54 | "import requests\n", 55 | "import imageio\n", 56 | "\n", 57 | "import matplotlib.pyplot as plt\n", 58 | "import numpy as np\n", 59 | "from PIL import Image, ImageDraw\n", 60 | "from io import BytesIO\n", 61 | "from hashlib import md5\n", 62 | "from IPython.display import display, HTML\n", 63 | "\n", 64 | "from itertools import chain\n", 65 | "import mwparserfromhell\n", 66 | "\n", 67 | "from keras.models import Model\n", 68 | "from keras.layers import Embedding, Dense, Input, Lambda, Reshape, merge\n", 69 | "import keras.backend as K\n", 70 | "from keras.layers.merge import Dot\n", 71 | "\n", 72 | "from sklearn.manifold import TSNE" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": { 78 | "deletable": true, 79 | "editable": true 80 | }, 81 | "source": [ 82 | "The fetch_image function below fetches an image from wikipedia given a wikipedia id for that image:" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 2, 88 | "metadata": { 89 | "collapsed": false, 90 | "deletable": true, 91 | "editable": true 92 | }, 93 | "outputs": [ 94 | { 95 | "data": { 96 | "text/plain": [ 97 | "'Suicide_Squad_(film)_Poster.png'" 98 | ] 99 | }, 100 | "execution_count": 2, 101 | "metadata": {}, 102 | "output_type": "execute_result" 103 | } 104 | ], 105 | "source": [ 106 | "IMAGE_PATH_EN = 'http://upload.wikimedia.org/wikipedia/en/%s/%s/%s'\n", 107 | "IMAGE_PATH_COMMONS = 'http://upload.wikimedia.org/wikipedia/commons/%s/%s/%s'\n", 108 | "image_cache = 'movie_images'\n", 109 | "\n", 110 | "def fetch_image(image_name):\n", 111 | " if not image_name or image_name.endswith('.tiff'):\n", 112 | " return None\n", 113 | " image_name = image_name.replace(' ', '_')\n", 114 | " if image_name[0].upper() != image_name[0]:\n", 115 | " image_name = image_name.capitalize()\n", 116 | " file_path = os.path.join(image_cache, image_name)\n", 117 | " if os.path.isfile(file_path):\n", 118 | " return image_name\n", 119 | " else:\n", 120 | " m = md5()\n", 121 | " m.update(image_name.encode('utf-8'))\n", 122 | " c = m.hexdigest()\n", 123 | " path = IMAGE_PATH_EN % (c[0], c[0:2], image_name)\n", 124 | " r = requests.get(path)\n", 125 | " if r.status_code == 404:\n", 126 | " path = IMAGE_PATH_COMMONS % (c[0], c[0:2], image_name)\n", 127 | " r = requests.get(path)\n", 128 | " if r.status_code == 404:\n", 129 | " print image_name\n", 130 | " return None\n", 131 | " try:\n", 132 | " image = Image.open(BytesIO(r.content))\n", 133 | " except IOError:\n", 134 | " return None\n", 135 | " except ValueError:\n", 136 | " return None\n", 137 | " image.save(file(file_path, 'w'))\n", 138 | " image.thumbnail((240, 640), Image.ANTIALIAS)\n", 139 | " res = BytesIO()\n", 140 | " if image.mode == 'P':\n", 141 | " image = image.convert('RGB')\n", 142 | " try:\n", 143 | " image.save(res, 'WEBP', quality=15)\n", 144 | " except IOError as err:\n", 145 | " print image_name, err.message\n", 146 | " return None\n", 147 | " return image_name\n", 148 | "\n", 149 | "fetch_image('Suicide Squad (film) Poster.png')" 150 | ] 151 | }, 152 | { 153 | "cell_type": "markdown", 154 | "metadata": { 155 | "deletable": true, 156 | "editable": true 157 | }, 158 | "source": [ 159 | "The code here relies on wikipedia having been imported into Postgres using [Wiki Import](https://github.com/DOsinga/wiki_import). So we setup a connection to postgres, fetch the 10000 most popular movies and then extract for each the movie name, the image for the movie and the outgoing links from that page" 160 | ] 161 | }, 162 | { 163 | "cell_type": "code", 164 | "execution_count": 3, 165 | "metadata": { 166 | "collapsed": false, 167 | "deletable": true, 168 | "editable": true 169 | }, 170 | "outputs": [], 171 | "source": [ 172 | "postgres_conn = psycopg2.connect('dbname=douwe user=notebook')\n", 173 | "postgres_cursor = postgres_conn.cursor(cursor_factory=psycopg2.extras.DictCursor)" 174 | ] 175 | }, 176 | { 177 | "cell_type": "code", 178 | "execution_count": 4, 179 | "metadata": { 180 | "collapsed": false, 181 | "deletable": true, 182 | "editable": true 183 | }, 184 | "outputs": [ 185 | { 186 | "name": "stdout", 187 | "output_type": "stream", 188 | "text": [ 189 | "Getting top movies...\n", 190 | "done\n" 191 | ] 192 | } 193 | ], 194 | "source": [ 195 | "print 'Getting top movies...'\n", 196 | "postgres_cursor.execute(\n", 197 | " \"SELECT wikipedia.*, wikistats.viewcount FROM wikipedia \"\n", 198 | " \"JOIN wikistats ON wikipedia.title = wikistats.title WHERE wikipedia.infobox = 'film' \"\n", 199 | " \"ORDER BY wikistats.viewcount DESC limit 10000\"\n", 200 | ")\n", 201 | "print 'done'" 202 | ] 203 | }, 204 | { 205 | "cell_type": "code", 206 | "execution_count": 5, 207 | "metadata": { 208 | "collapsed": false, 209 | "deletable": true, 210 | "editable": true 211 | }, 212 | "outputs": [ 213 | { 214 | "name": "stdout", 215 | "output_type": "stream", 216 | "text": [ 217 | "Veyil4.jpg\n" 218 | ] 219 | }, 220 | { 221 | "data": { 222 | "text/plain": [ 223 | "10000" 224 | ] 225 | }, 226 | "execution_count": 5, 227 | "metadata": {}, 228 | "output_type": "execute_result" 229 | } 230 | ], 231 | "source": [ 232 | "movies = []\n", 233 | "for movie in postgres_cursor:\n", 234 | " wikicode = mwparserfromhell.parse(movie['wikitext'])\n", 235 | " image = None\n", 236 | " for template in wikicode.filter_templates():\n", 237 | " if template.name.lower().startswith('infobox '):\n", 238 | " for param in template.params:\n", 239 | " key = param.name.strip()\n", 240 | " if key == 'image':\n", 241 | " image = param.value.strip()\n", 242 | " break\n", 243 | " if image:\n", 244 | " image_name = fetch_image(image)\n", 245 | " movies.append((movie['title'], image_name, [unicode(x.title) for x in wikicode.filter_wikilinks()], movie['viewcount']))\n", 246 | "\n", 247 | "len(movies)\n" 248 | ] 249 | }, 250 | { 251 | "cell_type": "markdown", 252 | "metadata": { 253 | "deletable": true, 254 | "editable": true 255 | }, 256 | "source": [ 257 | "Now that we have all the movies, extract all the outgoing links (refs) and keep the ones that are used more than once." 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": 6, 263 | "metadata": { 264 | "collapsed": false, 265 | "deletable": true, 266 | "editable": true 267 | }, 268 | "outputs": [ 269 | { 270 | "data": { 271 | "text/plain": [ 272 | "(101797, 218227)" 273 | ] 274 | }, 275 | "execution_count": 6, 276 | "metadata": {}, 277 | "output_type": "execute_result" 278 | } 279 | ], 280 | "source": [ 281 | "ref_counts = Counter()\n", 282 | "for _, _, refs, _ in movies:\n", 283 | " ref_counts.update(refs)\n", 284 | "all_refs = [ref for ref, count in ref_counts.items() if count > 1]\n", 285 | "ref_to_id = {ref: idx for idx, ref in enumerate(all_refs)}\n", 286 | "movie_to_id = {title: idx for idx, (title, _, _, _) in enumerate(movies)}\n", 287 | "len(all_refs), len(ref_counts)\n" 288 | ] 289 | }, 290 | { 291 | "cell_type": "markdown", 292 | "metadata": { 293 | "deletable": true, 294 | "editable": true 295 | }, 296 | "source": [ 297 | "Now createthe refs_movie structure that holds for each ref, the movies that refer to it:" 298 | ] 299 | }, 300 | { 301 | "cell_type": "code", 302 | "execution_count": 7, 303 | "metadata": { 304 | "collapsed": false, 305 | "deletable": true, 306 | "editable": true 307 | }, 308 | "outputs": [ 309 | { 310 | "data": { 311 | "text/plain": [ 312 | "101796" 313 | ] 314 | }, 315 | "execution_count": 7, 316 | "metadata": {}, 317 | "output_type": "execute_result" 318 | } 319 | ], 320 | "source": [ 321 | "refs_movies = defaultdict(list)\n", 322 | "for movie, image, refs, viewcounts in movies:\n", 323 | " movie_id = movie_to_id[movie]\n", 324 | " for ref in refs:\n", 325 | " ref_id = ref_to_id.get(ref)\n", 326 | " if ref_id:\n", 327 | " refs_movies[ref_id].append(movie_id)\n", 328 | "refs_movies = list(refs_movies.items())\n", 329 | "len(refs_movies)" 330 | ] 331 | }, 332 | { 333 | "cell_type": "markdown", 334 | "metadata": { 335 | "deletable": true, 336 | "editable": true 337 | }, 338 | "source": [ 339 | "We now construct a generator that yields tupels that encode whether or not two movies link to the same entity. (The generator can also be used with yield_movie_pairs=False to get movie/entity pairs). +1 indicates co-occurance, -1 indicates non occurance:" 340 | ] 341 | }, 342 | { 343 | "cell_type": "code", 344 | "execution_count": 8, 345 | "metadata": { 346 | "collapsed": false, 347 | "deletable": true, 348 | "editable": true 349 | }, 350 | "outputs": [ 351 | { 352 | "data": { 353 | "text/plain": [ 354 | "({'first': array([8597, 8597, 8597, 8597, 8597, 8597, 145, 145, 145, 145, 145]),\n", 355 | " 'second': array([8704, 1377, 405, 3232, 7740, 6794, 245, 4028, 8469, 9101, 9537])},\n", 356 | " array([ 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1]))" 357 | ] 358 | }, 359 | "execution_count": 8, 360 | "metadata": {}, 361 | "output_type": "execute_result" 362 | } 363 | ], 364 | "source": [ 365 | "import random\n", 366 | "random.seed(5)\n", 367 | "\n", 368 | "def data_generator(refs_movies, negative_ratio=5, yield_movie_pairs=True):\n", 369 | " random.shuffle(refs_movies)\n", 370 | " for ref, movies in refs_movies:\n", 371 | " if yield_movie_pairs:\n", 372 | " if len(movies) < 2: continue\n", 373 | " a, b = random.sample(movies, 2)\n", 374 | " else:\n", 375 | " a = ref\n", 376 | " b = random.choice(movies)\n", 377 | " yield a, b, 1\n", 378 | "\n", 379 | " seen = set(movies)\n", 380 | " left = negative_ratio\n", 381 | " while left > 0:\n", 382 | " n = random.randrange(len(movie_to_id))\n", 383 | " if not n in seen:\n", 384 | " left -= 1\n", 385 | " seen.add(n)\n", 386 | " yield a, n, -1\n", 387 | "\n", 388 | "\n", 389 | "def batchify(gen, batch_size):\n", 390 | " ax, bx, lx = [], [], []\n", 391 | " while True:\n", 392 | " for a, b, label in gen():\n", 393 | " ax.append(a)\n", 394 | " bx.append(b)\n", 395 | " lx.append(label)\n", 396 | " if len(ax) > batch_size:\n", 397 | " yield { 'first': np.asarray(ax), 'second': np.asarray(bx)}, np.asarray(lx)\n", 398 | " del ax[:]\n", 399 | " del bx[:]\n", 400 | " del lx[:]\n", 401 | "\n", 402 | "next(batchify(lambda: data_generator(refs_movies), batch_size=10))" 403 | ] 404 | }, 405 | { 406 | "cell_type": "markdown", 407 | "metadata": { 408 | "deletable": true, 409 | "editable": true 410 | }, 411 | "source": [ 412 | "The model itself is fairly straightforward:" 413 | ] 414 | }, 415 | { 416 | "cell_type": "code", 417 | "execution_count": 9, 418 | "metadata": { 419 | "collapsed": false, 420 | "deletable": true, 421 | "editable": true 422 | }, 423 | "outputs": [ 424 | { 425 | "name": "stderr", 426 | "output_type": "stream", 427 | "text": [ 428 | "/home/notebook/notebook/venv2/lib/python2.7/site-packages/ipykernel/__main__.py:8: UserWarning: The `merge` function is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc.\n", 429 | "/home/notebook/notebook/venv2/local/lib/python2.7/site-packages/keras/legacy/layers.py:456: UserWarning: The `Merge` layer is deprecated and will be removed after 08/2017. Use instead layers from `keras.layers.merge`, e.g. `add`, `concatenate`, etc.\n", 430 | " name=name)\n" 431 | ] 432 | } 433 | ], 434 | "source": [ 435 | "N = 20\n", 436 | "\n", 437 | "def model_simple():\n", 438 | " src = Input(name='first', shape=(1,))\n", 439 | " dst = Input(name='second', shape=(1,))\n", 440 | " src_embedding = Embedding(name='src_embedding', input_dim=len(movie_to_id), output_dim=N)(src)\n", 441 | " dst_embedding = Embedding(name='dst_embedding', input_dim=len(movie_to_id), output_dim=N)(dst)\n", 442 | " dot = merge([src_embedding, dst_embedding], mode='cos')\n", 443 | " dot = Reshape((1,))(dot)\n", 444 | " model = Model(inputs=[src, dst], outputs=[dot])\n", 445 | " model.compile(optimizer='nadam', loss='mse')\n", 446 | " return model\n", 447 | "\n", 448 | "model = model_simple()" 449 | ] 450 | }, 451 | { 452 | "cell_type": "markdown", 453 | "metadata": { 454 | "deletable": true, 455 | "editable": true 456 | }, 457 | "source": [ 458 | "It converges quite quickly too. The achieved loss isn't super impressive - 0.4 or so:" 459 | ] 460 | }, 461 | { 462 | "cell_type": "code", 463 | "execution_count": 10, 464 | "metadata": { 465 | "collapsed": false, 466 | "deletable": true, 467 | "editable": true 468 | }, 469 | "outputs": [ 470 | { 471 | "name": "stdout", 472 | "output_type": "stream", 473 | "text": [ 474 | "Epoch 1/25\n", 475 | "24s - loss: 0.5171\n", 476 | "Epoch 2/25\n", 477 | "24s - loss: 0.4338\n", 478 | "Epoch 3/25\n", 479 | "24s - loss: 0.4276\n", 480 | "Epoch 4/25\n", 481 | "24s - loss: 0.4248\n", 482 | "Epoch 5/25\n", 483 | "24s - loss: 0.4230\n", 484 | "Epoch 6/25\n", 485 | "24s - loss: 0.4218\n", 486 | "Epoch 7/25\n", 487 | "24s - loss: 0.4209\n", 488 | "Epoch 8/25\n", 489 | "24s - loss: 0.4203\n", 490 | "Epoch 9/25\n", 491 | "24s - loss: 0.4197\n", 492 | "Epoch 10/25\n", 493 | "24s - loss: 0.4192\n", 494 | "Epoch 11/25\n", 495 | "24s - loss: 0.4189\n", 496 | "Epoch 12/25\n", 497 | "24s - loss: 0.4184\n", 498 | "Epoch 13/25\n", 499 | "24s - loss: 0.4183\n", 500 | "Epoch 14/25\n", 501 | "24s - loss: 0.4180\n", 502 | "Epoch 15/25\n", 503 | "24s - loss: 0.4178\n", 504 | "Epoch 16/25\n", 505 | "24s - loss: 0.4177\n", 506 | "Epoch 17/25\n", 507 | "24s - loss: 0.4174\n", 508 | "Epoch 18/25\n", 509 | "24s - loss: 0.4173\n", 510 | "Epoch 19/25\n", 511 | "24s - loss: 0.4172\n", 512 | "Epoch 20/25\n", 513 | "24s - loss: 0.4170\n", 514 | "Epoch 21/25\n", 515 | "24s - loss: 0.4169\n", 516 | "Epoch 22/25\n", 517 | "24s - loss: 0.4170\n", 518 | "Epoch 23/25\n", 519 | "24s - loss: 0.4167\n", 520 | "Epoch 24/25\n", 521 | "24s - loss: 0.4167\n", 522 | "Epoch 25/25\n", 523 | "24s - loss: 0.4166\n" 524 | ] 525 | }, 526 | { 527 | "data": { 528 | "text/plain": [ 529 | "" 530 | ] 531 | }, 532 | "execution_count": 10, 533 | "metadata": {}, 534 | "output_type": "execute_result" 535 | } 536 | ], 537 | "source": [ 538 | "model.fit_generator(\n", 539 | " batchify(lambda: data_generator(refs_movies, yield_movie_pairs=True), 2048),\n", 540 | " epochs=25,\n", 541 | " steps_per_epoch=3500,\n", 542 | " verbose=2\n", 543 | ")" 544 | ] 545 | }, 546 | { 547 | "cell_type": "markdown", 548 | "metadata": { 549 | "deletable": true, 550 | "editable": true 551 | }, 552 | "source": [ 553 | "Extract the weights for the movie embeddings:" 554 | ] 555 | }, 556 | { 557 | "cell_type": "code", 558 | "execution_count": 11, 559 | "metadata": { 560 | "collapsed": false, 561 | "deletable": true, 562 | "editable": true 563 | }, 564 | "outputs": [ 565 | { 566 | "data": { 567 | "text/plain": [ 568 | "(1.0, (10000, 20))" 569 | ] 570 | }, 571 | "execution_count": 11, 572 | "metadata": {}, 573 | "output_type": "execute_result" 574 | } 575 | ], 576 | "source": [ 577 | "src = model.get_layer('src_embedding')\n", 578 | "src_weights = src.get_weights()[0]\n", 579 | "lens = np.linalg.norm(src_weights, axis=1)\n", 580 | "normalized = (src_weights.T / lens).T\n", 581 | "np.linalg.norm(normalized[0]), normalized.shape" 582 | ] 583 | }, 584 | { 585 | "cell_type": "markdown", 586 | "metadata": { 587 | "deletable": true, 588 | "editable": true 589 | }, 590 | "source": [ 591 | "Test whether it works by looking for \"star wars\" related movies." 592 | ] 593 | }, 594 | { 595 | "cell_type": "code", 596 | "execution_count": 12, 597 | "metadata": { 598 | "collapsed": false, 599 | "deletable": true, 600 | "editable": true 601 | }, 602 | "outputs": [ 603 | { 604 | "name": "stdout", 605 | "output_type": "stream", 606 | "text": [ 607 | "(6444, 'Return of the Ewok', 0.95703477)\n", 608 | "(683, 'Superman (1978 film)', 0.95719445)\n", 609 | "(9456, 'Doppelg\\xc3\\xa4nger (1969 film)', 0.95741284)\n", 610 | "(4145, 'Dragonslayer', 0.96169114)\n", 611 | "(639, 'Indiana Jones and the Temple of Doom', 0.9632467)\n", 612 | "(141, 'Alien (film)', 0.96762782)\n", 613 | "(303, 'Raiders of the Lost Ark', 0.98218834)\n", 614 | "(44, 'Return of the Jedi', 0.98419368)\n", 615 | "(74, 'The Empire Strikes Back', 0.98707592)\n", 616 | "(18, 'Star Wars (film)', 0.99999988)\n" 617 | ] 618 | } 619 | ], 620 | "source": [ 621 | "def neighbors(movie):\n", 622 | " dists = np.dot(normalized, normalized[movie_to_id[movie]])\n", 623 | " closest = np.argsort(dists)[-10:]\n", 624 | " for c in closest:\n", 625 | " print(c, movies[c][0], dists[c])\n", 626 | "\n", 627 | "neighbors('Star Wars (film)')" 628 | ] 629 | }, 630 | { 631 | "cell_type": "markdown", 632 | "metadata": { 633 | "deletable": true, 634 | "editable": true 635 | }, 636 | "source": [ 637 | "Another way to explore the data is by using TSNE to group the movies on a two dimensional grid. " 638 | ] 639 | }, 640 | { 641 | "cell_type": "code", 642 | "execution_count": 13, 643 | "metadata": { 644 | "collapsed": false, 645 | "deletable": true, 646 | "editable": true 647 | }, 648 | "outputs": [ 649 | { 650 | "data": { 651 | "text/plain": [ 652 | "array([[ 3.04852687, -1.84250886],\n", 653 | " [ 5.80860702, -2.40014016],\n", 654 | " [ 3.10556136, -1.96007714],\n", 655 | " ..., \n", 656 | " [ 5.74482433, 3.30837116],\n", 657 | " [ 4.40213956, -3.6699006 ],\n", 658 | " [-0.18579654, -0.58216759]])" 659 | ] 660 | }, 661 | "execution_count": 13, 662 | "metadata": {}, 663 | "output_type": "execute_result" 664 | } 665 | ], 666 | "source": [ 667 | "model = TSNE(n_components=2, random_state=0)\n", 668 | "np.set_printoptions(suppress=True)\n", 669 | "xy = model.fit_transform(normalized)\n", 670 | "xy" 671 | ] 672 | }, 673 | { 674 | "cell_type": "markdown", 675 | "metadata": { 676 | "deletable": true, 677 | "editable": true 678 | }, 679 | "source": [ 680 | "Scatter Plot the first 300 movies to get an idea of whether what the shape is we are looking at:" 681 | ] 682 | }, 683 | { 684 | "cell_type": "code", 685 | "execution_count": 14, 686 | "metadata": { 687 | "collapsed": false, 688 | "deletable": true, 689 | "editable": true 690 | }, 691 | "outputs": [ 692 | { 693 | "data": { 694 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAYYAAAD8CAYAAABzTgP2AAAABHNCSVQICAgIfAhkiAAAAAlwSFlz\nAAALEgAACxIB0t1+/AAAIABJREFUeJzt3X+0HHWZ5/H3k5tGb9DhRokiF0LY1QlLBiEaEZaZXQGH\nnwIZRIEdZnWdYwZX3YHhZCYMDAnqHKJR0RlcXVT2jAsiyI9rGNCAB2YdORv0hpsQImSN/Ag0rEbh\nosAFbpJn/+juS3enqruqu6qrqvvzOodD3+q63d/crq6n6vt9vs/X3B0REZGaWVk3QERE8kWBQURE\nGigwiIhIAwUGERFpoMAgIiINFBhERKSBAoOIiDRQYBARkQYKDCIi0mB21g3oxL777usLFizIuhki\nIoWyYcOGX7v7vHb7FTIwLFiwgPHx8aybISJSKGb2eJT91JUkIiINFBhERKSBAoOIiDRQYBARkQYK\nDCI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2/Kui0tfAT4fkbvHaUWWKbMbAGwGLgv25YA8CUqFxm7s25InYOBHcD/\nrHZxfcPM9s66Ue5epnKO2g48DTzn7nf2uh19s1BPq5pOwPHAhe5+s5l9kMpVQielPpJu12zgDVRu\n+98F3Ghm/8Z7kCrWpl1/S6Ubqeei1OYys0uodJtc18u2FYWZvQ64GbjA3X+bcVveB/zK3TeY2Xuy\nbEuT2cA7gE+6+31m9mVgBfB3WTbKzOZSufs8GJgEvmtm57n7tb1sR98EhlY1nczsW1T6OAG+Sw9v\nadu062PALdVA8BMz202lPsqOrNplZodROSg3VSqjcwBwv5kd6e7/L6t21bXvw8D7gON7EUBDRKkF\nlgkzK1EJCte5+y1Ztwc4BjjdzE4BXgv8npld6+7nZdyuJ4En3b12R3UTlcCQtfcCj7r7DgAzuwX4\n90BPA8OgdCU9BfzH6uPjgJ9n2JZ6Y8CxAGb2+8BeZFzMy903u/ub3H2Buy+g8gV6Ry+CQjtmdhKV\nLonT3f3FDJvyU+Bt1RUI96IyOLg2w/YAM2ucfBN4yN2/mHV7ANz9Ync/oHosnQPcnYOgQPV4fsLM\nFlY3HU+lhE/WtgNHmdmc6ud5PBkMivfNHUMbHwW+XB3MeYlq+e4cuAa4xsweBF4BPpThVXARXAW8\nBrirejez3t3P73Uj3H2nmX0CWEcla+Saan2wrB0D/Bmw2cw2Vrf9rbvfkWGb8uyTwHXV4P4I8F8y\nbg/Vbq2bgPupdJdOkMEMaM18FhGRBoPSlSQiIhEpMIiISAMFBhERaaDAICIiDRQYRESkgQKDiIg0\nUGAQEZEGCgwiItLg/wOnI4fk4AbnOAAAAABJRU5ErkJggg==\n", 695 | "text/plain": [ 696 | "" 697 | ] 698 | }, 699 | "metadata": {}, 700 | "output_type": "display_data" 701 | } 702 | ], 703 | "source": [ 704 | "plt.scatter(xy[:,0][:200], xy[:,1][:200])\n", 705 | "plt.show()" 706 | ] 707 | }, 708 | { 709 | "cell_type": "markdown", 710 | "metadata": { 711 | "deletable": true, 712 | "editable": true 713 | }, 714 | "source": [ 715 | "We can now create a large bitmap that has the movie posters of all movies on it which we can then use to interactively explore neighborhoods of movies. We just loop through all the movies in reverse order and plot them at the position where they are needed, making sure to " 716 | ] 717 | }, 718 | { 719 | "cell_type": "code", 720 | "execution_count": 40, 721 | "metadata": { 722 | "collapsed": false, 723 | "deletable": true, 724 | "editable": true 725 | }, 726 | "outputs": [ 727 | { 728 | "data": { 729 | "text/plain": [ 730 | "(-9.1501788539350546,\n", 731 | " -9.2011315734468635,\n", 732 | " 9.3792594010873813,\n", 733 | " 8.6547486666455313,\n", 734 | " 7325,\n", 735 | " 2396)" 736 | ] 737 | }, 738 | "execution_count": 40, 739 | "metadata": {}, 740 | "output_type": "execute_result" 741 | } 742 | ], 743 | "source": [ 744 | "w = 144\n", 745 | "h = 220\n", 746 | "res = []\n", 747 | "sz = 100\n", 748 | "sz_1 = sz + 1\n", 749 | "taken = [[False] * sz_1 for _ in range(sz_1)]\n", 750 | "x_min = xy.T[0].min()\n", 751 | "y_min = xy.T[1].min()\n", 752 | "x_max = xy.T[0].max()\n", 753 | "y_max = xy.T[1].max()\n", 754 | "img = Image.new('RGB', (sz_1 * w, sz_1 * h))\n", 755 | "drw = ImageDraw.Draw(img)\n", 756 | "c1 = 0\n", 757 | "c2 = 0\n", 758 | "for movie, coo in zip(movies, xy):\n", 759 | " if not movie[1]:\n", 760 | " continue\n", 761 | " poster = Image.open(image_cache + '/' + movie[1])\n", 762 | " poster.thumbnail((w, h), Image.ANTIALIAS)\n", 763 | " x = int(sz * (coo[0] - x_min) / (x_max - x_min))\n", 764 | " y = int(sz * (coo[1] - y_min) / (y_max - y_min))\n", 765 | " if taken[x][y]:\n", 766 | " c1 += 1\n", 767 | " for dx, dy in (-1, 0), (2, 0), (-1, -1), (0, 2):\n", 768 | " x += dx\n", 769 | " y += dy\n", 770 | " if x >= 0 and y >= 0 and x < sz_1 and y < sz_1 and not taken[x][y]:\n", 771 | " break\n", 772 | " else:\n", 773 | " continue\n", 774 | " c2 += 1\n", 775 | " taken[x][y] = True\n", 776 | " x *= w\n", 777 | " y *= h\n", 778 | " drw.rectangle((x, y, x + w, y + h), (50, 50, 50))\n", 779 | " res.append((x, y, movie[1], poster.size[0], poster.size[1]))\n", 780 | " img.paste(poster, (x + (w - poster.size[0]) / 2, y + (h - poster.size[1]) / 2))\n", 781 | "\n", 782 | "img.save(open('/home/notebook/notebook/poster.png', 'wb'))\n", 783 | " \n", 784 | "x_min, y_min, x_max, y_max, c1, c2" 785 | ] 786 | }, 787 | { 788 | "cell_type": "markdown", 789 | "metadata": { 790 | "collapsed": false, 791 | "deletable": true, 792 | "editable": true 793 | }, 794 | "source": [ 795 | "As a last step, we write the resulting data back into the database to power the interactive demo" 796 | ] 797 | }, 798 | { 799 | "cell_type": "code", 800 | "execution_count": 41, 801 | "metadata": { 802 | "collapsed": false, 803 | "deletable": true, 804 | "editable": true 805 | }, 806 | "outputs": [], 807 | "source": [ 808 | "cursor = postgres_conn.cursor()\n", 809 | "cursor.execute('DROP TABLE IF EXISTS movie_recommender')\n", 810 | "cursor.execute('CREATE TABLE movie_recommender ('\n", 811 | " ' wikipedia_id TEXT PRIMARY KEY,'\n", 812 | " ' viewcount INT,'\n", 813 | " ' image TEXT,'\n", 814 | " ' x FLOAT,'\n", 815 | " ' y FLOAT,'\n", 816 | " ' vec FLOAT[] NOT NULL DEFAULT \\'{}\\''\n", 817 | " ')')\n", 818 | "cursor.execute('CREATE INDEX movie_recommender_vec ON movie_recommender USING gin(vec)')\n", 819 | "cursor.execute('CREATE INDEX movie_recommender_name_pattern ON movie_recommender USING btree(lower(wikipedia_id) text_pattern_ops)')\n", 820 | "cursor.execute('CREATE INDEX movie_recommender_viewcount ON movie_recommender(viewcount)')\n" 821 | ] 822 | }, 823 | { 824 | "cell_type": "code", 825 | "execution_count": 42, 826 | "metadata": { 827 | "collapsed": false, 828 | "deletable": true, 829 | "editable": true 830 | }, 831 | "outputs": [], 832 | "source": [ 833 | "for movie, coo, weights in zip(movies, xy, src_weights):\n", 834 | " x = int(sz * (coo[0] - x_min) / (x_max - x_min)) * w\n", 835 | " y = int(sz * (coo[1] - y_min) / (y_max - y_min)) * h\n", 836 | " v_len = np.linalg.norm(weights)\n", 837 | " cursor.execute('INSERT INTO movie_recommender (wikipedia_id, image, viewcount, x, y, vec) '\n", 838 | " 'VALUES (%s, %s, %s, %s, %s, %s)',\n", 839 | " (movie[0], movie[1], movie[-1], x, y,\n", 840 | " [float(weight) / v_len for weight in weights]))\n", 841 | " " 842 | ] 843 | }, 844 | { 845 | "cell_type": "code", 846 | "execution_count": 43, 847 | "metadata": { 848 | "collapsed": false, 849 | "deletable": true, 850 | "editable": true 851 | }, 852 | "outputs": [], 853 | "source": [ 854 | "postgres_conn.commit()\n", 855 | "cursor.close()" 856 | ] 857 | }, 858 | { 859 | "cell_type": "code", 860 | "execution_count": 48, 861 | "metadata": { 862 | "collapsed": false, 863 | "deletable": true, 864 | "editable": true 865 | }, 866 | "outputs": [ 867 | { 868 | "name": "stdout", 869 | "output_type": "stream", 870 | "text": [ 871 | "(6444, 'Return of the Ewok', 0.95703477)\n", 872 | "(683, 'Superman (1978 film)', 0.95719445)\n", 873 | "(9456, 'Doppelg\\xc3\\xa4nger (1969 film)', 0.95741284)\n", 874 | "(4145, 'Dragonslayer', 0.96169114)\n", 875 | "(639, 'Indiana Jones and the Temple of Doom', 0.9632467)\n", 876 | "(141, 'Alien (film)', 0.96762782)\n", 877 | "(303, 'Raiders of the Lost Ark', 0.98218834)\n", 878 | "(44, 'Return of the Jedi', 0.98419368)\n", 879 | "(74, 'The Empire Strikes Back', 0.98707592)\n", 880 | "(18, 'Star Wars (film)', 0.99999988)\n" 881 | ] 882 | } 883 | ], 884 | "source": [ 885 | "neighbors('Star Wars (film)')" 886 | ] 887 | }, 888 | { 889 | "cell_type": "code", 890 | "execution_count": 49, 891 | "metadata": { 892 | "collapsed": false, 893 | "deletable": true, 894 | "editable": true 895 | }, 896 | "outputs": [ 897 | { 898 | "data": { 899 | "text/plain": [ 900 | "(5040, 11660)" 901 | ] 902 | }, 903 | "execution_count": 49, 904 | "metadata": {}, 905 | "output_type": "execute_result" 906 | } 907 | ], 908 | "source": [ 909 | "coo = xy[639]\n", 910 | "x = int(sz * (coo[0] - x_min) / (x_max - x_min)) * w\n", 911 | "y = int(sz * (coo[1] - y_min) / (y_max - y_min)) * h\n", 912 | "x, y" 913 | ] 914 | }, 915 | { 916 | "cell_type": "code", 917 | "execution_count": 50, 918 | "metadata": { 919 | "collapsed": false, 920 | "deletable": true, 921 | "editable": true 922 | }, 923 | "outputs": [ 924 | { 925 | "data": { 926 | "text/plain": [ 927 | "13" 928 | ] 929 | }, 930 | "execution_count": 50, 931 | "metadata": {}, 932 | "output_type": "execute_result" 933 | } 934 | ], 935 | "source": [ 936 | "frames = []\n", 937 | "size = 4800\n", 938 | "i = 0\n", 939 | "x1 = x + 75\n", 940 | "y1 = y + 200\n", 941 | "while size > 480:\n", 942 | " width2 = int(size / 2)\n", 943 | " height2 = int(size / 3)\n", 944 | " img_crop = img.crop((x1 - width2, y1 - height2, x1 + width2, y1 + height2))\n", 945 | " img_crop = img_crop.resize((600, 400))\n", 946 | " fn = 'movie_images/frame_%d.png' % i\n", 947 | " img_crop.save(fn)\n", 948 | " frames.append(fn)\n", 949 | " size /= 1.2\n", 950 | " i += 1\n", 951 | "len(frames)" 952 | ] 953 | }, 954 | { 955 | "cell_type": "code", 956 | "execution_count": 51, 957 | "metadata": { 958 | "collapsed": false, 959 | "deletable": true, 960 | "editable": true 961 | }, 962 | "outputs": [ 963 | { 964 | "data": { 965 | "text/html": [ 966 | "" 967 | ], 968 | "text/plain": [ 969 | "" 970 | ] 971 | }, 972 | "metadata": {}, 973 | "output_type": "display_data" 974 | } 975 | ], 976 | "source": [ 977 | "imageio.mimsave('movie_recommend.gif', [imageio.imread(frame) for frame in frames], 'GIF', duration=0.5)\n", 978 | "display(HTML(''))" 979 | ] 980 | } 981 | ], 982 | "metadata": { 983 | "kernelspec": { 984 | "display_name": "Python 2", 985 | "language": "python", 986 | "name": "python2" 987 | }, 988 | "language_info": { 989 | "codemirror_mode": { 990 | "name": "ipython", 991 | "version": 2 992 | }, 993 | "file_extension": ".py", 994 | "mimetype": "text/x-python", 995 | "name": "python", 996 | "nbconvert_exporter": "python", 997 | "pygments_lexer": "ipython2", 998 | "version": "2.7.12" 999 | } 1000 | }, 1001 | "nbformat": 4, 1002 | "nbformat_minor": 2 1003 | } 1004 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # notebooks 2 | Collection of iPython notebooks with some quick demos 3 | -------------------------------------------------------------------------------- /Style_Transfer_Interpolation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Style Transfer Interpolation\n", 8 | "\n", 9 | "Modified version of the https://github.com/fchollet/keras/blob/master/examples/neural_style_transfer.py neural style transfer. Rather than having one style image, we have two. We first train the network for a number of iterations to get to converge on the first image, before interpolating for the rest of the iterations between the first and the second.\n", 10 | "\n", 11 | "Interpolation is done by having step variable that controls the weight of the loss" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 38, 17 | "metadata": { 18 | "collapsed": false, 19 | "deletable": true, 20 | "editable": true 21 | }, 22 | "outputs": [], 23 | "source": [ 24 | "from keras.preprocessing.image import load_img, img_to_array\n", 25 | "from scipy.misc import imsave\n", 26 | "import numpy as np\n", 27 | "from scipy.optimize import fmin_l_bfgs_b\n", 28 | "import time\n", 29 | "import argparse\n", 30 | "import os\n", 31 | "import imageio\n", 32 | "from IPython.display import Image, display, HTML\n", 33 | "\n", 34 | "from keras.applications import vgg16\n", 35 | "from keras import backend as K\n", 36 | "import requests" 37 | ] 38 | }, 39 | { 40 | "cell_type": "markdown", 41 | "metadata": {}, 42 | "source": [ 43 | "Some functions to convert from and to the internal format used. Make sure we end up with images of the right size and take care of the colors being at the position that the selected back end expects." 44 | ] 45 | }, 46 | { 47 | "cell_type": "code", 48 | "execution_count": 25, 49 | "metadata": { 50 | "collapsed": true, 51 | "deletable": true, 52 | "editable": true 53 | }, 54 | "outputs": [], 55 | "source": [ 56 | "def preprocess_image(image_path):\n", 57 | " img = load_img(image_path, target_size=(img_nrows, img_ncols))\n", 58 | " img = img_to_array(img)\n", 59 | " img = np.expand_dims(img, axis=0)\n", 60 | " img = vgg16.preprocess_input(img)\n", 61 | " return img\n", 62 | "\n", 63 | "# util function to convert a tensor into a valid image\n", 64 | "\n", 65 | "\n", 66 | "def deprocess_image(x):\n", 67 | " if K.image_data_format() == 'channels_first':\n", 68 | " x = x.reshape((3, img_nrows, img_ncols))\n", 69 | " x = x.transpose((1, 2, 0))\n", 70 | " else:\n", 71 | " x = x.reshape((img_nrows, img_ncols, 3))\n", 72 | " # Remove zero-center by mean pixel\n", 73 | " x[:, :, 0] += 103.939\n", 74 | " x[:, :, 1] += 116.779\n", 75 | " x[:, :, 2] += 123.68\n", 76 | " # 'BGR'->'RGB'\n", 77 | " x = x[:, :, ::-1]\n", 78 | " x = np.clip(x, 0, 255).astype('uint8')\n", 79 | " return x\n" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "Fetch the three images we need from the Internet if they aren't already loaded. Base Image is the image that we'll render a style transfered version of, style reference 1 & 2 are the style images to interpolate between." 87 | ] 88 | }, 89 | { 90 | "cell_type": "code", 91 | "execution_count": 26, 92 | "metadata": { 93 | "collapsed": true, 94 | "deletable": true, 95 | "editable": true 96 | }, 97 | "outputs": [], 98 | "source": [ 99 | "IMAGE_BASE = 'style_transfer/'\n", 100 | "\n", 101 | "def fetch_image(url, fn=None):\n", 102 | " if not fn:\n", 103 | " fn = url.rsplit('/', 1)[-1]\n", 104 | " fn = IMAGE_BASE + fn\n", 105 | " if os.path.isfile(fn):\n", 106 | " return fn\n", 107 | " img = requests.get(url).content\n", 108 | " with open(fn, 'wb') as fout:\n", 109 | " fout.write(img)\n", 110 | " return fn\n", 111 | "\n", 112 | "base_image_path = fetch_image('https://upload.wikimedia.org/wikipedia/commons/0/08/Okerk2.jpg')\n", 113 | "style_reference_image_path_2 = fetch_image('https://upload.wikimedia.org/wikipedia/commons/9/99/Jan_van_Goyen_004b.jpg')\n", 114 | "style_reference_image_path_1 = fetch_image('https://upload.wikimedia.org/wikipedia/commons/6/66/VanGogh-starry_night_ballance1.jpg')\n", 115 | "Image(filename=base_image_path)" 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "metadata": {}, 121 | "source": [ 122 | "Some working variables and constants we are going to need. Change img_nrows to influence the size of the output picture. The various *_weight variables will determine how much influence the three loss functions have (see below). Iterations is the total of number of iterations, the first warm_up will be used to get to a stable version of the image, the rest will be used for the interpolation frames. result_prefix is the prefix used for the intermediate images" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": 16, 128 | "metadata": { 129 | "collapsed": false, 130 | "deletable": true, 131 | "editable": true 132 | }, 133 | "outputs": [], 134 | "source": [ 135 | "width, height = load_img(base_image_path).size\n", 136 | "img_nrows = 400\n", 137 | "img_ncols = int(width * img_nrows / height)\n", 138 | "\n", 139 | "total_variation_weight = 1.0\n", 140 | "style_weight = 1.0\n", 141 | "content_weight = 0.025\n", 142 | "\n", 143 | "iterations = 120\n", 144 | "warm_up = 30\n", 145 | "\n", 146 | "result_prefix = 'star_goyen'" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": {}, 152 | "source": [ 153 | "Load the images into three variables and create a place holder for the resulting combination image. Then create a tensor that contains all four of them next to each other so we can process them together in the same way as we'd process a mini-batch when training." 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": 31, 159 | "metadata": { 160 | "collapsed": false, 161 | "deletable": true, 162 | "editable": true 163 | }, 164 | "outputs": [ 165 | { 166 | "data": { 167 | "text/plain": [ 168 | "" 169 | ] 170 | }, 171 | "execution_count": 31, 172 | "metadata": {}, 173 | "output_type": "execute_result" 174 | } 175 | ], 176 | "source": [ 177 | "base_image = K.variable(preprocess_image(base_image_path))\n", 178 | "style_reference_image_1 = K.variable(preprocess_image(style_reference_image_path_1))\n", 179 | "style_reference_image_2 = K.variable(preprocess_image(style_reference_image_path_2))\n", 180 | "\n", 181 | "# this will contain our generated image\n", 182 | "if K.image_data_format() == 'channels_first':\n", 183 | " combination_image = K.placeholder((1, 3, img_nrows, img_ncols))\n", 184 | "else:\n", 185 | " combination_image = K.placeholder((1, img_nrows, img_ncols, 3))\n", 186 | "\n", 187 | "# combine the 4 images into a single Keras tensor\n", 188 | "input_tensor = K.concatenate([base_image,\n", 189 | " style_reference_image_1,\n", 190 | " style_reference_image_2,\n", 191 | " combination_image], axis=0)\n", 192 | "input_tensor" 193 | ] 194 | }, 195 | { 196 | "cell_type": "markdown", 197 | "metadata": {}, 198 | "source": [ 199 | "Now load the pretrained vgg16 model and load it up with the four images as input." 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": 7, 205 | "metadata": { 206 | "collapsed": false, 207 | "deletable": true, 208 | "editable": true 209 | }, 210 | "outputs": [ 211 | { 212 | "name": "stdout", 213 | "output_type": "stream", 214 | "text": [ 215 | "Model loaded.\n" 216 | ] 217 | } 218 | ], 219 | "source": [ 220 | "model = vgg16.VGG16(input_tensor=input_tensor,\n", 221 | " weights='imagenet', include_top=False)\n", 222 | "print('Model loaded.')" 223 | ] 224 | }, 225 | { 226 | "cell_type": "markdown", 227 | "metadata": {}, 228 | "source": [ 229 | "Create a simple helper dictionary to get to the outputs of the layers in the model:" 230 | ] 231 | }, 232 | { 233 | "cell_type": "code", 234 | "execution_count": 16, 235 | "metadata": { 236 | "collapsed": true, 237 | "deletable": true, 238 | "editable": true 239 | }, 240 | "outputs": [], 241 | "source": [ 242 | "outputs_dict = {layer.name: layer.output for layer in model.layers}\n" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": {}, 248 | "source": [ 249 | "### The clever bit\n", 250 | "\n", 251 | "Now for the clever bit. We define three loss functions that we combine into one overall loss function to optimize. Each of the three functions tries to control one aspect of the process:\n", 252 | "\n", 253 | "* Style Loss - keep the style of the target image close to the style we selected\n", 254 | "* Content Loss - keep the overall image similar to the base image\n", 255 | "* Variation - supress local variation to keep the image locally coherent" 256 | ] 257 | }, 258 | { 259 | "cell_type": "markdown", 260 | "metadata": {}, 261 | "source": [ 262 | "#### Style loss\n", 263 | "\n", 264 | "We need two functions. gram_matrix calculates the feature activation of an image by taking the outer product of a particular layer. We then calculate the style loss between our target image and the source of the style summing the squares of the gram_matrix() for these images scaled for the size of the tensor." 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "execution_count": null, 270 | "metadata": { 271 | "collapsed": true 272 | }, 273 | "outputs": [], 274 | "source": [ 275 | "def gram_matrix(x):\n", 276 | " assert K.ndim(x) == 3\n", 277 | " if K.image_data_format() == 'channels_first':\n", 278 | " features = K.batch_flatten(x)\n", 279 | " else:\n", 280 | " features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))\n", 281 | " gram = K.dot(features, K.transpose(features))\n", 282 | " return gram\n", 283 | "\n", 284 | "def style_loss(style, combination):\n", 285 | " assert K.ndim(style) == 3\n", 286 | " assert K.ndim(combination) == 3\n", 287 | " S = gram_matrix(style)\n", 288 | " C = gram_matrix(combination)\n", 289 | " channels = 3\n", 290 | " size = img_nrows * img_ncols\n", 291 | " return K.sum(K.square(S - C)) / (4. * (channels ** 2) * (size ** 2))" 292 | ] 293 | }, 294 | { 295 | "cell_type": "markdown", 296 | "metadata": {}, 297 | "source": [ 298 | "#### Content loss\n", 299 | "\n", 300 | "Content is the straight forward sum of squares between the base and the target image. " 301 | ] 302 | }, 303 | { 304 | "cell_type": "code", 305 | "execution_count": null, 306 | "metadata": { 307 | "collapsed": true 308 | }, 309 | "outputs": [], 310 | "source": [ 311 | "def content_loss(base, combination):\n", 312 | " return K.sum(K.square(combination - base))" 313 | ] 314 | }, 315 | { 316 | "cell_type": "markdown", 317 | "metadata": {}, 318 | "source": [ 319 | "#### Variation Loss\n", 320 | "\n", 321 | "Minimize the local variation by comparing effectively pixels next to each other and minimizing the variation. This keeps the resulting image somewhat fuzzy, but it avoids large jumps in the pixels and keeps the image locally coherent." 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": 9, 327 | "metadata": { 328 | "collapsed": true, 329 | "deletable": true, 330 | "editable": true 331 | }, 332 | "outputs": [], 333 | "source": [ 334 | "def total_variation_loss(x):\n", 335 | " assert K.ndim(x) == 4\n", 336 | " if K.image_data_format() == 'channels_first':\n", 337 | " a = K.square(x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, 1:, :img_ncols - 1])\n", 338 | " b = K.square(x[:, :, :img_nrows - 1, :img_ncols - 1] - x[:, :, :img_nrows - 1, 1:])\n", 339 | " else:\n", 340 | " a = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, 1:, :img_ncols - 1, :])\n", 341 | " b = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, :img_nrows - 1, 1:, :])\n", 342 | " return K.sum(K.pow(a + b, 1.25))" 343 | ] 344 | }, 345 | { 346 | "cell_type": "markdown", 347 | "metadata": {}, 348 | "source": [ 349 | "### The combined loss function\n", 350 | "\n", 351 | "Now combine the three loss functions from above into one that we can optimize for. We use selected layers from the neural network for style and content loss, while the variation loss is calculated on just the resulting image.\n", 352 | "\n", 353 | "We introduce an extra place holder variable \"step\" indicating where we are transitioning from one style to another and calculate the style loss for both style images and scale the result accordingly between these two loss values. Finally we calculate the gradient with regard to the combination image." 354 | ] 355 | }, 356 | { 357 | "cell_type": "code", 358 | "execution_count": 12, 359 | "metadata": { 360 | "collapsed": false, 361 | "deletable": true, 362 | "editable": true 363 | }, 364 | "outputs": [], 365 | "source": [ 366 | "loss = K.variable(0.)\n", 367 | "layer_features = outputs_dict['block4_conv2']\n", 368 | "base_image_features = layer_features[0, :, :, :]\n", 369 | "combination_features = layer_features[3, :, :, :]\n", 370 | "loss += content_weight * content_loss(base_image_features,\n", 371 | " combination_features)\n", 372 | "step = K.placeholder()\n", 373 | "feature_layers = ['block1_conv1', 'block2_conv1',\n", 374 | " 'block3_conv1', 'block4_conv1',\n", 375 | " 'block5_conv1']\n", 376 | "for layer_name in feature_layers:\n", 377 | " layer_features = outputs_dict[layer_name]\n", 378 | " style_reference_features_1 = layer_features[1, :, :, :]\n", 379 | " style_reference_features_2 = layer_features[2, :, :, :]\n", 380 | " combination_features = layer_features[3, :, :, :]\n", 381 | " sl_1 = style_loss(style_reference_features_1, combination_features) * step\n", 382 | " sl_2 = style_loss(style_reference_features_2, combination_features) * (1 - step)\n", 383 | " loss += (style_weight / len(feature_layers)) * (sl_1 + sl_2)\n", 384 | "loss += total_variation_weight * total_variation_loss(combination_image)\n", 385 | "\n", 386 | "# get the gradients of the generated image wrt the loss\n", 387 | "grads = K.gradients(loss, combination_image)\n", 388 | "\n", 389 | "outputs = [loss]\n", 390 | "if isinstance(grads, (list, tuple)):\n", 391 | " outputs += grads\n", 392 | "else:\n", 393 | " outputs.append(grads)\n", 394 | "\n", 395 | "f_outputs = K.function([combination_image, step], outputs)" 396 | ] 397 | }, 398 | { 399 | "cell_type": "markdown", 400 | "metadata": {}, 401 | "source": [ 402 | "### Evalutor object\n", 403 | "\n", 404 | "Some extra plumbing to make it possible to use the above in combination with fmin_l_bfgs_b. Scipy.optimize requires two seperate loss and grads functions so rather than calculating those twice, we cache the values in an Evaluator object. We use the same object to store the value of where we are between the two style images." 405 | ] 406 | }, 407 | { 408 | "cell_type": "code", 409 | "execution_count": 13, 410 | "metadata": { 411 | "collapsed": true, 412 | "deletable": true, 413 | "editable": true 414 | }, 415 | "outputs": [], 416 | "source": [ 417 | "def eval_loss_and_grads(x, perc):\n", 418 | " if K.image_data_format() == 'channels_first':\n", 419 | " x = x.reshape((1, 3, img_nrows, img_ncols))\n", 420 | " else:\n", 421 | " x = x.reshape((1, img_nrows, img_ncols, 3))\n", 422 | " outs = f_outputs([x, perc])\n", 423 | " loss_value = outs[0]\n", 424 | " if len(outs[1:]) == 1:\n", 425 | " grad_values = outs[1].flatten().astype('float64')\n", 426 | " else:\n", 427 | " grad_values = np.array(outs[1:]).flatten().astype('float64')\n", 428 | " return loss_value, grad_values\n", 429 | "\n", 430 | "class Evaluator(object):\n", 431 | "\n", 432 | " def __init__(self):\n", 433 | " self.loss_value = None\n", 434 | " self.grads_values = None\n", 435 | " self.perc = 0\n", 436 | "\n", 437 | " def loss(self, x):\n", 438 | " assert self.loss_value is None\n", 439 | " loss_value, grad_values = eval_loss_and_grads(x, self.perc)\n", 440 | " self.loss_value = loss_value\n", 441 | " self.grad_values = grad_values\n", 442 | " return self.loss_value\n", 443 | "\n", 444 | " def grads(self, x):\n", 445 | " assert self.loss_value is not None\n", 446 | " grad_values = np.copy(self.grad_values)\n", 447 | " self.loss_value = None\n", 448 | " self.grad_values = None\n", 449 | " return grad_values\n", 450 | "\n", 451 | "evaluator = Evaluator()" 452 | ] 453 | }, 454 | { 455 | "cell_type": "markdown", 456 | "metadata": {}, 457 | "source": [ 458 | "### Run the model\n", 459 | "\n", 460 | "Now run the model. We start with a randomized image and then use the scipy-based L-BFGS algorithm to optimize the pixels. The first number of \"warm_up\" iterations we just target the first style image. After that we start to interpolate. While interpolating we store the name of the intermediate image in the frames variable." 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": null, 466 | "metadata": { 467 | "collapsed": false, 468 | "deletable": true, 469 | "editable": true 470 | }, 471 | "outputs": [ 472 | { 473 | "name": "stdout", 474 | "output_type": "stream", 475 | "text": [ 476 | "Start of iteration 0 0\n", 477 | "Current loss value: 2.77769e+09\n", 478 | "Image saved as style_transfer/star_goyen_at_iteration_0.png\n", 479 | "Iteration 0 completed in 311s\n", 480 | "Start of iteration 1 0\n", 481 | "Current loss value: 2.19096e+09\n", 482 | "Image saved as style_transfer/star_goyen_at_iteration_1.png\n", 483 | "Iteration 1 completed in 291s\n", 484 | "Start of iteration 2 0\n", 485 | "Current loss value: 1.96724e+09\n", 486 | "Image saved as style_transfer/star_goyen_at_iteration_2.png\n", 487 | "Iteration 2 completed in 292s\n", 488 | "Start of iteration 3 0\n", 489 | "Current loss value: 1.84749e+09\n", 490 | "Image saved as style_transfer/star_goyen_at_iteration_3.png\n", 491 | "Iteration 3 completed in 292s\n", 492 | "Start of iteration 4 0\n", 493 | "Current loss value: 1.77549e+09\n", 494 | "Image saved as style_transfer/star_goyen_at_iteration_4.png\n", 495 | "Iteration 4 completed in 292s\n", 496 | "Start of iteration 5 0\n", 497 | "Current loss value: 1.7281e+09\n", 498 | "Image saved as style_transfer/star_goyen_at_iteration_5.png\n", 499 | "Iteration 5 completed in 312s\n", 500 | "Start of iteration 6 0\n", 501 | "Current loss value: 1.69238e+09\n", 502 | "Image saved as style_transfer/star_goyen_at_iteration_6.png\n", 503 | "Iteration 6 completed in 292s\n", 504 | "Start of iteration 7 0\n", 505 | "Current loss value: 1.66306e+09\n", 506 | "Image saved as style_transfer/star_goyen_at_iteration_7.png\n", 507 | "Iteration 7 completed in 293s\n", 508 | "Start of iteration 8 0\n", 509 | "Current loss value: 1.64026e+09\n", 510 | "Image saved as style_transfer/star_goyen_at_iteration_8.png\n", 511 | "Iteration 8 completed in 292s\n", 512 | "Start of iteration 9 0\n", 513 | "Current loss value: 1.62088e+09\n", 514 | "Image saved as style_transfer/star_goyen_at_iteration_9.png\n", 515 | "Iteration 9 completed in 300s\n", 516 | "Start of iteration 10 0\n", 517 | "Current loss value: 1.60472e+09\n", 518 | "Image saved as style_transfer/star_goyen_at_iteration_10.png\n", 519 | "Iteration 10 completed in 301s\n", 520 | "Start of iteration 11 0\n", 521 | "Current loss value: 1.59089e+09\n", 522 | "Image saved as style_transfer/star_goyen_at_iteration_11.png\n", 523 | "Iteration 11 completed in 293s\n", 524 | "Start of iteration 12 0\n", 525 | "Current loss value: 1.5785e+09\n", 526 | "Image saved as style_transfer/star_goyen_at_iteration_12.png\n", 527 | "Iteration 12 completed in 292s\n", 528 | "Start of iteration 13 0\n", 529 | "Current loss value: 1.56806e+09\n", 530 | "Image saved as style_transfer/star_goyen_at_iteration_13.png\n", 531 | "Iteration 13 completed in 292s\n", 532 | "Start of iteration 14 0\n", 533 | "Current loss value: 1.55861e+09\n", 534 | "Image saved as style_transfer/star_goyen_at_iteration_14.png\n", 535 | "Iteration 14 completed in 305s\n", 536 | "Start of iteration 15 0\n", 537 | "Current loss value: 1.55002e+09\n", 538 | "Image saved as style_transfer/star_goyen_at_iteration_15.png\n", 539 | "Iteration 15 completed in 297s\n", 540 | "Start of iteration 16 0\n", 541 | "Current loss value: 1.54235e+09\n", 542 | "Image saved as style_transfer/star_goyen_at_iteration_16.png\n", 543 | "Iteration 16 completed in 293s\n", 544 | "Start of iteration 17 0\n", 545 | "Current loss value: 1.53529e+09\n", 546 | "Image saved as style_transfer/star_goyen_at_iteration_17.png\n", 547 | "Iteration 17 completed in 292s\n", 548 | "Start of iteration 18 0\n", 549 | "Current loss value: 1.52888e+09\n", 550 | "Image saved as style_transfer/star_goyen_at_iteration_18.png\n", 551 | "Iteration 18 completed in 293s\n", 552 | "Start of iteration 19 0\n", 553 | "Current loss value: 1.52311e+09\n", 554 | "Image saved as style_transfer/star_goyen_at_iteration_19.png\n", 555 | "Iteration 19 completed in 306s\n", 556 | "Start of iteration 20 0\n", 557 | "Current loss value: 1.51797e+09\n", 558 | "Image saved as style_transfer/star_goyen_at_iteration_20.png\n", 559 | "Iteration 20 completed in 294s\n", 560 | "Start of iteration 21 0\n", 561 | "Current loss value: 1.51328e+09\n", 562 | "Image saved as style_transfer/star_goyen_at_iteration_21.png\n", 563 | "Iteration 21 completed in 293s\n", 564 | "Start of iteration 22 0\n", 565 | "Current loss value: 1.50881e+09\n", 566 | "Image saved as style_transfer/star_goyen_at_iteration_22.png\n", 567 | "Iteration 22 completed in 292s\n", 568 | "Start of iteration 23 0\n", 569 | "Current loss value: 1.50453e+09\n", 570 | "Image saved as style_transfer/star_goyen_at_iteration_23.png\n", 571 | "Iteration 23 completed in 293s\n", 572 | "Start of iteration 24 0\n", 573 | "Current loss value: 1.50043e+09\n", 574 | "Image saved as style_transfer/star_goyen_at_iteration_24.png\n", 575 | "Iteration 24 completed in 310s\n", 576 | "Start of iteration 25 0\n", 577 | "Current loss value: 1.49666e+09\n", 578 | "Image saved as style_transfer/star_goyen_at_iteration_25.png\n", 579 | "Iteration 25 completed in 292s\n", 580 | "Start of iteration 26 0\n", 581 | "Current loss value: 1.493e+09\n", 582 | "Image saved as style_transfer/star_goyen_at_iteration_26.png\n", 583 | "Iteration 26 completed in 293s\n", 584 | "Start of iteration 27 0\n", 585 | "Current loss value: 1.48948e+09\n", 586 | "Image saved as style_transfer/star_goyen_at_iteration_27.png\n", 587 | "Iteration 27 completed in 293s\n", 588 | "Start of iteration 28 0\n", 589 | "Current loss value: 1.48604e+09\n", 590 | "Image saved as style_transfer/star_goyen_at_iteration_28.png\n", 591 | "Iteration 28 completed in 293s\n", 592 | "Start of iteration 29 0\n", 593 | "Current loss value: 1.48271e+09\n", 594 | "Image saved as style_transfer/star_goyen_at_iteration_29.png\n", 595 | "Iteration 29 completed in 307s\n", 596 | "Start of iteration 30 0\n", 597 | "Current loss value: 1.47949e+09\n", 598 | "Image saved as style_transfer/star_goyen_at_iteration_30.png\n", 599 | "Iteration 30 completed in 293s\n", 600 | "Start of iteration 31 0.011235955056179775\n", 601 | "Current loss value: 2.38148e+09\n", 602 | "Image saved as style_transfer/star_goyen_at_iteration_31.png\n", 603 | "Iteration 31 completed in 293s\n", 604 | "Start of iteration 32 0.02247191011235955\n", 605 | "Current loss value: 3.26933e+09\n", 606 | "Image saved as style_transfer/star_goyen_at_iteration_32.png\n", 607 | "Iteration 32 completed in 293s\n", 608 | "Start of iteration 33 0.033707865168539325\n", 609 | "Current loss value: 4.14178e+09\n", 610 | "Image saved as style_transfer/star_goyen_at_iteration_33.png\n", 611 | "Iteration 33 completed in 293s\n", 612 | "Start of iteration 34 0.0449438202247191\n", 613 | "Current loss value: 4.99854e+09\n", 614 | "Image saved as style_transfer/star_goyen_at_iteration_34.png\n", 615 | "Iteration 34 completed in 309s\n", 616 | "Start of iteration 35 0.056179775280898875\n", 617 | "Current loss value: 5.83909e+09\n", 618 | "Image saved as style_transfer/star_goyen_at_iteration_35.png\n", 619 | "Iteration 35 completed in 293s\n", 620 | "Start of iteration 36 0.06741573033707865\n", 621 | "Current loss value: 6.6628e+09\n", 622 | "Image saved as style_transfer/star_goyen_at_iteration_36.png\n", 623 | "Iteration 36 completed in 293s\n", 624 | "Start of iteration 37 0.07865168539325842\n", 625 | "Current loss value: 7.46884e+09\n", 626 | "Image saved as style_transfer/star_goyen_at_iteration_37.png\n", 627 | "Iteration 37 completed in 293s\n", 628 | "Start of iteration 38 0.0898876404494382\n", 629 | "Current loss value: 8.25536e+09\n", 630 | "Image saved as style_transfer/star_goyen_at_iteration_38.png\n", 631 | "Iteration 38 completed in 301s\n", 632 | "Start of iteration 39 0.10112359550561797\n" 633 | ] 634 | } 635 | ], 636 | "source": [ 637 | "if K.image_data_format() == 'channels_first':\n", 638 | " x = np.random.uniform(0, 255, (1, 3, img_nrows, img_ncols)) - 128.\n", 639 | "else:\n", 640 | " x = np.random.uniform(0, 255, (1, img_nrows, img_ncols, 3)) - 128.\n", 641 | "\n", 642 | "\n", 643 | "frames = []\n", 644 | "for i in range(0, iterations):\n", 645 | " start_time = time.time()\n", 646 | " if i > warm_up:\n", 647 | " frames.append(fname)\n", 648 | " evaluator.perc = float(i - warm_up) / (iterations - warm_up - 1)\n", 649 | " else:\n", 650 | " evaluator.perc = 0\n", 651 | " print('Start of iteration', i, evaluator.perc)\n", 652 | " x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(),\n", 653 | " fprime=evaluator.grads, maxfun=20)\n", 654 | " print('Current loss value:', min_val)\n", 655 | " # save current generated image\n", 656 | " img = deprocess_image(x.copy())\n", 657 | " fname = IMAGE_BASE + result_prefix + '_at_iteration_%d.png' % i\n", 658 | " imsave(fname, img)\n", 659 | " end_time = time.time()\n", 660 | " print('Image saved as', fname)\n", 661 | " print('Iteration %d completed in %ds' % (i, end_time - start_time))" 662 | ] 663 | }, 664 | { 665 | "cell_type": "markdown", 666 | "metadata": {}, 667 | "source": [ 668 | "To display the result as an animated gif, we create a cycle from the frames variable and then use imageio to create an animated gif." 669 | ] 670 | }, 671 | { 672 | "cell_type": "code", 673 | "execution_count": 18, 674 | "metadata": { 675 | "collapsed": false, 676 | "deletable": true, 677 | "editable": true 678 | }, 679 | "outputs": [], 680 | "source": [ 681 | "cycled = frames + list(reversed(frames[1:-1]))\n", 682 | "# Save them as frames into a gif \n", 683 | "kargs = { 'duration': 0.1 }\n", 684 | "imageio.mimsave(IMAGE_BASE + 'animated.gif', [imageio.imread(x) for x in cycled], 'GIF', **kargs)\n", 685 | "\n", 686 | "HTML('' % (IMAGE_BASE + 'animated.gif'))" 687 | ] 688 | }, 689 | { 690 | "cell_type": "markdown", 691 | "metadata": { 692 | "collapsed": true 693 | }, 694 | "source": [ 695 | "![style transfer](https://douweosinga.com/static/projects/style_transfer/style_transfer.gif \"Result\")" 696 | ] 697 | }, 698 | { 699 | "cell_type": "code", 700 | "execution_count": null, 701 | "metadata": { 702 | "collapsed": true 703 | }, 704 | "outputs": [], 705 | "source": [] 706 | } 707 | ], 708 | "metadata": { 709 | "kernelspec": { 710 | "display_name": "Python 3", 711 | "language": "python", 712 | "name": "python3" 713 | }, 714 | "language_info": { 715 | "codemirror_mode": { 716 | "name": "ipython", 717 | "version": 3 718 | }, 719 | "file_extension": ".py", 720 | "mimetype": "text/x-python", 721 | "name": "python", 722 | "nbconvert_exporter": "python", 723 | "pygments_lexer": "ipython3", 724 | "version": "3.5.2" 725 | } 726 | }, 727 | "nbformat": 4, 728 | "nbformat_minor": 2 729 | } 730 | --------------------------------------------------------------------------------