<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Shitij Nigam on Medium]]></title>
        <description><![CDATA[Stories by Shitij Nigam on Medium]]></description>
        <link>https://medium.com/@shitijnigam?source=rss-65eb3c05bb84------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jtA5NMFLeiwTQYnNsuciyA.jpeg</url>
            <title>Stories by Shitij Nigam on Medium</title>
            <link>https://medium.com/@shitijnigam?source=rss-65eb3c05bb84------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:19:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shitijnigam/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Deploying a Django app on Docker & Fly.io]]></title>
            <link>https://medium.com/@shitijnigam/django-journey-jottings-e6e5ff10a869?source=rss-65eb3c05bb84------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6e5ff10a869</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[flyio]]></category>
            <category><![CDATA[django]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[heroku]]></category>
            <dc:creator><![CDATA[Shitij Nigam]]></dc:creator>
            <pubDate>Tue, 06 Aug 2024 11:17:53 GMT</pubDate>
            <atom:updated>2024-08-16T09:11:45.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>Deploying Django on Docker &amp; Fly.io</h3><p>This was .. a journey.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ADrqcp_2fGGt1lt2su3A5w.jpeg" /><figcaption><em>Gemini generates the weirdest stuff</em></figcaption></figure><p>Dear Diary, after tepidly engaging with Javascript, I’m going back to what I know best: Python (and Django, which I did years ago, but still impresses me). Treat these as revision notes in case in case I take another break.</p><blockquote>N.B: All this runs on an early Macbook Pro 2015. Ref: <a href="https://djangoforprofessionals.com/">Django for Professionals</a></blockquote><h3>Chapters</h3><p><a href="#819c"><strong>Setup</strong></a><br> ∘ <a href="#bd09">Prerequisites</a><br> ∘ <a href="#fbe7">Overall workflow</a><br><a href="#6cc8"><strong>Github</strong></a><br> ∘ <a href="#174e">Shell Commands</a><br> ∘ <a href="#9288">GitHub files</a><br><a href="#1dea"><strong>Databases</strong></a><br> ∘ <a href="#e3d7">PostgreSQL</a><br><a href="#36eb"><strong>Python / Django</strong></a><br> ∘ <a href="#988f">Shell Commands</a><br> ∘ <a href="#08f4">Technical User Flow</a><br> ∘ <a href="#7d53">URLs &amp; Views</a><br> ∘ <a href="#8d6b">Templates</a><br> ∘ <a href="#4634">Static files</a><br> ∘ <a href="#b89d">Models, esp. Custom User Models</a><br> ∘ <a href="#8e2a">Forms, esp. Custom User Forms</a><br> ∘ <a href="#3b42">Tests</a><br> ∘ <a href="#c0ef">Settings.py</a><br><a href="#51e2"><strong>Docker</strong></a><br> ∘ <a href="#2886">Overview</a><br> ∘ <a href="#1346">Workflow</a><br> ∘ <a href="#34ac">Shell Commands</a><br> ∘ <a href="#0d57">Docker Files</a><br><a href="#bdf5"><strong>Fly / Deployment</strong></a><br> ∘ <a href="#5a87">Dockerfile</a><br> ∘ <a href="#4d9b">docker-compose.yml</a><br> ∘ <a href="#39cf">Settings.py</a></p><h3>Setup</h3><h4>Prerequisites</h4><ul><li>Github</li><li>Database Config (e.g. PostgreSQL)</li><li>Python / Django</li><li>Docker</li><li>Fly</li></ul><h4>Overall workflow</h4><ul><li>Create new virtual environment and install Django</li><li>Create new Django project within it</li><li>Write <strong><em>Dockerfile</em></strong> and build initial image</li><li>Write <strong><em>docker-compose.yml</em></strong> and run container with <strong><em>docker-compose up</em></strong></li></ul><h3>Github</h3><h4>Shell Commands</h4><ul><li><strong><em>git init</em></strong>: Initialize new git repository</li><li><strong><em>git status</em></strong>: See which files/directories are being tracked</li><li><strong><em>git add .</em></strong>: Add all current files to git (except anything under <strong><em>.gitignore</em></strong>), i.e. stage changes</li><li><strong><em>git commit -m ‘&lt;message&gt;’</em></strong>: Commit files to staging with message, i.e. take whatever is in the staging area and wrap it in a new commit snapshot</li><li><strong><em>git push origin &lt;branch-name&gt;</em></strong>: Upload commits to remote repository</li></ul><h4>GitHub files</h4><ul><li><strong><em>.gitignore</em></strong>: Tells github which files to exclude (e.g. <strong><em>.venv</em></strong>, <strong><em>db.sqlite3</em></strong>, <strong><em>__pycache__/</em></strong>, <strong><em>.DS_Store</em></strong>, etc.)</li></ul><h3>Databases</h3><h4>PostgreSQL</h4><ul><li>PostgreSQL can be used by almost any programming language</li><li>However, we need adapters to connect the language / framework to databases</li><li>Psycopg is the most popular database adapter for Python; the binary version is simpler, while the non-binary version requires multiple additional steps of configuration</li><li>In case of Django, <strong><em>requirements.txt</em></strong> needs to contain <strong><em>psycopg2-binary</em></strong>==2.9.3 — the most popular database adapter; however, for production, you want to use <strong><em>psycopg2 </em></strong>instead, as recommended by <em>fly.io</em></li></ul><h3>Python / Django</h3><h4>Shell Commands</h4><ul><li><strong><em>python3 -m venv .venv</em></strong>: Create virtual environment</li><li><strong><em>source .venv/bin/activate</em></strong>: Activate virtual environment</li><li>(venv) <strong><em>python -m pip install django~=4.0.0</em></strong>: Install django 4.0; ensure subsequent security updates are automatically installed</li><li>(venv) <strong><em>python -m pip install — — upgrade pip</em></strong>: Update pip :)</li><li>(venv) <strong><em>django-admin startproject django_project .</em></strong> :Start a django project using django preinstalled on your device (notice the . at the end, it ensures that Django avoids adding additional directories)</li><li>(venv) <strong><em>python manage.py migrate</em></strong>: Initialize database</li><li>(venv) <strong><em>python manage.py runserver</em></strong>: Start local web server</li><li>(venv) <strong><em>python manage.py startapp pages</em></strong>: Start a new django app within the project<br>Django loads apps from top to bottom, so generally speaking it’s a good practice to add new apps below built-in apps</li><li>(venv) <strong><em>pip freeze &gt; requirements.txt</em></strong>: output contents of current virtual environment into a new file</li><li>(venv) <strong><em>deactivate</em></strong>: Deactivate virtual environment</li></ul><h4>Technical User Flow</h4><ul><li>User enters homepage</li><li>User routed to <strong><em>django_project/urls.py</em></strong></li><li>User re-routed to <strong><em>pages/urls.py</em></strong> (after adding an explicit path redirecting <strong><em>“”</em></strong> to <strong><em>pages.urls</em></strong>)<br><strong><em>path(“”, include(“pages.urls”))</em></strong></li><li>User re-routed to <strong><em>home_page_view</em></strong> (after adding an explicit path redirecting <strong><em>“”</em></strong> to <strong><em>home_page_view</em></strong><br><strong><em>path(“”, home_page_view, name = “home”)</em></strong></li></ul><h4>URLs &amp; Views</h4><p><strong>Coding Workflow</strong></p><ul><li>Create App</li><li>Add App to global <strong><em>settings.py</em></strong></li><li>Add URL to global <strong><em>urls.py</em></strong> which point’s to app’s <strong><em>urls.py</em></strong></li><li>Add URL to app’s <strong><em>urls.py</em></strong> which points to specific view</li><li>Add view to app’s <strong><em>views.py</em></strong> which points to model and template</li></ul><h4>Templates</h4><p><strong>Coding Workflow</strong></p><ul><li>Create Templates folder</li><li>Add templates URL to global <strong><em>settings.py</em></strong></li><li>Add relevant files into Template folder, e.g. <strong><em>_base.html</em></strong> which is meant to be inherited / standardized</li></ul><h4>Static files</h4><ul><li>Contain CSS, JS, Images, and other relevant info</li><li>Create relevant folders for each and making them available using staticfiles directory settings in <strong><em>settings.py</em></strong></li><li>Make sure to include “<strong><em>{% load static %}</em></strong>” in your template to call upon static files</li><li><strong><em>collectstatic</em></strong> combines all static files into a single location to serve a single larger HTTP request — which is a more efficient approach for production environments</li></ul><h4>Models, esp. Custom User Models</h4><p><strong>Coding Workflow<br></strong><em>Note: Need to be setup before migrations given how tightly interwoven models are to Django framework.</em></p><ul><li>Create <strong><em>CustomUser</em></strong> model</li><li>Update <strong><em>django_project/settings.py</em></strong></li><li>Customize <strong><em>UserCreationForm</em></strong> and <strong><em>UserChangeForm</em></strong></li><li>Add custom user model to <strong><em>admin.py</em></strong></li></ul><blockquote>At any point, retrieving custom user models should typically be done using the following syntax: <strong>from django.contrib.auth import get_user_model </strong>, to ensure that all code points to the same source</blockquote><h4>Forms, esp. Custom User Forms</h4><ul><li>Models can be created and edited in admin as well as on user front</li><li>Built-in forms can point to <strong><em>User </em></strong>model or <strong><em>CustomUser</em></strong> models</li><li>Custom forms can inherit built-in forms (e.g. <strong><em>UserCreationForm</em></strong>, <strong><em>UserChangeForm</em></strong>)</li><li>Forms &amp; models need to be registered in <strong><em>admin.py</em></strong> to appear in admin<br>e.g. <strong><em>admin.site.register(CustomUser, CustomUserAdmin)</em></strong></li><li>Forms typically sit in an app’s <strong><em>forms.py</em></strong>, though they need to be registered (alongside models) in <strong><em>admin.py <br></em></strong>N.B. <strong><em>accounts/forms.py</em></strong> and <strong><em>accounts/admin.py</em></strong> contain these declarations for account-related models &amp; corresponding forms</li></ul><h4>Tests</h4><p>Two main types of tests.</p><ul><li><strong>Unit tests:</strong> Small, fast, isolated to specific functionality; ideally lots of unit tests</li><li><strong>Integration tests:</strong> Large, slow, test entire app / user flow (e.g. payment); ideally few integration tests</li></ul><p><strong>Unit Tests</strong></p><ul><li>Django’s <strong><em>TestCase</em></strong> (which is an extension of Python’s <strong><em>TestCase</em></strong>) is used to write Unit Tests</li><li>These tests typically sit in <strong><em>tests.py</em></strong> (e.g. <strong><em>accounts/tests.py</em></strong> for account-related models &amp; corresponding views, etc.)</li><li>Each test method should start with the word ‘test’ to ensure that it is run by Django</li></ul><p><strong>Other notes</strong></p><ul><li><strong><em>django.urls.reverse</em></strong>: Easy way to get and call URLs associated with specific URL names<br>e.g. <strong><em>reverse(“home”)</em></strong> returns the URL associated with “<strong><em>home</em></strong>” (e.g. “”, which is typically defined in <strong><em>urls.py</em></strong>)</li><li><strong><em>django.urls.resolve</em></strong>: .. resolve a given path</li><li>response code <strong><em>200</em></strong>: Implies that the URL exists; does not say anything about the contents</li><li>Setup functions within test classes prevent code repetition within test functions</li></ul><blockquote>Sidenote: Tests are so boring :(</blockquote><h4>Settings.py</h4><p>The holy grail of a Django project. This summarizes most key things you need to keep an eye out for in <strong><em>settings.py (</em></strong>in the main project directory)</p><p><strong>General Settings</strong></p><ul><li><strong><em>INSTALLED_APPS = [ .. ]</em></strong>, to add new apps whenever a new app is created</li><li><strong><em>TEMPLATES</em></strong><br>- <strong><em>“DIRS”: [BASE_DIR / “templates” ]</em></strong>, with the templates folder containing relevant .html files</li></ul><p><strong>Database</strong> <strong>Settings</strong></p><p>When going with non production environments, use the following:</p><ul><li><strong><em>DATABASE </em></strong>settings update for PostgreSQL, including<br>- <strong><em>ENGINE </em></strong>(typically <strong><em>django.db.backends.postgresql</em></strong>)<br>- <strong><em>NAME<br>- USER<br>- PASSWORD</em></strong><br>- <strong><em>HOST</em></strong> (<em>typically “db”</em>)<br>- <strong><em>PORT</em></strong></li></ul><p>In case of production environments / docker containers, use the following:</p><ul><li><strong><em>DATABASES = {<br> “default”: env.dj_db_url(https://medium.com/%E2%80%9CDATABASE_URL%E2%80%9D,%20%3Cbr%3E%20default%20=%20%E2%80%9Cpostgres://postgres@db/postgres%E2%80%9D)<br>}</em></strong></li></ul><blockquote><em>Note: </em><strong>docker-compose.yml</strong><em> likely needs to contain this / be updated for this</em></blockquote><p><strong>Authentication Settings</strong></p><ul><li><strong><em>AUTH_USER_MODEL = “accounts.CustomUser”</em></strong>, for specifying new / custom user models</li><li><strong><em>LOGIN_REDIRECT_URL = “home”</em></strong>, for specifying the redirect URL after the user has logged in</li><li><strong><em>LOGOUT_REDIRECT_URL = “home”</em></strong>, similar to above</li></ul><p><strong>Static File Settings</strong></p><p><em>N.B: I don’t fully understand this static file stuff. Deep dive for another day</em></p><ul><li><strong><em>STATICFILES_DIRS = [BASE_DIR / “static”]</em></strong>, to allow project wide access to static files</li><li><strong><em>STATIC_ROOT = BASE_DIR / “staticfiles”</em></strong>, which sets absolute location of collected files after running the <strong><em>collectstatic</em></strong> command</li><li><strong><em>STATICFILES_STORAGE = “django.contrib.staticfiles.storage.StaticFilesStorage”</em></strong>, which is the file storage engine used when collecting static files with the collectstatic command</li><li><strong><em>MEDIA_ROOT = BASE_DIR / “media”</em></strong>, the absolute file system path to the directory for user-uploaded files</li><li><strong><em>MEDIA_URL = “/media/”</em></strong>, the URL we use in our <em>templates</em> for the files</li></ul><p><strong>Environment &amp; Security settings<br></strong>These allow environment specific settings, prevent API key exposure, esp. if you’re using github, etc.</p><ul><li><strong><em>from environs import Env<br>env = Env()<br>env.read_env()</em></strong></li><li>Change <strong><em>SECRET_KEY</em></strong> to point to the secret key stored in docker-compose.yml, which contains details about the environment</li><li><strong><em>DEBUG = env.bool(“DJANGO_DEBUG”, default = False)</em></strong>, to change the default DEBUG setting in production to mimic the production file (in this case <strong><em>docker-compose.yml</em></strong>)</li><li><strong><em>ALLOWED_HOSTS = [“.herokuapp.com”, “localhost”, “127.0.0.1”]</em></strong>, to control the specific hosts or domains that can access the website</li><li>(Production only) <strong><em>SECURE_SSL_REDIRECT = env.bool(“DJANGO_SECURE_SSL_REDIRECT”, default=True)</em></strong>, for enabling https</li><li><strong><em>SECURE_HSTS_SECONDS = env.int(“DJANGO_SECURE_HSTS_SECONDS”, default=2592000)</em></strong> (0 by default; the greater, the better for security, set to 30 days worth here)</li><li><strong><em>SECURE_HSTS_INCLUDE_SUBDOMAINS = env.bool(“DJANGO_SECURE_HSTS_INCLUDE_SUBDOMAINS”,<br>default=True)</em></strong>; forces subdomains to use SSL; set to True in Production</li><li><strong><em>SECURE_HSTS_PRELOAD = env.bool(“DJANGO_SECURE_HSTS_PRELOAD”, default=True)</em></strong>; only has an effect when there is a non-zero value for <strong><em>SECURE_HSTS_SECONDS</em></strong></li><li><strong><em>SESSION_COOKIE_SECURE = env.bool(“DJANGO_SESSION_COOKIE_SECURE”, default=True)</em></strong>; forces cookies over https connections</li><li><strong><em>CSRF_COOKIE_SECURE = env.bool(“DJANGO_CSRF_COOKIE_SECURE”, default=True)</em></strong>; forces only cookies marked as “secure” to be sent with an https connection</li></ul><p><strong>Crispy Form Settings<br></strong>(in addition to <strong>INSTALLED_APPS</strong> — <strong><em>crispy_forms</em></strong>, <strong><em>crispy_bootstrap5</em></strong>)</p><ul><li><strong><em>CRISPY_ALLOWED_TEMPLATE_PACKS = “bootstrap5”</em></strong></li><li><strong><em>CRISPY_TEMPLATE_PACK = “bootstrap5”</em></strong></li></ul><p><strong>AllAuth Settings<br></strong>(in addition to <strong>INSTALLED_APPS</strong> — <strong><em>allauth</em></strong>, <strong><em>allauth.account</em></strong>; sometimes you may need to add <strong><em>allauth.socialaccount</em></strong> if you get a <strong><em>socialaccount</em></strong> error)</p><ul><li><strong><em>SITE_ID = 1</em></strong></li><li><strong><em>AUTHENTICATION_BACKENDS = (“django.contrib.auth.backends.ModelBackend”, “allauth.account.auth_backends.AuthenticationBackend”,)</em></strong><br>Note: First one is a default but is needed; second one is for allauth</li><li><strong><em>ACCOUNT_LOGOUT_REDIRECT = “home”</em></strong>, to explicitly <strong><em>replace LOGOUT_REDIRECT_URL</em></strong>, even though <strong><em>allauth</em></strong> implicitly overrides this</li><li><strong><em>ACCOUNT_SIGNUP_PASSWORD_ENTER_TWICE = False</em></strong>, to ensure password is asked for only once</li><li><strong><em>ACCOUNT_USERNAME_REQUIRED = False</em></strong>, to skip to email only sign-in</li><li><strong><em>ACCOUNT_AUTHENTICATION_METHOD = “email”</em></strong>, to allow users to login via email</li><li><strong><em>ACCOUNT_EMAIL_REQUIRED = True</em></strong>, to remove email optionality</li><li><strong><em>ACCOUNT_UNIQUE_EMAIL = True</em></strong>, to ensure emails are unique identifiers</li></ul><p><strong>Email Settings</strong></p><ul><li><strong><em>DEFAULT_FROM_EMAIL</em></strong>; default setting for where admin emails (e.g. signup confirmation) goes from</li><li><strong><em>EMAIL_BACKEND = “django.core.mail.backends.console.EmailBackend”</em></strong><em>, </em>allowing Django to output any emails to command line instead in the absence of an SMTP server</li><li><strong><em>EMAIL_BACKEND = “django.core.mail.backends.smtp.EmailBackend”</em></strong>, allowing Django to attempt to communicate to an SMTP server to send emails</li></ul><p><strong>Cache Settings</strong></p><blockquote>N.B. There are 4 broad types of cache: per-site cache (simplest), per-view cache (for specific views), template fragment cache (for specific template components), low-level cache API (for specific objects)</blockquote><ul><li>To implement per-site caching, add <strong><em>django.middleware.cache.UpdateCacheMiddleware</em></strong> and <strong><em>django.middleware.cache.FetchFromCacheMiddleware</em></strong> to the top and bottom of <strong><em>MIDDLEWARE</em></strong></li><li>Add the following three additional fields (author’s note: unsure what they do)<br>- <strong><em>CACHE_MIDDLEWARE_ALIAS = “default”</em></strong><br>- <strong><em>CACHE_MIDDLEWARE_SECONDS = 604800 </em></strong>(i.e. 1 week, default is 600s)<br>- <strong><em>CACHE_MIDDLEWARE_KEY_PREFIX = “”</em></strong></li></ul><p><strong>Debug Toolbar Settings</strong></p><p>N.B. This has some prerequisites!</p><ul><li>Add the following to <strong><em>urls.py<br>if settings.DEBUG:<br> import debug_toolbarurlpatterns = [path(“__debug__/”, include(debug_toolbar.urls)),] + urlpatterns</em></strong></li><li><strong><em>django-debug-toolbar</em></strong> is included in <strong><em>requirements.txt</em></strong></li></ul><p>Now onto <strong><em>settings.py</em></strong></p><ul><li><strong><em>import socket </em></strong>at the top</li><li>For remote / production environments:<br><strong><em>hostname, _, ips = socket.gethostbyname_ex(socket.gethostname())<br>INTERNAL_IPS = [ip[:-1] + “1” for ip in ips]</em></strong></li><li>For <a href="https://stackoverflow.com/questions/10517765/django-debug-toolbar-not-showing-up">docker</a> environments:<br><strong><em>def show_toolbar(request): return True<br>DEBUG_TOOLBAR_CONFIG = { “SHOW_TOOLBAR_CALLBACK”: show_toolbar }</em></strong></li></ul><h3>Docker</h3><h4>Overview</h4><ul><li>Reproduces production environment locally (incl. proper Python version, database, etc.)</li><li>Collaboration is easier; just share <strong><em>Dockerfile</em></strong> and <strong><em>docker-compose.yml</em></strong></li><li>Helps isolate an entire OS via Linux containers</li><li>Avoids the size &amp; speed requirements of regular virtualization<br>e.g. a typical guest OS takes 700MB space; one server supports 3 VMs, implying 2.1GB alongside separate CPU &amp; memory space needs. Docker virtualizes from the Linus layer instead</li><li><strong>VMs</strong> are homes (stand-alone buildings with plumbing heating bathrooms bedrooms, etc); <strong>Docker containers</strong> are apartments (shared plumbing &amp; heating, come in various sizes to fit owner needs)</li><li><strong>Virtual Environments</strong> isolate Python packages (done using <em>venv</em>); they can’t isolate non-Python software like PostgreSQL or MySQL; they rely on computer’s python installation &amp; point to it (rather than containing Python); Linux <strong>containers </strong>isolate entire OS (not just Python)</li></ul><h4>Workflow</h4><ul><li>Create <strong><em>Dockerfile</em></strong> with custom image instructions</li><li>Add <strong><em>.dockerignore</em></strong> file</li><li>Build image (<strong><em>docker build</em></strong>)</li><li>Create <strong><em>docker-compose.yml</em></strong></li><li>Run container (<strong><em>docker-compose up</em></strong>)</li><li>Deactivate container (<strong><em>docker-compose down</em></strong>)</li></ul><h4>Shell Commands</h4><ul><li><strong><em>docker run hello-world</em></strong>: Simple run to check if its working</li><li><strong><em>docker info</em></strong>: generic info; important to look at # of containers and how many are running vs. stopped (under Server)</li><li><strong><em>docker build .</em></strong>: Build custom image</li><li><strong><em>docker-compose up</em></strong>: Run docker container</li><li><strong><em>docker-compose up -d</em></strong>: Run docker container in detached mode, i.e. in background, to avoid switching back and forth</li><li><strong><em>docker-compose up -d — — build</em></strong>: Run docker container in detached mode but also rebuild using new files</li><li><strong><em>docker-compose logs</em></strong>: See logs manually especially during detached mode</li><li><strong><em>docker-compose down</em></strong>: Deactivate container and save memory</li><li><strong><em>docker-compose exec [service]</em></strong>: Run services within docker (rather than locally)</li><li><strong><em>docker-compose exec web python manage.py migrate</em></strong>: Initialize database on docker container (before creating any users, etc.)</li><li><strong><em>docker-compose exec web python manage.py createsuperuser</em></strong>: Create superuser (ensure you have initialized database)</li><li>(In case of custom models) <strong><em>docker-compose exec web python manage.py makemigrations accounts</em></strong>: Makes relevant database migrations / models based on custom defined user models</li><li><strong><em>docker-compose exec web python manage.py test:</em></strong> Run any tests :)</li><li><strong><em>docker-compose exec web python manage.py collectstatic</em></strong>: Combine all static files into a new staticfiles directory</li><li><strong><em>docker-compose exec web python manage.py check — — deploy</em></strong>: Deployment checklist to track potential bugs, etc.</li><li><strong><em>docker-compose -f docker-compose-prod.yml up -d</em></strong>: To use a separate docker-compose file for checking production related bugs</li><li><strong><em>docker-compose exec web python -c “import secrets; print(secrets.token_urlsafe(38))”</em></strong>: Generate random secret key with base64 encoding, with 38 resulting in 51 characters; this typically goes into <strong><em>docker-compose-prod.yml</em></strong> in case you accidentally commit your <strong><em>docker-compose.yml</em></strong> file to git</li></ul><h4>Docker Files</h4><p><strong><em>Docker Image</em></strong></p><ul><li>Read-only template to describe how to create a Docker container</li><li><strong><em>Image</em></strong> = instructions or blueprint or set of plans for building an apartment; <strong><em>container</em></strong> = actual running instance of image or actual fully-built building</li></ul><p><strong><em>Dockerfile</em></strong></p><ul><li>Defines the steps to create and run the custom image</li><li><strong><em>FROM</em></strong> tells Docker what base image we would like to use; images can be inherited from other images (e.g. official python image has relevant tools &amp; packages needed for django apps)</li><li><strong><em>ENV</em></strong> to set environment variables, e.g.<br>- <strong><em>PIP_DISABLE_PIP_VERSION_CHECK</em></strong>: Disable automatic pip updates check<br>- <strong><em>PYTHONDONTWRITEBYTECODE</em></strong>: Avoid writing .pyc files<br>- <strong><em>PYTHONUNBUFFERED</em></strong>: ensure console output isn’t buffered by Python</li><li><strong><em>WORKDIR</em></strong> to set relative working directory for future commands</li><li><strong><em>COPY</em></strong> takes 2 parameters: what file to copy into the image, where to copy the file to (for example, “<em>./requirements.txt .”</em> copies <em>requirements.txt</em> from local computer to the working directory)</li><li><strong><em>RUN</em></strong> executes similar to command line, but on the image; <em>-r</em> flag asks pip to open the file <em>requirements.txt</em> and install its contents</li></ul><p><strong><em>.dockerignore</em></strong></p><ul><li>Specify files and directories that shouldn’t be included in the Docker image</li><li>Reduces overall image size, improves security.doc</li></ul><p><strong><em>docker-compose.yml</em></strong></p><ul><li>After building image, we need instructions to run the container, which is in this file</li><li><strong><em>version</em>:</strong> Most recent version of Docker Compose (considered obsolete at this point)</li><li><strong><em>services</em>:</strong> Specify which services / containers we want to have running within our host; <strong>web</strong> is most common; <strong>db </strong>is another<br><em>— both are separate containers; web is dependent on db</em></li><li>(service) <strong><em>web</em>:</strong> <br>- <strong><em>build</em></strong>: Look in current directory for Dockerfile<br>- <strong><em>ports</em></strong>: Django default of 8000<br>- <strong><em>command</em></strong>: execute “python manage.py runserver 0.0.0.0:8000” to run server locally<br>- <strong><em>volumes</em></strong>: ensures any creation on docker is reflected on the local host (same as db)<br>- <strong><em>depends_on</em></strong>: (typically ‘db’) to ensure web container is connected to the database or any other container<br>- <strong><em>environment</em></strong>:<br> — Insert your django project key here, using the moniker, <strong><em>“DJANGO_SECRET_KEY = ..” </em></strong>(airquotes included, with an extra <strong><em>$ </em></strong>sign needed if the key includes a <strong><em>$</em></strong> sign), and adjust the <strong><em>SECRET_KEY</em></strong> variable in <strong><em>settings.py<br> — </em></strong>Insert your debug defaults here, using <strong><em>“DJANGO_DEBUG=True”</em></strong>, and adjust <strong><em>DEBUG</em></strong> in<strong><em> settings.py</em></strong> to point to environment settings</li><li>(service) <strong><em>db</em>:<br>- <em>image</em>: </strong>Version (e.g. postgres:13)<br>- <strong><em>volumes</em></strong>: Location of dedicated directory to which data is binded (more on this below)<br>- <strong><em>environment</em></strong>: Helps specify trust authentication<br><em>N.B. I’m not sure what this last bit actually means</em></li><li><strong><em>volumes</em>:</strong> Mount which is bound to a dedicated directory within the db container at the location specified (e.g. <strong><em>/var/lib/postgresql/data/</em></strong>)<br><em>N.B. This is needed since containers are ephemeral in nature, and any info is lost when the container stops</em></li></ul><h3>Fly / Deployment</h3><p>This is tricky, despite <a href="https://fly.io/django-beats/deploying-django-to-production/">this</a> splendid guide by fly.io. Some of it is driven by versions of Django, others due to some odd dependencies.</p><p>Some necessary deviations from the aforementioned guide:</p><h4><strong><em>Dockerfile</em></strong></h4><p><em>N.B. Fly’s natural deployment process will generate a new Dockerfile for you; best to have a copy of the original you use in Docker for local testing</em></p><ul><li><strong><em>pillow</em></strong>* has a lot of dependencies; you need to add <br><strong><em>libjpeg62-turbo-dev \</em></strong> and, ..<br><strong><em>zlipb1g-dev \<br></em></strong><em>.. </em>as separate lines under <br><strong><em>RUN apt-get-update &amp;&amp; apt-get install -y \<br></em></strong>*checkout <strong><em>requirements.txt</em></strong></li></ul><h4>docker-compose.yml</h4><p><strong><em>db</em></strong> connections don’t always work, and I’m unsure if this flows to the production environment, but for the sake of completion, including these:</p><ul><li>under the <strong><em>web </em></strong>container, add <br><strong><em>links:<br> — db:db<br>networks:<br> — djangonetwork</em></strong></li><li>under the <strong><em>db</em></strong> container, add<br><strong><em>container_name: db<br>networks:<br> — djangonetwork</em></strong></li><li>Add a separate spec (on top of ‘<strong><em>services’ </em></strong>and ‘<strong><em>volumes’</em></strong>), called ‘<strong><em>networks</em></strong>’, i.e.<br><strong><em>djangonetwork:</em></strong><br> <strong><em>driver: bridge</em></strong></li></ul><h4>Settings.py</h4><ul><li><strong><em>SECRET_KEY</em></strong> declaration needs to be updated from <strong><em>DJANGO_SECRET_KEY</em></strong> to <strong><em>SECRET_KEY</em></strong>, i.e.<br><strong><em>SECRET_KEY = env.str(“SECRET_KEY”, default=get_random_secret_key())</em></strong></li></ul><p>Will keep adding as they come \o/</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6e5ff10a869" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Ultimate Machine Learning Glossary for Data Scientists]]></title>
            <link>https://medium.com/@shitijnigam/machine-learning-fundamentals-0594696db3cc?source=rss-65eb3c05bb84------2</link>
            <guid isPermaLink="false">https://medium.com/p/0594696db3cc</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[statistics]]></category>
            <dc:creator><![CDATA[Shitij Nigam]]></dc:creator>
            <pubDate>Thu, 23 May 2024 13:30:06 GMT</pubDate>
            <atom:updated>2024-05-30T13:09:25.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEtGOYLC39XphOCOAKh55Q.jpeg" /></figure><blockquote><strong><em>Table of Contents</em></strong></blockquote><blockquote><a href="#6571"><strong><em>Baseline Concepts</em></strong></a><em><br> ∘ </em><a href="#f3ca"><em>Types of Data</em></a><em><br> ∘ </em><a href="#df7c"><em>Training vs. Validation vs. Test data</em></a><em><br> ∘ </em><a href="#fb94"><em>Bias vs. Variance</em></a><em><br> ∘ </em><a href="#13d8"><em>Bootstrapping, Bagging, Regularization</em></a><em><br> ∘ </em><a href="#ead8"><em>Probability vs. Likelihood</em></a><em><br></em><a href="#68f2"><strong><em>Supervised Learning</em></strong></a><em><br> ∘ </em><a href="#8725"><em>Overview</em></a><em><br> ∘ </em><a href="#26ff"><em>Naive Bayes</em></a><em><br> ∘ </em><a href="#b03a"><em>Gaussian Naive Bayes (GNB)</em></a><em><br> ∘ </em><a href="#8cc5"><em>Support Vector Machines (SVM)</em></a><em><br> ∘ </em><a href="#3186"><em>Classification Decision Trees</em></a><em><br> ∘ </em><a href="#1148"><em>Regression Decision Trees</em></a><em><br> ∘ </em><a href="#332c"><em>Random Forests</em></a><em><br> ∘ </em><a href="#0685"><em>AdaBoost</em></a><em><br> ∘ </em><a href="#e58a"><em>K-nearest neighbors</em></a><em><br> ∘ </em><a href="#55f1"><em>Linear Regression</em></a><em><br> ∘ </em><a href="#ea4f"><em>Multiple Regression</em></a><em><br> ∘ </em><a href="#0864"><em>Logistic Regression</em></a><em><br></em><a href="#c1b7"><strong><em>Unsupervised Learning</em></strong></a><em><br> ∘ </em><a href="#4fbe"><em>k-Means Clustering</em></a><em><br> ∘ </em><a href="#b788"><em>Dimensionality reduction</em></a><em><br> ∘ </em><a href="#c378"><em>Association rules</em></a><em><br></em><a href="#8bff"><strong><em>Other Important Concepts</em></strong></a><em><br> ∘ </em><a href="#9e2f"><em>Cross Validation</em></a><em><br> ∘ </em><a href="#4156"><em>Principal Component Analysis (PCA)</em></a><em><br></em><a href="#f4d8"><strong><em>Appendix</em></strong></a><em><br> ∘ </em><a href="#7e14"><em>SciKit Learn Coding Pattern</em></a><em><br> ∘ </em><a href="#8d15"><em>Filetypes</em></a></blockquote><h3>Baseline Concepts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZxAexY9Yc-1T9ZvJbendw.jpeg" /></figure><h4>Types of Data</h4><ul><li><strong>Numerical,</strong> e.g. Salary information</li><li><strong>Categorical</strong>, i.e. limited number discrete values, <em>e.g. man / woman, stars given to a movie, etc.</em></li><li><strong>Time series,</strong> i.e. data with temporal value <em>e.g. date, timestamp</em></li><li><strong>Test,</strong> i.e. words — typically turned into numbers <em>(via tokenization, word2vec, etc.)</em></li></ul><h4>Training vs. Validation vs. Test data</h4><ul><li><strong>Training</strong>: Data on which algorithm / model is trained on</li><li><strong>Validation:</strong> ~10% of data, data on which algorithm / model is tested</li><li><strong>Test: </strong>Data on which algorithm is validated</li></ul><p><em>N.B. Sometimes Test and Validation terminology is reversed</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/0*SX-oXCPftNZhSFxC.png" /><figcaption><a href="https://towardsdatascience.com/train-validation-and-test-sets-72cb40cba9e7">https://towardsdatascience.com/train-validation-and-test-sets-72cb40cba9e7</a></figcaption></figure><h4>Bias vs. Variance</h4><ul><li><strong>Bias: </strong>When data is <strong>underfit</strong> to training data; a high bias algorithm practically ‘ignores’ data, i.e.<em> “inability of a machine learning method to capture the true relationship” between variables”</em></li><li><strong>Variance: </strong>When data is <strong>overfit</strong> to training data, resulting in difference in fits between training and test data sets; a high variance algorithm is unable to generalize to new information</li></ul><p><em>Ideal models have low bias and low variability — via semi complicated models. Regularization, Boosting, and Bagging help achieve this.</em></p><h4>Bootstrapping, Bagging, Regularization</h4><ul><li><strong>Bootstrapping:</strong> Creating a new sample dataset by randomly sampling from the existing dataset (with replacement — which allows us to have duplicate data in the generated bootstrap)</li><li><strong>Bagging: </strong>Using the average of model predictions trained on multiple bootstrap samples</li><li><strong>Regularization: </strong>This is an automatic form of feature selection to trade-off between “goodness” of fit and complexity of fitting a lot of features. Usually added in regression<br><strong><em>Lasso Regression (L1): Penalizes extra features</em></strong><em>, by minimizing<br>[ Error + (Penalty Parameter λ * Number of Features) ]<br></em><strong><em>Ridge Regression (L2): Reduces variance</em></strong><em> via bias, by minimizing<br>[ Error + (Penalty Parameter λ * Slope²) ]; the larger the lambda, the less our dependent variable y prediction becomes sensitive to independent variables</em></li></ul><h4>Probability vs. Likelihood</h4><p>For a normal distribution of any parameter with mean <em>μ</em> and standard deviation <em>σ</em></p><ul><li><strong>Probability:</strong> The area under the curve <strong>between</strong> a certain range represents the probability of this range<br>i.e. P (<em>a</em> <em>&lt; x</em> <em>&lt; b</em> | Mean = <em>μ</em>, Standard Deviation = <em>σ</em>) is the area under the normal distribution curve between <em>a</em> and <em>b</em></li><li><strong>Likelihood:</strong> This is the point on the curve on the <em>y axis</em>, when <em>x</em> is <strong>equal to</strong> <em>a </em>(i.e. likelihood of a distribution given data)<em><br></em>i.e. L (Mean = <em>μ</em>, Standard Deviation = <em>σ </em>| <em>x = a</em>) is the point on the y axis of a normal distribution curve, where x = a</li></ul><h4><strong>Classification vs. Regression problems</strong></h4><ul><li><strong>Classification:</strong> Aims to determine <em>discrete class labels</em> through <em>decision boundaries</em>, which can be evaluated via <em>accuracy</em></li><li><strong>Regression:</strong> Aims to determine continuous numbers through a <em>best fit line</em>, which can be evaluated via <em>R², SSEs, etc.</em></li></ul><h4>Feature Scaling &amp; Standardization</h4><ul><li><strong>Feature scaling:</strong> Allows us to easily compare different features using a simple formula by pushing them between 0 and 1; suitable when there’s no outliers (which may skew the min/max)<br><em>x_scaled = (x — x_min) ÷ (x_max — x_min)</em></li><li><strong>Feature standardization: </strong>Allows us to transform features into standard distribution of zero mean and unit variance through a simple formula<br><em>x_standardized = (x — x_mean) ÷ x_std</em></li></ul><h4>Evaluation Metrics</h4><ul><li><strong>Accuracy:</strong> # of all data points labeled correctly ÷ All data points<br><em>N.B. Not ideal for skewed classes; depending on denominator, it could push skews one way or the other</em></li><li><strong>Confusion Matrices:</strong> 2x2 table of actual vs. predicted classes — positive and negative, representing counts of each.</li><li><strong>Precision:</strong> True Positive / (True Positive + False Positive). Out of all the items labeled as positive, how many truly belong to the positive class.<br><em>i.e. 10 out of the 20 values classified as a particular class were correctly classified (‘True Positive’), the rest were incorrectly classified (‘False Positive’), implying 50% Precision</em></li></ul><blockquote><strong>Precision: </strong>“If you shot a bird X times, how precise was your shot?”</blockquote><ul><li><strong>Recall</strong>: True Positive / (True Positive + False Negative). Out of all the items that are truly positive, how many were correctly classified as positive. Or simply, how many positive items were ‘recalled’ from the dataset<br><em>i.e. 10 out of the 16 values of a particular class were correctly classified (‘True Positive’); the rest were misclassified as other classes (‘False Negative’), implying 62.5% Recall</em></li></ul><blockquote><strong>Recall: </strong>“If you tried to remember how many marbles there are in a pouch, how many did you correctly recall?”</blockquote><h3>Supervised Learning</h3><p>TL;DR — Show examples, let machine learn.</p><h4>What goes in and what comes out</h4><ul><li><strong>Inputs:</strong> Features (e.g. intensity, tempo, genres)</li><li><strong>Outputs: </strong>Labels (e.g. ‘like’, ‘don’t like’)</li></ul><h4>Naive Bayes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdHfTR3_QWzVX1Ru6P53UA.jpeg" /></figure><p>Common algorithm to determine decision surface; typically used for text classification; it takes all words, assigns probabilities to a label for each word, and multiplies and sums them up to get a “net” probability or score <em>(using bayes algorithm)</em></p><ul><li><strong>Pros: </strong>Does well with large features / large # of words; has <strong><em>low variance</em></strong></li><li><strong>Cons:</strong> Ignores word <strong><em>order</em></strong> (that’s why ‘naive’); breaks with phrases (e.g. ‘Chicago Bulls’); has <strong><em>high bias</em></strong></li></ul><p><strong>Notable adjustments</strong></p><ul><li><strong>Alpha α: </strong>If a word doesn’t occur in our spam histogram, e.g. “Lunch”, then a message may never be marked as spam since P(Lunch | Spam) = 0. For this reason, we typically add a single number to each word in a histogram to ensure non zero probability. <strong>This number (1, in this case), is known as alpha α</strong></li></ul><p><strong>Naive Bayes Example<br></strong><em>Source: </em><a href="https://www.youtube.com/watch?v=O2L2Uv9pdDA&amp;ab_channel=StatQuestwithJoshStarmer"><em>StatQuest</em></a></p><ul><li>Suppose we want to filter spam from family messages</li><li>First, we make a <strong>histogram of all words occurring in messages from friends and family</strong>; use the histogram to calculate <strong><em>(conditional)</em></strong> probabilities of seeing each word <strong><em>given </em></strong>that it was a normal message, <em>e.g. P (Dear | Normal), P (Friend | Normal), ..</em></li><li><strong>Do the same thing for spam messages,</strong> <em>e.g. P (Dear | Spam), P (Friend | Spam), ..</em></li><li><strong>Now estimate the</strong> <strong>Prior Probability</strong> <strong>P(Normal) </strong>of a normal message using training data. e.g. if 8 out of total 12 messages are normal messages, P(Normal) = 0.67, P(Spam) = 0.33</li></ul><p>For a new message (e.g. <em>“Dear Friend”</em>)</p><ul><li><strong>To get the SCORE that “Dear Friend” gets if its a normal message</strong>, i.e. P(Normal | Dear Friend)<em>, </em>multiply P(Normal), P(Dear | Normal), P (Friend | Normal)<br><em>i.e. P(N | Dear Friend) </em><strong><em>∝</em></strong><em> P(N) * P(Dear | N) * P (Friend | N)<br></em><strong><em>i.e. P(Normal | Dear Friend) ∝ 0.09</em></strong></li><li><strong>To get the SCORE that “Dear Friend” gets if its a Spam message</strong>, i.e. P(Spam | Dear Friend)<em>, </em>multiply P(Spam), P(Dear | Spam), P (Friend | Spam)<br><em>i.e. P(S | Dear Friend) </em><strong><em>∝</em></strong><em> P(S) * P(Dear | S) * P (Friend | S)<br></em><strong><em>i.e. P(Normal | Spam) ∝ 0.01</em></strong></li></ul><p>Based on the score, we decide “Dear Friend” is a normal message.</p><h4>Gaussian Naive Bayes (GNB)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6TMTZ-AR0jAMTyTkc21LQ.jpeg" /></figure><p>Named after the Gaussian Distributions that represent the data in the training set for different features; notable differences vs. Naive Bayes:</p><ul><li>GNB relies on distributions of underlying features of training data</li><li>GNB relies on likelihoods instead of probabilities</li><li>GNB relies on logs</li><li>We can use cross-validations to decide which features can be used to make classifications</li></ul><p><strong>Gaussian Naive Bayes Example<br></strong><em>Source: </em><a href="https://www.youtube.com/watch?v=H3EjCKtlVog&amp;ab_channel=StatQuestwithJoshStarmer"><em>StatQuest</em></a></p><ul><li>For 2 groups of people (Loves Movie, Hates Movie), we will plot Gaussian distributions of (i) popcorn consumption, (ii) soda consumption, (iii) candy consumption</li><li><strong>Prior probabilities</strong> — P(Loves Movie), P(Hates Movie) are similarly calculated as in Naive Bayes, using training data distribution</li></ul><p>For a new person with a specific consumption, i.e. popcorn <em>p</em>, soda pop <em>s</em>, candy <em>c</em>, scores will be calculated using likelihood, i.e.</p><ul><li><strong>P(Loves Movie | p, s, c) ∝</strong> <em>log [</em> P (Loves Movie) * L (Popcorn = <em>p</em> | Loves Movie) * L (Soda Pop = <em>s</em> | Loves Movie) * L(Candy = <em>c</em> | Loves movie) <em>]</em></li><li><strong>P(Hates Movie | p, s, c) ∝</strong> <em>log [</em> P (Hates Movie) * L (Popcorn = <em>p</em> | Hates Movie) * L (Soda Pop = <em>s</em> | Hates Movie) * L(Candy = <em>c</em> | Hates movie) <em>]</em></li></ul><blockquote><strong>Sidebar:</strong> Sometimes, for small numbers / small likelihoods, taking <strong>Log</strong> of numbers can help <strong>avoid underflows</strong>; natural log, i.e. log base e is the most commonly used log</blockquote><h4>Support Vector Machines (SVM)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Owh4VVhyRQnfh4kfC8yENA.jpeg" /></figure><p><strong>SVMs </strong>(i) start with data in lower dimension, (ii) move data into higher dimension, (iii) find SVC (Support Vector Classifier) separating higher dimension data into two groups (<a href="https://www.youtube.com/watch?v=efR1C6CvhmE&amp;ab_channel=StatQuestwithJoshStarmer">from StatQuest</a>)</p><ul><li><strong>Margin: </strong>The Hyperplane (<em>may be a line, plane, etc. depending on the number of parameters</em>) maximizes the distance between two categories, known as <em>Margin</em> (“distance between line and the nearest point of either of the 2 classes”)<br><em>Choosing a threshold that allows misclassifications is an example of bias/variance trade-off</em></li><li>When we <strong>allow misclassifications</strong>, it is known as <strong>soft margin<br></strong><em>We use cross validation to determine the best soft margin</em></li><li><strong>Pros:</strong> Effective in high-D even if # of dimensions &gt; # of samples; can tolerate outliers relatively well</li><li><strong>Cons:</strong> Poor performance if # of features &gt; # of samples, esp. for large datasets</li></ul><p><strong>Key parameters</strong></p><ul><li><strong>Kernel,</strong> i.e. type of kernel<em>, e.g. radial, linear, sigmoid, etc. (more details below)</em></li><li><strong>C: </strong>It “controls the tradeoff between smooth decision boundary and classifying training points correctly”; the larger C is, the more “intricate” the classification boundary will be<br><em>N.B. C is inversely proportional to regularization, i.e. the higher the C, the less the regularization, implying that the loss function is allowed to fit more intricate (and potentially large) weights to determine the hyperplane.</em></li><li><strong>Gamma</strong>: Defines how far the influence of a single training example reaches; the higher the gamma, the more influence a datapoint far away from the hyperplane has on it, and the more “wiggly” the decision boundary becomes</li></ul><p><strong>Kernels</strong></p><p>Kernel functions systematically find Support Vector Classifiers (SVCs) in higher dimensions in order to decide how to transform data (i.e. from <em>x</em> to <em>x²</em> or <em>x³</em>)</p><ul><li><strong>Polynomial Kernel:</strong> An example of kernel functions; parameter <em>d</em> stands for degree of polynomial. The polynomial kernel “systematically increases dimensions by setting <em>d</em>, and the relationships between each pair are used to find an SVC”<br>e.g.<br>- When <em>d = 1</em>, relationships are computed in 1 function to determine the SVC<br>- When <em>d = 2</em>, we get a second dimension based on x², and the kernal computes 2D relationships between each pair of observation to determine the SVC<br>.. and so on<br><em>N.B. A good value of d can be found using cross validation</em></li><li><strong>Radial Kernel</strong> — finds SVCs in infinite dimensions; the closest observations / nearest neighbors have a lot of influence on classification</li></ul><blockquote><strong>The Kernel Trick: </strong>To reduce computation required, kernel functions only calculate relationships between every pair of points as if they are in higher dimensions without actually doing the transformation. This also makes radial kernel possible</blockquote><h4>Classification Decision Trees</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0xIdNPFJPSNX7HKW4SdQQ.jpeg" /></figure><p>Decision trees allow you to ask multiple linear questions, one after the other; the <strong>aim of the decision tree is to find variables and split points that make subsets as pure as possible.<br></strong><em>N.B. Purity is the % of examples in a node in a tree that are of the same class</em></p><p>The top of the tree is called the <strong>root node </strong>or the <strong>root; </strong>The middle parts are called <strong>internal nodes</strong> or <strong>branches; </strong>The end parts are called <strong>leaf nodes</strong> or <strong>leaves</strong></p><p><strong>Key Concepts</strong></p><ul><li><strong>Impurity: </strong>A node containing a mixture of different classes of data is termed as impure; impurity is the total measure of this within a node</li><li><strong>Gini Impurity of a Node </strong>= <em>1 — (probability of A)² — (probability of B)²<br>- 0 when all samples are of the same class<br>- 0.5 if they are evenly split</em><br><strong>Total Gini Impurity </strong>= Weighted Avg. Gini Impurities of Nodes<br><em>Weights distributed based on # of samples in each node</em></li><li><strong>Entropy</strong>:<em> </em>(formula below)<br>- 0 when all samples are of the same class<br>- 1 if they are evenly split (max)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCgUCed_kWaGjinSacyoxA.jpeg" /><figcaption><a href="https://www.ejable.com/tech-corner/ai-machine-learning-and-deep-learning/introduction-to-decision-trees-in-supervised-learning/">Source</a></figcaption></figure><ul><li><strong>Information gain</strong> = Entropy (Parent) — [Weighted Avg.] Entropy (Children)<br><em>N.B. The Decision Tree algorithm focuses on maximizing information gain</em></li></ul><p><strong>Pros and Cons</strong></p><ul><li><strong>Pros:</strong> Easy to use; graphically easy to understand data; you can build bigger classifiers using ensemble methods</li><li><strong>Cons:</strong> Prone to overfitting esp if data has a lot of features; you have to be careful about parameter tunes</li></ul><p><strong>Key Parameters</strong></p><ul><li><strong>min_samples_split: </strong>The size of the sample at which we stop splitting. When it’s too small, we can end up overfitting</li><li><strong>criterion: </strong>default is <em>gini</em>, which is similar to <strong><em>entropy</em></strong>; you can manually switch to entropy</li></ul><h4>Regression Decision Trees</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Q7QOlZslZESXHlCA9YNUA.jpeg" /></figure><p>Regression trees are a type of decision tree, with each leaf representing a numerical value; splits / Thresholds are determined by <strong>minimizing the sum of squared residuals at each step</strong></p><ul><li>Useful with multiple predictors where drawing graphs is harder, which are easily accommodated by Regression trees.</li><li>To avoid overfitting — similar to classification trees — we set min_samples_limit (typically 20)</li><li>With multiple possible predictors, multiple candidates are decided for SSR (sum of squared residual) and the one with lowest SSR is used</li></ul><h4>Random Forests</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jdaD5DVXs3u8AZ2-FcgY2g.jpeg" /></figure><p>Combines simplicity of decision trees and adds additional flexibility by creating multiple different trees using bootstrapped samples, with accuracy measured using out of bag error.</p><p><strong>Random Forest Example<br></strong><em>Source: </em><a href="https://www.youtube.com/watch?v=J4Wdy0Wc_xQ&amp;ab_channel=StatQuestwithJoshStarmer"><em>StatQuest</em></a></p><ul><li><strong>Step 1:</strong> Create a bootstrapped dataset by randomly selecting samples from the dataset<br><em>N.B. you can pick the same sample more than once</em></li><li><strong>Step 2:</strong> Create a decision tree using bootstrapped dataset, but ..<br><strong>2a</strong>. Start by considering a random subset of variables / columns <em>(e.g. 2 out of 4 potential variables)</em> to determine how to split data<br><strong>2b</strong>. After using a variable to split data, consider another random 2 variables<br><em>N.B.</em><strong><em> </em></strong><em>A single variable can appear multiple times in a tree, i.e. every time we select a subset of features to choose from, we choose from the full list of features, even if we already used them.</em></li><li><strong>Step 3:</strong> Repeat step 1 and 2 with another bootstrapped sample to generate a variety of trees</li><li><strong>Step 4:</strong> Run new data through all trees to determine which class / option received the most votes</li></ul><blockquote>Typically, about 1/3rd of the data does not end up in the bootstrap; this is called the “Out-of-Bag Dataset”</blockquote><ul><li><strong>Step 5: To determine the accuracy of the random forest, </strong>we run the “out-of-bag samples” through each tree to determine if it gets correctly labeled by the random forest<br><strong><em>The proportion of Out-of-Bag samples that were incorrectly classified is the “Out-of-Bag Error”</em></strong></li><li><strong>Step 6:</strong> We redo this process by building a random forest, <br>.. by considering 3 variables per step, estimating accuracy<br>.. by considering 4 variables per step, estimating accuracy<br>.. and so on — to determine the most accurate forest</li></ul><blockquote>The number of variables we start with is typically the square root of the total number of variables — and then we go above and below depending on how our random forest accuracy changes based on our out-of-bag error rate</blockquote><p><strong>Handling Missing Data<br></strong><em>Source: </em><a href="https://www.youtube.com/watch?v=sQ870aTKqiM&amp;ab_channel=StatQuestwithJoshStarmer"><em>StatQuest</em></a></p><p>(a) <strong>Missing data in the original dataset used to create the random forest: </strong>In order to solve this, we make an initial guess, run random forests, and refine values using a proximity matrix</p><p><strong>Proximity Matrix Example</strong></p><ul><li><strong>Step 1: Initialize with approximate data: </strong>If a sample has a label <em>‘No disease’,</em> then its missing data could be filled out based on the average or median data of other samples with the same label<br><em>i.e. if avg. blocked arteries data for other samples with No heart disease is No, then</em> <em>the missing ‘heart disease’ data for this sample should be filled out as ‘No’; similarly for weight, it would be the median of other samples</em></li><li><strong>Step 2: Random Forest Run </strong>(1) Create a Random Forest, and (2) Run <strong><em>all</em></strong> data down the random forest</li><li><strong>Step 3: Create Proximity Matrix &amp; Values: </strong>For each tree — based on the results, <strong>create a proximity matrix based on which leaf nodes each sample ends up in</strong>. The number of times each sample appears alongside another sample in a leaf node steers us in the direction of how similar that sample is to other samples<br><em>N.B. In order to arrive at proximity values, the frequencies of appearance next to other samples needs to be normalized by the # of trees</em></li><li><strong>Step 4: Optimize weights based on proximity values</strong>: Calculate the weighted frequency using proximity values as weights to determine possible missing values<br>- <strong>Frequency:</strong> “Yes” occurs in 1/3 samples <em>(i.e. Sample 2)</em>, “No” occurs in 2/3 samples <em>(i.e. Samples 1 and 3)</em><br>- <strong>Weights:</strong> Weight of “Yes” = Proximity of “Yes” ÷ All Proximities<em>, with Proximity of “Yes” being the proximity value in the proximity matrix for Sample 2, and total proximity value being sum of proximity values for Samples 1, 2, 3<br>.. with Weighted Frequency of “Yes” = Frequency of “Yes” * Weight of “Yes”, and Weighted Frequency of “No” calculated similarly</em></li><li><strong>Step 5: Fill in missing values.<br>- Classifications:</strong> Fill in the highest Frequency * Weight<br>- <strong>Numerical:</strong> Fill in the net weighted average, Σ (Frequency * Weight)</li><li><strong>Step 6: </strong>Repeat process a few times until weights converge / have limited change</li></ul><p>(b) <strong>Missing data in a new sample that you want to categorize</strong>: In order to solve this, create copies of data with theoretical guesses on the labels, and iterate using a similar proximity value method to fill in missing values — eventually selecting the copy which is guessed most often by random forests</p><p><strong>Proximity Matrix Example 2</strong></p><ul><li><strong>Step 1: Create Copies with Pseudo Label guesses: </strong>Create 2 copies of data, one with each class or “guess” about what the new sample should be labeled as</li><li><strong>Step 2: Iterate on both copies to fill missing values using proximity values:</strong> Using the proximity matrix method (described above), iteratively guess the missing values and (in case of a class), select the option which is most frequent</li></ul><h4>AdaBoost</h4><p>AdaBoost is similar to Random Forests, but <strong>only contains trees with 1 node and 2 leaves</strong>, called<strong> ‘Stumps’ </strong>— thus making AdaBoost a <strong>Forest of Stumps</strong>. Additionally, there are 3 conceptual differences:</p><ul><li>Forest of Stumps have <strong>fixed depth</strong>, making them <strong>weak learners</strong><br><em>This is unlike Random Forests (which have no predetermined length)</em></li><li><strong>Some stumps get more say than others,</strong> i.e. they are weighted<br><em>This is unlike Random Forests, where each tree is weighted equally</em></li><li><strong>Order is important;</strong> errors made by the first stump influence subsequent stumps, and so on<br><em>This is unlike Random Forests, where order is irrelevant</em></li></ul><h4>K-nearest neighbors</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8x9uijOGuCNuJ0QfOFZ2lg.jpeg" /></figure><p>Pick the nearest neighbors for classification :)</p><p><strong>How it works</strong></p><ul><li><strong>Step 1:</strong> Start with a dataset with known categories; cluster that data using PCA</li><li><strong>Step 2:</strong> Add a new cell with unknown category to the PCA plot</li><li><strong>Step 3:</strong> <strong>Look at nearest annotated cells to classify new cell.</strong> If k = 1, then only use the nearest (single) neighbor to define the category; if k = 11, use the 11 nearest neighbours.<br><em>If there are multiple categories, then pick the category with the most votes</em></li></ul><p><strong>How to pick K</strong></p><ul><li>No clear way to determine k, so try a few values before settling</li><li><strong>Low values</strong> <strong>for K</strong> (e.g. 1, 2) <strong>can be noisy</strong> and subject to outliers</li><li>Large values for K can smooth over things, but <strong>an extra-large K can lead to smaller categories always being outvoted </strong>by larger ones</li></ul><h4>Linear Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*76aVx_iwKfJFB1Fhjzxt3g.jpeg" /></figure><p>Draws a linear relationship a dependent variable <em>y</em> and independent variable(s) <em>x, </em>by minimizing the sum of squared errors. For a single dependent variable, it can be described simply by <em>y = m*x + c</em>, with <em>m</em> representing the slope and <em>c</em> representing the intercept</p><p><strong>3 Key Concepts</strong>: (1) Fit a line, (2) calculate R², (3) calculate p-value</p><p><strong>(1) Fit a line to the data using<br></strong><em>by minimizing sum of squared residuals</em></p><ul><li>Sum of Squared Residuals (SSR) = Σ (Actual — Predicted)<em>²<br>N.B. Distance from the line to the data point called the Residual</em></li><li>Derivatives are used to minimize SSR <em>e.g. via gradient descent, OLS, etc.</em></li><li>In case of a single variable, this line can be represented as <em>y = mx + c</em></li></ul><p><strong>(2) Measure fit by calculating R²<br></strong><em>This tells us how much variation in y can be explained by x</em></p><ul><li><strong>R² = [ Var(mean) — Var(fit) ] ÷</strong> <strong>Var(mean)<br></strong><em>- SS(mean) = (data — mean of data)²<br>- Var(mean) = SS(mean) ÷ n<br>- SS(fit) = (data — line)²<br>- Var(fit) = SS(fit) ÷ n</em></li><li>R² lies<strong> between 0 and 1 —</strong>the better the fit, the lower the var(fit), the higher the R²</li><li>R² is independent of # of datapoints, making it easier to compare across datasets</li></ul><p><strong>(3) Calculate p-value of R²<em><br></em></strong><em>This tells us how statistically significant fit is, using F-tables</em></p><ul><li><strong>F = [ SS(mean) — SS(fit) </strong>÷<strong> (<em>p-fit</em> — <em>p-mean</em>) ] </strong>÷<strong> [ SS(fit) </strong>÷<strong> (n — <em>p-fit</em>) ]</strong></li><li><strong><em>p-fit</em></strong> is the number of parameters in the fit line <em>(e.g. y = </em><strong><em>m</em></strong><em>*a + </em><strong><em>n</em></strong><em>*b </em><strong><em>+ c</em></strong><em> has </em><strong><em>p-fit = 3</em></strong><em>, i.e. </em><strong><em>m</em></strong><em>, </em><strong><em>n</em></strong><em> and </em><strong><em>c</em></strong><em>)</em></li><li><strong><em>p-mean</em></strong><em> </em>is the number of parameters in the mean line <em>(e.g. y = </em><strong><em>m</em></strong><em>*a + </em><strong><em>n</em></strong><em>*b </em><strong><em>+ c</em></strong><em> has </em><strong><em>p-mean = 1</em></strong><em>, i.e. </em><strong><em>c</em></strong><em>)</em></li><li><strong><em>n</em></strong><em> </em>is the number of data points<br>The less data we have (i.e. the smaller the <em>n</em>), the larger the denominator of <em>F</em>. The larger the denominator, the smaller the <em>F</em>. With more data points, we can “validate” <em>F</em> better, implying that the denominator becomes smaller with more datapoints, and <em>F</em> becomes larger</li><li>F-values can be <a href="http://www.socr.ucla.edu/Applets.dir/F_Table.html">looked up</a> using sample size and degrees of freedom</li></ul><h4>Multiple Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vjgbKhJdZtNSheHxdk_EPA.jpeg" /></figure><p>Similar to linear regression, i.e.</p><ul><li><strong>#1: </strong>Fit a <strong>plane</strong> or a <strong>higher dimensional object</strong> to your data</li><li><strong>#2: Calculate R²</strong></li><li><strong>#2: Calculate p-value using F</strong><br><em>p-fit</em> changes depending on the number of parameters in the new equation; <em>p-mean</em> still equals 1</li></ul><p><strong>By comparing multiple regression to simple regression</strong>, you can determine if adding another parameter is ‘worth the trouble’:</p><ul><li>Calculate <strong>R² for both</strong> to arrive at <strong>difference in R²<br></strong><em>N.B. Higher difference better</em></li><li>Calculate <strong><em>p-value</em></strong> by calculating F as the <strong><em>difference</em></strong> between multiple regression and simple regression by replacing (i) <em>fit</em> by <em>multiple</em>, (ii)<em> mean</em> by <em>simple</em>, i.e.<br>F = [ SS(simple) — SS(multiple) ÷ (<em>p-multiple</em>— <em>p-simple</em>) ] ÷ [ SS(fit) ÷ (n — <em>p-multiple</em>) ]<br><em>N.B. Lower p-value better</em></li></ul><h4>Logistic Regression</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLLbLxa7zAU7J7CG7BA0Cg.jpeg" /></figure><p>Similar to linear regression, but <strong>predicts if something is True or False</strong> (instead of a continuous value):</p><ul><li><strong>Fits an S-shaped logistic function</strong> to data, with the <strong>curve going from 0 to 1 </strong>using <strong>maximum likelihood</strong></li><li>Used for<strong> classification </strong>(e.g. if &gt; 50%, then Obese, else Not Obese) instead of predicting a continuous value in case of Regression</li><li>Similar to multiple regression, can use multiple variables (whether discrete or continuous)</li><li>We can’t compare simple and complicated models easily; we can only tell if a new variable’s effect on the prediction is <strong><em>significantly</em></strong> different from 0 — and if not, it implies that the variable is not helping the prediction</li></ul><p><strong>Coefficients<br></strong><em>Source: </em><a href="https://www.youtube.com/watch?v=vN5cNN2-HWE&amp;list=PLblh5JKOoLUKxzEP5HA2d-Li7IJkHfXSe&amp;index=2&amp;ab_channel=StatQuestwithJoshStarmer"><em>StatQuest</em></a></p><ul><li>When using logistic regression, the function generates slope and intercepts for the coefficient line</li><li>Let’s say we have a logistic regression graph to represent weight (<em>x-axis</em>) and probability <em>p </em>of obesity (<em>y-axis</em>) — with <em>1</em> representing <em>Obese</em>, and <em>0</em> representing <em>Not Obese</em></li><li><strong>The coefficient line</strong> is generated by taking the <em>log(Odds of Obesity)</em>, with <em>Odds of obesity = p / (1-p), </em>and <strong>can be represented as <em>y = m*x + c</em></strong>, which is the slope and intercept generated by the logistic regression function</li><li><strong>Intercept: </strong>If <em>Intercept</em> is <em>-3.48</em>, then for weight (<em>x </em>= 0), <em>log(odds of Obesity)</em> = -3.48; if intercept’<em>s z-value </em>is <em>-1.471</em>, that means it is <em>1.471</em> std. deviations to the left of 0 in a standard normal curve. Since <em>z-value</em> is &lt; <em>1.96</em>, it is not statistically significant, which is further confirmed by the large <em>p-value</em> (<em>0.1414</em>) — larger than <em>0.05</em></li><li><strong>Slope: </strong>If <em>Slope</em> is <em>1.83</em>, it implies that for every 1 unit of weight gained, the <em>log(Odds of Obesity)</em> increase by <em>1.83. </em>If the slope’s <em>z-value</em> is <em>1.678</em> (i.e. &lt; 1.96), that implies it is not statistically significant, further confirmed by the large <em>p-value (0.0934) </em>— larger than <em>0.05</em></li></ul><h3>Unsupervised Learning</h3><p>Discerning patterns without human intervention — i.e. typically without labels — with the most common types being <strong>Clustering</strong> <em>(i.e. reducing data into different types / classes)</em> and <strong>Dimensionality Reduction</strong> <em>(e.g. drawing a line to determine patterns in 2D data)</em></p><h4>k-Means Clustering</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lHXbqa_aRw15tRL-wGM3zg.jpeg" /></figure><p>k-means uses <strong><em>means</em></strong> as <em>‘</em><strong><em>centroids</em></strong><em>’</em> of a <em>cluster</em> to determine optimal clustering for <strong><em>clusters</em></strong><em> (</em><strong><em>k</em></strong><em> or </em><strong><em>n_clusters</em></strong><em>) </em>over multiple <strong><em>iterations</em></strong> (<strong><em>max_iter</em></strong>). It does this for multiple cluster <strong><em>initializations</em></strong><em> (</em><strong><em>n_init</em></strong><em>)</em>, selecting the final clustering with the <strong><em>least total variance</em></strong> at the end of all <em>iterations</em> (in each <em>initialization</em>).</p><p><strong>Key steps per <em>Iteration</em></strong></p><ul><li>1) Decide the # of clusters <em>k</em></li><li>2) Randomly select <em>k</em> distinct datapoints as initial cluster centroids</li><li>3) Measure the distance between all points and <em>k</em> initial clusters</li><li>4) Assign the points to the nearest clusters</li><li>5) Calculate the mean of each cluster</li><li>6) Repeat steps 3, 4 using the <strong><em>mean</em></strong> values as the new centroids</li><li>7) Stop when centroids stop moving, &amp; measure total variance</li></ul><p>These iterations are done multiple times for multiple cluster <strong><em>initializations</em></strong>, and the clusters with the least total variance at the end are decided as the most optimal cluster.</p><p><strong>Managing multiple dimensions</strong></p><p>Assuming we have data mapped over <em>x, y</em> — similar to the previous process, we follow a similar process, but instead use Euclidean distance</p><ul><li>2) Randomly select <em>k</em> distinct datapoints of the format <em>[x, y]</em></li><li>3) Measure the <strong>Euclidean </strong>distance, <em>e.g. in case of 2 dimensions, the distance is √ x² + y² (+ .. depending on # of dimensions)</em></li><li>4) Assign points to the nearest cluster</li><li>Repeat subsequent steps 5), 6), 7) a few times for different cluster initializations, to ensure we have the least variance</li></ul><p><strong>Key parameters</strong></p><ul><li><strong>n_clusters</strong> <em>(i.e. k, with default = 8 in sklearn)</em> — You can typically start with small values and work upwards to determine total variance, with <em>variance = 0</em> when <em>k = n</em> (i.e. # of clusters = # of datapoints). You can pick <em>k</em> using the elbow plot, which will typically show a huge reduction in variation after specific # of clusters <em>k</em></li><li><strong>max_iter</strong> <em>(default is 300)</em>, i.e. # of iterations or epochs <em>(i.e. step 1: assign centroid, step 2: move centroid)</em></li><li><strong>n_init</strong><em> (default is 10)</em> i.e. number of different initializations for the algorithm, i.e. how many times it comes up with clusters. Typically bumped up higher if we think our initialization is poor</li></ul><p><strong>Key challenges</strong></p><ul><li><strong>Inconsistent results: </strong>Given it is a hill-climbing algorithm, it is thus very dependent on where we put our initial cluster centers</li><li><strong>Counterintuitive results due to bad local minima:</strong> Given it is a local hill-climbing algorithm, it can give you suboptimal local minima, e.g.:<br><em>- 2 centroids b/w a single actual cluster + 1 centroid b/w 2 actual clusters<br>- 2 centroids next to each other which can slice data within actual clusters amongst each other</em></li></ul><h4>Principal Component Analysis (PCA) for Dimensionality Reduction</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jRNprmyrDrBwnV2hB1_cjQ.jpeg" /></figure><p>PCA aims to determine the key features (amongst a set of features) that drive most variance, whilst minimizing information loss. In addition to ranking feature importance, it can also be used as a general algorithm for feature transformation.</p><p><strong>Key Notes </strong>(from Udacity)</p><ul><li>Sytematized way to transform input features into principle components</li><li>Principle Components (PC) can be used as new features</li><li>PCs are <strong><em>directions</em></strong> in data that <strong><em>maximize variance </em></strong>&amp; <strong><em>minimize information loss</em></strong> when you project/compress down onto them</li><li>More variance of data along a PC, the higher it will be ranked</li><li><strong>1st PC: </strong>Most variance &amp; most information<br><strong>2nd PC: </strong>2nd-most variance (without overlapping w/ 1st PC)<br><em>.. and so on</em></li><li>Max # of PCs = # of input features —<em> typically we use the first few in regression or classification tasks</em></li></ul><p><strong>When to use PCA</strong></p><ul><li><strong>Access to latent features</strong> that may show up in your data</li><li><strong>Dimensionality reduction</strong> by (i) visualizing high dimensional data (e.g. only PC1, PC2), (ii) reducing noise</li><li><strong>Pre-processing </strong>for other algorithms (e.g. regression, classification) for to work better because of fewer inputs</li></ul><p><strong>Principle Component Analysis Example<br></strong><em>Source: </em><a href="https://www.youtube.com/watch?v=FgakZw6K1QQ&amp;ab_channel=StatQuestwithJoshStarmer"><em>Stat Quest</em></a></p><ul><li>Take a 2D chart <em>x</em> vs. <em>y</em>, e.g. <em>x axis</em> = Gene 1, <em>y axis = </em>Gene 2</li><li>Calculate center of graph <em>c</em> via. avg. of <em>x</em> and <em>y</em> values respectively</li><li>Shift center to <em>c</em> to the <em>origin</em> <em>[0,0</em>] without changing relative positions of data</li><li>Draw a line through the center which either<br>(i) minimizes the distances from the <strong>points to the line</strong>, or<br>(ii) maximizes the distances from the <strong>projected points on the line</strong> <strong>to the origin [0,0]</strong><em> — the latter being mathematically easier to calculate</em></li><li>We sum up the squares of (ii), known as <strong>SS(distances)</strong><br>(<em>ii) Distance = distance from projected points on line to the origin</em></li><li><strong>We optimize to have the line with the largest SS(distances)</strong> — known as PC1 (Principal Component 1)<br><em>If PC1 slope = 0.25, that implies for every 4 units that we go along the x axis (Gene 1), we go 1 unit up along the y axis (Gene 2) — implying the data is largely spread along the Gene 1 axis</em></li></ul><blockquote><strong>Linear Combination:</strong> “To make PC1, mix 4 parts Gene 1, 1 part Gene 2”</blockquote><ul><li>This combination of Gene 1 and Gene 2 can be represented as a right angled triangle, with <strong><em>Gene 1 (4 parts) representing the base,</em></strong> and <strong><em>Gene 2 (1 part) representing the perpendicular</em></strong>, to calculate the size of the <strong><em>hypotenuse = 4.12</em></strong> (using Pythagoras Theorem)</li><li><strong>The hypotenuse is scaled down to 1 to turn it into a unit vector</strong>, along with the base (Gene 1) scaled down to 0.97 and perpendicular (Gene 2) scaled down to 0.242. <strong>This 1 unit vector is called the Singular Vector or the Eigenvector for PC1</strong></li></ul><blockquote><strong>Eigenvalue for PC1:</strong> The average of SS(distances for PC1) for the best fit line (divided by n-1 instead of n) — this is similar to variance<br><strong>Singular value for PC1:</strong> Square root of SS(distances for PC1)</blockquote><ul><li><strong>PC2 is simply a perpendicular to PC1,</strong> i.e. -2.42 parts Gene 1, 0.97 Gene 1 — these two values are the <strong>Loading Scores </strong>for PC2 (i.e. in terms of how values are projected to PC2, Gene 2 is 4 times as important as Gene 1)</li></ul><blockquote><strong>Eigenvalue for PC2:</strong> The average of SS(distances for PC2) — this is similar to variance</blockquote><ul><li>Finally, PC1 is rotated to become the <em>x axis</em>, and PC2 is rotated to become the <em>y axis</em></li><li>Since Eigenvalues for both PC1 and PC2 represent variance, we can aggregate the variances to determine how much variance is driven by PC1 vs. PC2</li><li>A <strong><em>screeplot</em></strong> represents the % of variance explained by individual PC1, PC2</li></ul><h4>Dimensionality reduction</h4><p>..</p><h4>Association rules</h4><p>..</p><h3>Other Important Concepts</h3><h4>Cross Validation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQrJptUQqwNcytxD2XhBfQ.jpeg" /></figure><p>This allows us to compare different ML methods and get a sense of how well they will work in practice</p><p><strong>How is data divided for cross validation?</strong></p><ul><li><strong>k-fold cross validation: </strong>When data is divided into k blocks, it is called a k-fold cross validation — e.g. 4 blocks = 4-fold validation; <strong>in practice, it is common to divide data into 10 blocks</strong></li><li><strong>Leave One Out Cross Validation:</strong> When each sample is tested individually</li></ul><p><strong>Cross Validation Example<br></strong><em>Source: </em><a href="https://www.youtube.com/watch?v=fSytzGwwBVw&amp;ab_channel=StatQuestwithJoshStarmer"><em>StatQuest</em></a></p><p>Assume we have a stream of data representing all the data collected about people with and without heart disease. We thus need to do 2 things:</p><ul><li><strong>Train the algorithm: </strong>Estimate the parameters e.g. we have to use some data to estimate the logistic regression curve</li><li><strong>Test the algorithm: </strong>Evaluate how well the ML method works / test e.g. test if the curve will do a good job classifying test data</li></ul><p>Let’s say our data is split into 4 blocks</p><ul><li>Cross validation would use the first 3 blocks to train the method, then use the last block to test the method; it would keep track of how this combination does with test data</li><li>Then it uses a different combination of 3 blocks, etc.</li></ul><p>At the end of the cross validation, <strong><em>every</em></strong> block of data is used for testing across <strong><em>all methods </em></strong>(e.g. SVM, Logistic, Naive Bayes). <strong>Cross Validation keeps track of net scores for each method</strong> to let us determine which method performs best.</p><h3>Appendix</h3><h4>SciKit Learn Coding Pattern</h4><ul><li><strong>Import package</strong> <em>e.g. GaussianNB</em></li><li><strong>Create model</strong> <em>e.g. model = package instance, e.g. svm.SVC(), GaussianNB()</em></li><li><strong>Split data into training, test, etc. </strong><em>e.g. X_train, Y_train, X_test, Y_test = train_test_split(X, y, test_size = 0.2)</em></li><li><em>(Optional)</em> <strong>PCA for dimensionality reduction</strong> on training data</li><li><strong>Fit model to training data</strong> <em>e.g. model.fit(x_train, y_train)</em></li><li><strong>Predict using test data</strong> <em>e.g. pred_test = model.predict(x_test)</em></li><li><strong>Check accuracy vs. actuals</strong>, <em>e.g. (pred_test == y_test).mean()</em></li></ul><h4>GridSearchCV</h4><p>Helps test different combinations of parameters to help deploy the most optimal one, e.g.</p><pre>from sklearn import svm<br>from sklearn.model_selection import GridSearchCV<br><br># create parameter grid<br>parameters_grid = {<br>  &#39;kernel&#39;: (&#39;linear&#39;, &#39;rbf&#39;), # test 2 different kernel types for svm<br>  &#39;C&#39;: [1, 10]  # higher means tighter fit<br>}<br><br># initialize empty instance<br>svr = svm.SVC()<br><br># create classifier using gridsearch<br>classifier = GridSearchCV(svr, parameters_grid)<br><br># fit data into classifier<br>classifier.fit(X_train, y_train)<br><br># give best parameters as dictionary<br>classifier.best_params_</pre><h4>Filetypes</h4><ul><li>Pickle (pkl) fikles are a handy way to store and load python objects</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0594696db3cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Down Stable Diffusion]]></title>
            <link>https://medium.com/@shitijnigam/breaking-down-stable-diffusion-1cfe9d71ded3?source=rss-65eb3c05bb84------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cfe9d71ded3</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[stable-diffusion]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shitij Nigam]]></dc:creator>
            <pubDate>Tue, 14 May 2024 08:11:09 GMT</pubDate>
            <atom:updated>2024-05-27T13:16:07.733Z</atom:updated>
            <content:encoded><![CDATA[<p>Stable diffusion is a strange beast. I’m here to try and decode it for myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*RCNd3YmRE0tXLFfLpR12Dg.png" /><figcaption>After many many experiments, I landed on this. Stable diffusion is sick. <a href="https://github.com/shitijnigam/kaggle-repo/blob/main/stable-diffusion-deep-dive.ipynb">Github notebook here</a></figcaption></figure><h3>Overview</h3><ul><li><strong>Stable diffusion works via noise reduction (i.e. denoiser).</strong> The architecture is essentially, “feed a noisy picture into the model, use the model to determine how much noise there is, and then remove a part of the noise from the original input, and iterate.”</li><li>It requires<strong> latents or latent images,</strong> which are essentially compressed images to ensure that we can save on compute (latents are generated via a part of the VAE encoder)</li><li>In addition to latents, we also need<strong> supporting text captions</strong> which can be used to create corresponding text embeddings associated with each picture</li><li><strong>Noise is generated using a time step function</strong>, <strong>with key parameters <em>σ</em> (</strong>the strength of the noise added/removed) <strong>and <em>β </em></strong>(scaling factor for sigma). It helps to train the stable diffusion model by adding noise to an image based on a pre-specified amount, and using that to train the model</li><li><strong>C </strong>is the amount of noise that is removed from the picture<br><em>(This sounds similar to learning rate in regular optimizers, but I could be wrong)</em></li></ul><h3>Key Components</h3><h4><strong>Diffusion model</strong></h4><p>This is the pre-trained model containing the necessary weights, etc. needed to generate your image. It is trained on massive pairs of images and texts, by feeding in gradually corrupted images via increasing amounts of noise, and having the model learn how to reduce noise to “predict” a cleaner version of the image</p><pre>diffusion_model = &quot;CompVis/stable-diffusion-v1-4&quot;</pre><h4><strong>Tokenizer</strong></h4><p>This is the model needed to tokenize and encode your prompt text; it lets you create tokens, token embeddings, positional embeddings, and the final ‘hidden states’ for your text. e.g. <em>openai/clip-vit-large-patch14 on Hugging Face</em></p><pre>text_tokenizer_model = &quot;openai/clip-vit-large-patch14&quot;</pre><h4><strong>VAE (‘Variational Auto Encoder’) Decoder</strong></h4><p>This is the decompression mechanism used to <strong><em>turn small latents into large images</em></strong>. It requires specification of the diffusion model you will be using the encoder / decoder for. Pretty straightforward</p><ul><li><strong><em>Inputs:</em></strong><em> Small Latent Tensor</em></li><li><strong><em>Outputs:</em></strong><em> Large Image</em></li></ul><pre># Autoencoder to decode latents into images<br>vae = AutoencoderKL.from_pretrained(diffusion_model, subfolder = &quot;vae&quot;)</pre><h4><strong>CLIP (Contrastive Language Image Pre-training) Text Encoder</strong></h4><p>This takes text associated with images in the training data and ensures that (i) the dot product of the text (<em>“japanese scroll art with a horse in the wind”</em>) and image embeddings is large, and that (ii) similar sounding text has similar embeddings (e.g. <em>“beautiful horse in the wind, japanese scroll art”, “horse, japanese scroll art”</em>, etc. should have similar embeddings)</p><ul><li><strong><em>Inputs:</em></strong><em> Text</em></li><li><strong><em>Outputs:</em></strong><em> Embeddings</em></li></ul><pre># Tokenizer and Text Encoder for text<br>tokenizer = CLIPTokenizer.from_pretrained(text_tokenizer_model)<br>text_encoder = CLIPTextModel.from_pretrained(text_tokenizer_model)<br><br># note: this is based on transformers</pre><h4><strong>Denoiser: UNet</strong></h4><p>This is the model we need to train to act as a ‘denoiser’. It also requires the specification of a pre-trained diffusion model like Stable Diffusion</p><ul><li><strong><em>Inputs: </em></strong><em>Noisy Latents</em></li><li><strong><em>Outputs: </em></strong><em>Noise (to be removed)</em></li></ul><pre>unet = UNet2DConditionModel.from_pretrained(diffusion_model, subfolder = &quot;unet&quot;)</pre><h4><strong>Scheduler</strong> (a.k.a. <strong>Samplers</strong>)</h4><p>This guides the process of denoising and is responsible for handling a lot of details — e.g. how many steps to take towards denoising, how much noise to aim for at each step, whether the steps are random or linear, the specific algorithm used for denoising, etc. While running a stable diffusion loop, all these things become critical.<br><em>e.g. LMSdiscreteScheduler (‘Latent Minus Step Discrete Scheduler’) — other examples and details can be found </em><a href="https://blog.segmind.com/sdxl-samplers-2/"><em>here</em></a></p><pre>scheduler = LMSDiscreteScheduler(<br>    beta_start = 0.00085,<br>    beta_end = 0.012,<br>    beta_schedule = &quot;scaled_linear&quot;,<br>    num_train_timesteps = 1000<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-WX3dvwhMQWxlTkS.png" /><figcaption>Step illustration: <a href="https://blog.segmind.com/sdxl-samplers-2/">https://blog.segmind.com/sdxl-samplers-2/</a></figcaption></figure><h3>Sample Diffusion Loop</h3><h4><strong>Calibrate hyperparameters</strong></h4><ul><li>Pretty straightforward, I won’t give explanations until a bit later for some of them (e.g. guidance scale — which comes into play during <em>classifier free guidance</em>)</li></ul><pre>prompt = [&quot;A watercolor painting of a stray black and white dog&quot;]<br>height = 512 # default<br>width = 512 # default<br>num_inference_steps = 30 # denoising steps<br>guidance_scale = 7.5 # scale for classifier free guidance<br>generator = torch.manual_seed(20)<br>batch_size = 1</pre><h4><strong>Prepare text embeddings</strong></h4><p>This is where we create 2 types of text embeddings that we concatenate together to feed into our model: The prompt specific embeddings (which contain specifics of our prompt), and the unconditioned embeddings. Unconditioned embeddings add a bit of randomness to the text prompt to help smoothen out image generation. (<a href="https://forums.fast.ai/t/why-do-we-need-the-unconditioned-embedding/101134/2">example here</a> with and without unconditioned embeddings)</p><pre># text input and embeddings based on prompt<br>text_input = tokenizer(<br>    prompt,<br>    padding = &quot;max_length&quot;,<br>    max_length = tokenizer.model_max_length,<br>    truncation = True,<br>    return_tensors = &quot;pt&quot; # pt stands for pytorch :)<br>)<br>with torch.no_grad():<br>    text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]<br>    # gradients don&#39;t need to be updated during image generation; this saves computational resources<br><br># uncond_input is random noise with the same shape as the text input<br>max_length = text_input.input_ids.shape[-1] # anchored to the text input/prompt<br>uncond_input = tokenizer(<br>    [&quot;&quot;]*batch_size, # depending on # of batches of text, this could be expanded<br>    padding = &quot;max_length&quot;,<br>    max_length = max_length,<br>    return_tensors = &quot;pt&quot; # pt stands for pytorch<br>)<br>with torch.no_grad():<br>    uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]<br><br># concatenate the 2 embeddings to get an &quot;average&quot; to avoid being too specific<br>text_embeddings = torch.cat([uncond_embeddings, text_embeddings])</pre><h4><strong>Set up the noise scheduler</strong></h4><pre># Noise scheduler<br>def set_timesteps(scheduler, num_inference_steps):<br>    scheduler.set_timesteps(num_inference_steps)<br>    scheduler.timesteps = scheduler.timesteps.to(torch.float32)<br><br>set_timesteps(scheduler, num_inference_steps)</pre><h4><strong>Initialize (random) latents</strong></h4><p>.. with height and weight 1/8th of what the stable diffusion default is — since latents can be a lot smaller.<br><em>N.B. The model is trained to associate a specific amount of noise per timestep. init_noise_sigma is what the model is trained for at timestep t = 0 (~14.6146). The latents — which are random values representing noise — “</em><a href="https://forbo7.github.io/forblog/posts/13_implementing_stable_diffusion_from_its_components.html"><em>needs to be scaled so it can work with the scheduler</em></a><em>”</em></p><pre># Latent images - initialized to serve as a starting point<br>latents = torch.randn(<br>    (batch_size, unet.in_channels, height//8, width//8), # compress 8-fold<br>    generator = generator<br>)<br>latents = latents.to(torch_device)<br>latents = latents * scheduler.init_noise_sigma # scaling</pre><h4><strong>Iterate through loop over timesteps</strong></h4><pre>with autocast(&quot;cuda&quot;):<br>    for i, t in tqdm(enumerate(scheduler.timesteps), total = len(scheduler.timesteps)):<br>        <br>        # expand latents by 2 if doing classifier free guidance to do parallel processing <br>        latent_model_input = torch.cat([latents] * 2)<br>        sigma = scheduler.sigmas[i]<br>        <br>        # scale latents (preconditioning)<br>        latent_model_input = scheduler.scale_model_input(<br>          latent_model_input, <br>          t<br>          )<br>        <br>        # predict noise residual by passing text embeddings through unet<br>        with torch.no_grad():<br>            noise_pred = unet(<br>              latent_model_input, <br>              t, <br>              encoder_hidden_states = text_embeddings<br>            ).sample<br>        <br>        # perform cfg (classifier free guidance)<br>        noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)<br>        noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)<br>        <br>        # compute previous noisy sample<br>        latents = scheduler.step(noise_pred, t, latents).prev_sample</pre><h4><strong>Decode Latents into images using VAE / AutoEncoder</strong></h4><p><em>N.B. 0.18215 is a “constant used to scale the latents so it can be decoded back into a image” — a scale factor introduced in the </em><a href="https://arxiv.org/abs/2112.10752"><em>latent diffusion paper</em></a><em> (more explanations by smarter people </em><a href="https://github.com/huggingface/diffusers/issues/437"><em>here</em></a><em>)</em></p><pre># decode image latents with vae<br>def latents_to_pil(latents):<br>    # reverse scaling<br>    latents = (1/0.18215) * latents<br>    with torch.no_grad():<br>        # decode sample<br>        image = vae.decode(latents).sample<br>    <br>    # normalize, shift from -1 and 1 to 0 to 1 and clamp values in that range<br>    image = (image/2 + 0.5).clamp(0, 1)<br>    <br>    # permute used to convert tensor to image, with channels as last dimension<br>    image = image.detach().cpu().permute(0, 2, 3, 1).numpy()<br>    <br>    # convert to format expected by PIL images (scale to 255, round, convert to unsigned 8 bit integers)<br>    images = (image * 255).round().astype(&quot;uint8&quot;)<br>    pil_images = [Image.fromarray(image) for image in images]<br>    return pil_images    </pre><h3>Image to Image generation</h3><p>The basic concept of image to image generation is similar to what we see above: (i) Start with an image, (ii) add some noise, then (iii) do the final few denoising steps within the loop with a new prompt (i.e. starting with a <em>start_step = 10</em>)</p><p><strong>Settings</strong> remain the same</p><pre># settings, new prompt<br>prompt = [&quot;An african lady in traditional garb&quot;]<br>height = 512<br>width = 512<br>num_inference_steps = 50<br>guidance_scale = 8<br>generator = torch.manual_seed(1024)<br>batch_size = 1</pre><ul><li><strong>Text embeddings are prepared the same way</strong> — unconditioned + conditioned inputs</li></ul><pre># prepare text<br>text_input = tokenizer(<br>    prompt,<br>    padding = &quot;max_length&quot;,<br>    max_length = tokenizer.model_max_length,<br>    truncation = True,<br>    return_tensors = &quot;pt&quot; # pytorch tensor<br>)<br>with torch.no_grad():<br>    text_embeddings = text_encoder(text_input.input_ids.to(torch_device))[0]<br>max_length = text_input.input_ids.shape[-1]<br>uncond_input = tokenizer(<br>    [&quot;&quot;]*batch_size,<br>    padding = &quot;max_length&quot;,<br>    max_length = max_length,<br>    return_tensors = &quot;pt&quot;<br>)<br>with torch.no_grad():<br>    uncond_embeddings = text_encoder(uncond_input.input_ids.to(torch_device))[0]<br>text_embeddings = torch.cat([uncond_embeddings, text_embeddings])</pre><ul><li><strong>Scheduler</strong> is set up the same way</li></ul><pre># prep scheduler<br>set_timesteps(scheduler, num_inference_steps)</pre><ul><li><strong>Convert a starting image to an encoded image i.e. latents</strong></li></ul><pre>def pil_to_latent(input_image):<br>    # turn single image into a latent in a batch<br>    with torch.no_grad():<br>        # use pre-trained vae to convert to tensor<br>        # unsqueeze: add a single dimension of size 1 at beginning<br>        # normalize pixel values to between -1 and 1<br>        latent = vae.encode(tfms.ToTensor()(input_image).unsqueeze(0).to(torch_device)*2 - 1)<br>        <br>    # scale factor from https://arxiv.org/pdf/2112.10752<br>    return 0.18215 * latent.latent_dist.sample()<br><br># get image<br>img_url = &#39;input.jpg&#39;<br>input_img = Image.open(img_url).resize((512, 512))<br><br># turn image to latent space<br>encoded_img = pil_to_latent(input_img)<br><br># Optional - visualize channels in encoded latent<br>fig, axs = plt.subplots(1, 4, figsize = (16, 4))<br>for c in range(4):<br>    axs[c].imshow(encoded_img[0][c].cpu(), cmap = &#39;Greys&#39;)</pre><ul><li><strong>Latents are set up differently!</strong> You begin with a different start_step, generate a noise tensor (i.e. a random tensor) in the shape of the encoded image, use the scheduler to add noise to the encoded image corresponding to the starting</li></ul><pre># prep latents<br>start_step = 10<br># start_sigma = scheduler.sigmas[start_step]<br>noise = torch.randn_like(encoded_img)<br>latents = scheduler.add_noise(<br>    encoded_img,<br>    noise,<br>    timesteps = torch.tensor([scheduler.timesteps[start_step]])<br>)<br>latents = latents.to(torch_device).float()</pre><ul><li>Run an adjusted loop <strong><em>only</em></strong> after the start_step</li></ul><pre>for i, t in tqdm(enumerate(scheduler.timesteps), total = len(scheduler.timesteps)):<br>    if i &gt;= start_step: # start after step 10 since we already added noise<br>        <br>        # expand latents if doing cfg<br>        latent_model_input = torch.cat([latents] * 2)<br>        sigma = scheduler.sigmas[i]<br><br>        # scale latents (preconditioning)<br>        latent_model_input = scheduler.scale_model_input(latent_model_input, t)<br>        <br>        # predict noise residual using unet<br>        with torch.no_grad():<br>            noise_pred = unet(<br>                latent_model_input, <br>                t,<br>                encoder_hidden_states = text_embeddings<br>            )[&quot;sample&quot;]<br>        <br>        # perform guidance based on scale to which prompt should tip<br>        noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)<br>        noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)<br>        <br>        # compute previous noisy sample<br>        latents = scheduler.step(noise_pred, t, latents).prev_sample</pre><ul><li><strong>Generate image using final latents</strong> from the loop</li></ul><pre>latents_to_pil(latents)[0]</pre><h3>How Text Embeddings Work</h3><p>There’s a few things happening under the hood when it comes to text embeddings — a lot of it similar to how transformer architecture treats text:</p><ul><li><strong>Text is converted into tokens</strong></li></ul><pre># initialize prompt<br>puppy_prompt = &quot;A watercolor painting of a stray black and white puppy&quot;<br><br># turn text into tokens using tokenizer (CLIPTokenizer)<br>text_input = tokenizer(<br>    puppy_prompt,<br>    padding = &quot;max_length&quot;,<br>    max_length = tokenizer.model_max_length,<br>    truncation = True,<br>    return_tensors = &quot;pt&quot;<br>)<br>print(text_input[&#39;input_ids&#39;][0])</pre><ul><li><strong>Tokens are fed into a token embedding layer to convert them into token embeddings</strong>. Each token is mapped to a multi dimensional vector (in this case, 768).<br>- <strong>Vocabulary size</strong>: 49,408<em> — this is the total # of unique tokens contained in our text encoder</em><br>- <strong>Shape of a single embedding:</strong> torch.Size([768]) <em>— this is the total ‘features’ of an embedding</em><br>- Shape of <strong><em>all_token_embeddings</em></strong>: torch.Size([1,77,768])<em>, i.e. batch size 1, 77 tokens (i.e. max length of model), 768 values per token</em></li></ul><pre># access token embedding layer<br>token_embedding_layer = text_encoder.text_model.embeddings.token_embedding<br><br># get embeddings for all tokens using text_input (i.e. tokens)<br>all_token_embeddings = token_embedding_layer(<br>                          text_input.input_ids.to(torch_device)<br>                        )</pre><ul><li><strong>Positional embeddings are created as well — these contain information about the order of the tokens</strong>; these can usually be carried over across different prompts. Only instead of a huge vocabulary, we only need to remember the individual positions of 77 tokens :)<br>- Shape of position_embeddings: torch.size([1,77,768])</li></ul><pre># access position embedding layer<br>position_embedding_layer = text_encoder.text_model.embeddings.position_embedding<br><br># get position IDs and corresponding embeddings for each position<br>position_ids = text_encoder.text_model.embeddings.position_ids[:, :77]<br>position_embeddings = position_embedding_layer(position_ids)</pre><ul><li><strong>Add Token and Position embeddings</strong> — these will be fed into the transformer model!</li></ul><pre>input_embeddings_for_model = all_token_embeddings + position_embeddings</pre><ul><li><strong>Generate a hidden</strong> state using these embeddings<br><em>N.B. The mask is a part of the attention model and ensures that the attention mechanism isn’t “cheating” by looking ahead at future tokens that come after the current token in order to establish context</em></li></ul><pre># create hidden state after parsing input embeddings through transformer<br><br># following function plucked from here: https://github.com/fastai/diffusion-nbs/issues/37<br>def build_causal_attention_mask(bsz, seq_len, dtype):<br>    mask = torch.empty(bsz, seq_len, seq_len, dtype=dtype)<br>    mask.fill_(torch.tensor(torch.finfo(dtype).min))<br>    mask.triu_(1)  # zero out the lower diagonal<br>    mask = mask.unsqueeze(1)  # expand mask<br>    return mask<br><br>def get_output_embeds(input_embeddings):<br><br>    # applied within the CLIP text model to ensure it processes the text prompt in the correct order<br>    bsz, seq_len = input_embeddings.shape[:2]<br>    causal_attention_mask = build_causal_attention_mask(<br>        bsz, <br>        seq_len, <br>        dtype = input_embeddings.dtype<br>    )<br>    <br>    # get output embeddings by calling model with passing output_hidden_states = True<br>    encoder_outputs = text_encoder.text_model.encoder(<br>        inputs_embeds = input_embeddings,<br>        attention_mask = None,<br>        causal_attention_mask = causal_attention_mask.to(torch_device),<br>        output_attentions = None,<br>        output_hidden_states = True,<br>        return_dict = None<br>    )<br>    <br>    output = encoder_outputs[0] # output hidden state only<br>    output = text_encoder.text_model.final_layer_norm(output)<br>    <br>    return output<br><br>out_embs_test = get_output_embeds(input_embeddings_for_model)</pre><p><strong>Super important note:</strong></p><blockquote>out_embs_test <em>is the same as what we get from </em>text_encoder(text_input.input_ids.to(torch_device))[0]</blockquote><p>Fin (for now)</p><h4><em>More to come! Including ..</em></h4><ul><li>How to mess around with embeddings</li><li>Textual Inversion</li><li>Guidance via separate loss functions</li><li>Other funny details</li></ul><h3>Appendix</h3><h4>Visualizing the scheduler</h4><p>Here’s what the noise schedule looks like (you’ll see that at t = 0, sigma is 14.6146, i.e. the <em>init_noise_sigma</em>)</p><pre># set # of sampling steps<br>set_timesteps(scheduler, 15)</pre><pre>print(scheduler.timesteps) # original 1000 steps<br>print(scheduler.sigmas) # equivalent noise levels</pre><pre># plot noise schedule<br>plt.plot(scheduler.sigmas)<br>plt.title(&#39;Noise schedule&#39;)<br>plt.xlabel(&#39;Sampling step&#39;)<br>plt.ylabel(&#39;sigma&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*V-GtBYydVAcCDLc3GfrOcQ.jpeg" /><figcaption>With each subsequent step, the amount of noise introduced reduces — this is a property of the LMS scheduler</figcaption></figure><h4>What does the encoder part of the transformer do, exactly?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*kliXdz1aW3J7oH-Rli1tDQ.png" /></figure><p>(I covered this briefly <a href="https://medium.com/@shitijnigam/breaking-down-the-components-of-a-gpt-49ca1ec86518">here</a> for decoder-only transformers). Essentially, the transformer ..</p><ul><li><strong>Takes in embeddings</strong> (tokenized + position embeddings)</li><li><strong>Parses them through multiple transformer blocks</strong>, which comprise of ..<br>(i) multi-headed attention <em>(to determine the relationships between words within a prompt)</em><br>(ii) a feed forward layer <em>(to capture additional aspects / context)</em><br>.. whilst ensuring a bunch of residual connections &amp; layer normalizations along the way</li><li><strong>Spits out hidden states</strong> — an intermediate step before the text is passed into a decoder</li></ul><p>Typically in a transformer model, hidden states may be passed into a decoder in order to conduct translations, etc. — in this case they are passed into unet to predict noise in a latent.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cfe9d71ded3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking Down the Components of ChatGPT]]></title>
            <link>https://medium.com/@shitijnigam/breaking-down-the-components-of-a-gpt-49ca1ec86518?source=rss-65eb3c05bb84------2</link>
            <guid isPermaLink="false">https://medium.com/p/49ca1ec86518</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Shitij Nigam]]></dc:creator>
            <pubDate>Tue, 07 May 2024 09:29:08 GMT</pubDate>
            <atom:updated>2024-05-27T12:46:29.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v-Limag7v9NpHYDPxd9fcw.jpeg" /></figure><blockquote><strong><em>Table of Contents</em></strong></blockquote><blockquote><em>· </em><a href="#e149"><em>Setup</em></a><em><br> ∘ </em><a href="#ea33"><em>Raw Data &amp; Data Loader</em></a><em><br> ∘ </em><a href="#81d8"><em>Encoder Decoder Solution</em></a><em><br> ∘ </em><a href="#1a89"><em>Loss Function</em></a><em><br> ∘ </em><a href="#486e"><em>Key Hyperparameters</em></a><em><br> ∘ </em><a href="#e66d"><em>Generative Function</em></a><em><br> ∘ </em><a href="#2d04"><em>Optimizer function</em></a><em><br> ∘ </em><a href="#88e5"><em>Training Loop</em></a><em><br>· </em><a href="#39f2"><em>Transformers</em></a><em><br> ∘ </em><a href="#4505"><em>(Basic) Scaled Dot-Product Attention</em></a><em><br> ∘ </em><a href="#1996"><em>Enhancing your Attention model</em></a><em><br>· </em><a href="#213a"><em>Appendix</em></a><em><br> ∘ </em><a href="#8f49"><em>Tensor Dimension Gotchas</em></a><em><br> ∘ </em><a href="#0db9"><em>Other Open Questions</em></a></blockquote><p><em>* This is not a how-to, simply an overview of the different parts that make up a GPT. For any unfamiliar terms, </em><a href="https://medium.com/@shitijnigam/the-deep-learning-mathematics-cheatsheet-f8e759ff0996"><em>definitions can be found here</em></a><em>. For other concepts such as batch / layer normalization, etc. — and why some things are done the way they are, check out </em><a href="https://medium.com/@shitijnigam/neural-network-gotchas-dc02cf6ec221"><em>neural network gotchas</em></a><em>.</em></p><h3>Setup</h3><h4>Raw Data &amp; Data Loader</h4><p>Text-based content is the core component on which you train your model to predict the next word — with each subsequent word acting as a label to the previous sequence. <em>e.g. Wikipedia pages, Shakespeare, etc.</em></p><p><strong>You also need a Data Loader </strong>to split data into<strong> training and validation sets </strong><em>(and often, test sets too)</em> and <strong>stack up data batches</strong> <em>(more on that below)</em>. The idea is to use the model to predict the next letter / word on a training set, then run the model on a validation set to see how far off the model was on predicting the next letter / word relative to what is actually in the validation set.</p><h4>Encoder Decoder Solution</h4><p>This converts letters / words into tokens. A token is simply a numerical representation of a word. e.g. Google uses SentencePiece, OpenAI uses TikToken.<br><em>Note: Things can get quite gnarly depending on how words are converted into numbers, e.g. </em><strong>“The ”</strong><em> could be the number 53914, but </em><strong>“ the”</strong><em> could be the number 29145. Sometimes when the tokenizer doesn’t recognize words, it splits up words into multiple tokens. It can be quite messy</em></p><h4>Loss Function</h4><p>This will help you evaluate the quality of your model,<em> e.g. Cross Entropy Loss</em></p><h4>Key Hyperparameters</h4><ul><li>Set <strong>Block Size T </strong>or <strong>Time</strong> (i.e. context length) for reading the training data; if the batch length is 8 (at a character level), then 9 characters are passed in<br><em>e.g. If the entire training data is the string of english alphabet ABCD…...XYZ and a random block of 8 is picked up — say LMNOPQRS — then context (x) would be L, LM, LMN, LMNO, LMNOP, LMNOPQ, LMNOPQR, LMNOPQRS, and the corresponding target (y) would be M, N, O, P, Q, R, S, T<br>N.B. The letters would be represented as tokens, not as actual letters :)</em></li><li>Set <strong>Batch size B,</strong> i.e. how many independent sequences we process in a forward / backward pass</li><li>Set <strong>Class Size C </strong>or <strong>Channels,</strong> i.e. number of potential options (letters or words) that can be predicted. This is typically also the number of embeddings esp. when you’re trying to decouple the vocabulary size<br><em>N.B. For a single attention head, C may be equal to head size (more on this below in multi-headed attention)</em></li></ul><h4>Generative Function</h4><p>A generative function uses the model’s predictions to determine the next letter. For e.g. in a Bigram generative model:<br><em>e.g. for a bigram,</em></p><ul><li>(i) Input = an <em>xB-like</em> tensor of shape <em>(B,T)</em></li><li>(ii) Input fed into model to generate <em>logits</em> of shape <em>(B,T,C)</em> — with <em>C</em> representing corresponding probabilities</li><li>(iii) Extract last <em>time (T) step</em> of these <em>logits</em> of shape <em>(B, C)</em> — since we want to predict what comes right after the input</li><li>(iv) Turn this into est. probabilities using a <em>Softmax</em> function</li><li>(v) Use probabilities predict <em>index</em> of next letter (<em>Multinomial</em> works best for <a href="https://stackoverflow.com/questions/61581774/what-is-the-point-of-multinomial-vs-argmax-evaluation-of-accuracy">multiple reasons</a>) — sometimes select letters may have similar probabilities of outcomes, so this randomization helps</li><li>(vi) Extract and append this letter’s <em>index</em> to the input</li></ul><h4>Optimizer function</h4><p>This is your gradient optimization function to run your backward pass; it takes gradients and updates parameters using gradients in order to optimize the model weights. <em>e.g. SCD, Adam, etc.<br>N.B. A good learning rate for Adam (a more advanced optimizer) is 1e-4. For smaller networks, a higher learning rate of 1e-3 works</em></p><h4>Training Loop</h4><p>A training loop essentially does the following:</p><ul><li>(i) Sample a new <em>batch</em> of data per step</li><li>(ii) evaluate the <em>loss</em> using your model</li><li>(iii) zero out the <em>gradients</em> to make sure they aren’t carried over</li><li>(iv) get the <em>gradients</em> for your parameters via <em>backward()</em> on the loss function</li><li>(v) update <em>(‘step’)</em> on the parameters</li></ul><h3><strong>Transformers</strong></h3><h4><strong>(Basic) Scaled Dot-Product Attention</strong></h4><p><em>Attention</em> of <em>tokens</em> (or <em>nodes</em>) is the crux of how relationships are determined between tokens. Arguably this deserves its own separate chapter, so here goes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*T5kHa0-vn3-mw4I4h_jH1w.jpeg" /><figcaption>This amazing paper 😇 <a href="https://arxiv.org/pdf/1706.03762">https://arxiv.org/pdf/1706.03762</a></figcaption></figure><p>Let’s say we start with a batch <em>x </em>of <em>shape (B,T,C)</em> — which holds a series of embeddings in a <em>batch size B</em>, for a <em>block size </em>or <em>time T</em>, with <em>channels C</em> ..</p><ul><li><strong>Head size: </strong>This determines the complexity of relationships that each token or node is allowed to hold about other tokens.<br>The larger the head size, the more information it can hold but the more computational costs increase; the smaller the head size</li><li><strong>Key <em>k</em>:</strong> This is a linear layer which holds information about every token corresponding to <strong><em>“What do I know”</em></strong></li></ul><pre>key = nn.Linear(C, head_size, bias = False)<br># Here, the # of inputs accepted by the linear layer will be of size C<br># .. the outputs of size head_size<br># .. with the weights W of shape (C, head_size)<br><br>k = key(x)<br># .. and key = x @ W<br># .. resulting in &#39;key&#39; of shape (B, T, C) @ (C, head_size) = (B, T, head_size)</pre><ul><li><strong>Query <em>q</em></strong>: Similar to Key, this is a linear layer that holds information about every token corresponding to <strong><em>“What am I looking for”</em></strong></li></ul><pre>query = nn.Linear(C, head_size, bias = False)<br>q = query(x)<br># A similar math holds true for the query layer too</pre><ul><li><strong><em>q @ k — Transposed</em></strong>: This holds information about the relationships between <em>keys</em> and <em>queries</em>; the larger the product, the more relevant the key is to the query. In case of self attention / decoder block, only <em>q @ k-transposed </em>pairs corresponding to the <em>previous</em> tokens in the <em>time step T</em> are used and normalized using softmax.<br><em>Important note: In an encoder block, the masking line wouldn’t be needed (e.g. for things like sentiment analysis, a transformer would need to understand the full context of the string of tokens)</em></li></ul><pre>qk = q @ k.transpose(-2, -1)<br># i.e. (B, T, head_size) @ (B, head_size, T), to give qk of shape (B, T, T)<br><br>tril = torch.tril(torch.ones(T,T)<br># to create a lower triangular tensor of 1<br><br>qk = qk.masked_fill(tril == 0, float(&#39;-inf&#39;))<br># this fills the portions that are 0 in tril with -infinity in kq</pre><ul><li><strong><em>Softmax ( q @ k-transposed </em></strong><em>÷</em><strong><em> sqrt (head_size) ) </em></strong>to get the “net” probabilities of the query key pairs with the highest relevance<br><em>N.B. q &amp; k-transposed needs to be normalized (i.e. divided) by square root of our head_size, since during initialization — esp. for large head sizes — “the dot products grow large in magnitude”</em></li></ul><pre>qk = qk * head_size**-0.5<br># normalize qk <br><br>qk = F.softmax(qk, dim = -1)<br># dim = -1 is to ensure that softmax is computed on the last dimension<br># softmax converts all values in last dimension to e^x<br># qk is of shape (B, T, T)</pre><ul><li><strong><em>Value</em>: </strong>Similar linear layer to <em>queries </em>and <em>keys</em> of shape <em>(B, T, head_size)</em>; the output is <em>“computed as a weighted sum of the values”</em> — where weight is computed by multiplying values to the <em>Softmax of q @ k-transposed</em><br><em>i.e. assign a set of values to each token in a batch, then use the query/key pairs to determine which values are most important</em></li></ul><pre>value = nn.Linear(C, head_size, bias = False)<br>v = value(x)<br>output = qk @ v<br># attention will have shape (B, T, head_size)</pre><p>Additional notes</p><ul><li><strong>Self attention:</strong> This type of deployment is called self attention because <em>keys,</em> <em>queries,</em> <em>values</em> all come from the same source <em>x</em></li><li><strong>Cross attention:</strong> This comes into place when a separate set of nodes is used to inform keys, queries, values</li></ul><h4><strong>Enhancing your attention model</strong></h4><p>Once attention is set up, a few more optimizations need to happen</p><ul><li><strong>Attention → Multi-headed Attention:</strong> This basically introduces additional context to attention by splitting up or adding more independent channels, applying them in parallel, and then concatenating their results over the channel dimension C<br><em>E.g. if attention was simply allowing tokens to understand basic relationships with each other (e.g. grammar), multi-headed attention allows more sophisticated relationships between tokens (e.g. grammar, sentiment, ..)<br>N.B. Given that we now add multiple heads, we could theoretically reduce the head_size when initializing multi-head attention proportional to the # of heads</em></li></ul><pre>class Head(nn.Module):<br><br>  def __init__(self, head_size):<br>    # key = ..<br>    # query = ..<br>    # value = ..<br>  def forward(self, x):<br>    # B, T, C<br>    # k = key(..)<br>    # q = query(..)<br>    # v = value(..)<br>    # qk calculation ..<br>    return x # of shape B,T,head_size</pre><pre>class MultiHeadAttention(nn.Module):<br><br>  def __init__(self, num_heads, head_size):<br>      super().__init__()<br>      self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])<br>      # create multiple heads, run all of them in parallel<br><br>  def forward(self, x):<br>      return torch.cat([h(x) for h in self.heads], dim = -1)<br>      # concatenated over channel dimension (last dimension)</pre><ul><li><strong>Multi-headed attention (“Communication”) → Feed Forward (“Computation”):</strong> Typically, with only multi-headed attention, you can go “too fast” into logits calculation (i.e. tokens “look at each other but don’t have time to think about what they found”). Feed forward is a multi layer perceptron (MLP) with at least one hidden layer, which introduces more context and adds non linearity. Feed forward theoretically allows capturing of other aspects (e..g sentiment, etc.) to allow the model to go beyond surface level connections</li></ul><pre>class FeedForward(nn.Module):<br>  <br>  def __init__(self, n_embeddings):<br>    super().__init__()<br><br>    self.net = nn.Sequential(<br>      nn.Linear(n_embeddings, n_embeddings),<br>      # takes inputs with n_embeddings as last dimension<br>      # .. and pushes outputs with n_embeddings<br><br>      nn.ReLu()<br>      # adds non linearity to avoid entire network being linear<br>    )<br>  <br>  def forward(self, x):<br>    return self.net(x)<br></pre><ul><li><strong>Block = Multi Headed Attention + Feed Forward</strong>: Blocks are grouped representations of communication (using attention) followed by computation (using feed forward), that can be stacked over multiple times</li></ul><pre>class Block(nn.Module):<br><br>  def __init__(self, n_embeddings, num_heads):<br>    super().__init__()<br><br>    head_size = n_embeddings // num_heads <br>    # to allow embeddings to spread across multiple heads<br><br>    self.sa = MultiHeadAttention(num_heads, head_size)<br>    self.ffwd = FeedForward(n_embeddings)<br><br>  def forward(self, x):<br>    x = self.sa(x)<br>    x = self.ffwd(x)<br>    return x</pre><pre>## ## ##<br>## in your transformer<br>## ##<br><br>token_embedding_table = nn.Embedding(vocab_size, n_embeddings)<br>position_embedding_table = nn.Embedding(block_size, n_embeddings)<br>blocks = nn.Sequential(<br>  Block(n_embeddings, num_heads = 4),<br>  Block(n_embeddings, num_heads = 4),<br>  Block(n_embeddings, num_heads = 4)<br>)</pre><ul><li><strong>Blocks -&gt; Blocks with Residual Connections or Skip Connections: </strong>With multiple blocks sequentially stacked — the network becomes deeper, making it harder to optimize the network, especially since deeper / older blocks have a lower impact on the overall outcome due to multiple transformations (typically referred to as <em>vanishing gradient</em>). Residual connections solve this issue by allowing older blocks to have a say in the final output through an ongoing ‘pathway’ of information.</li></ul><pre>class Block(nn.Module):<br><br>  def __init__(self, n_embeddings, num_heads):<br>    super().__init__()<br><br>    ## same as above<br>    head_size = n_embeddings // num_heads<br>    self.sa = MultiHeadAttention(num_heads, head_size)<br>    self.ffwd = FeedForward(n_embeddings)<br> <br>  def forward(self, x):<br>    # this is where things depart from the previous implementation<br>    x = x + self.sa(x) # &quot;Fork off, communicate, come back&quot;<br>    x = x + self.ffwd(x) # &quot;Fork off, compute, come back&quot;<br>    return x</pre><ul><li><strong>Blocks with Residual Connections need Projections: </strong>When residual connections are added, often the inputs and outputs don’t match Dimensionality. Projections ensure that inputs / outputs match dimensions (and can often also add an additional layer of non linearity)</li></ul><pre>class MultiHeadAttention(nn.Module):<br><br>  def __init__(self, num_heads, head_size):<br><br>      # following bits same as before<br>      super().__init__()<br>      self.heads = nn.ModuleList([Head(head_size) for _ in range(num_heads)])<br><br>      # projection layer added in<br>      self.proj = nn.Linear(n_embeddings, n_embeddings)<br><br>  def forward(self, x):<br>      # changed forward pass with projection<br>      out = torch.cat([h(x) for h in self.heads], dim = -1)<br>      <br>      ##<br>      ## simple linear transformation of concatenation of outputs<br>      ##<br>      out = self.proj(out)<br>      return out</pre><pre>class FeedForward(nn.Module):<br><br>  def __init__(self, n_embeddings):<br><br>    # following bits same as before<br>    super().__init__()<br><br>    self.net = nn.Sequential(<br>      nn.Linear(n_embeddings, n_embeddings),<br>      nn.ReLu()<br><br>      ##<br>      ## add simple linear projection layer<br>      ##<br>      nn.Linear(n_embeddings, n_emebeddings)<br>    )<br>  <br>  def forward(self, x):<br>    return self.net(x)</pre><ul><li><strong>Blocks with Residual Connections → LayerNorm: </strong>LayerNorm normalizes features (across <em>C</em>) using their mean and variance, ensuring that they have unit Gaussian distribution (i.e. 0 mean, 1 standard deviation). It is typically applied before determining attention and feed forward (‘pre norm formulation’). <br><em>N.B. Batch &amp; Time act as batch dimensions; this is per Token normalization; eventually — with the existence of gamma and beta, they may not be normal anymore given that they are trainable parameters</em><br><em>N.B. Batch normalization — which happens at a batch level B. Since ‘the computation doesn’t span across examples (or batches)’ there is no running buffer needed. (</em><a href="https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html"><em>Good NLP example here</em></a><em> at the bottom)</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*jL3tuYU76_MfcD0wt8qc3w.jpeg" /><figcaption>Source: <a href="https://arxiv.org/pdf/1803.08494#page=3">https://arxiv.org/pdf/1803.08494#page=3</a></figcaption></figure><pre>class Block(nn.Module):<br><br>  def __init__(self, n_embeddings, num_heads):<br>    super().__init__()<br><br>    ## same as above<br>    head_size = n_embeddings // num_heads<br>    self.sa = MultiHeadAttention(num_heads, head_size)<br>    self.ffwd = FeedForward(n_embeddings)<br><br>    ## layer norms<br>    self.ln1 = nn.LayerNorm(n_embeddings)<br>    self.ln2 = nn.LayerNorm(n_embeddings)<br> <br>  def forward(self, x):<br>    # layer norms are applied before passing them into attention &amp; ff<br>    x = x + self.sa(self.ln1(x))<br>    x = x + self.ffwd(self.ln2(x))<br>    return x</pre><pre>##<br>## at the end of the transformer, there should be another layerNorm<br>##<br><br>token_embedding_table = nn.Embedding(vocab_size, n_embeddings)<br>position_embedding_table = nn.Embedding(block_size, n_embeddings)<br>blocks = nn.Sequential(<br>  Block(n_embeddings, num_heads = 4),<br>  Block(n_embeddings, num_heads = 4),<br>  Block(n_embeddings, num_heads = 4),<br><br>  ## <br>  ## here<br>  ##<br>  nn.LayerNorm(n_embeddings),<br>)<br># ..</pre><ul><li><strong>Dropouts: </strong>Another regularization technique to avoid overfitting! Dropout is typically added to “randomly prevent some of the nodes from communicating” based on an allocated percentage (by dropping them to zero). This mask of turning nodes to 0 changes every forward/backward pass, allowing us to train an ensemble of test networks — with the ensemble merged during testing.<br><em>N.B. These are typically added right before a connection back into the residual connection pathway (i.e. at the end of multi-headed attention, at the end of feed forward, at the end of calculating affinities)</em></li></ul><p>Woof. This took longer than usual.</p><h3>Appendix</h3><h4>Tensor Dimension Gotchas</h4><p>Play with and match up dimensions of B/T/C with your loss function<br>e.g. If you’re going with a simple bigram model which takes one character and predicts another character, you can select cross entropy loss. However, Pytorch’s <a href="https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html">cross entropy function</a> requires inputs to be setup with class size being the second dimension, thus requiring some tweaking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*njATh5RPeURPl2GcSy5rkw.jpeg" /><figcaption>C refers to the class size, i.e. number of possible outcomes that the model is expected to predict</figcaption></figure><p>What does this mean? Let’s say we have training data which contains all letters from A-Z tokenized at 0–26 (with one extra for space), containing the sentences “how are you” and “are you okay”</p><ul><li><strong>Your xB (x-Batch) is a tensor of dimensions (B, T) </strong>with batch size B Time/Block Size T<br><em>e.g. xB = [how, are] = [ [7, 14, 22], [0, 17, 4] ] with each letter corresponding to its relevant tokens. Here, the batch size is 2 i.e. 2 rows, the block size is 3, i.e. 3 letters, with xB of shape (2,3)</em></li><li><strong>yB (y-Batch) is the target, and is of the same corresponding shape</strong> <strong>as xB</strong> (B, T)<br><em>e.g. yB = [ow_, re_] (_ referring to space) = [ [14, 22, 26], [17, 4, 26] ] with each letter corresponding to relevant tokens, with yB of shape (2,3)</em></li><li>In a Bigram model, the <strong>Class Size C = vocab. size</strong>, implying a <strong>token embedding table of shape (C, C)</strong>, i.e. for every letter appearing in the training data, there are equivalent possible outcomes but with varying probabilities<br><em>e.g. using the above example, the embedding table will be of size 26,26, where 26 is the vocab size</em></li><li>Therefore, <strong>Logits = Embedding(xB), with a shape of (B, T, C)</strong>, with logits representing a tensor which contains — <em>for each element in xB</em> — the corresponding probabilities of each letter in the vocabulary 🤯<br><em>e.g. the logits table will basically be of the shape (2,3,26) and look something like this ..</em></li></ul><pre>[[[-8.6626e-01, -1.3694e+00,  1.0005e-01, -2.4852e-01, -9.1255e-01,<br>          -8.4218e-01,  9.0579e-01,  8.8845e-01, -7.9284e-01,  5.3425e-01,<br>          -7.9848e-01,  5.1823e-01, -1.1608e+00, -1.0227e+00, -5.0643e-01,<br>           7.8016e-01, -3.3962e-02,  4.1387e-01, -3.7672e-02, -1.4856e+00,<br>          -2.3876e-01, -2.6241e-01, -5.8329e-01, -7.2831e-01,  3.9296e-01,<br>          -1.3158e+00], # 26 possible outcomes, 26 probabilities :)<br>         [ .. ],<br>         [ .. ]],</pre><pre>        [[ .. ],<br>         [ .. ],<br>         [ .. ]]]</pre><ul><li><strong>Now, since Cross Entropy function requires the class size (in this case the vocab size) to be the second dimension</strong>, we would need to modify logits and targets so that the second dimension of logits is C (instead of the third)</li></ul><pre>B, T, C = logits.shape<br>logits = logits.view(B*T, C)<br>yB = yB.view(B*T) # also the targets</pre><ul><li>After this reshaping, cross entropy can evaluate the loss because C is now the second dimension for <em>logits</em></li></ul><h4>Other Open Questions</h4><ul><li><strong>Why is LayerNorm needed?</strong> Is it just for normalization in general? I’m not fully sure, and I think once I do some passes before/after LayerNorm I’ll feel more comfortable. So far the answers have been unsatisfactory (<a href="https://arxiv.org/pdf/2305.02582">This paper</a> suggests ‘expressivity’)</li><li><strong>Utility of projections:</strong> I get that it helps with dimensionality, but beyond that I’m unclear</li><li><strong>Do residual connections need to exploding gradients?</strong> This was the issue that LSTM aims to avoid. Does LayerNorm prevent this?</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49ca1ec86518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network Gotchas]]></title>
            <link>https://medium.com/@shitijnigam/neural-network-gotchas-dc02cf6ec221?source=rss-65eb3c05bb84------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc02cf6ec221</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Shitij Nigam]]></dc:creator>
            <pubDate>Mon, 29 Apr 2024 06:56:17 GMT</pubDate>
            <atom:updated>2024-04-29T12:01:01.292Z</atom:updated>
            <content:encoded><![CDATA[<p>Some common gotchas I’ve been noticing that are worth keeping track of while setting up neural networks, mostly for the sake of practicing the rubber duck method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*X7-KzI1qVz5d5r2L9O_5Cw.jpeg" /><figcaption>Big thank you to Andrej Karpathy’s videos what a tremendously amazing resource <a href="https://www.youtube.com/watch?v=P6sfmUTpUmc&amp;t=248s&amp;ab_channel=AndrejKarpathy">https://www.youtube.com/watch?v=P6sfmUTpUmc&amp;ab_channel=AndrejKarpathy</a></figcaption></figure><h3>Common gotchas</h3><ul><li><strong>Initialized random weights lead to incredibly high initial loss:</strong> Sometimes, the initial loss function of your network may be too high given how your forward pass is set up and how your weights are initialized, leading to a lot of wasted epochs simply trying to squeeze your weights down.</li></ul><blockquote><strong>Potential Solution: </strong>Squish the weights down during initialization e.g. multiplying randomly initialized weights by a factor of 0.1, 0.2, etc. — more on this below, and setting the initial biases to 0</blockquote><ul><li><strong>Vanishing Gradient / unstable gradient problem a.k.a. activation functions end up not activating / hyper activating. </strong>e.g. if your inputs to a tanH function are extremely skewed, a lot of the resulting values will be -1 or 1. And given how the derivative of tanH works (<em>f’(tanH) = 1 — (tan²H)</em>), gradient descent won’t help you optimize weights i.e. <em>weights -= learning_rate * weights.grad</em> will yield the same <em>x</em>, since <em>weights.grad </em>will end up being zero. [Research paper <a href="https://arxiv.org/pdf/1502.01852">here</a>]</li></ul><blockquote><strong>Potential Solution: </strong>Normalize weights using methods such as Kaiming initialization — before passing them into the activation function (<a href="https://pytorch.org/docs/stable/nn.init.html">link</a>)</blockquote><ul><li><strong>Internal covariate shift i.e. changing distributions </strong>in layers as a result of previous layers. This is agnostic of weights and typically starts happening in deep neural networks with multiple layers [Research paper <a href="http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43442.pdf">here</a>].</li></ul><blockquote><strong>Potential Solution: </strong>Batch normalization! Normalization is made a part of neural network design, by normalizing as follows: For a value x in a batch of mean μ and standard deviation sigma σ, normalize by X = (x — μ)/σ. After that, create scaling (bngain) and shifting (bnbias) parameters on top of this, i.e. bngain*(X) + bnbias</blockquote><p><em>N.B. Batch normalization has a lot of internal gotchas. Because it introduces batch mean and batch standard deviation during forward passes, which are required during inference. As a result, batch normalization takes batch mean and batch variance during training, but uses the running mean &amp; running variance (calculated during training) for inference. There are other alternatives (e.g. layer normalization, etc.)</em></p><ul><li><strong>Linear-Layer-Only networks don’t work very well:</strong> While we get easy and nice activations, “a massive linear sandwich tends to collapse into a single linear layer in terms of its representation” (quote: Andrej Karpathy), making them less than optimal to adhere to the universal approximation theorem.</li></ul><blockquote><strong>Potential Solution:</strong> Include other layers in the middle, e.g. tanH, sigmoid, etc. to turn the sandwich from a linear function into a neural network that can in principle approximate any arbitrary function. (But apply corresponding weight <strong>gains</strong> between layers to ensure that functions don’t overactivate / underactivate — see aforementioned points)</blockquote><h3>Common stats to observe</h3><p><em>Note: Most of the following stats typically start looking better via batch normalization</em></p><ul><li><strong>Saturation: </strong>Observing specific forward pass activations (e.g. <em>tanH</em>) to determine if an activation function is particularly saturated<br><em>e.g. for each layer, observe the number of neurons (parameters) that take on specific values as an output of the tanH function. If there are too many neuron ouputs clustered near the ends (i.e. too many large values) or shrinking towards the center of the function (i.e. tan H is squishing inputs too much towards the center), it implies some tweaking is needed to the inputs.</em></li></ul><blockquote><strong>Potential Solution: </strong>This can typically be avoided by adding gains prior to pushing inputs into a non-linear activation function (e.g. 5/3 for TanH for a linear sandwich). Typically, some gains are needed to avoid squashing since the TanH function / Sigmoid functions have a tendency to squash :). However, if the gain is too high, then the tanH function will start pushing activations too much towards the end</blockquote><ul><li><strong>Gradient Distribution:</strong> Observing gradients of specific forward pass functions (e.g. TanH) to determine if the gradients are smoothly distributed across functions or if they follow specific patterns<br><em>e.g. for each layer, observe the number of neurons (parameters) that take on specific grad values as an output of the tanH function. If there is asymmetry in distributions (i.e. if the gradient distributions across layers), it implies some tweaking is needed to the inputs. The reason asymmetry isn’t ideal is because in deeper neural nets with much more layers, the asymmetry can lead to obtuse outcomes</em></li></ul><blockquote><strong>Potential Solution:</strong> Similar to above, i.e. tweaking gains fixes this</blockquote><ul><li><strong><em>[To be confirmed] </em>Gradient to Data ratio / Weights’ only gradient Distribution for all parameters:</strong> Observing distribution gradients for all weights (not biases and any other parameters) to see how they distribute across layers. If some layers are particularly flat or particularly pointed, it implies that some weight sizes may be too skewed<br>Note: TBD — I’m still trying to fully understand this</li></ul><blockquote><strong>(TBD) Potential solution: </strong>Tweaking # of epochs of training can help solve for this and smoothen out the gradient distribution for weights (tbd</blockquote><ul><li><strong>Update magnitude to data ratio,</strong> i.e. (learning rate x parameter’s gradient’s standard deviation) / log (parameter’s data’s standard deviation) — for weights only (not biases and any other parameters) <em>over epochs. </em>These ratios should not be too far above -log(1000) i.e. -3. If they are far below, then our learning rate would have been very low and needs to be boosted up. If the ratios are too high, the learning rate may be way too high</li></ul><blockquote><strong>Potential solution:</strong> Tweak learning rates depending on where the update magnitude ratio is relative to the -3 line</blockquote><p>More to come.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc02cf6ec221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Essential Deep Learning Mathematics Cheat Sheet]]></title>
            <link>https://medium.com/@shitijnigam/the-deep-learning-mathematics-cheatsheet-f8e759ff0996?source=rss-65eb3c05bb84------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8e759ff0996</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[backpropagation]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Shitij Nigam]]></dc:creator>
            <pubDate>Wed, 17 Apr 2024 15:35:51 GMT</pubDate>
            <atom:updated>2024-05-27T13:04:44.067Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*miuf6Uu5yaO7Cu7I7L2lcg.jpeg" /></figure><blockquote><strong><em>Table of Contents</em></strong></blockquote><blockquote><a href="#1a07"><em>Activation Functions</em></a><em><br> ∘ </em><a href="#919b"><em>ReLU</em></a><em><br> ∘ </em><a href="#43c6"><em>Sigmoid Activation function</em></a><em><br> ∘ </em><a href="#248f"><em>SoftMax</em></a><em><br> ∘ </em><a href="#53b3"><em>ArgMax</em></a><em><br> ∘ </em><a href="#1bd1"><em>TanH</em></a><em><br></em><a href="#120d"><em>Loss Functions</em></a><em><br> ∘ </em><a href="#b9c0"><em>Mean Squared Error</em></a><em><br> ∘ </em><a href="#566e"><em>Cross Entropy Loss</em></a><em><br> ∘ </em><a href="#60b1"><em>Important Loss Adjustments</em></a><em><br></em><a href="#c627"><em>Calculus for Backpropagation</em></a><em><br> ∘ </em><a href="#0ee1"><em>Common Derivatives</em></a><em><br> ∘ </em><a href="#7f58"><em>Important Calculus Concepts</em></a><em><br></em><a href="#0e16"><em>Tensor Related Math</em></a><em><br> ∘ </em><a href="#a15a"><em>Matrix Multiplication</em></a><em><br> ∘ </em><a href="#06eb"><em>Broadcasting</em></a><em><br></em><a href="#5f75"><em>Other Concepts</em></a><em><br> ∘ </em><a href="#ec2f"><em>One Hot Encoding</em></a><em><br> ∘ </em><a href="#b46a"><em>Dot Product</em></a><em><br> ∘ </em><a href="#10b6"><em>Logits</em></a></blockquote><h3><strong>Activation Functions</strong></h3><p>Activation functions are functions that are usually applied to the output of a math equation and/or a parameter (in some ways helping us decide the importance of parameters.)</p><h4>ReLU</h4><p><strong>Also known as Rectified Linear Unit.</strong> Basically ReLU(x) = MAX(0, x). Can be combined with other ReLUs to form fancy fitting graphs. Super cool in my opinion. (and a cute name to boot)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/0*MRqUJlx5W7Oc7uD7.png" /></figure><h4><strong>Sigmoid Activation function</strong></h4><p>Basically Squishes up numbers into a nice smooth curve ranging <strong><em>from 0 to 1</em></strong>, with extremely large and extremely small numbers having a diminishing effect</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*IZe5jbdF5I5CfeNJYNbFkA.jpeg" /><figcaption>Euler’s number is the real MVP of math</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*C1SfeqKeg5lfZCv3.png" /><figcaption>As they say, when in doubt, chuck it through a sigmoid</figcaption></figure><h4><strong>Softmax</strong></h4><p>Softmax <strong>normalizes probabilities</strong> by passing it through the following function: <em>e^n1 / (e^n1 + e^n2 + .. e^nN)</em> for <em>N</em> categories. It is especially useful for negative predictions thanks to the e^x function</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*R8M4ySNfN32TICgmTwl7YA.jpeg" /><figcaption>softmax!</figcaption></figure><h4><strong>ArgMax</strong></h4><p>Returns the <strong><em>index of the max value</em></strong> of an array. Pretty nifty when a range of predictions are being made on the same input</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2784dob3zbSuEJ-bBh1zg.jpeg" /><figcaption>Index instead of value, which is the important bit</figcaption></figure><h4>TanH</h4><p>Similar to sigmoid; it transforms inputs into a <strong><em>range between -1 and 1</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/0*tf7wBV-toz9JldNc.png" /><figcaption>Note the difference vs. sigmoid, which converts inputs to a range of y = 0 to 1, vs. tanH which converts to a range of y = -1 to 1</figcaption></figure><h3><strong>Loss Functions</strong></h3><p>These functions help us determine how good or bad our model is relative to our validation data. Some examples of loss functions:</p><h4>Mean Squared Error</h4><p><em>Sum of (Actual — Predictions)² / N</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*RXzjWHCksbHSEkWli032RQ.jpeg" /><figcaption>mean squared error!</figcaption></figure><h4>Cross Entropy Loss</h4><p>Explained by the following formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*yPKq5yqQzFjRXiS-XmVGEw.jpeg" /><figcaption>um.</figcaption></figure><ul><li>(i) <strong>Take the softmax of predicted variable</strong> <em>(‘y-pred’)</em> <strong>across multiple categories</strong><br><em>N.B. I haven’t seen too many examples apply softmax to a network’s generated values, so I assume it is already ‘implied’ in the definition, since taking a log of negative probabilities doesn’t make much sense. TLDR if your y-pred is already a set of probabilities that sum up to 1, then you don’t need to do this step :)</em></li><li>(ii) <strong>Generate the one-hot encoded actual variable for the actual <em>y </em></strong>(<em>‘y-true’</em>)<br><em>i.e. assuming our actual y-values for 4 predictions are Apple, Blueberry, Orange, Apple — the one-hot encoded vector would be [1,0,0], [0,1,0],[0,0,1],[1,0,0] — with ‘1’ implying that the actual probability of prediction should be 100% for the category that was one-hot encoded, and 0% for the rest</em></li><li>(iii) <strong>Multiply the log of softmax</strong> (i.e. <em>log(softmax(y-pred)</em>) <strong>with the one-hot encoded probability</strong></li><li>(iv) <strong>Sum it all up and add a negative</strong></li></ul><p><em>N.B. Binary cross entropy is very similar, just two cases — either you’re a schrodingers cat or you’re not. If your one-hot encoding of being schrodinger’s cat is 1 and the probability of being Schrodinger’s cat is 0.7, then your row of </em><strong><em>iscat</em></strong><em>, </em><strong><em>isNotCat</em></strong><em>, </em><strong><em>probCat</em></strong><em>, </em><strong><em>probNotCat</em></strong><em> is 1, 0, 0.7, 0.3, and the CE loss for that row is -1*log(0.7)-0*log(0.3). Easy! Sum it all up across all predictions, and you get the total Cross Entropy Loss for a set of predictions</em></p><h4>Important Loss Adjustments</h4><p><strong>Regularization </strong>is<strong> </strong>used to combat overfitting by normalizing loss functions, controlling weights. The idea is to add an extra function or “penalty” to your loss function to “regularize” the loss function so that your weights don’t become too large.</p><ul><li><strong>L1 regularization (Lasso)</strong> adds the <em>sum of weights to the loss function</em>. Since weights can be both positive and negative, they may cancel each other out, but this does help drive some weights down to zero and can help with feature selection</li><li><strong>L2 regularization (Ridge)</strong> adds the <em>sum of squares of weights</em> <em>to the loss function</em>; this doesn’t necessarily drive weights to zero but does shrink them towards zero to minimize the overall loss</li></ul><h3>Calculus for Backpropagation</h3><h4>Common Derivatives</h4><ul><li><strong>f(x) = a * x</strong>; f’(x) = a<br><em>if a = 1, f(x) = x, and f’(x) = 1</em></li><li><strong>f(x) = x^n</strong>; f’(x) = n*(x^(n-1))<br><em>e.g. f(x) = 3x³, f’(x) = 9x² (combined with the above rule)</em></li><li><strong>f(x) = log</strong>₁₀<strong>(x)</strong>; f’(x) = 1/(x*<em>ln</em>(10))<br>N.B. <em>ln</em> is a log function with base e. <em>10</em> is replaced by the corresponding base of the log function. If the base is <em>e</em> instead of <em>10</em>, i.e. f(x) = <em>ln</em>(x), then f’(x) = 1/x, since <em>ln</em>(e) = 1<br><em>Useful for Sigmoid activation</em></li><li><strong>f(x) = tan(x)</strong>; f’(x) = 1 — (tan(x))²<br><em>Useful for TanH activation</em></li><li><strong>f(x) = e^x;</strong> f’(x) = e^x</li><li><strong>f(x) = a @ x;</strong> (more on this below in the <em>Matrix Multiplication</em> section) .. the formula is too strange; try to simply match the dimensions of the expected vector</li></ul><h4>Important Calculus Concepts</h4><ul><li><strong>Chain Rule:</strong> Possibly the most useful tool. If L = a + b, a = x + y, x = m + n, then <em>d</em>L/<em>d</em>m = (<em>d</em>L/<em>d</em>x) * (<em>d</em>x/<em>d</em>a) * (<em>d</em>a/<em>d</em>m)<br><em>Essentially derivatives have multiplicative properties and can be ‘chained’ together</em></li><li><strong>Gradients are additive. </strong>e.g. if a tensor / variable occurs multiple times in a neural network, then its impact (and therefore gradient) to the final output (e.g. the impact to a loss function) will cumulatively add up, since a small change to that tensor / variable will have impact multiple times</li><li><strong>When backpropagating across tensors</strong>, it’s important to <strong>check the shape of each tensor</strong> and <strong>ensure consistency in gradient and tensor </strong>dimensions<br><em>e.g. if x-normal = x — (x^max), with x being a tensor [10,10] and x^max being a tensor [10,1] (i.e. the max of each row), then the gradient of x^max should be a tensor of dimensions [10,1]</em></li></ul><h3>Tensor Related Math</h3><h4>Matrix Multiplication</h4><ul><li><strong>Basic math behind matrix multiplication: </strong>Multiply the numbers in the row of matrix 1 (‘a’) by the numbers in the column of matrix 2 (‘W’), then add them up together<br><strong>This is represented by <em>aW = b</em></strong></li><li><strong>Order &amp; Size matters:</strong> <em>The order will dictate the size and outputs</em>. Because the order matters, the size matters, i.e. <em>the # of columns of matrix 1 (‘a’) should be equal to the # of rows of matrix 2</em> (‘W’)<br>e.g. if matrix 1 (‘a’) is 1x2 (i.e. 1 row, 2 columns), and matrix 2 (‘W’) is 2x2 (i.e. 2 rows, 2 columns), then the matrix multiplication will mean each column of matrix 1 (‘a’) is multiplied by each row in matrix 2 (‘W’) to generate 1 item for the final matrix</li><li><strong>Final matrix: </strong>The # of rows of the final matrix (‘b’) is the equal to the # of rows in matrix 1 (‘a’). The # of columns in the final matrix is equal to the # of columns in matrix 2 (‘W’)</li><li><strong>Transposing the output requires flipping the order and transposing the original matrices<br></strong><em>e.g. if the transpose of ‘a’ is ‘A’, the transpose of ‘W’ is ‘w’, and the transpose of ‘b’ is ‘B’, then..<br>- aW = b<br>- wA = B</em> <br><em>.. the order is flipped and the final matrix is transposed</em></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/0*3H5fKjuRMUOXQhGS.png" /><figcaption>amazing summary here — <a href="https://androidkt.com/pytorch-matrix-multiplication-from-scratch/">https://androidkt.com/pytorch-matrix-multiplication-from-scratch/</a></figcaption></figure><p><em>N.B. Why do matrix multiplication? It’s faster and more efficient than running loops (good explanation </em><a href="https://softwareengineering.stackexchange.com/questions/312445/why-does-expressing-calculations-as-matrix-multiplications-make-them-faster"><em>here</em></a><em> — it comes down to: using multiple threads instead of just one to boost performance, using cache, SIMD instructions i.e. breaking down matrices into smaller chunks allowing parallel operations, etc.) Python is slow esp. for loops, but Matrix Multiplication is fast, especially thanks to underlying optimizations done by PyTorch.</em></p><h4>Broadcasting</h4><p><em>Source: </em><a href="https://pytorch.org/docs/stable/notes/broadcasting.html"><em>Pytorch Documentation</em></a></p><ul><li>a) <strong>Each tensor should have at least one dimension</strong></li><li>b) <strong>Tensor dimensions should be compared starting from the right </strong><br><em>e.g. when multiplying a 27/25 tensor to a 25 only tensor — 25 will be compared to 25</em></li><li>c) <strong>Dimensions being compared to each other should either</strong><br>- <strong>have the same size</strong> <em>e.g. (28,27) &amp; (25) </em><strong><em>can’t</em></strong><em> </em><strong><em>be</em></strong><em> broadcast because 25 != 27, but a (28,27) &amp; (27) tensor </em><strong><em>can be</em></strong><em> broadcast since 27==27</em><br>- <strong>not exist</strong>, <em>e.g (28,27) &amp; (27) tensor </em><strong><em>can be</em></strong><em> broadcast, since the missing dimension can be filled in as 1 to make the sizes equal</em><br>- <strong>be of size 1</strong>, <em>e.g. (28,27) &amp; (3,27) </em><strong><em>can’t be</em></strong><em> broadcast, but (28,27) &amp; (1,27) </em><strong><em>can be</em></strong><em>; similarly, (27,1) &amp; (27,27) </em><strong><em>can be</em></strong><em> broadcast, but (27,3) &amp; (27,27) </em><strong><em>can’t be</em></strong></li></ul><p>Assuming both tensors are broadcastable, <strong>the final size of the output is the max of dimensions for both tensors.</strong></p><h3>Other Concepts</h3><h4><strong>One Hot Encoding</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TMJUPKVRFNfeb5pO" /><figcaption><a href="https://medium.com/@michaeldelsole/what-is-one-hot-encoding-and-how-to-do-it-f0ae272f1179">https://medium.com/@michaeldelsole/what-is-one-hot-encoding-and-how-to-do-it-f0ae272f1179</a></figcaption></figure><h4><strong>Dot Product</strong></h4><p>A relic of the cosine similarity function, meant to capture similarity between vectors, minus the denominators to ignore normalization</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*667sGHS06SY-Ph2dGd0ZZw.jpeg" /><figcaption>The denominator is meant to normalize the distances which is sometimes useful but often ignored. The larger the numerator value the more likely it is that the two numbers are similar. For more</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*znmkuD6RowiAcFN2CdIuwQ.jpeg" /><figcaption>Numerator, basically.</figcaption></figure><h4><strong>Logits</strong></h4><p>Logits are outputs of a network before any sort of activation function is applied (see above for activation functions). They are typically non normalized. For example:</p><ul><li><em>A one-hot encoded vector (X) matrix multiplied by a set of weights (W) would yield a set of values called </em><strong><em>logits,</em></strong><em> i.e. logits = X @ W</em></li><li><em>Passing them through an exponentiation function, i.e. counts = e^logits will give a normalized set of numbers.</em></li><li><em>Normalizing counts will give probabilities, i.e. probs = counts / counts.sum(1, keepdims = True)</em></li></ul><p><strong>This is different from </strong><a href="https://en.wikipedia.org/wiki/Logit"><strong>math logits</strong></a><strong> which are specific probability calculation functions — </strong>more detailed context <a href="https://stackoverflow.com/questions/41455101/what-is-the-meaning-of-the-word-logits-in-tensorflow/52111173#52111173">here</a><strong>)</strong></p><p>Will keep adding more relevant math as I uncover it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8e759ff0996" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tensor Tailor Soldier Spy]]></title>
            <link>https://medium.com/@shitijnigam/tensor-tailor-soldier-spy-a41bd23acab1?source=rss-65eb3c05bb84------2</link>
            <guid isPermaLink="false">https://medium.com/p/a41bd23acab1</guid>
            <category><![CDATA[fastai]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Shitij Nigam]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 14:18:55 GMT</pubDate>
            <atom:updated>2024-05-07T14:25:58.816Z</atom:updated>
            <content:encoded><![CDATA[<h3>🤖 Tensor Tailor Soldier Spy 🤖</h3><p>Today I’m learning all about Tensors. Josh Starmer’s courses touched upon this briefly while doing an introduction to Pytorch (great channel and course, btw), what blows my mind is that when you don’t get into the details for too long, you miss out on basic concepts.</p><p>Anyway, a notepad of things I’ve noticed / learned (mostly obvious but not too bad.)</p><ul><li><strong>NumPy Arrays</strong> and<strong> PyTorch Tensors</strong> are similar. Notably, np can have jagged aka the innermost arrays can have different sizes, and np can store other types of data. tensors = no jag, numbers only.</li><li>I guess tensors are basically vectors; the length of a tensor’s shape is its ‘<strong><em>rank</em></strong>’. Put differently, <strong><em>rank</em></strong> is the number of axes or dimensions in a tensor; <strong><em>shape</em></strong> is the size of each axis of a tensor</li><li><strong>Broadcasting: </strong>Pytorch Tensors have a property called broadcasting, which “<em>will automatically expand the tensor with the smaller rank to have the same size as the one with the larger rank. Broadcasting is an important capability that makes tensor code much easier to write.”. </em>Insane.</li><li><strong>Tensor Shapes: </strong>Some funny shape manipulations when working with broadcasting (<em>valid_3_tensor</em> is a collection of 1k images which look like the letter ‘3’, — aka the <em>validation</em> set; <em>mean3</em> is the average of ~8k images that should look like the letter ‘3’ — aka the <em>training</em> set)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ehCvl8S9FvXqi6nYWChvg.jpeg" /></figure><ul><li><strong>backward() </strong>propagation is the real MVP. Such fantastic use of high-school calculus. I remember preparing for these in 6th grade.<br><em>Funny tangential story. I was asked to participate in a Aryabhatta National Mathematics Competition in 5th or 6th grade which tested us on 10th grade and above math. Ridiculously challenging, but my main takeway from that was that most math is easy, but your understanding is just a function of time.</em></li><li><strong>Tensor Views is weird</strong>. I’m not sure yet what the underlying mechanics of the stored data are — e.g. if an image of size 28x28 is reshaped to a single tensor, does that somehow transform the two axes into a single array containing the two axes? Anyway I wrote some pseudo code to visualize this</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3mBCvo6bjvt6f7iAxqxwkw.jpeg" /><figcaption>concat combines them along the most basic axes, view reshapes the image into ..?</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mF7bXqIaS1vU28dc83ugYQ.jpeg" /><figcaption>yeah okay, so the info order is retained, but transformed. (look at the last command). fabulous.</figcaption></figure><ul><li><strong>Tensor Unsqueeze</strong> is another new piece of work. I don’t quite understand what it’s meant to do; <a href="https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch">StackOverflow</a> suggests it turns an n dimensional tensor into an n+1 dimensional. If you look at the different shapes, you get some interesting outputs (unsqueeze can range from -2 to 1 given this is a .. rank-1 tensor / 1 dimensional tensor .. The negative corresponds to</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Soe2Sub4Lx05fis81u4kQ.jpeg" /><figcaption>unsqueeze this. also, what the f is happening.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*BPc24EYLRhWjfMIR.png" /><figcaption>Amazingly helpful graphic from <a href="https://stackoverflow.com/questions/57237352/what-does-unsqueeze-do-in-pytorch">StackOverflow</a></figcaption></figure><ul><li><strong>torch.where</strong> is a funny (good) way to generate new tensors based on specific conditions. I’d written up an explanation but the docs do a good job with their example so there you have it.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*2ZO9Kw8AFI8oHoARmIET-Q.jpeg" /></figure><ul><li><strong>torch.linspace</strong> is useful; helps create a quick set of tensors with equivalent steps. Adding <strong>[:, None] </strong>to the function also immediately warps its shape by adding a dimension</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*icesaMoYUUeuWqxSaeCX2g.jpeg" /><figcaption>torch.linspace() introduces a rank-1 vector; [:, None] warps it to rank-2. Nice.</figcaption></figure><ul><li><strong>torch.t()</strong> can transpose your matrix :-) Cool for one hot encoding matrix multiplications</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDEpgVqpIJwH88QKx1_RNw.jpeg" /><figcaption>If someone can reasonably understand this in the first go, you deserve a Nobel prize</figcaption></figure><ul><li><strong>torch.Storage</strong> — this blew my mind. It essentially shows how PyTorch stores tensors in a single long dimension. This is essentially what allows efficient operations, allows view creation, squeezing, unsqueezing, etc.</li><li><strong>torch.tril</strong> returns the lower part of the triangle of a 2D tensor. This is useful when trying to make things like rolling means, etc. more efficient via matrix multiplication<br><em>e.g. <br>- torch.tril(torch.ones(3,3)) returns a tensor [[1,0,0], [1,1,0], [1,1,1]]<br>- Dividing a by the sum of a along the second dimension i.e. columns (i.e. a.sum(1, keepdim = True)) gives us a tensor [[1,0,0], [0.5, 0.5, 0], [0.33, 0.33, 0.33]]<br>- This can be matrix multiplied by another tensor to give us rolling averages while keeping things efficient</em></li></ul><p>Onwards and upwards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a41bd23acab1" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>