<?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 W&amp;B on Medium]]></title>
        <description><![CDATA[Stories by W&amp;B on Medium]]></description>
        <link>https://medium.com/@weights_biases?source=rss-d81e29d20045------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*oq3E48lI76VIuL84u-HHWA.png</url>
            <title>Stories by W&amp;amp;B on Medium</title>
            <link>https://medium.com/@weights_biases?source=rss-d81e29d20045------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 23:51:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@weights_biases/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[Walking through Neural Style Transfer with Weights & Biases]]></title>
            <link>https://medium.com/@weights_biases/walking-through-neural-style-transfer-with-weights-biases-95bdfb89b79c?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/95bdfb89b79c</guid>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-style-transfer]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Thu, 05 Dec 2019 00:11:36 GMT</pubDate>
            <atom:updated>2019-12-05T00:11:36.749Z</atom:updated>
            <content:encoded><![CDATA[<h4>A step-by-step tutorial for understanding Gatys, content and style features</h4><h4>By: <strong>Ayush Chaurasia</strong></h4><p>In this tutorial, we’ll go through the neural style transfer algorithm by Gatys, implement it and track it using the W&amp;B library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVX83GnGUFzCOyB3oNWXqw.png" /></figure><p>Let’s assume that we’re building a style transfer app for production. We’ll need to compare the results generated by changing various parameters. This requires subjective comparison because we cannot use an accuracy metric as no style transfer result is more “accurate” than the other. So, we’ll need to choose the parameters according to our preference and this requires side-by-side comparison which can easily be done using wandb library. Let’s take it step-by-step.</p><h3>Intro To Neural Style Transfer</h3><p>Neural style transfer is an optimization technique that takes as input a content and a style image, and optimizes a target image to resemble the contents of the content image and style of the style image. <em>The key finding of this research paper by Gatys was that the content and style features of an image can be separated using deep neural networks.</em></p><h3>Separating Style and Content</h3><p>Our next task is to understand how the style and content of a given image can be approximated using a deep neural network. If you ever wander into the nitty-gritty of training and visualizing the training process, you’ll find that the lower layers of the network learn to recognize the lines, edges, and colors which represent the low level details of the image while the deeper layers learn to recognize shapes, orientation and other high level aspects of the image. Thus, we can use lower layers to extract style as it consists of textures and colors of the image while the deeper levels can be utilized to extract the content. Here’s an excerpt from the research paper — <em>“along the processing hierarchy of the network, the input image is transformed into representations that increasingly care about the actual content of the image compared to its detailed pixel values.”</em></p><p>Now, we’ve got the tools necessary to build our style transfer algorithm. We just need to optimize another image(tensor) to represent the style and content of the input images. But to optimize, we’ll need a metric, which brings us to the cost function.</p><h3>Cost Function For Style Transfer</h3><p>The total cost function is the weighted sum of two separate costs namely, style cost and content cost calculated separately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mrFHwkr-eYzi059h.png" /></figure><p>Here, α is called the content weight and 𝛽 is called the style weight. Generally, style weight is much higher than the content weight as we want to emphasize more on the “style transfer”. In this experiment, we’ll set α =1e2and 𝛽 =1e8. We’ll use a pre-trained VGG19 network to calculate style and content losses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*g2r0BvN2fY01uRk6.png" /></figure><p>The layers underlined in red will be used for the extraction of style features and more weight will be given to the layers at the front as compared to the deeper layers.</p><p>The layer underlined in blue will be used for the extraction of content features. Only one layer deep into the network is used for content extraction as the lower layers don’t capture the content but only texture(style).</p><p>Let’s look into the details of the two cost functions.</p><h3>Content Loss</h3><p>The content loss is pretty straight-forward. let <em>p</em>and <em>x</em>be the original image and the image that is generated and <em>P</em>and <em>F</em>their respective feature representation in layer<em>i</em>. We then define the squared-error loss between the two feature representations as the content loss.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/0*ac_TwAMzzzNZAT8g.png" /></figure><h3>Style Loss</h3><p>let <em>a</em>and <em>x</em>be the original image and the image that is generated and <em>Ai</em>and <em>Gi</em>their respective style representations in layer<em>i</em> . The contribution of that layer to the total loss is then</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/0*FUbCiYzlKjg0YKB4.png" /></figure><p>Here <em>G</em>represents a correlation between style features known as “<em>gram matrix</em>”.</p><p>It is essentially a measure of style captured by the features.</p><p>Wl represents the weight of a particular layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/0*4pWdHUsOhgBFqPEs.png" /></figure><p>We’ll provide more weight to the lower layers as they are responsible for capturing the style.</p><p>Here are the weights that I’ve used for this experiment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/0*iwGlTAGVER9z0H8q.png" /></figure><p>Now that we have our separate losses, let’s combine them to form the cost function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/0*HyDJt7f0pi-ElNMS.png" /></figure><p>This is all we need to optimize our algorithm to generate artistic style. I’ve covered a more detailed explanation of the research paper and code implementation from scratch <a href="https://www.youtube.com/watch?v=0tTRA3emrr4&amp;list=PLbMqOoYQ3MxwV-xLpzWNQ70IvctU7H-yl">here</a>.</p><h3>Weights and Biases Integration</h3><p>Wandb library can be easily installed using pip. We’ll use it to track the performance and outputs of various optimizers that we’ll use to optimize our style transfer algorithm. The saved logs and metrics for this project are public and can be viewed on this <a href="https://app.wandb.ai/cayush/neural-style">wandb workspace</a>.</p><p>In order to use wandb to track a project,we need to initialize it using the init()function which takes the name of the workspace and an optional name for the current execution. wandb.config helps us keep track of other important parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/0*rhEe3GtPkFXbHytU.png" /></figure><p>The picture above represents the initialization for the execution where we’ve used the Adamoptimizer.</p><h3>Tracking Loss and Outputs</h3><p>Next, we’ll track the total cost function and the target image that our optimizer produces. But before that, let’s see what are the style and content image that we’ll be using for this task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Zssg7TTHemFmwTaC.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*N3faHuLI09QEYeO1.jpeg" /></figure><p>Now let’s print and log the total loss after every 10 iterations using wandb. The syntax to do that is pretty straightforward.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/0*usmsqX6Dgw0LtVw4.png" /></figure><p>Here, we are logging only the loss and not the accuracy because it’s quite obvious that there is no accuracy metric for style transfer. We’ll also save the output image generated after every 20 iterations in a list and log that list in order to track the generated outputs. Here’s the code snippet for logging images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*aBMKMo0XETybY-3I.png" /></figure><p>Wandb can also be used to log plots, charts, tensors, audio video and other data formats. Detailed information about the log function can be in the official documentation for <a href="https://docs.wandb.com/library/python/log">wandb.log</a>.</p><h3>Moving On To Experimentation</h3><p>In neural style transfer algorithm, a slight change in any of the parameters or hyper-parameters such as optimizer function, learning rate, layer weights, style and content weights can dramatically change the end results. In this case study, we’ll analyse how different optimizer algorithms affect the results. We’ll compare these optimizers — Adam,Adagrad,RMSPropand LBFGS. After running the code with the different optimizers, wandb will automatically log the necessary data needed for comparing the executions in the workspace. Let’s take a look at our wandb workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xAMhPjD0ygFSD0lY.png" /></figure><p>Various visualizations are automatically generated by wandb and are listed under the AUTO VISUALIZATIONS tab.</p><p>We can manually add visualization for the desired parameters using the “add visualization” button. The generated visualizations are listed under the VISUALIZATION tab.</p><p>All the executions are listed on the left pane and the details of each execution can be viewed by clicking on its name.</p><h3>Visualizing The Cost Function</h3><p>Let’s take a look at how various optimization algorithms stack up against each other. To do that, we’ll have a look at the visualization of losses that we’ve logged.</p><p>As it is clearly visible from the plot, Adam optimizer starts to converge faster than any other optimizer but in the end LBFGS is the clear winner if minimizing the loss is the comparison metric.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cNf3HrW5pq8-WA2r.png" /></figure><p>Adagrad executes fairly smoothly but it takes much longer to converge. RMSProp is the most unstable optimizer among these four optimizers as it is clearly visible from its plot.</p><p><strong><em>Deduction — </em></strong>If minimizing the loss function has the highest priority, the best optimizer would be LBFGS. We’ve easily deduced this by comparing the plot generated by wandb.</p><p>But in style transfer, the loss metric does not capture the whole picture. Remember that we’re building a style transfer app for production and choosing a technique over another is fairly subjective as “style” is subjective. So, now let’s compare the results. We’ve logged 50 outputs for each execution. Let’s compare them.</p><p>Visualizing Results at Index 15</p><p>Wandb allows up to generate and save reports by choosing and comparing specific runs. I’ve saved a report which compares the outputs of various indices. Let’s have a look at index 15.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-zI-apVp1MtehlVe.png" /></figure><p>Looking at the results, we can easily conclude that RMSprop optimizer is the outlier among the others as the output generated by it has a lot of distortions without the visible signs of transference of style. This can be fixed by tuning the hyper-parameters but for the sake of experimentation, we’ll hold the parameters constant. The image looks dull and faded. Again, it is purely subjective and might be considered as a “whitened” version of the image. So, we can use this optimizer when trying to apply a whitening filter.</p><p>Adagrad’s output has sharp contrast but as the convergence its convergence is slow, the style is not yet prominent when compared with the outputs of LBGFS and Adam.</p><p><em>Deduction</em></p><ul><li>LBGFS resultant has the most prominent style features at 15th output followed closely by Adam</li><li>Adagrad’s output is sharp but as the convergence rate is slow, the style features are not yet prominent.</li><li>RMSProp’s output can be described as a whitened version of Adagrad’s resultant.</li></ul><p>Visualizing Results at Index 25</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*gkkYq_7K2a6NLz5J.png" /></figure><p>The LBGFS optimizer has achieved the highest level of style transfer, closely followed by Adam. RMSProp again seems to be the obvious outlier with white-filter touch. Adagrad has the least prominent style features.</p><p><em>Deduction</em>- If the speed for execution(number of epochs) is concerned, we should go for LBGFS as our optimizer of choice.</p><p>Visualizing the Final Results</p><p>Let’s have a look at the final output of our algorithm</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4a4dqte11WbqmqbT.png" /></figure><p><em>Final Deduction-</em></p><ul><li>Although it boils down to personal preference, I like the output of LBGFS the best. It captures both the style and content while maintaining the sharp textures.</li><li>Adam preserved the concrete features of the content image while transferring the style from the style image.</li><li>RMSProp algorithm acts an aggregate of style image and a faded white filter.</li><li>Adagrad shows success in transferring the color of style image but it is not able to transfer the texture. This might be due to its unstable training as we deduced from the loss function plot.</li></ul><p>Now we have sufficient insights to choose the optimizers accordingly to build our application. We can even offer multiple forms of style transfer as we’ve got different yet consistent results in all the 4 experiment.</p><p>Finally, we can easily tune this algorithm by changing even one of many parameters. I’d recommend that you try to change the hyper-parameters and compare the executions at various levels. Wandb makes it really easy to compare and log the results. So go ahead and experiment!</p><h3>Creating Reports on wandb</h3><p>Wandb allows you create reports which contain detailed analysis of an experiment with supporting visualization and explanation. The detailed report of this experiment can be found <a href="https://app.wandb.ai/cayush/neural-style/reports?view=lavanyashukla%2FExploring%20Neural%20Style%20Transfer%20Paper%20With%20W%26B">here</a>.</p><h3>More Results</h3><p>Here are some more results from the test runs that I performed on my system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*HQN50TUjRFayEC1PuFlwCg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*SwJBYUfSv5epGIWV.jpeg" /></figure><h3>References:</h3><p><a href="https://arxiv.org/abs/1508.06576">The original neural style transfer research paper</a></p><p><a href="https://youtu.be/0tTRA3emrr4">A video explaining the research paper</a></p><p><a href="https://youtu.be/K_xBhp1YsrE">A video explaining the code implementation of the research paper</a></p><p><a href="https://app.wandb.ai/cayush/neural-style?workspace=user-cayush">Wandb workspace for this project.</a></p><p>‍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95bdfb89b79c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Use GCP with Weights & Biases]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/how-to-use-gcp-with-weights-biases-2ee52f986498?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ee52f986498</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Mon, 25 Nov 2019 03:33:39 GMT</pubDate>
            <atom:updated>2019-11-25T04:37:38.240Z</atom:updated>
            <content:encoded><![CDATA[<p>By: <a href="https://www.sayak.dev/">Sayak Paul</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IL1KolvqmBQodmKjBVgXng.jpeg" /></figure><p>Google Cloud Platform or more popularly GCP makes it really easy to quickly fire up a virtual machine that’s loaded with a GPU and all the necessary setup to help accelerate your machine learning experimentation. Among the various services that GCP offers in this line, <a href="https://cloud.google.com/ai-platform/notebooks">Notebooks</a> from the <a href="https://cloud.google.com/ai-platform/">AI Platform</a> section are my favorite.</p><p>In this article, I will be showing you how to quickly spin up a Notebook instance via the AI Platform and how to configure Weights and Biases in that instance. I’ll also highlight some cool features that come with Weights and Biases (W&amp;B) that make it a lot of fun to work with.</p><p>Note: The rest of this post assumes you already have a <strong>billing-enabled</strong> GCP account.</p><h3>Getting up and running with a Notebook instance</h3><ul><li>In your browser, go to <a href="https://console.cloud.google.com/">https://console.cloud.google.com</a>.</li><li>Navigate to AI Platform -&gt; Notebooks.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/0*62uMuwrfmufwxFiQ" /></figure><ul><li>After navigating to the Notebooks section, click on <strong>NEW INSTANCE.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eAAv4LdsG1OUIKov" /></figure><ul><li>You will have a number of pre-configured environment choices. Since TensorFlow 2.0 is new and officially released, let’s go with that version.</li><li>Let’s also use a GPU.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/693/0*XTqgcyaZ8OKR1cvf" /></figure><p><strong>Note</strong> that in the <strong>Customize Instance</strong>, you get a lot more options including a range of GPU choices. Upon selecting the environment you wish to proceed with, you will be given a popup like the following to specify the additional details. <em>Be sure to tick the installation option for the NVIDIA GPU drivers.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*f158hqIffStl9nd3" /></figure><ul><li>After you click <strong>CREATE </strong>on that popup, it will take some time to create the instance. So hold tight. If your notebook instance was successfully created you should see something like so -</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8MLPfsG77hKO9zF6" /></figure><ul><li>Now click <strong>OPEN JUPYTERLAB </strong>to access your notebook instance. This will cause a Jupyter Lab instance to start running where you will be able to:</li><li>Fire up notebooks</li><li>Execute your Python scripts via the terminal</li></ul><p>Now let’s configure Weights and Biases within this instance.</p><h3>Configuring W&amp;B within a GCP notebook instance</h3><p>Your notebook instance comes with both Python2 and Python3 (3.5) installed. So, we will have to very careful about using python and pip aliases here. By default, when you type python in the terminal version 2.7 gets selected. We can, of course, configure it accordingly. But let’s not focus on that for the time being.</p><p>Let’s go ahead and execute the following from a terminal of your notebook instance</p><pre>pip3 install wandb</pre><p>Notice, I am using pip3 here. Let’s verify the installation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IA9Q6mZSI2hbsmWj" /></figure><p>Next, let’s ensure that the CLI interface of W&amp;B is also working. We can verify that here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*wT1Nht8mG2dDaMjJ" /></figure><p>In this instance, it is not working as expected. So what is going on here? This is a common error for beginners and those new to working with Python. This is because the <strong>PATH</strong> environment variable is not configured properly which tells the operating system from where to load wandb.</p><p>Let’s fix this.</p><p>First, we need to find out the location directory of wandb. The easiest way to do this I know of is to simply run pip3 uninstall wandb and it logs out information. Below is an example -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/0*4VC5DFzLkIhK4G4P" /></figure><p>Note the path of wandb (this is not the Python library but the CLI utility) which in this case is: /home/jupyter/.local/bin/wandb. Now, we need to symlink wandb inside /usr/bin -</p><p>$ cd /usr/bin</p><p>$ sudo ln -s /home/jupyter/.local/bin/wandb wandb</p><p>The next step is to update the value of the following environment variable correctly: <strong>PATH. </strong>So, type in nano ~/.bashrc and enter the following -</p><pre>export PATH=”$PATH:/usr/bin/wandb”</pre><p>After you are done typing the above, go ahead and save it. <em>After that, do not forget to run source ~/.bashrc otherwise, the changes won’t take effect.</em></p><p>Now, when you run wandb login, you should see the following -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*xyPkqVOKJYiwYxsL" /></figure><p>Proceed with an option accordingly and you should be good to go. After this step has been completed, W&amp;B should be authorized.</p><h3>Tracking metrics: Using W&amp;B to keep track of model’s performance</h3><p>Now that we have set up and authorized W&amp;B for our Notebook instance, let’s actually see how to use it to keep track of a model’s performance while it is training. We will be using TensorFlow 2.0 and particularly the high level tf.keras API.</p><p>I will walk you through the primary steps you would need to perform in order to use W&amp;B to keep track of your model’s performance. You may find <a href="https://colab.research.google.com/github/sayakpaul/TF-2.0-Hacks/blob/master/Hyperparameter%20Sweeps%20with%20TF%202.0%20%26%20W%26B/TensorBoard%20Integration%20in%20W%26B.ipynb">this notebook</a> handy if you want to follow along.</p><ul><li>Initialize wandb:</li></ul><p><em># Initialize your W&amp;B project allowing it to sync with TensorBoard</em></p><p>wandb.init(project=&quot;tensorboard-integration&quot;, sync_tensorboard=<strong>True</strong>)</p><p>config = wandb.config</p><ul><li><strong>Note </strong>the sync_tensorboard argument in the above code block. If we set it to True, W&amp;B will spin up a TensorBoard instance on your W&amp;B project (<strong>tensorboard-integration</strong>) dashboard provided that we are supplying the TensorBoardCallback in the right manner.</li><li>After running the above code block, W&amp;B will create a run for you and it will also provide you with an online run page that should be similar to this: <a href="https://app.wandb.ai/sayakpaul/tensorboard-integration/runs/e8kv5zab">https://app.wandb.ai/sayakpaul/tensorboard-integration/runs/e8kv5zab</a>.</li><li>Specify the configuration variables:</li></ul><p><em># Specify the configuration variables</em></p><p>config.dropout = 0.2</p><p>config.hidden_layer_size = 128</p><p>config.layer_1_size = 16</p><p>config.layer_2_size = 32</p><p>config.learn_rate = 0.01</p><p>config.decay = 1e-6</p><p>config.momentum = 0.9</p><p>config.epochs = 25</p><ul><li>These are essentially your model’s <a href="https://www.wandb.com/articles/running-hyperparameter-sweeps-to-pick-the-best-model-using-w-b">hyperparameters</a>.</li><li>Prepare your dataset that will go into your model and kickstart the training process with the appropriate callback(s):</li></ul><p># Specify your model definition</p><p># Try supplying the configuration variables</p><p>model = Sequential([...])</p><p># Compile the model</p><p>model.compile(loss=loss, optimizer=optimizer, metrics=[&#39;accuracy&#39;])</p><p><em># The WandbCallback logs metrics and some examples of the test data</em></p><p>model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=config.epochs,</p><p>callbacks=[WandbCallback(data_type=&quot;image&quot;, labels=labels),</p><p>TensorBoard(log_dir=wandb.run.dir)])</p><ul><li>Two things to pay attention to in the above code block:</li><li>Note how the number of epochs has been specified. Instead of just supplying a hard-coded value, we are supplying config.epochs which we defined earlier. Doing this will allow W&amp;B to keep track of the configuration variables as well.</li><li>WandbCallback(data_type=”image”, labels=labels): We can simply supply WandbCallback without any arguments and it will keep track of the performance of the model. Additionally, if we supply the data_type and labels arguments, <em>W&amp;B will log some sample predictions on the validation data points as the model is training</em>.</li></ul><p>And that’s it! Now if you go to this run page (h<a href="https://app.wandb.ai/sayakpaul/tensorboard-integration/runs/e8kv5zab">ttps://app.wandb.ai/sayakpaul/tensorboard-integration/runs/e8kv5zab</a>) you will see:</p><p><strong>Visualizing the model performance:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bdKSrkd09mALiW_-.png" /></figure><p><a href="https://app.wandb.ai/sayakpaul/tensorboard-integration/runs/e8kv5zab/tensorboard"><strong>TensorBoard</strong></a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/0*GmLD1rdMlZc322qQ.png" /></figure><p><strong>Sample predictions from different steps in the training</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OdPpAdfJOdG17T40.png" /></figure><h3>How to read metrics automatically using W&amp;B with GCP</h3><p>Weights and Biases allows reading your previous runs for analysis purpose. <a href="https://www.wandb.com/articles/exploring-deep-learning-hyperparameters-with-random-forests">Here’s</a> an excellent analysis done by Lukas on some publicly available Weights and Biases runs. Instrumenting runs is as easy as -</p><p>api = wandb.Api()</p><p>run = api.run(&quot;sayakpaul/arxiv-project-complex-models/6t93vdp7&quot;)</p><p>In the above example, <a href="https://app.wandb.ai/sayakpaul/arxiv-project-complex-models/runs/6t93vdp7">https://app.wandb.ai/sayakpaul/arxiv-project-complex-models/runs/6t93vdp7</a> is a publicly available run. Now, after the run is loaded, you can extract the configuration variables of the run like so — run.config. It will print out -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/0*m3DvORcTTkX9vGZ7" /></figure><p>If you want to read the metrics associated with a particular run along with other important stuff, you can easily do so by -</p><p>api = wandb.Api()</p><p>run = api.run(&quot;sayakpaul/arxiv-project-complex-models/6t93vdp7&quot;)</p><p>run.history()</p><p>You get -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/0*ywz2oJ_7NQGHfWXT" /></figure><p>In order to read multiple runs residing in a project and summarizing them, you need three lines of code -</p><p>runs = api.runs(&quot;sayakpaul/arxiv-project-complex-models&quot;)</p><p>for run in runs:</p><p>print(run.summary)</p><p>And -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5dIt9AIwWQTQDCJS" /></figure><p>Of course, you have the flexibility of trimming the parts from the summary you don’t need. To know about the full potential of the Weights and Biases API check out the official documentation: <a href="https://docs.wandb.com/library/api">https://docs.wandb.com/library/api</a>.</p><h3>Advanced Features: Resuming and Grouping Runs</h3><h3>Resuming Runs</h3><p>In machine learning, MemoryErrors are extremely common — even when training is taking place on GPUs. When these errors occur, model training is impacted. In addition to MemoryErrors, it is also common for those new to Machine Learning to encounter a power failure and lose the progress of days of training. This is all to say that setting up your development environment thoughtfully will pay dividends in the long run.</p><p>But let’s say you are training a model, water spills on your computer, and your computer shuts down unexpectedly. Weights and Biases help you prepare for these types of situations by allowing users to <em>resume a run</em> if it was not completed. Let’s use an example to demonstrate.</p><p>First things first — you need to set the <em>resume</em> argument in wandb.init() to True:</p><pre>wandb.init(project=”resume-read-group-runs”, name=”resume_runs”, resume=True)</pre><p>Now, let’s say, while training my model I accidentally restarted my Jupyter Notebook instance. After I restarted the kernel, to be able to resume the training from exactly where it was last, I would do the following -</p><pre>model = tf.keras.models.load_model(wandb.restore(“model-best.h5”).name)</pre><p>It is important to note this will only work if you supply the WandbCallback while calling model.fit().</p><p>After loading the model, I simply need to compile it in exactly the same way I did before restarting the kernel and I would call model.fit() then -</p><p>model.compile(loss=&#39;categorical_crossentropy&#39;, optimizer=sgd, metrics=[&#39;accuracy&#39;])</p><p>model.fit(X_train, y_train, validation_data=(X_test, y_test),</p><p>epochs=20, initial_epoch=wandb.run.step,</p><p>callbacks=[WandbCallback(data_type=&quot;image&quot;, labels=labels, save_model=True)])</p><p>Pay attention to the initial_epoch argument. The training will begin from exactly where it was left off.</p><h3>Grouping Runs</h3><p>You might want to group many different runs with respect to one or more configuration variables. This helps to draw comparisons between many different runs within a project or even distributed training. I am going to show a simple example of grouping runs together.</p><p>Go to your project page (the URL should be like <a href="https://app.wandb.ai/sayakpaul/arxiv-project-complex-models">https://app.wandb.ai/sayakpaul/arxiv-project-complex-models</a>) and press “ALT + Space”. It should look like -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jehZ3xvM897zgbFS" /></figure><p>Now, click on <strong>Group</strong> and you will see a list of the available configuration variables -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/285/0*e7lg2MwrUkAc1K8-" /></figure><p>Now, I wish to group the runs with respect to the learning rate which is present as lr. I will select it accordingly and I am done -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_H1L0nctn3EHwA_D" /></figure><p>You can go beyond just one field and select any field you may find necessary to group together the runs for your purpose -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kHqSAgnom1LU4JXu" /></figure><p><strong>Note</strong>: Be sure to turn off your notebook instance after you are done with your work -</p><ol><li>Just go to your Notebook homepage: <a href="https://console.cloud.google.com/ai-platform/notebooks/instances">https://console.cloud.google.com/ai-platform/notebooks/instances</a>.</li><li>Select the running instance that you want to stop.</li><li>Click on <strong>STOP</strong> from the upper panel.</li></ol><h3>What runs will you be grouping?</h3><p>I hope this article gave you a flavor of different useful features offered by Weights and Biases to help you keep track of your deep learning experiments smoothly and systematically. I have made available all the experiments I did for this article <a href="https://github.com/sayakpaul/Resume-Group-Read-Runs-WnB">here</a>. I hope they are useful :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ee52f986498" width="1" height="1" alt=""><hr><p><a href="https://medium.com/six-ways-to-debug-a-machine-learning-model/how-to-use-gcp-with-weights-biases-2ee52f986498">How to Use GCP with Weights &amp; Biases</a> was originally published in <a href="https://medium.com/six-ways-to-debug-a-machine-learning-model">Weights &amp; Biases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tracking the heartbeat of ML models by exploring gradients]]></title>
            <link>https://medium.com/@weights_biases/tracking-the-heartbeat-of-ml-models-by-exploring-gradients-cca852af0f6e?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/cca852af0f6e</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[computational-biology]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Fri, 08 Nov 2019 17:53:39 GMT</pubDate>
            <atom:updated>2019-11-08T17:53:39.138Z</atom:updated>
            <content:encoded><![CDATA[<h4>In-depth Analysis</h4><h3>TL;DR</h3><p>I’m using graph convolutional models to predict protein structure and interactions between different proteins. I use visualizations of gradients to track the heartbeat of my models, make architectural adjustments, and diagnose problems during training.</p><h3>Background</h3><p>My background is in biology, and I’m using machine learning to solve hard problems in genetics. In my undergrad research I used statistical methods to explore the interplay between an organism’s genetic makeup and its environment, and when I got to Stanford I jumped at the chance to deepen my understanding of machine learning. It was challenging to get up to speed with the math, but implementing models from scratch in <a href="https://www.youtube.com/playlist?list=PL3FW7Lu3i5JvHM8ljYj-zLfQRF3EO8sYv">CS 231n</a> and <a href="https://www.youtube.com/watch?v=UzxYlbK2c7E&amp;list=PLA89DCFA6ADACE599">CS 229</a> gave me a strong foundation. I’m now using machine learning techniques every day in <a href="http://www.fordycelab.com/">Polly Fordyce’s lab</a>, working to better define and predict molecular interactions.</p><h3>Research</h3><p>My graduate research specifically focuses on the biophysics of molecular interactions. A fancy way of saying that I predict how tightly proteins stick together in living organisms. Processes governed by the interactions between two or more biological molecules are responsible for an amazing array of different functions. These interactions are:</p><ul><li>what your cells use to determine which genes to turn on when</li><li>how your immune system recognizes whether a substance in your blood is you or a foreign invader</li><li>and increasingly the basis of cutting-edge medical treatments</li></ul><p>To understand how deep learning can apply to comprehending, and ultimately designing, these interactions, we first have to understand a bit more about how proteins are constructed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/273/0*yTBAN2UgTOiwuSYj.gif" /></figure><p>An example of an important intermolecular interaction: an antibody in complex with a short protein sequence from the human rhinovirus (PDB ID: 1A3R)</p><h3>Proteins</h3><p>Proteins are composed of long chains of amino acids, small chemical compounds also referred to as “residues”, strung together like beads on a string. Only 20 of these amino acids comprise the set from which proteins can be constructed. However, despite such a limited alphabet, nature has been able to devise proteins that perform a dizzying array of functions, from binding and regulating other proteins to synthesizing chemicals critical to sustaining life.</p><p>Proteins accomplish these myriad tasks through differences in their three-dimensional structure. The structure, in turn, is ultimately defined by the chemical properties of the amino acids themselves and the order in which they are strung together. For instance, the core of most proteins is usually where we find the hydrophobic (“water-hating”) amino acid residues, while the protein’s surface is more likely to have more hydrophilic (“water-loving”) residues. In a world made of water, it’s generally best for the water-hating amino acids to hide on the inside of the protein. These chemical properties help define the protein’s structure, which determines its function by positioning key functional residues. The functional residues might reside on the protein’s surface, as with many binding proteins, or in its core, as with many enzymes — proteins that catalyze chemical reactions.</p><h3>Connecting protein sequence to 3D structure</h3><p>Now that we know a bit about protein sequence and its connection to protein function by way of structure, it sure seems like it would be nice if we had a model to connect the sequence of a protein’s amino acids to its fully-folded 3D structure. Unfortunately, this is an incredibly challenging task that remains one of the <a href="https://en.wikipedia.org/wiki/Levinthal%27s_paradox">largest open problems</a> in computational biology. Despite recent progress by <a href="https://deepmind.com/blog/article/alphafold">DeepMind</a> and <a href="https://www.biorxiv.org/content/10.1101/265231v1">others</a>, we remain a long way from a generalizable model to perfectly predict a protein’s structure from its sequence alone.</p><p>Although the protein folding problem is far from solved, there are many proxy measures of structure that can still provide useful insights into potential function. Contact maps are one of the most widely used methods to abstract away the important components of a folded protein without having to predict the full structure. Contact maps are simply 2D binary matrices where each row and column represent one amino acid in the protein. If a contact of a certain type (for example a covalent bond or a hydrogen bond) exists between two residues, the value at that point in the matrix is one, otherwise, it is zero. Since these contacts are undirected, contact maps are symmetric about the main diagonal. Contact maps can be significantly easier to predict that complete 3D structures because of the correlation between contacts in local regions and the projection of the problem from three dimensions into two. These maps still retain information relevant to protein function such as the position of potential binding pockets and local structure. Consequently, I have decided to predict multi-channel contact maps from the protein’s sequence alone, with the hope that these contact maps will serve as a useful intermediate when dissecting the strength and mechanism of protein-protein interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SyE2RqrfOBNe-1ZD.png" /><figcaption>An example of a contact map. On the left is the contact map predicted by a deep learning model. The ground truth map is shown on the right.</figcaption></figure><h3>My process</h3><p>One of the most interesting and frustrating parts of my research is having the freedom to play around with novel deep learning architectures. I find it endlessly rewarding to read a paper, implement the paper’s new method in PyTorch, and see the results (good or bad) for the prediction task I’m trying to solve. However, not all new methods are right for my problems, and even the ones that can help significantly often don’t work perfectly on the first try.</p><h3>Recognizing promising directions</h3><p>The toughest part of my job is resisting the temptation to be a glutton for novelty. Shiny object syndrome is real and in a world like academia, where deadlines can be much more of a suggestion than a requirement, it can lead to months spent chasing a new method that offers no improvement for your prediction task. As a result, I’ve learned to be very careful when deciding whether to pursue any new method. I try my best to allow the data structures, and the biological processes that generate them, to help guide my decision whether to change direction or hold the course. Before I implement a single new line of code, I like to ask myself:</p><ul><li>Does the method fit the process that generates the data? — e.g. Binding curves have underlying biochemical intuition that can reduce the number of parameters that need to be fit.</li><li>Does the data structure match the ideal type for a given architecture? — e.g. 2D CNNs for image data/RNNs for sequences.</li><li>Are there logistical challenges associated with using a specific method on my target dataset? — e.g. Can I fit the entire model into GPU memory when working with protein structure data?</li></ul><p>In the case of predicting contact maps for protein-protein interactions, graph convolutional networks (GCNs) meet all three of these requirements. The atoms that make up proteins are connected by sets of bonds and each atom is not bonded to a uniform number of partners. Therefore, a graph better approximates the natural data structure of proteins than a 2D or 3D CNN would. GCNs also offer a significant performance gain over 2D CNNs for the specific problem of contact map prediction. Whereas 2D CNNs would, in effect, be predicting the same value twice in the case of symmetric contact maps, graph convolutions can be designed to predict each contact only once, leading to dramatic improvements in memory efficiency.</p><h3>Overcoming obstacles</h3><p>GCNs represent a relatively new and rapidly evolving area of study in deep learning. As a result, the processes of implementing and using these architectures can be a fair bit harder than for established tasks like using a CNN on image data. I’ve run into a number of interesting and puzzling failure modes, including constant prediction of the mean value, overflow of parameter values producing NaNs, and even complete failure to train. Each failure mode has required its own unique debugging process, but there’s one technique I’ve found to be indispensable across all failure types: visualizing patterns within a model’s gradients.</p><h3>Why gradients?</h3><p>Why might you want to visualize the distribution of the gradients within your model? The answer might not be immediately obvious, given that you are already tracking your target metrics like loss or accuracy. But what do you turn to if you see no improvement in these standard measures of performance? Here I’d like to remind you of the update rule that your optimizer is using every step it takes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/129/0*mQfuTCQSZzG1EHHe.gif" /></figure><p>Where <em>Θ</em> is your parameter, <em>α</em> is your learning rate, and <em>J</em> is the loss function for the current batch or example. Now it may be a bit more obvious why we are interested in tracking gradients as our model trains: the only two values affecting your parameter updates are your learning rate and your gradient. Since the learning rate is usually fixed (though this isn’t always the case for all optimizers), the gradients generally dictate the direction and magnitude of a given update.</p><h4>Gradients vs. parameters</h4><p>Since the gradients are being used to update the parameters, you might ask, “why not just look at the parameters of the model directly?” The answer is that gradients are information-rich and they have the same interpretation no matter where you are in the training process. The gradient will always tell you the direction and “steepness” at your current location in the optimization landscape. If you are near a local optimum, gradients will generally be smaller than if you are far from a local optimum. Moreover, methods like regularization exist to directly control the scale of the parameters, but the scale of the gradients is far harder to directly control as the experimenter.</p><h4>Gradient trends</h4><p>Over time, you should expect all of the gradients to trend toward zero as your model’s parameters approach a set of (locally) optimum values. If you notice the variance of your distribution of gradients trending upward as your model trains, you may want to take steps such as lowering the learning rate or introducing regularization to ensure you do not overstep the optimum.</p><p>As you approach an optimum value for your model’s parameters, you should see the histogram of gradients shrink toward zero at the same time that you see your loss and/or accuracy begin to plateau. If the gradients are shrinking and the accuracy/loss is not where you would expect, that may be an indication that you’ve reached a local optimum and might be trapped. In this case, increasing the learning rate or relaxing regularization constraints might be helpful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LqW2NGk37_NL0NUs.png" /><figcaption>Gradient distributions for two parameter sets of a model showing a (noisy) trend of decreasing magnitude with increased model accuracy/decreased model loss.</figcaption></figure><h4>Gradient scale</h4><p>One final pattern that is often worth examining is the scale of the gradients themselves. Because the gradient is the derivative of the loss function with respect to the parameter, parameters for which a small change would drastically change the loss of an example would be expected to have a large derivative relative to that of an unimportant parameter. Paying attention to the relative scale of different layers of module of your network can tell you a lot about which components might be critical for accurate prediction versus those playing only a minor or supporting role. If you notice a difference of an order of magnitude or more between the gradients flowing to different parts of your model, that may be an indication that a certain module may not be critical, and in some cases may be actively detrimental to network performance.</p><p>I was recently able to use this trick to identify that one of my models was effectively failing to update an embedding layer. Instead, it was simply adapting the network that sat on top of the embeddings to adjust to their random initialization. By focusing more time on creating an informative embedding layer before adding the network on top of it, I’ll likely be able to achieve better results than trying to simultaneously train the network and the embeddings.</p><p>In the example below, you’ll have the chance to play around with a network that contains an unnecessary module that injects random noise. You’ll be able to see for yourself the effect of unimportant components on network performance during training.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L__Q2x2G5zJNcset.png" /><figcaption>Different parameters within the same model showing low magnitude gradients (left) and high magnitude gradients (right).</figcaption></figure><h3>Visualizing gradients</h3><p>Weights &amp; Biases offers a great, easy to use tool to directly track and visualize histograms of your gradients as your model trains. By just including wandb.watch(model, log=’all’) before your training loop, you’ll be able to have W&amp;B display histograms of both your model’s parameters and their gradients at each update step. Hopefully, you’ll be able to use some of the tricks I discussed here to shortcut debugging of your next model!</p><h3>Live example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1m9SNPoqqdw1WGA8.png" /></figure><p>Since most people don’t work on problems related to protein folding, I’ve implemented the following <a href="https://colab.research.google.com/drive/1bsoWY8g0DkxAzVEXRigrdqRZlq44QwmQ">Google Colab Notebook</a> for you to play around with gradient visualizations yourself. Click “Open in playground” in the upper left corner to interact with the model yourself. Try adjusting the learning rate, batch size, momentum, etc. to get a feel for the effect on the spread and magnitude of the gradients for each model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cca852af0f6e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Tags from Arvix: An Intro to NLP and Experiment Tracking]]></title>
            <link>https://medium.com/@weights_biases/generating-tags-from-arvix-an-intro-to-nlp-and-experiment-tracking-e79127604207?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/e79127604207</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[in-depth-analysis]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 18:01:03 GMT</pubDate>
            <atom:updated>2019-11-08T05:41:31.097Z</atom:updated>
            <content:encoded><![CDATA[<h4>In depth analysis</h4><h3>arXiv Search: Generating Tags from Paper Titles with NLP</h3><h3>Inspiration &amp; Ideation</h3><p><a href="https://arxiv.org/">arXiv</a> is the repository to tens of thousands of openly accessible papers in the fields of physics, mathematics, computer science and so on. For machine learning practitioners, researchers, data scientists (and all the other positions pertaining to the fields of machine learning and data science) arXiv is the dosage of research, application, and theoretical know-how.</p><p>The pace at which the field of machine learning is evolving is just unreal. There are new papers getting released every day. It really gets challenging to keep up with this pace. Moreover, there are so many sub-categories in each of the primary arXiv categories. For example, in the Computer Science category (cs) there are sub-categories like <em>cs.LG</em> (Machine Learning), <em>cs.CV</em> (Computer Vision and Pattern Recognition), <em>cs.AI</em> (Artificial Intelligence), <em>cs.CL</em> (Computation and Language) and so on. These sub-categories are also called <em>tags</em>.</p><p>As mentioned above, a huge number of papers get submitted to arXiv on a daily basis. To maintain a smooth and consistent user experience, it is important to accurately categorize the papers. Because of the vastness of the field (machine learning), it can get confusing for an author to decide these categories in the event of submission of a paper. In situations like this, an automatic tag identification can help which would be able to correctly identify the right tags from the title of a paper.</p><p>Being a new entrant to the field of Natural Language Processing (NLP), I took this idea to develop on a cool project around it. In this article, I will be walking you through some of the critical aspects of the projects and how <strong>Weights and Biases</strong> helped me to keep track of my experiments. Let’s get started!</p><p>The source code of the project is available <a href="https://github.com/sayakpaul/Generating-categories-from-arXiv-paper-titles">here</a>.</p><h3>Thinking about the problem statement</h3><p>Formulating a problem statement for a machine learning project is a serious business and it requires a good amount of brainstorming. I am not going to get into its details but if you are interested, be sure to check out this crash course on <a href="https://developers.google.com/machine-learning/problem-framing">Problem Framing</a> by Google. To get started with the project, I needed to start with a definite problem statement. It’s safe enough to say that data plays a very crucial role in that. So, I first started to look for datasets that capture solid information on arXiv papers and luckily, I found <a href="https://www.kaggle.com/neelshah18/arxivdataset">one</a> on Kaggle containing a bunch of information on arXiv papers from 1992 to 2017.</p><p>After quickly glaring through the dataset, I could frame a minimal problem statement -</p><blockquote><em>Given the title of an arXiv paper can we generate its tag(s)?</em></blockquote><p>Of course, I first saw what features the above-mentioned dataset contains and among them the following two features helped to frame the problem statement I just mentioned:</p><ul><li>Title of the paper</li><li>Tag of the paper</li></ul><p>A paper can have multiple tags. For example, the seminal paper on Transformers namely <a href="https://arxiv.org/abs/1706.03762">Attention is All You Need</a> has two tags: <em>cs.CL</em> and <em>cs.LG</em>. So keeping this aspect in mind, our problem statement could be modeled as a <em>multi-label text classification problem</em>.</p><p>There were other features as well (in total there were 9):</p><ul><li>Paper ID</li><li>Date of submission</li><li>Day</li><li>Month</li><li>Year</li><li>Link of the paper</li><li>Abstract of the paper</li><li>Name of the author(s)</li></ul><h3>Preparing the Dataset</h3><p>The dataset comes in a <strong>JSON</strong> format. When I loaded it in using <strong>pandas </strong>it looked something like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zGna2IUnOWfDTxd-.png" /></figure><p>As you can see if I wanted to get any insights from the dataset, this format won’t really help. After a few efforts to wrangle this, I could get the dataset down to the following form:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/0*AdG0yvxd6gzqqkYl.png" /></figure><p>Just like the way it’s needed for our problem statement!</p><p>After exploring further, I learned that there is a total of 41,000 paper titles and 2,606 unique tags (some of them are single and some are multi) present in the wrangled dataset. When I start with a project, I prefer to start simple, so I chose to keep the dataset to the top 100 tags. After filtering the results, I arrived at the following distribution of the top 10 tags:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/0*X1Hmb-Xe4AwysjNF.png" /></figure><p>As you can see — this is a clear sight of <em>class imbalance</em> (more on this later). It is important to note that an unexpected aspect of the project also the issue of duplicate entries I had to deal with.</p><p>After I learned about the types of papers, I was interested in learning if <em>the length of a paper’s title had any impact in determining its tags</em>; Pearson’s correlation, of course, was <em>zero</em>. Before we proceed to the next section, I also want to show you the following plot which shows the distribution of the title lengths (isn’t that a sleek distribution?):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*KqGu0fGVqWl1BCjq.png" /></figure><h3>Addressing the major data issues</h3><p>First, the filtered dataset was highly imbalanced. I tackled this in the following way:</p><ul><li>I first derived the weights (the number of instances a particular label(s) is associated with) of the classes.</li><li>Then I used those weights while I trained the models. This enables one to weigh minority classes higher than the majority classes.</li></ul><p>The next issue occurred when I tried to binarize to labels. Take a look at the first ten labels:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/0*t1ZuexG31xaSt0gl.png" /></figure><p>Pay close attention to the <em>double-quotes</em>. For these, whenever I was trying to use the <strong>MultiLabelBinarizer </strong>class of <strong>scikit-learn </strong>it was not happening in the proper way. It actually took me some time to realize that and finally, I came across <a href="https://stackoverflow.com/questions/29552950/when-to-use-ast-literal-eval">this thread on StackOverflow</a> which helped me to solve this issue (spoiler: I had to use <strong>literal_eval</strong>). After I got past this issue, I was able to properly represent the tags in terms of 0 and 1 (below are the multi-binarized version of the first ten labels):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/0*LHQOKwGvAi3scU3a.png" /></figure><p>For the paper titles, I used standard data preprocessing steps:</p><ul><li>Representation of the titles in all lower case</li><li>Removal special characters/whitespaces</li><li>Tokenization</li><li>Removal of stopwords</li></ul><p>At this point, I was ready to do some machine learning.</p><h3>Experimentation with machine learning models: Simple to complex</h3><p>In the case of<strong> </strong>my machine learning experiments, I also like to start off simple and then gradually ramp up the complexity. This allows me to analyze the behavior of individual models and how their prediction dynamics are varying. This approach also helps with my choice about the architecture of a model, which depends on a number of different aspects like:</p><ul><li>Model training time</li><li>Model’s performance on the validation set</li><li>Inference speed</li><li>Size of the model</li></ul><p>As some of you may already know, picking the best model architecture also requires a high amount of experimentation. The challenge is that you may miss out on a good model if you do not keep track of your experiments properly. I delegate this responsibility to <strong>Weights and Biases</strong>. It plays well with a number of popular Python machine learning frameworks like TensorFlow, PyTorch, Scikit-Learn, XGBoost, and so on. Moreover, it requires only a few lines of code to set things up so that Weight and Biases can get started in tracking your experiments.</p><p>For this project, I started with simple models like <em>Naive Bayes</em>, <em>Logistic Regression</em> and so on. I used the ever-trusty Scikit-Learn for that. You can see the two most important charts from those experiments <a href="https://app.wandb.ai/sayakpaul/arxiv-project-simple-models">here</a>. You can see them in the following figure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*fC9tWkof6sAEkNqd.png" /></figure><p>Weights and Biases also provided me with a comprehensive report which makes it easy to share my findings across teams:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ugLT4xb-CKaniu5f.png" /></figure><p>As you can see the model from the <em>fourth run </em>yielded the best performance here. Now was the perfect time to bring some deep learning to the table. I tried the following three architectures with <em>trainable</em> embeddings:</p><ul><li>CNN-based</li><li>GRU-based</li><li>Bidirectional LSTM-based</li></ul><p>You can find a <a href="https://app.wandb.ai/sayakpaul/arxiv-project-complex-models">summary of the experiments</a> I conducted with them in the below charts:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/0*xPHkV3ehVGq9IZiT.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/0*kscZeRHfpJ1sDlgc.png" /></figure><p>As usual, it came with a table too:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jdzzHOhFKxXzSW4T.png" /></figure><p>The visualizations make it easier for me to compare different models and pick the best one. This is particularly helpful when the number of experiments keeps increasing, which almost always happens in a real-world scenario.</p><p>After finding out the most performant model (CNN) from the set of experiments, I used it to make predictions on some recent paper titles. Here is a snap:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/0*3ZQHndv7wXtvQCM-.png" /></figure><p>Not bad!</p><p>Weights and Biases gives you the flexibility to log many other information you might want to add to your dashboard. For this case, I wanted to see how a model is doing on some sample validation data as it is training and I wanted to log that in a nice format on my Weight and Biases dashboard. I was able to do so by writing a few lines of code:</p><pre><em># A custom callback to view predictions on the above samples in real-time</em></pre><pre><strong>class</strong> <strong>TextLogger</strong>(tf.keras.callbacks.Callback):</pre><pre><strong>def</strong> __init__(self):</pre><pre>super(TextLogger, self).__init__()</pre><pre><strong>def</strong> on_epoch_end(self, logs, epoch):</pre><pre>samples = []</pre><pre><strong>for</strong> (title, true_label) <strong>in</strong> sample_paper_titles.items():</pre><pre>predicted_label = generate_predictions(self.model, title)</pre><pre>sample = [title, predicted_label, true_label]</pre><pre>samples.append(sample)</pre><pre>wandb.log({“text”: wandb.Table(data=samples,</pre><pre>columns=[“Text”, “Predicted Label”, “True Label”])})</pre><p>I really liked what I could achieve with the above chunk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JWYQAIXxD-ufd9Jw.png" /></figure><p>As you can see, I am able to change the step number and see how my model’s prediction is getting varied on the provided samples. You can check out <a href="https://app.wandb.ai/sayakpaul/text-prediction-logger/runs/eendlfxo">this run page</a> to see the predictions from different steps. This is very valuable to have in your practical deep learning toolbox.</p><p>The GRU and LSTM-based models were taking a significant amount of time for training (not days, though). So, I decided to run them using <em>Cloud TPUs </em>and I was kind of blown away by the speedup. You can find the corresponding notebook <a href="https://github.com/sayakpaul/Generating-categories-from-arXiv-paper-titles/blob/master/TPU_Experimentation.ipynb">here</a>.</p><h3>Further undertakings</h3><p>Among the deep learning models I tried, I am sure that I did not train them hard enough. I am definitely going to train the CNN-based model and the LSTM-based model for larger epochs (the current number of epochs is 10). There are a bunch of other hyperparameters I did not experiment with — <em>embedding dimension</em>, <em>maximum words to be allowed in the tokenizer</em>, <em>maximum length of a sequence</em> and so on. To that end, I would also want to incorporate the paper abstracts now in the dataset to see if the predictions are improving. Of course, this is gonna come at a cost — increased model complexity, increased computation cost and so on.</p><p><a href="https://docs.wandb.com/library/sweeps">Hyperparameter sweeps</a> make it a whole lot easier to properly manage the heavy load of hyperparameter tuning experiments. I am definitely going to use it in the next iteration of this project.</p><p>I am also excited to try out <a href="https://huggingface.co/">Hugging Face</a>’s <a href="https://huggingface.co/transformers/model_doc/bert.html">BERT models</a> for improving the classification performance. My ultimate plan is to expose the final model as a REST API so that it can be used by other developers.</p><h3>References and acknowledgments</h3><p>Following are some of the references which helped me a lot in reaching this stage of the project:</p><ul><li><a href="https://towardsdatascience.com/deep-transfer-learning-for-natural-language-processing-text-classification-with-universal-1a2c69e5baa9">Deep Transfer Learning for Natural Language Processing — Text Classification with Universal Embeddings</a></li><li><a href="https://www.wandb.com/tutorials">This awesome set of tutorials by Weights and Biases</a></li><li><a href="https://www.kaggle.com/roccoli/multi-label-classification-with-keras">Multi-label classification with keras</a></li></ul><p>I would also like to thank the ones who provided me with tremendous support:</p><ul><li><strong>Lavanya</strong>, <strong>Stacey</strong>, and <strong>Chelsea</strong> from Weights and Biases team who carefully reviewed this article and also the project.</li><li>The entire <a href="https://developers.google.com/programs/experts/">GDE team</a> at Google for providing me with GCP credits as part of the GDE program.</li><li><a href="http://g.co/tfrc">TensorFlow Research Cloud</a> program for providing me with access to Cloud TPUs which indeed accelerated the execution of this project.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e79127604207" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Deep Learning Hyperparameters with Random Forests]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/exploring-deep-learning-hyperparameters-with-random-forests-c3161689fb7a?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3161689fb7a</guid>
            <category><![CDATA[random-forest]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[kaggle]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Tue, 05 Nov 2019 19:37:44 GMT</pubDate>
            <atom:updated>2019-11-05T19:40:25.219Z</atom:updated>
            <content:encoded><![CDATA[<p>My colleague Lavanya ran a large hyperparameter sweep on a Kaggle simpsons dataset in colab <a href="https://colab.research.google.com/drive/181GCGp36_75C2zm7WLxr9U2QjMXXoibt">here</a>. She ran a large search with the intention of finding the best model for the data. In the process of running the sweep she created a lot of hyperparameter data, and I was wondering if I could find useful insights in it.</p><p>Here’s a parallel co-ordinates plot visualizing the results of the hyperparameter search. As you can see she tried a lot of different values for epochs, learning rate, weight decay, optimizers and batch size. In this plot we can see how they map to validation accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6-wziyyg5TQwOqxU.png" /></figure><p>Doing hyperparameter searches like these is expensive and there’s never time to test every possible combination of inputs, so most people want to find general purpose insights to guide their search. One problem with looking for insights is that hyperparameter searches tend to be messy — the inputs are correlated and there are lots of complicated interactions between them. I was talking to Jeremy Howard at <a href="http://fast.ai/">fast.ai</a> and he mentioned how he uses random forest feature importance to explore hyperparameters, which turned out to be really useful on this dataset.</p><p>The techniques here are less useful for drawing hard conclusions and more useful as a guide for which hyperparameter values to explore next. All of this analysis could be done on the results of any hyperparameter sweep.</p><p>You can find the full code to reproduce this analysis <a href="http://colab.research.google.com/drive/1QLTgkaTz327df24RqSTi4yd7-ONrhmYh">here</a>.</p><h3>Load the Sweep results</h3><p>First we need to load the sweep results from the wandb API. Lavanya’s sweep results are public at <a href="https://app.wandb.ai/sweep/simpsons">https://app.wandb.ai/sweep/simpsons</a> and we can copy all of the data into pandas dataframes.</p><p>Our dataframes are:</p><ol><li>config_df — dataframe of hyperparameters (such as optimizer, learning rate)</li><li>summary_df — dataframe of output metrics (such as val_loss, val_acc)</li><li>name_df — list of names of individual runs</li></ol><h3>Data Pre-Processing</h3><p>Next, we use the scikit-learn random forest algorithm. It doesn’t accept categorical variables and it doesn’t handle NaNs. This is a real world data set and as such some of the hyperparameter values are missing.</p><p>We preprocess our data by turning NaNs in hyperparameters into the average for the column, which is probably fine for preliminary exploration. We turn categorical hyperparameters into dummy variables where each value has its own column.</p><pre><em># Remove cases where target is NaN</em></pre><pre>hyperparams = hyperparams[target.notnull()]</pre><pre>target = target[target.notnull()]</pre><pre><em># convert categorical columns into dummy variables</em></pre><pre><em># ie a column with “sgd”, “rmsprop” and “adam” will become</em></pre><pre><em># three separate binary columns</em></pre><pre>hyperparams_categorical = pd.get_dummies(hyperparams)</pre><h3>Plot Correlations</h3><p>Now we can look at the individual correlation between each of our input hyperparameters and our output variable. This gives a quick look at what values are independently correlated with higher accuracy and what values a negatively correlated with higher accuracy.</p><pre><em># correlations of hyperparams to target</em></pre><pre>corr_list = hyperparams_categorical.corrwith(target)</pre><pre>corr_list</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-EhxZQeQoRJyL9lf.png" /></figure><h3>Linear Regression</h3><p>Next up we build a linear model and check which parameters it uses. The coefficients of the linear regression are different from the correlation values for two reasons.</p><ol><li>The coefficients are dependent on the absolute magnitude of the inputs, so input values with a small range will have a smaller coefficient.</li><li>The coefficients are dependent on each other. So for example the Adam optimizer is independently slightly correlated with higher accuracy, but when all of the other inputs are considered in a linear model it has a small negative effect on accuracy.</li></ol><p>The P&gt;|t| value will give a sense of how meaningful the hyperparameter is for predicting loss in our linear model. A low P&gt;|t| gives us confidence that the hyperparameter is directly correlated with validation accuracy given the other variables. In this dataset rmsprop seems to be generally having a negative effect, while higher values of batch size and weight decay have a positive effect.</p><pre>import statsmodels.api as sm</pre><pre>est = sm.OLS(target, hyperparams_categorical)</pre><pre>est.fit().summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ylAluvHQFqd8xz1z.png" /></figure><h3>Build the Random Forest</h3><p>The biggest problem with the linear models is that they don’t account for interactions between the hyperparameters and we know that hyperparameters can have quite a lot of interaction with each other. A tree model will give us a feature importance metric on how much the given feature (hyperparameter) is used to predict the validation accuracy.</p><p>We will use scikit learn’s ExtraTreesRegressor where the input is our hyperparameters and the output is our validation accuracy. The ExtraTreesRegressor is a random forest algorithm that decides how many trees to build and how large to make the trees. Trees are nice for this case because they are scale invariant. This means we can more safely use this approach on many different types of hyperparameters at once.</p><pre>from sklearn.ensemble import ExtraTreesRegressor</pre><pre>forest = ExtraTreesRegressor(n_estimators=250,</pre><pre>random_state=0)</pre><pre>forest.fit(hyperparams_categorical, target)</pre><pre>importances = forest.feature_importances_</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aHfJPO1Hh6AoSiXj9y5m6Q.png" /></figure><h3>Conclusions</h3><p>We can see that learning rate had the highest importance, but did lot have a low P value in our regression model. This means that it has a complicated interaction with the other hyperparameters we used. We can probably conclude that elu vs relu had limited importance across the range of parameters that we tried. Using weight decay was generally correlated with good outcomes.</p><p>I encourage you to run a hyperparameter sweep on your own dataset then use this analysis as a guide to find which hyperparameter values to explore next.</p><p>Good luck!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3161689fb7a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/six-ways-to-debug-a-machine-learning-model/exploring-deep-learning-hyperparameters-with-random-forests-c3161689fb7a">Exploring Deep Learning Hyperparameters with Random Forests</a> was originally published in <a href="https://medium.com/six-ways-to-debug-a-machine-learning-model">Weights &amp; Biases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Model Best Practices]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/machine-learning-model-best-practices-3f90b657e944?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f90b657e944</guid>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[keras]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning-models]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 19:58:13 GMT</pubDate>
            <atom:updated>2019-10-22T19:58:13.249Z</atom:updated>
            <content:encoded><![CDATA[<p>The number of shiny models out there can be overwhelming, which means a lot of times people fallback on a few they trust the most, and use them on all new problems. This can lead to sub-optimal results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*z8HDXUWRepB49Ld6WCTLIQ.png" /></figure><p>Today we’re going to learn how to quickly and efficiently narrow down the space of available models to find those that are most likely to perform best on your problem type. We’ll also see how we can keep track of our models’ performances using Weights and Biases and compare them.</p><h3>What We’ll Cover</h3><ul><li>Model selection in competitive data science vs real world</li><li>A Royal Rumble of Models</li><li>Comparing Models</li></ul><p>Let’s get started!</p><p>Unlike Lord of the Rings, in machine learning there is no one ring (model) to rule them all. Different classes of models are good at modeling the underlying patterns of different types of datasets. For instance, decision trees work well in cases where your data has a complex shape:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kfKMWLz_3Cu0_ndC.png" /></figure><p>Whereas linear models work best where the dataset is linearly separable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XkgwkjW8sCEdtt3G.png" /></figure><p>Before we begin, let’s dive a little deeper into the disparity between model selection in the real world vs for competitive data science.</p><h3>Model selection in competitive data science vs real world</h3><p>As William Vorhies said in his <a href="https://www.datasciencecentral.com/profiles/blogs/want-to-win-at-kaggle-pay-attention-to-your-ensembles">blog post</a> “The Kaggle competitions are like formula racing for data science. Winners edge out competitors at the fourth decimal place and like Formula 1 race cars, not many of us would mistake them for daily drivers. The amount of time devoted and the sometimes extreme techniques wouldn’t be appropriate in a data science production environment.”</p><p>Kaggle models are indeed like racing cars, they’re not built for everyday use. Real world production models are more like a Lexus — reliable but not flashy.</p><p>Kaggle competitions and the real world optimize for very different things, with some key differences being:</p><h3>Problem Definition</h3><p>The real world allows you to define your problem and choose the metric that encapsulates the success of your model. This allows you to optimize for a more complex utility function than just a singular metric, where Kaggle competitions come with a single pre-defined metric and don’t let you define the problem efficiently.</p><h3>Metrics</h3><p>In the real world we care about inference and training speeds, resource and deployment constraints and other performance metrics, whereas in Kaggle competitions the only thing we care about is the one evaluation metric. Imagine we have a model with 0.98 accuracy that is very resource and time intensive, and another with 0.95 accuracy that is much faster and less compute intensive. In the real world, for a lot of domains we might prefer the 0.95 accuracy model because maybe we care more about the time to inference. In Kaggle competitions, it doesn’t matter how long it takes to train the model or how many GPUs it requires, higher accuracy is always better.</p><h3>Interpretability</h3><p>Similarly in the real world, we prefer simpler models that are easier to explain to stakeholders, whereas in Kaggle we pay no heed to model complexity. Model interpretability is important because it allows to take concrete actions to solve the underlying problem. For example, in the real world looking at our model and being able to see a correlation between a feature (e.g. potholes on a street), and the problem (e.g. likelihood of car accident on the street), is more helpful than increasing the prediction accuracy by 0.005%.</p><h3>Data Quality</h3><p>Finally in Kaggle competitions, our dataset is collected and wrangled for us. Anyone who’s done data science knows that is almost never the case in real life. But being able to collect and structure our data also gives us more control over the data science process.</p><h3>Incentives</h3><p>All this incentivizes a massive amount of time spent tuning our hyperparameters to extract the last drops of performance from our model, and at times convoluted feature engineer methodologies. While Kaggle competitions are an excellent way to learn data science and feature engineering, they don’t address real world concerns like model explainability, problem definition, or deployment constraints.</p><h3>A Royal Rumble of Models</h3><p>It’s time to start selecting models!</p><p>When picking our initial set of models to test, we want to be mindful of a few things:</p><h3>Pick a diverse set of initial models</h3><p>Different classes of models are good at modeling different kinds of underlying patterns in data. So a good first step is to quickly test out a few different classes of models to know which ones capture the underlying structure of your dataset most efficiently! Within the realm of our problem type (regression, classification, clustering) we want to try a mixture of tree based, instance based, and kernel based models. Pick a model from each class to test out. We’ll talk more about the different model types in the ‘models to try’ section below.</p><h3>Try a few different parameters for each model</h3><p>While we don’t want to spend too much time finding the optimal set of hyper-parameters, we do want to try a few different combinations of hyper-parameters to allow each model class to have the chance to perform well.</p><h3>Choose the strongest contenders</h3><p>We can use the best performing models from this stage to give us intuition around which class of models we want to further dive into. Your Weights and Biases dashboard will guide you to the class of models that performed best for your problem.</p><h3>Dive deeper into models in the best performing model classes.</h3><p>Next we select more models belonging to the best performing classes of models we shortlisted above! For example if linear regression seemed to work best, it might be a good idea to try lasso or ridge regression as well.</p><h3>Explore the hyper-parameter space in more detail.</h3><p>At this stage, I’d encourage you to spend some time tuning the hyper-parameters for your candidate models. (The next post in this series will dive deeper into the intuition around selecting the best hyper-parameters for your models.) At the end of this stage you should have the best performing versions of all your strongest models.</p><h3>Making the final selection — Kaggle</h3><h4>Pick final submissions from diverse models.</h4><p>Ideally we want to select the best models from more than one class of models. This is because if you make your selections from just one class of models and it happens to be the wrong one, all your submissions will perform poorly. Kaggle competitions usually allow you to pick more than one entry for your final submission. I’d recommend choosing predictions made by your strongest models from different classes to build some redundancy into your submissions.</p><h4>The leaderboard is not your friend, your cross-validation scores are.</h4><p>The most important thing to remember is that the public leaderboard is not your friend. Picking you models solely based on your public leaderboard scores will lead to overfitting the training dataset. And when the private leaderboard is revealed after the competition ends, sometimes you might see your rank dropping a lot. You can avoid this little pitfall by using cross-validation when training your models. Then pick the models with the best cross-validation scores, instead of the best leaderboard scores. By doing this you counter overfitting by measuring your model’s performance against multiple validation sets instead of just the one subset of test data used by the public leaderboard.</p><h3>Making the final selection — Real world</h3><h4>Resource constraints</h4><p>Different models hog different types of resources and knowing whether you’re deploying the models on a IoT/mobile device with a small hard drive and processor or a in cloud can be crucial in picking the right model.</p><h4>Training time vs Prediction time vs Accuracy</h4><p>Knowing what metric(s) you’re optimizing for is also crucial for picking the right model. For instance self driving cars need blazing fast prediction times, whereas fraud detection systems need to quickly update their models to stay up to date with the latest phishing attacks. For other cases like medical diagnosis, we care about the accuracy (or area under the ROC curve) much more than the training times.</p><h4>Complexity vs Explainability Tradeoff</h4><p>More complex models can use orders of magnitude more features to train and make predictions, require more compute but if trained correctly can capture really interesting patterns in the dataset. This also makes them convoluted and harder to explain though. Knowing how important it is to easily to explain the model to stakeholders vs capturing some really interesting trends while giving up explainability is key to picking a model.</p><h4>Scalability</h4><p>Knowing how fast and how big your model needs to scale can help you narrow down your choices appropriately.</p><h4>Size of training data</h4><p>For really large datasets or those with many features, neural networks or boosted trees might be an excellent choice. Whereas smaller datasets might be better served by logistic regression, Naive Bayes, or KNNs.</p><h4>Number of parameters</h4><p>Models with a lot of parameters give you lots of flexibility to extract really great performance. However there maybe cases where you don’t have the time required to, for instance, train a neural network’s parameters from scratch. A model that works well out of the box would be the way to go in this case!</p><h3>Comparing Models</h3><p>Weights and Biases lets you track and compare the performance of you models with one line of code.</p><p>Once you have selected the models you’d like to try, train them and simply add <em>wandb.log({‘score’: cv_score})</em> to log your model state. Once you’re done training, you can compare your model performances in one easy dashboard!</p><p>I encourage you to fork this <a href="https://www.kaggle.com/lavanyashukla01/picking-the-best-model-a-whirlwind-tour-of-model">kernel</a> and play with the code!</p><pre># WandB</pre><pre>import wandb</pre><pre>import tensorflow.keras</pre><pre>from wandb.keras import WandbCallback</pre><pre>from sklearn.model_selection import cross_val_score</pre><pre># Import models (Step 1: add your models here)</pre><pre>from sklearn import svm</pre><pre><strong>from</strong> sklearn.linear_model <strong>import</strong> Ridge, RidgeCV</pre><pre><strong>from</strong> xgboost <strong>import</strong> XGBRegressor</pre><pre># Model 1</pre><pre># Initialize wandb run</pre><pre># You can change your project name here. For more config options, see <a href="https://docs.wandb.com/docs/init.html">https://docs.wandb.com/docs/init.html</a></pre><pre>wandb.init(anonymous=’allow’, project=”pick-a-model”)</pre><pre># Initialize model (Step 2: add your classifier here)</pre><pre>clf = svm.SVR(C= 20, epsilon= 0.008, gamma=0.0003)</pre><pre># Get CV scores</pre><pre>cv_scores = cross_val_score(clf, X_train, train_labels, cv=5)</pre><pre># Log scores</pre><pre>for cv_score in cv_scores:</pre><pre>wandb.log({‘score’: cv_score})</pre><pre># Model 2</pre><pre># Initialize wandb run</pre><pre># You can change your project name here. For more config options, see <a href="https://docs.wandb.com/docs/init.html">https://docs.wandb.com/docs/init.html</a></pre><pre>wandb.init(anonymous=’allow’, project=”pick-a-model”)</pre><pre># Initialize model (Step 2: add your classifier here)</pre><pre>clf = XGBRegressor(learning_rate<strong>=</strong>0.01,</pre><pre>n_estimators<strong>=</strong>6000,</pre><pre>max_depth<strong>=</strong>4,</pre><pre>min_child_weight<strong>=</strong>0,</pre><pre>gamma<strong>=</strong>0.6,</pre><pre>subsample<strong>=</strong>0.7,</pre><pre>colsample_bytree<strong>=</strong>0.7,</pre><pre>objective<strong>=</strong>’reg:linear’,</pre><pre>nthread<strong>=-</strong>1,</pre><pre>scale_pos_weight<strong>=</strong>1,</pre><pre>seed<strong>=</strong>27,</pre><pre>reg_alpha<strong>=</strong>0.00006,</pre><pre>random_state<strong>=</strong>42)</pre><pre># Get CV scores</pre><pre>cv_scores = cross_val_score(clf, X_train, train_labels, cv=5)</pre><pre># Log scores</pre><pre>for cv_score in cv_scores:</pre><pre>wandb.log({‘score’: cv_score})</pre><pre># Model 3</pre><pre># Initialize wandb run</pre><pre># You can change your project name here. For more config options, see <a href="https://docs.wandb.com/docs/init.html">https://docs.wandb.com/docs/init.html</a></pre><pre>wandb.init(anonymous=’allow’, project=”pick-a-model”)</pre><pre># Initialize model (Step 2: add your classifier here)</pre><pre>ridge_alphas <strong>=</strong> [1e-15, 1e-10, 1e-8, 9e-4, 7e-4, 5e-4, 3e-4, 1e-4, 1e-3, 5e-2, 1e-2, 0.1, 0.3, 1, 3, 5, 10, 15, 18, 20, 30, 50, 75, 100]</pre><pre>clf = Ridge(alphas=ridge_alphas)</pre><pre># Get CV scores</pre><pre>cv_scores = cross_val_score(clf, X_train, train_labels, cv=5)</pre><pre># Log scores</pre><pre>for cv_score in cv_scores:</pre><pre>wandb.log({‘score’: cv_score})</pre><p>That’s it now you have all the tools you need to pick the right models for your problem!</p><p>Model selection and can be very complicated, but I hope this guide sheds some light and gives you a good framework for picking models.</p><p>In <a href="https://www.wandb.com/articles/tour-of-machine-learning-models">part II</a> we’ll dive deeper into the different models you can train and when you should use them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f90b657e944" width="1" height="1" alt=""><hr><p><a href="https://medium.com/six-ways-to-debug-a-machine-learning-model/machine-learning-model-best-practices-3f90b657e944">Machine Learning Model Best Practices</a> was originally published in <a href="https://medium.com/six-ways-to-debug-a-machine-learning-model">Weights &amp; Biases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hyperparameter Optimization using sweeps with W&B]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/hyperparameter-optimization-using-sweeps-with-w-b-1e9d94dda46?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e9d94dda46</guid>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 19:53:02 GMT</pubDate>
            <atom:updated>2019-10-22T21:16:39.155Z</atom:updated>
            <content:encoded><![CDATA[<p>Hyperparameters play a crucial role in determining a machine learning model’s performance. In this post we’ll talk about searching through the hyperparameter space and finding the optimal model using <a href="https://docs.wandb.com/library/sweeps">sweeps</a> from Weights &amp; Biases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c8O8j-fo4qf_6MZP88JDbQ.jpeg" /></figure><p>Some people use parameters and hyperparameters interchangeably. Before we get started, it’s important that we explicitly call out the difference between the two:</p><ul><li>Parameters are not explicitly specified by a developer. Instead they are approximated and learned by a machine learning model. Weights and biases are the most granular parameters when it comes to neural networks.</li><li>Hyperparameters are explicitly specified by a developer. In a neural network, examples of hyperparameters include the number of epochs, batch size, number of layers, number of nodes in each layer, and so on.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R4CGmmiHyp92HTNm.png" /><figcaption>Parallel Coordinates Plot Visualizing the Performance of Multiple Runs Over a Set Number of Hyperparameters</figcaption></figure><p>Most of a machine learning model’s performance is driven by hyperparameters. For example with a large dataset, if you train your neural network with a small number of epochs, it is very likely to <em>underfit</em> the data. So you might begin to ask yourself questions like:</p><ul><li>What should the ideal number of epochs be?</li><li>What batch size should I use?</li><li>How many layers should there be in the network?</li><li>How many nodes should be in one layer?</li></ul><p>All of these questions collectively lead us to: what model architecture should be used for the given dataset?</p><p>Google researchers address this in their seminal work on <a href="https://ai.google/research/pubs/pub45826">Neural Architecture Search</a> (NAS), but one challenge stands out: NAS does not scale well. NAS is computationally expensive, and many organizations do not have the bandwidth to support it.</p><p>However, there are ways to work around this:</p><ul><li>Specify the number of epochs that is close enough to the ideal one.</li><li>Train multiple neural networks with a varying number of epochs and then come to a conclusion</li></ul><p>The first takes quite a bit of deliberate practice and may not always produce the expected or even accurate result. That is why the latter is heavily used today. In machine learning literature, the process of experimenting with different hyperparameter values to select the best model is referred to as hyperparameter tuning. The following are very popular methods for hyperparameter tuning:</p><ul><li>Grid search</li><li>Random search</li><li>Bayesian optimization</li><li>Hyperband</li></ul><p>This brings us to Hyperparameter Sweeps — a way to efficiently select the right model for a given dataset using <a href="https://www.wandb.com/">Weights &amp; Biases</a> (<strong>wandb</strong>).</p><h3>What are Hyperparameter Sweeps?</h3><p>Hyperparameter Sweeps offer efficient ways of automatically finding the best possible combination of hyperparameter values for your machine learning model with respect to a particular dataset.</p><p>Conducting hyperparameter search is not a trivial task since not all hyperparameters in a machine learning model have an equal priority when it comes to tuning them. <a href="http://josh-tobin.com/">Josh Tobin</a>, in his <a href="http://josh-tobin.com/assets/pdf/troubleshooting-deep-neural-networks-01-19.pdf">Troubleshooting Deep Neural Networks</a> presentation, has beautifully listed the hyperparameters in a typical neural network along with their priorities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/0*urZ2wfMFALKD9zW_.png" /><figcaption>Typical Hyperparameters in Neural Network Architecture — <a href="http://josh-tobin.com/assets/pdf/troubleshooting-deep-neural-networks-01-19.pdf"><strong>Source</strong></a></figcaption></figure><p>Hyperparameter Sweeps organize search in a very elegant way, allowing us to:</p><ul><li>Set up hyperparameter searches using <a href="https://blog.floydhub.com/training-neural-nets-a-hackers-perspective/#introduction-to-declarative-configuration">declarative configurations</a></li><li>Experiment with a variety of hyperparameter tuning methods including grid search, random search, Bayesian optimization, and <a href="https://arxiv.org/abs/1603.06560">Hyperband</a></li></ul><h3>Running Hyperparameter Sweeps using Weights &amp; Biases</h3><p>Weights &amp; Biases makes it really easy to run Hyperparameter Sweeps. To start, you need a model training script (more on that shortly) and a dataset. You can use this <a href="https://colab.research.google.com/github/sayakpaul/TF-2.0-Hacks/blob/master/Hyperparameter%20Sweeps%20with%20TF%202.0%20%26%20W%26B/Hyperparameter%20Sweeps%20(part%20I)%20with%20TF%202.0%20and%20W%26B.ipynb">Colab notebook</a> if you want to follow along without working in the code directly. If you want to take a more active role set up <strong>wandb</strong>. If you have not, be sure to check <a href="https://docs.wandb.com/getting-started">this</a> out. We will also use <a href="https://www.tensorflow.org/guide/effective_tf2">TensorFlow 2.0</a>, specifically its high-level <a href="https://www.tensorflow.org/guide/keras">Keras</a> API.</p><p>To start, let’s load up the <a href="https://github.com/zalandoresearch/fashion-mnist">FashionMNIST</a> dataset that ships with <strong>Keras</strong>.</p><pre><em># Load the dataset</em></pre><pre>fashion_mnist = tf.keras.datasets.fashion_mnist</pre><pre>(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()</pre><pre># Scale the pixel values of the images</pre><pre>train_images = train_images / 255.0</pre><pre>test_images = test_images / 255.0</pre><pre># Select the hyperparameters you want to tune. This is specified like the following:</pre><pre>sweep_config = {</pre><pre>‘method’: ‘grid’,</pre><pre>‘parameters’: {</pre><pre>‘layers’: {</pre><pre>‘values’: [32, 64, 96, 128, 256]</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Where <strong>method</strong> is the hyperparameter tuning method we are going for and <strong>parameters </strong>is a dictionary containing the hyperparameters we want to tune.</p><pre># Next, we initialize this sweep by running:</pre><pre>sweep_id = wandb.sweep(sweep_config)</pre><p>When you run this, you should get a link to the sweep which you can view in the browser and use to track your sweep runs.</p><p>Once you have initialized the sweep you need an agent. An agent is a model training script you can use to pair the sweep configurations. Let’s define a simple training script:</p><pre>def train():</pre><pre><em># Initialize wandb with a sample project name</em></pre><pre>wandb.init(project=”hyperparameter-sweeps-partI”)</pre><pre>(X_train, y_train) = train_images, train_labels</pre><pre>(X_test, y_test) = test_images, test_labels</pre><pre><em># Specify the hyperparameter to be tuned along with</em></pre><pre><em># an initial value</em></pre><pre>configs = {</pre><pre>‘layers’: 128</pre><pre>}</pre><pre><em># Specify the other hyperparameters to the configuration</em></pre><pre>config = wandb.config</pre><pre>config.epochs = 5</pre><pre><em># Add the config item (layers) to wandb</em></pre><pre>if wandb.run:</pre><pre>wandb.config.update({k: v for k, v in configs.items() if k not in dict(wandb.config.user_items())})</pre><pre>configs = dict(wandb.config.user_items())</pre><pre><em># Define the model</em></pre><pre>model = tf.keras.Sequential([</pre><pre>tf.keras.layers.Flatten(input_shape=(28, 28)),</pre><pre>tf.keras.layers.Dense(wandb.config.layers, activation=tf.nn.relu),</pre><pre>tf.keras.layers.Dense(10, activation=tf.nn.softmax)</pre><pre>])</pre><pre><em># Compile the model</em></pre><pre>model.compile(optimizer=’adam’,</pre><pre>loss=’sparse_categorical_crossentropy’,</pre><pre>metrics=[‘accuracy’])</pre><pre><em># Train the model</em></pre><pre>model.fit(X_train, y_train, epochs=config.epochs,</pre><pre>validation_data=(X_test, y_test),</pre><pre>callbacks=[WandbCallback(data_type=”image”, labels=labels)])</pre><p>It’s super important to call <strong>wandb.init()</strong> at the beginning of the training script itself; otherwise, the different runs in the hyperparameter sweep will not be able to log the specified outputs to your <strong>wandb</strong> dashboard.</p><p>As you can see, we are trying to train a shallow fully-connected network. We are allowing the network to train for 5 epochs with the <a href="https://arxiv.org/abs/1412.6980">Adam optimizer</a> (set to minimize the <a href="https://keras.io/losses/">Sparse Category Crossentropy</a> loss as the class labels are integers). This method is based on this <a href="https://docs.wandb.com/sweeps/python">example</a>.</p><p>Once the model training script is done, you can run it as an agent to start the hyperparameter sweeping process.</p><pre>wandb.agent(sweep_id, function=train)</pre><p>And that’s it! You should see something like this in your notebook:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Rfv9q53jgiPkBiwN.png" /></figure><p>If you click on the sweep URL you got from the <em>third</em> step as described above, you should see a number of interesting things.</p><p>First, a dashboard giving you a summary of all the different runs (i.e. the network’s performance with a different set of layers) like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ESqT0liQMvUqC-fh.png" /></figure><p><strong>Note</strong> each run has its unique ID (left).</p><ul><li>Now if you click on any of the runs (that you can see on the left), you will be able to see the network’s performance individually:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Gi1DA0o-ANhh5a2y.png" /></figure><p>Along with the network’s performance details, <em>for each run</em>, you also get:</p><ul><li>Network architecture</li><li>A serialized version of the network in .h5 format</li><li>Stats on bandwidth usage, CPU/GPU usage, memory footprint</li></ul><p>Just click on a run of your choice, and you will have these buttons available on the left:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/545/0*E9jl2I4voWefpLWG.png" /></figure><p>While choosing the best model from the sweep we focus on the trade-off between the validation loss and training loss, i.e. we find the runs for which the validation loss kept on decreasing with respect to the training loss. The following table can come in really handy here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pbdFMVyGsSq-m-f2.png" /></figure><p>On your Weights and Biases project page (<a href="https://app.wandb.ai/sayakpaul/hyperparameter-sweeps-partI">example here</a>), you can press ‘option+space’ to expand the runs table, and compare all the results. From here you can sort by validation accuracy (or validation loss) to find the model that performed best. You can also explore the results of the sweep by adding a parallel coordinates plot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/0*W1tUAm05cBGHwp7t.png" /></figure><h3>How to Add a Parallel Coordinates Chart</h3><pre>Step 1: Click ‘Add visualization’ on the project page.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TytnZty1Pt7FTEOL.png" /></figure><pre><strong>Step 2</strong>: Choose the parallel coordinates plot.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XAfFjCiY3TddU81T.png" /></figure><pre><strong>Step 3</strong>: Pick the dimensions (hyperparameters) you would like to visualize. Ideally, you want the last column to be the metric you are optimizing for (e.g. validation loss).</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VUWM8Co4lqYeVOc-.png" /></figure><pre><strong>Step 4: </strong>And voila! You have a parallel coordinates plot!</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tdLg9zzOPPgUEgtk.png" /></figure><p>In this plot, for example, we can see that a lower learning rate and a higher number of channels in our convolutional layers leads to a better validation accuracy. Parallel coordinate plots can be extremely useful in quickly seeing the trends in our hyperparameter values compared to our optimization metric. This, in turn, lets us narrow down our hyperparameter space and get to better accuracy faster.</p><p>If you’d like to learn more about how to choose the best model, check out these articles:</p><ul><li><a href="https://www.wandb.com/articles/p-picking-a-machine-learning-model">Part I: Best Practices for Picking a Machine Learning Model</a></li><li><a href="https://www.wandb.com/articles/tour-of-machine-learning-models">Part II: A Whirlwind Tour of Machine Learning Models</a></li></ul><h3>Conclusion</h3><p>Now that you understand how to use sweeps, I encourage you to try sweeps with multiple hyperparameters. In this tutorial, we only tuned the <strong>layers </strong>hyperparameter; you could also try tuning the <strong>batch_size</strong>, <strong>epochs</strong>, <strong>optimizer</strong> and so on.</p><p>I hope you enjoyed reading this tutorial. Stay tuned for the second part where we dive deeper with more advanced hyperparameter sweeps and many practical tips of using them effectively.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e9d94dda46" width="1" height="1" alt=""><hr><p><a href="https://medium.com/six-ways-to-debug-a-machine-learning-model/hyperparameter-optimization-using-sweeps-with-w-b-1e9d94dda46">Hyperparameter Optimization using sweeps with W&amp;B</a> was originally published in <a href="https://medium.com/six-ways-to-debug-a-machine-learning-model">Weights &amp; Biases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyEnv Tutorial for Machine Learning]]></title>
            <link>https://medium.com/@weights_biases/pyenv-tutorial-for-machine-learning-9638e43a790f?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/9638e43a790f</guid>
            <category><![CDATA[virtual-environment]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Tue, 22 Oct 2019 18:33:27 GMT</pubDate>
            <atom:updated>2019-11-08T05:40:39.419Z</atom:updated>
            <content:encoded><![CDATA[<h4>Data Science in the Real World</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfULqqtS67S0Nz0xPrTWzw.jpeg" /></figure><h4>TL;DR</h4><p>If you’re doing machine learning and tired of python dependency hell, use pyenv!</p><p>If you jump between a lot of different machine learning projects, you probably find yourself running something like <strong>pip install -r requirements.txt</strong> quite often. By default, <strong>pip install</strong> puts libraries in your systemwide libraries folder. If one of your projects has requirements that conflicts with another, switching to that project and running <strong>pip install</strong> will effectively break your other project by modifying the systemwide python libraries it needs to run.</p><p>Worse yet, many projects haven’t fully moved to python3 yet! So you may find yourself juggling systemwide requirements across python2 and python3.</p><p>A lot of folks use docker for this type of workflow issue. You spin up a container from an image that has python2 or python3 tools already installed, and then install your requirements in that container. You then just use a new container for every project. That’s a totally fine way to do things! But using docker means incurring a bit of overhead (especially on mac, where you don’t quite get native performance), and is perhaps overkill for just this use case (assuming you’re mostly just working alone and don’t need to <a href="https://www.wandb.com/articles/towards-reproducibility">solve reproducibility for you and your teammates</a>).</p><p>Instead of configuring a unique docker container for each project, how about a unique python environment? What if you could just run <strong>pip install</strong>, and have the resulting libraries installed somewhere <em>local</em> to the project you’re working on?</p><p>I’ve been using <strong>pyenv-virtualenv</strong> to accomplish just that. <strong>pyenv</strong> is a utility that manages several python installations and virtual environments for you. <strong>pyenv</strong> can install different versions of python in isolation from each other, <em>and</em> create virtual environments for each of your projects. Once a project is associated with a specific virtual environment, running python inside that project resolves to the correct version of python with the correct libraries installed every time.</p><h4>Let’s walk through an example.</h4><p>First, you’ll want to install pyenv. There are several ways to do this depending on whether you’re running MacOS or Linux (a Windows version exists too, though it may not work exactly as described here), but the simplest way that works in any unix-like OS is to simply run:</p><pre>$ curl <a href="https://pyenv.run/">https://pyenv.run</a> | bash</pre><p>Assuming your OS already has python installed, running pyenv versions should now show the system python installation.</p><pre>$ pyenv versions</pre><pre>* system</pre><p>Let’s find a project to work on. As a simple example, I’ll use the starter code for W&amp;B’s <a href="https://app.wandb.ai/wandb/superres/benchmark">superres benchmark</a>.</p><pre>$ git clone <a href="https://github.com/wandb/superres.git">https://github.com/wandb/superres.git</a></pre><pre>Cloning into ‘superres’…</pre><pre>…</pre><pre>$ cd superres</pre><p>All the code in this repo happens to run fine on python3, so let’s now install python3 in pyenv.</p><pre>$ pyenv install 3.6.8</pre><pre>&lt;Lots of output follows. Should eventually succeed.&gt;</pre><pre>$ pyenv versions</pre><pre>* system</pre><pre>3.6.8</pre><p>The output of <strong>pyenv versions</strong> is telling us that pyenv now sees two versions of python: the default system installation you had before pyenv, and version 3.6.8. It’s also saying that system python is the current active version. We can prove this to ourselves by asking pyenv which python binary would run if we were to invoke python right now.</p><pre>$ pyenv which python</pre><pre>/usr/bin/python # or similar</pre><p>Let’s try switching to python 3.6.8 and running that same command.</p><pre>$ pyenv shell 3.6.8</pre><pre>$ pyenv which python</pre><pre>$HOME/.pyenv/versions/3.6.8/bin/python</pre><p>Now we can run python and we know we’ll get version 3.6.8. We’re almost fully set up. Now let’s create a virtualenv for this superres project.</p><pre>$ pyenv virtualenv 3.6.8 superres</pre><pre>&lt;Some output follows.&gt;</pre><pre>$ pyenv versions</pre><pre>system</pre><pre>* 3.6.8 (set by PYENV_VERSION environment variable)</pre><pre>3.6.8/envs/superres</pre><pre>superres</pre><p>It looks like we now have four environments, but don’t worry, superres is just an alias for “3.6.8/envs/superres”, so there are actually only three.</p><h4>What did running this virtualenv command actually do?</h4><p>It basically “forked” (without copying or reinstalling) the installation for version 3.6.8, and created a new subdirectory where we can install packages to the <em>superres </em>environment only.</p><p>On to the last step: associating this project with our <em>superres </em>environment.</p><pre>$ pyenv shell — unset # Undoes our previous pyenv shell command.</pre><pre>$ pyenv local superres</pre><p>This creates a file in your current directory called .python-version, which contains the name of the environment we want to use whenever we’re in this directory. Let’s test that everything works as expected.</p><pre>$ cd ..</pre><pre>$ pyenv versions # In the previous folder, we should default to system python.</pre><pre>* system</pre><pre>3.6.8</pre><pre>3.6.8/envs/superres</pre><pre>superres</pre><pre>$ cd superres</pre><pre>$ pyenv versions</pre><pre>system</pre><pre>3.6.8</pre><pre>3.6.8/envs/superres</pre><pre>* superres (set by /superres/.python-version)</pre><p>Now we can run <strong>pip install -r requirements.txt</strong> and trust that everything will get installed only in the superres environment!</p><pre>$ pip install -r requirements.txt</pre><pre><em>&lt;Lots of output follows.&gt;</em></pre><pre>$ pip show tensorflow # Let’s prove to ourselves the installation is really local.</pre><pre><em>&lt;…&gt;</em></pre><pre>Location: $HOME/.pyenv/versions/3.6.8/envs/superres/lib/python3.6/site-packages</pre><pre><em>&lt;…&gt;</em></pre><p>You can now repeat the steps starting at <strong>pyenv virtualenv &lt;version&gt; &lt;virtualenv name&gt;</strong> for each project, and your dependencies will never get mixed up again!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9638e43a790f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Network Fundamentals]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/neural-network-fundamentals-4a56d1ef5a58?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a56d1ef5a58</guid>
            <category><![CDATA[neural-network-algorithm]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[machine-learning-tools]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 20:54:52 GMT</pubDate>
            <atom:updated>2019-10-21T20:56:24.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldj9agGDn6mgki10BXqdUA.png" /></figure><p>Training neural networks can be very confusing. What’s a good learning rate? How many hidden layers should your network have? Is dropout actually useful? Why are your gradients vanishing?</p><p>In this post we’ll peel the curtain behind some of the more confusing aspects of neural nets, and help you make smart decisions about your neural network architecture.</p><p>We’ll also see how we can use <a href="http://wandb.com/">Weights and Biases</a> inside Kaggle kernels to monitor performance and pick the best architecture for our neural network!</p><p>I highly recommend forking <a href="https://www.kaggle.com/lavanyashukla01/training-a-neural-network-start-here">this kernel</a> and playing with the different building blocks to hone your intuition.</p><p>If you have any questions, feel free to message me. Good luck!</p><h3>1. Basic Neural Network Structure</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*9phXSDfKceK7NoTM.png" /></figure><h4><strong>Input neurons</strong></h4><ul><li>This is the number of features your neural network uses to make its predictions.</li><li>The input vector needs one input neuron per feature. For tabular data, this is the number of relevant features in your dataset. You want to carefully select these features and remove any that may contain patterns that won’t generalize beyond the training set (and cause overfitting). For images, this is the dimensions of your image (28*28=784 in case of MNIST).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/0*JVVZ2zl9F7Fc7wLj.png" /></figure><h4><strong>Output neurons</strong></h4><ul><li>This is the number of predictions you want to make.</li><li>Regression: For regression tasks, this can be one value (e.g. housing price). For multi-variate regression, it is one neuron per predicted value (e.g. for bounding boxes it can be 4 neurons — one each for bounding box height, width, x-coordinate, y-coordinate).</li><li>Classification: For binary classification (spam-not spam), we use one output neuron per positive class, wherein the output represents the probability of the positive class. For multi-class classification (e.g. in object detection where an instance can be classified as a car, a dog, a house etc.), we have one output neuron per class, and use the <a href="https://sebastianraschka.com/faq/docs/softmax_regression.html">softmax activation</a> function on the output layer to ensure the final probabilities sum to 1.</li></ul><h4>Hidden Layers and Neurons per Hidden Layers</h4><ul><li>The number of hidden layers is highly dependent on the problem and the architecture of your neural network. You’re essentially trying to Goldilocks your way into the perfect neural network architecture — not too big, not too small, just right.</li><li>Generally, 1–5 hidden layers will serve you well for most problems. When working with image or speech data, you’d want your network to have dozens-hundreds of layers, not all of which might be fully connected. For these use cases, there are pre-trained models (<a href="https://pjreddie.com/media/files/papers/YOLOv3.pdf">YOLO</a>, <a href="https://arxiv.org/abs/1512.03385">ResNet</a>, <a href="https://arxiv.org/abs/1409.1556">VGG</a>) that allow you to use large parts of their networks, and train your model on top of these networks to learn only the higher order features. In this case, your model will still have only a few layers to train.</li><li>In general using the same number of neurons for all hidden layers will suffice. For some datasets, having a large first layer and following it up with smaller layers will lead to better performance as the first layer can learn a lot of lower-level features that can feed into a few higher order features in the subsequent layers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*2cvgYR_ROnllzXQ0.jpeg" /></figure><ul><li>Usually you will get more of a performance boost from adding more layers than adding more neurons in each layer.</li><li>I’d recommend starting with 1–5 layers and 1–100 neurons and slowly adding more layers and neurons until you start overfitting. You can track your loss and accuracy within your <a href="http://wandb.com/">Weights and Biases</a> dashboard to see which hidden layers + hidden neurons combo leads to the best loss.</li><li>Something to keep in mind with choosing a smaller number of layers/neurons is that if the this number is too small, your network will not be able to learn the underlying patterns in your data and thus be useless. An approach to counteract this is to start with a huge number of hidden layers + hidden neurons and then use dropout and early stopping to let the neural network size itself down for you. Again, I’d recommend trying a few combinations and track the performance in your <a href="http://wandb.com/">Weights and Biases</a> dashboard to determine the perfect network size for your problem.</li><li>Andrej Karpathy also recommends the <a href="http://karpathy.github.io/2019/04/25/recipe/">overfit then regularize approach</a> — “first get a model large enough that it can overfit (i.e. focus on training loss) and then regularize it appropriately (give up some training loss to improve the validation loss).”</li></ul><h4>Loss function</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IlN36OIx-mgzl3qN.png" /></figure><ul><li>Regression: Mean squared error is the most common loss function to optimize for, unless there are a significant number of outliers. In this case, use mean absolute error or <a href="https://en.wikipedia.org/wiki/Huber_loss">Huber loss</a>.</li><li>Classification: <a href="https://en.wikipedia.org/wiki/Cross_entropy">Cross-entropy</a> will serve you well in most cases.</li></ul><h4>Batch Size</h4><ul><li>Large batch sizes can be great because they can harness the power of GPUs to process more training instances per time. <a href="https://openai.com/blog/science-of-ai/">OpenAI has found</a> larger batch size (of tens of thousands for <a href="https://arxiv.org/abs/1807.11205">image-classification</a> and <a href="https://arxiv.org/abs/1808.01371">language modeling</a>, and of millions in the case of <a href="https://blog.openai.com/openai-five/">RL agents</a>) serve well for scaling and parallelizability.</li><li>There’s a case to be made for smaller batch sizes too, however. According to <a href="https://arxiv.org/abs/1804.07612">this paper</a> by Masters and Luschi, the advantage gained from increased parallelism from running large batches is offset by the increased performance generalization and smaller memory footprint achieved by smaller batches. They show that increased batch sizes reduce the acceptable range of learning rates that provide stable convergence. Their takeaway is that smaller is, in-fact, better; and that the best performance is obtained by mini-batch sizes between 2 and 32.</li><li>If you’re not operating at massive scales, I would recommend starting with lower batch sizes and slowly increasing the size and monitoring performance in your <a href="http://wandb.com/">Weights and Biases</a> dashboard to determine the best fit.</li></ul><h4>Number of epochs</h4><ul><li>I’d recommend starting with a large number of epochs and use Early Stopping (see section 4. Vanishing + Exploding Gradients) to halt training when performance stops improving.</li></ul><h4>Scaling your features</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*usIvTnzaEbs3BUpA.png" /></figure><ul><li>A quick note: Make sure all your features have similar scale before using them as inputs to your neural network. This ensures faster convergence. When your features have different scales (e.g. salaries in thousands and years of experience in tens), the cost function will look like the elongated bowl on the left. This means your optimization algorithm will take a long time to traverse the valley compared to using normalized features (on the right).</li></ul><h3>2. Learning Rate</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*MPoCSbsIpxE61Tuu.png" /></figure><ul><li>Picking the learning rate is very important, and you want to make sure you get this right! Ideally you want to re-tweak the learning rate when you tweak the other hyper-parameters of your network.</li><li>To find the best learning rate, start with a very low values (10^-6) and slowly multiply it by a constant until it reaches a very high value (e.g. 10). Measure your model performance (vs the log of your learning rate) in your <a href="http://wandb.com/">Weights and Biases</a>dashboard to determine which rate served you well for your problem. You can then retrain your model using this optimal learning rate.</li><li>The best learning rate is usually half of the learning rate that causes the model to diverge. Feel free to set different values for learn_rate in the accompanying code and seeing how it affects model performance to develop your intuition around learning rates.</li><li>I’d also recommend using the <a href="https://arxiv.org/abs/1506.01186">Learning Rate finder</a> method proposed by Leslie Smith. It an excellent way to find a good learning rate for most gradient optimizers (most variants of SGD) and works with most network architectures.</li><li>Also, see the section on learning rate scheduling below.</li></ul><h3>3. Momentum</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LXLqeVB_88Fqu_KU.png" /></figure><ul><li><a href="https://hackernoon.com/gradient-descent-aynk-7cbe95a778da">Gradient Descent</a> takes tiny, consistent steps towards the local minima and when the gradients are tiny it can take a lot of time to converge. Momentum on the other hand takes into account the previous gradients, and accelerates convergence by pushing over valleys faster and avoiding local minima.</li><li>In general you want your momentum value to be very close to one. 0.9 is a good place to start for smaller datasets, and you want to move progressively closer to one (0.999) the larger your dataset gets. (Setting nesterov=True lets momentum take into account the gradient of the cost function a few steps ahead of the current point, which makes it slightly more accurate and faster.)</li></ul><h3>4. Vanishing + Exploding Gradients</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*FY-TRiUO-8tZxBV_.gif" /></figure><ul><li>Just like people, not all neural network layers learn at the same speed. So when the backprop algorithm propagates the error gradient from the output layer to the first layers, the gradients get smaller and smaller until they’re almost negligible when they reach the first layers. This means the weights of the first layers aren’t updated significantly at each step.</li><li>This is the problem of <a href="https://towardsdatascience.com/the-vanishing-gradient-problem-69bf08b15484">vanishing gradients</a>. (A similar problem of exploding gradients occurs when the gradients for certain layers get progressively larger, leading to massive weight updates for some layers as opposed to the others.)</li><li>There are a few ways to counteract vanishing gradients. Let’s take a look at them now!</li></ul><h4>Activation functions</h4><ul><li>Hidden Layer Activation</li><li>In general, the performance from using different <a href="https://isaacchanghau.github.io/post/activation_functions/">activation functions</a>improves in this order (from lowest→highest performing): logistic → tanh → ReLU → Leaky ReLU → ELU → SELU.</li><li>ReLU is the most popular activation function and if you don’t want to tweak your activation function, ReLU is a great place to start. But, keep in mind ReLU is becoming increasingly less effective than <a href="https://arxiv.org/pdf/1511.07289.pdf">ELU</a> or <a href="https://arxiv.org/pdf/1606.08415.pdf">GELU</a>.</li><li>If you’re feeling more adventurous, you can try the following:</li><li>to combat neural network overfitting: RReLU</li><li>reduce latency at runtime: leaky ReLU</li><li>for massive training sets: PReLU</li><li>for fast inference times: leaky ReLU</li><li>if your network doesn’t self-normalize: ELU</li><li>for an overall robust activation function: SELU</li><li>As always, don’t be afraid to experiment with a few different activation functions, and turn to your <a href="http://wandb.com/">Weights and Biases</a> dashboard to help you pick the one that works best for you!</li><li><a href="https://arxiv.org/pdf/1811.03378.pdf">This</a> is an excellent paper that dives deeper into the comparison of various activation functions for neural networks.</li><li>Output Layer Activation</li><li>Regression: Regression problems don’t require activation functions for their output neurons because we want the output to take on any value. In cases where we want out values to be bounded into a certain range, we can use tanh for -1→1 values and logistic function for 0→1 values. In cases where we’re only looking for positive output, we can use softplus activation.</li><li>Classification: Use the sigmoid activation function for binary classification to ensure the output is between 0 and 1. Use softmax for multi-class classification to ensure the output probabilities add up to 1.</li></ul><h4>Weight initialization method</h4><ul><li>The right weight initialization method can speed up time-to-convergence considerably. The choice of your initialization method depends on your activation function. Some things to try:</li><li>When using ReLU or leaky RELU, use <a href="https://arxiv.org/pdf/1502.01852.pdf">He initialization</a></li><li>When using SELU or ELU, use <a href="http://yann.lecun.com/exdb/publis/pdf/lecun-98b.pdf">LeCun initialization</a></li><li>When using softmax, logistic, or tanh, use <a href="http://proceedings.mlr.press/v9/glorot10a/glorot10a.pdf">Glorot initialization</a></li><li>Most initialization methods come in uniform and normal distribution flavors.</li></ul><h4>BatchNorm</h4><ul><li>BatchNorm simply learns the optimal means and scales of each layer’s inputs. It does so by zero-centering and normalizing its input vectors, then scaling and shifting them. It also acts like a regularizer which means we don’t need dropout or L2 reg.</li><li>Using BatchNorm lets us use larger learning rates (which result in faster convergence) and lead to huge improvements in most neural networks by reducing the vanishing gradients problem. The only downside is that it slightly increases training times because of the extra computations required at each layer.</li></ul><h4>Gradient Clipping</h4><ul><li>A great way to reduce gradients from exploding, specially when training RNNs, is to simply clip them when they exceed a certain value. I’d recommend trying clipnorm instead of clipvalue, which allows you to keep the direction of your gradient vector consistent. Clipnorm contains any gradients who’s l2 norm is greater than a certain threshold.</li><li>Try a few different threshold values to find one that works best for you.</li></ul><h4>Early Stopping</h4><ul><li>Early Stopping lets you live it up by training a model with more hidden layers, hidden neurons and for more epochs than you need, and just stopping training when performance stops improving consecutively for n epochs. It also saves the best performing model for you. You can enable Early Stopping by setting up a callback when you fit your model and setting save_best_only=True.</li></ul><h3>5. Dropout</h3><ul><li>Dropout is a fantastic regularization technique that gives you a massive performance boost (~2% for state-of-the-art models) for how simple the technique actually is. All dropout does is randomly turn off a percentage of neurons at each layer, at each training step. This makes the network more robust because it can’t rely on any particular set of input neurons for making predictions. The knowledge is distributed amongst the whole network. Around 2^n (where n is the number of neurons in the architecture) slightly-unique neural networks are generated during the training process, and ensembled together to make predictions.</li><li>A good dropout rate is between 0.1 to 0.5; 0.3 for RNNs, and 0.5 for CNNs. Use larger rates for bigger layers. Increasing the dropout rate decreases overfitting, and decreasing the rate is helpful to combat under-fitting.</li><li>You want to experiment with different rates of dropout values, in earlier layers of your network, and check your <a href="http://wandb.com/">Weights and Biases</a> dashboard to pick the best performing one. You definitely don’t want to use dropout in the output layers.</li><li>Read <a href="https://arxiv.org/abs/1801.05134">this paper</a> before using Dropout in conjunction with BatchNorm.</li><li>In this kernel I used AlphaDropout, a flavor of the vanilla dropout that works well with SELU activation functions by preserving the input’s mean and standard deviations.</li></ul><h3>6. Optimizers</h3><ul><li>Gradient Descent isn’t the only optimizer game in town! There’s a few different ones to choose from. <a href="https://isaacchanghau.github.io/post/parameters_update/">This post</a> does a good job of describing some of the optimizers you can choose from.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*FHpE4uih9tg8QgTp.gif" /></figure><ul><li>My general advice is to use Stochastic Gradient Descent if you care deeply about quality of convergence and if time is not of the essence.</li><li>If you care about time-to-convergence and a point close to optimal convergence will suffice, experiment with Adam, Nadam, RMSProp, and Adamax optimizers. Your <a href="http://wandb.com/">Weights and Biases</a> dashboard will guide you to the optimizer that works best for you!</li><li>Adam/Nadam are usually good starting points, and tend to be quite forgiving to a bad learning late and other non-optimal hyperparameters.</li><li><a href="http://karpathy.github.io/2019/04/25/recipe/">According to Andrej Karpathy</a>, “a well-tuned SGD will almost always slightly outperform Adam” in the case of ConvNets.</li><li>In this kernel, I got the best performance from Nadam, which is just your regular Adam optimizer with the Nesterov trick, and thus converges faster than Adam.</li></ul><h3>7. Learning Rate Scheduling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/459/0*FdFlKGBmEdEAxmoP.png" /></figure><p>We talked about the importance of a good learning rate already — we don’t want it to be too high, lest the cost function dance around the optimum value and diverge. We also don’t want it to be too low because that means convergence will take a very long time.</p><ul><li>Babysitting the learning rate can be tough because both higher and lower learning rates have their advantages. The great news is that we don’t have to commit to one learning rate! With learning rate scheduling we can start with higher rates to move faster through gradient slopes, and slow it down when we reach a gradient valley in the hyper-parameter space which requires taking smaller steps.</li><li>There are many ways to schedule learning rates including decreasing the learning rate exponentially, or by using a step function, or tweaking it when the performance starts dropping, or using 1cycle scheduling. In this kernel, I show you how to use the ReduceLROnPlateau callback to reduce the learning rate by a constant factor whenever the performance drops for n epochs.</li><li>I would highly recommend also trying out 1cycle scheduling.</li><li>Use a constant learning rate until you’ve trained all other hyper-parameters. And implement learning rate decay scheduling at the end.</li><li>As with most things, I’d recommend running a few different experiments with different scheduling strategies and using your <a href="http://wandb.com/">Weights and Biases</a> dashboard to pick the one that leads to the best model.</li></ul><h3>8. A Few More Things</h3><ul><li>Try <a href="https://arxiv.org/pdf/1905.11946.pdf">EfficientNets</a> to scale your network in an optimal way.</li><li>Read <a href="https://arxiv.org/pdf/1803.09820.pdf">this paper</a> for an overview of some additional learning rate, batch sizes, momentum and weight decay techniques.</li><li>And <a href="https://arxiv.org/abs/1803.05407">this one</a> on Stochastic Weight Averaging (SWA). It shows that better generalization can be achieved by averaging multiple points along the SGD’s trajectory, with a cyclical or constant learning rate.</li><li>Read Andrej Karpathy’s <a href="http://karpathy.github.io/2019/04/25/recipe/">excellent guide</a> on getting the most juice out of your neural networks.</li></ul><h3>Results</h3><p>We’ve explored a lot of different facets of neural networks in this post!</p><p>We’ve looked at how to setup a basic neural network (including choosing the number of hidden layers, hidden neurons, batch sizes etc.)</p><p>We’ve learnt about the role momentum and learning rates play in influencing model performance.</p><p>And finally we’ve explored the problem of vanishing gradients and how to tackle it using non-saturating activation functions, BatchNorm, better weight initialization techniques and early stopping.</p><p>You can compare the accuracy and loss performances for the various techniques we tried in one single chart, by visiting your <a href="https://app.wandb.ai/home">Weights and Biases</a> dashboard.</p><p>Neural networks are powerful beasts that give you a lot of levers to tweak to get the best performance for the problems you’re trying to solve! The sheer size of customizations that they offer can be overwhelming to even seasoned practitioners. Tools like <a href="http://wandb.com/">Weights and Biases </a>are your best friends in navigating the land of the hyper-parameters, trying different experiments and picking the most powerful models.</p><p>I hope this guide will serve as a good starting point in your adventures. Good luck!</p><p>I highly recommend forking <a href="https://www.kaggle.com/lavanyashukla01/training-a-neural-network-start-here">this kernel</a> and playing with the different building blocks to hone your intuition. And here’s a demo to walk you through using W+B to pick the perfect neural network architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a56d1ef5a58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/six-ways-to-debug-a-machine-learning-model/neural-network-fundamentals-4a56d1ef5a58">Neural Network Fundamentals</a> was originally published in <a href="https://medium.com/six-ways-to-debug-a-machine-learning-model">Weights &amp; Biases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Machine Learning Best Practices for Test Driven Development]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/machine-learning-best-practices-for-test-driven-development-44581f446d13?source=rss-d81e29d20045------2</link>
            <guid isPermaLink="false">https://medium.com/p/44581f446d13</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[engineering-mangement]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 20:47:03 GMT</pubDate>
            <atom:updated>2019-10-21T20:48:07.656Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMMrRIt27e0Xy_dAUloJzQ.png" /></figure><p>I sat down with the <a href="https://www.latentspace.co/">Latent Space</a> team to talk about best practices around collaboration and managing model iteration. In machine learning, bugs may affect the distribution of possible models more than any particular instance, making traditional deterministic tests misleading. Because of this, a test-driven development framework for large ML models must account for the statistical nature of training. This is especially crucial when multiple researchers and engineers are contributing to the same model, as it’s easy to silently introduce regressions into a codebase. Here, the team shares some insights about how this new form of test-driven development has been the key to moving quickly on a large-scale collaborative project.</p><p>Latent Space is democratizing creativity through AI. They are making the first fully AI-rendered 3D engine, where users create the world itself and objects in it. Creation is as easy as uploading a picture to Instagram. But when you upload in Latent Space, you see it come to life in 3D. Bring your family car or the Millennium Falcon into a shared world that could look like anything from the Taj Mahal to Winterfell. This new level of self expression enables greater diversity in 3D content, tackling one of the largest problems in the games industry.</p><h3>Process in a nutshell</h3><p>To iterate quickly and with confidence on cutting-edge generative models with a team, Latent Space has found two crucial strategies:</p><ol><li>Fully modular models.</li><li>Testing with rigor.</li></ol><h3>Fully Modular Models</h3><p>Latent Space built what they call the “block system” combined with <a href="https://github.com/google/gin-config">the gin configuration framework</a> to allow them to create new generators, discriminators, encoders, arbitrary skip connections, or tuning parameters in a high-level configuration file. The name was inspired by <a href="https://github.com/mila-iqia/blocks">MILA’s old Theano “Blocks” system</a>. <a href="https://www.linkedin.com/in/darrylbarnhart/">Darryl Barnhart</a>, architect of the block system, describes its benefits:</p><ol><li><em>Clarity of abstraction. By separating hyperparameters from the business logic of forward passes and model construction, configs become a higher level way to design a model.</em></li><li><em>Ease of ablation. Comparing two variants of a model is as easy as changing a few parameters in a config, lowering the barrier to experimentation significantly.</em></li><li><em>Ease of hyperparameter search. They use </em><a href="https://docs.wandb.com/docs/sweep.html"><em>W&amp;B’s sweep feature </em></a><em>to run thousands of variations of a model to find the best setup. (An even more extreme extension of this is </em><a href="https://arxiv.org/abs/1802.03268"><em>Neural Architecture Search </em></a><em>where an ML model drives architecture selection with even finer granularity.)</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*rXRKYtw0HsZBpAHN.png" /><figcaption><em>A W&amp;B “parallel coordinates” visualization of sweep results over learning rate, batch size and optimizer type, with the best performing runs interactively highlighted</em></figcaption></figure><p>Their config structure is hierarchical. They have one HEAD model that represents the latest and most effective changes. Everything else is a ‘child’ configuration. This makes ablations (A/B tests of changes) clear: inherit from the HEAD model, change the settings that are different/new and run that new config. Each config is essentially a model definition, and in W&amp;B each config gets its own tag.</p><p>Here’s an example gin config:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/0*4bdV7NIa4GQy6LCw.png" /></figure><p><a href="https://www.linkedin.com/in/chase-basich-658a46107/">Chase Basich</a> on the config system:</p><blockquote><em>One thing about our config system that has been very helpful is the checkpoint-like nature of the system. For any feature, we can easily find the config that first introduced that feature to see a canonical example of how it was setup and then run that config. We can then use that config to find the corresponding W&amp;B runs and reports. For example, I was recently investigating a regression and this provided a quick way to re-run the ablations and compare the new and old W&amp;B data.</em></blockquote><h3>Testing with Rigor</h3><h3>Finding the new SOTA</h3><p>One of the things that initially attracted them to W&amp;B was how shareable W&amp;B reports are. They loved the idea of associating reports with pull requests. Pull requests happen when code is merging into their develop branch, and when they are changing their HEAD model configs. To have stats to prove a set of changes are an improvement to their model was very enticing.</p><p>Initially, they compared the average and min/max of a few runs from a branch vs HEAD.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FAxHjB5Ff1EZOS3E.png" /><figcaption><em>Two ablations (orange and red) compared with one of their HEAD models over the course of training in W&amp;B. Each config is comprised of 5–10 separate runs. The solid lines indicate mean and the vertical bands indicate min/max values at a given iteration.</em></figcaption></figure><p>If you run the same config many times, you’ll get different results depending on model initialization, randomized shuffled data-loader reads, or the parallel nature of GPU operations. Moreover, they realized they don’t just care about improving the average, or even the min/max. If a change didn’t affect the mean/min/max, but the variance significantly reduced, it would be a win. These kinds of changes make the signal much clearer and reduce the number of runs needed.</p><p>Even during development, the team triggers a training run over 10 times for each of their changes. Using an in-house cloud setup, they can run them all in parallel, then analyze their changes in W&amp;B.</p><p>To communicate how changes improve their models, all their code pull requests use the following template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*nyD0qVP5PPUZqhOw.png" /></figure><p>They use one or more W&amp;B tags per config, and then use different run sets (with their corresponding tags) in the same section of a report to pull the different arms of the experiment together.</p><p>Tips from <a href="https://www.linkedin.com/in/jefftyling/">Jeff Ling</a><em>:</em></p><p><em>In W&amp;B, each of our configs is mapped to one or many tags. That’s how we find relevant runs. We use tags with reports to show the A/B comparison of a config change. For example, if I’m testing the effects of a new feature, I would find the head cloud model and the config with the feature, and put the same tag in both. When I run both, it appears in my report.</em></p><h3>Preventing Regressions</h3><p>According to <a href="https://twitter.com/latentcodes">Sarah Jane Hong</a>,</p><p><em>ML models are difficult to debug due to their adaptive nature; if you have a bug (or many!) the model can still perform adequately. The most insidious forms of bugs are the ones that “fail” silently. It can range from something unintended such as </em><a href="https://twitter.com/karpathy/status/1013244313327681536?s=21"><em>passing in softmax outputs to a loss that expects raw logits</em></a><em>, or as subtle as accidentally broadcasting a tensor somewhere in your model.</em></p><p>They have hourly, nightly, and weekly integration tests, and unit tests on every PR. The tests are used to ensure that their models won’t perform worse as new changes come in. The more frequent the integration test, the shorter the duration of the run. Runs have several key metrics (for them this includes <a href="https://arxiv.org/pdf/1706.08500.pdf">Fréchet Inception Distance</a>), and any of these can be compared to a distribution of baseline runs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*e6r6hLD-yT-dcxMB.png" /><figcaption><em>They use a W&amp;B report to track all their hourly integration test results over time. Each data point is the final score from a test (lower is better). Notice around 19–07–24 13:26 a bug results in spikes across all metrics for several runs, followed by a lasting improvement.</em></figcaption></figure><p>Getting fast <em>and</em> confident feedback on new features is central to Latent Space’s automated testing. They use a mixture of frequentist and Bayesian methods to compare the old and new distributions, but have increasingly relied on Bayesian approaches to more quickly update their beliefs based on new evidence (each run and sub-metrics within a run representing new evidence). Most tests involve comparing two distributions: a previous distribution from an earlier config/commit, and a new distribution for the integration test, PR, or ablation/sweep being run. As Latent Space has scaled their generative models, better automated statistical analysis has become increasingly beneficial the larger their training regime becomes. It creates a fast feedback loop for adding new features and understanding their effect at scale at minimal cost.</p><p>They also treat extremely out of distribution “good” results as a failure. If they were expected, they should have come in with a PR and established new baseline runs. If unexpected, likely there’s a new bug in how the metric is calculated and it’s not actually improved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/833/0*-mPC6Fsh-pA27JGm.png" /><figcaption><em>Slack tells them when integration tests pass or fail and posts links to W&amp;B runs.</em></figcaption></figure><p>Finally, they have Unit Tests that run via <a href="https://circleci.com/">CircleCI</a> on every PR to ensure the model can still mechanically train and key functionality always works as expected.</p><h3>Conclusion</h3><p>Latent Space’s meticulous approach to coordinating model improvements stood out to me as an example of a thoughtful and repeatable structure for pushing the envelope of best practices in the industry.</p><p>One of the most interesting parts of Latent Space’s system is their use of composable blocks. They’ll dive into more detail on that subject in a future post. Get ready to learn about how this design choice allows the team to sweep through different architectures instead of just tweaking hyperparameters!</p><p>If you found this blog post interesting or valuable feel free to share with a friend! Their team is always happy to hear feedback — contact me at <a href="#">carey@wandb.com</a> for any questions or ari@wandb.com to learn how to use W&amp;B at your company.</p><p><a href="http://www.latentspace.co/">Learn more about Latent Space here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44581f446d13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/six-ways-to-debug-a-machine-learning-model/machine-learning-best-practices-for-test-driven-development-44581f446d13">Machine Learning Best Practices for Test Driven Development</a> was originally published in <a href="https://medium.com/six-ways-to-debug-a-machine-learning-model">Weights &amp; Biases</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>