<?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[Weights &amp; Biases - Medium]]></title>
        <description><![CDATA[Building Developer Tools for Deep Learning - Medium]]></description>
        <link>https://medium.com/six-ways-to-debug-a-machine-learning-model?source=rss----13e9a80ef15a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Weights &amp;amp; Biases - Medium</title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model?source=rss----13e9a80ef15a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 00:07:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/six-ways-to-debug-a-machine-learning-model" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <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----13e9a80ef15a---4</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 04:35:53 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[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----13e9a80ef15a---4</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>Fri, 08 Nov 2019 05:29:54 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[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----13e9a80ef15a---4</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>Wed, 23 Oct 2019 16:20:32 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[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----13e9a80ef15a---4</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>Wed, 23 Oct 2019 15:36:08 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[Neural Network Fundamentals]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/neural-network-fundamentals-4a56d1ef5a58?source=rss----13e9a80ef15a---4</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----13e9a80ef15a---4</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>
        <item>
            <title><![CDATA[Six Ways to Debug a Machine Learning Model]]></title>
            <link>https://medium.com/six-ways-to-debug-a-machine-learning-model/six-ways-to-debug-a-machine-learning-model-57c0829e85f4?source=rss----13e9a80ef15a---4</link>
            <guid isPermaLink="false">https://medium.com/p/57c0829e85f4</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[W&B]]></dc:creator>
            <pubDate>Mon, 21 Oct 2019 20:31:28 GMT</pubDate>
            <atom:updated>2019-10-21T20:34:50.227Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHYMzdY4l2CzFBIgtBVOUQ.png" /></figure><p>In traditional software development, a bug usually leads to the program crashing. While this is annoying for the user, it is critical for the developer — when the program fails the developer can inspect errors to understand why.</p><p>With machine learning models, the developer sometimes encounters errors but all too often the program crashes without a clear reason why. While these issues can be debugged manually, machine learning models most often fail because of poor output predictions. What’s worse is that when they fail, there is usually no signal about why or when the models failed. And to make the situation even more complicated, it might be a result of a number of things, including bad training data, high loss error, or a lack of convergence rate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uzPFKalke6OkG-qc.jpeg" /></figure><p>In this blog post, we’ll look at how to debug these silent failures so that they don’t impact the performance of our machine learning algorithms. Here is a quick overview of what we are going to cover:</p><ol><li>How to find flaws in the input data</li><li>How to make the model learn more from less data</li><li>How to prepare data for training and avoid common pitfalls</li><li>How to find the optimal model hyper-parameters</li><li>How to schedule learning rates in order to reduce overfitting</li><li>How to monitor training progress with Weights and Biases</li></ol><p>It is worth noting that as a data science/machine learning practitioner, you need to acknowledge that there are many reasons why machine learning projects can fail. Most have nothing to do with the skills of the engineers and data scientists (just because it’s not working does not mean you’re faulty). The takeaway is that if we can identify common pitfalls or bugs early and often, we can save both time and money. In high-stakes application domains such as finance, government, and health care, this will be mission-critical.</p><h3>1 — How to find flaws in the input data</h3><p>There are two aspects to consider when wanting to know whether our data is up to the task of training a good model:</p><ul><li>Can the data predict what we want to predict?</li><li>Is there enough data?</li></ul><p>To figure out whether our model contains predictive information, we can ask ourselves: can a human make a prediction given this data?</p><p>If a human cannot understand an image or a text, chances are our model won’t make much sense of it either. If there is not enough predictive information, adding more inputs to our model won’t make it better; in contrast, the model will overfit and become less accurate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*36KfqlG22ElIlaE3.jpeg" /></figure><p>Once our data has enough predictive information, we need to figure out whether we have enough data to train a model to extract the signal. There are a couple of rules of thumb to follow:</p><p>(1) For classification, we should have at least 30 independent samples per class</p><p>(2) We should have at least 10 samples for any feature, especially for structured data problems, and finally</p><p>(3) The size of our dataset is directly proportional to the number of parameters in our model. These rules might need to be tailored to your specific application. If you can make use of transfer learning, then you can drastically reduce the number of samples needed.</p><h4>2 — How to make the model learn more from less data</h4><p>In many situations, we simply do not have enough data. In this case, one of the best options is to augment the data. Taking augmentation a step further, we can generate our own data with generative models such as autoencoders and generative adversarial networks.</p><p>Likewise, we can find external public data, which can be found available on the Internet. Even if the data were not originally collected for our purpose, we can potentially relabel it or use it for transfer learning. We can train a model on a large dataset for a different task and then use that model as a basis for our task. Similarly, we can find a model that someone else has trained for a different task and repurpose it for our task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yyKjxV7RkEGOeWe2.png" /></figure><p>It’s important to remember that in most cases the quality of the data trumps the quantity of the data. Having a small, high-quality dataset and training a simple model is the best practice to find problems in the data early in the training process. A mistake many data scientists make is that they spend time and money on getting a big dataset, only to figure out later that they have the wrong kind of data for their project.</p><h4>3 — How to prepare data for training and avoid common pitfalls</h4><p>There are 3 common ways to pre-process the data features for the training process:</p><ul><li><strong>Standardization</strong> ensures that all of the data has a mean of 0 and a standard deviation of 1. This is the most common way of scaling features. It is even more useful if you suspect that the data contains outliers.</li><li><strong>Min-Max rescaling</strong> scales all data between 0 and 1 by subtracting the minimum value and then dividing by the range of values.</li><li><strong>Mean normalization</strong> ensures your data has values between (-1) and 1 with a mean of 0. We subtract the mean and divide by the range of the data.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eOyaX_MH3q9qAwU-.jpeg" /></figure><p>However we prepare the features, it is important to only measure the scaling factors, the mean, and the standard deviation on the test set. If we measure these factors over the entire dataset, the algorithm might perform better on the test set than it will in production, due to this information exposure.</p><h4>4 — How to find the optimal model hyperparameters</h4><p>Manually tuning the hyperparameters of a neural network model can be extremely tedious. That is because there is not a scientific rule to use when it comes to hyper-parameter tuning. That is why many data scientists have moved towards automatic hyperparameter search, using some sort of non-gradient based optimization algorithm.</p><p>To see how we can find the optimal hyperparameters for our model with Weight and Biases, let’s take a look at<a href="https://www.wandb.com/articles/mask-r-cnn-hyperparameter-experiments-with-weights-and-biases"> this example from a Mask R-CNN computer vision model</a>. With the goal to implement Mask R-CNN for semantic segmentation tasks, Connor and Trent<a href="https://github.com/connorhough/Mask_RCNN/blob/master/mrcnn/config.py"> tweak different hyper-parameters that govern how the model operates</a>: learning rate, gradient clip normalization, momentum, weight decay, scale ratios, weights of various loss functions… They want to know how the semantic segmentation of the images progressed as the model trained with different hyper-parameters, so they integrated<a href="https://github.com/connorhough/Mask_RCNN/blob/master/samples/coco/coco.py"> an ImageCallback() class</a> to sync to wandb. Furthermore, they<a href="https://github.com/connorhough/Mask_RCNN/blob/master/samples/coco/inspect_weights.ipynb"> included a script to run parameters sweeps</a> that can be adapted to work with different hyper-parameters or different values of the same ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tp2EKiBswj9t99Ca.png" /></figure><p>Their results can be found on the<a href="https://app.wandb.ai/trentwatson1/mask-rcnn/runs"> wandb run page</a>. It seems like a high gradient clipping set and a high learning rate can lead to better model accuracy, with the validation loss scores decreasing quickly given an increasing number of iterations.</p><p><strong>5 — How to schedule learning rates in order to reduce overfitting</strong></p><p>One of the most important hyperparameters is the learning rate, which is difficult to optimize. Small learning rate leads to slow training, and large learning rate leads to model overfitting.</p><p>When it comes to finding a learning rate, standard hyperparameter search techniques are not the best choice. For the learning rate, it is better to perform a line search and visualize the loss for different learning rates, as this will give you an understanding of how the loss function behaves. When doing a line search, it is better to increase the learning rate exponentially. You are more likely to care about the region of smaller learning rates than about very large learning rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pSuhBfU4GaDetrkF.png" /></figure><p>In the beginning, our model might be far away from the optimal solution, and so because of that, we want to move as fast as possible. As we approach the minimum loss, however, we want to move slower to avoid overshooting. A popular method is to <strong>anneal the learning rate</strong> over time, which recommends starting with a relatively high learning rate and then gradually lowering the learning rate during training. The intuition is that we would like to move quickly from the initial parameters to a range of good-enough parameter values, and then we can explore the “<a href="http://cs231n.github.io/neural-networks-3/#anneal">deeper, but narrower parts of the loss function</a>.” The most popular form of learning rate annealing is a <strong>step decay</strong> where the learning rate is reduced by some percentage after a set number of training epochs. More generically, we should define a <strong>learning rate schedule</strong> to update the rate during training according to a specified rule.</p><h4>6 — How to monitor training progress with Weights and Biases</h4><p>An important part of debugging a model is knowing when things go wrong before you have invested significant amounts of time training the model. WandB provides a seamless way to visualize and track machine learning experiments. As described in<a href="https://github.com/wandb/client"> this GitHub repo</a>, you can search/compare/visualize training runs, analyze system usage metrics alongside runs, replicate historic results, and many more.</p><p>All we have to do after installing wandb is including this piece of code in our training script:</p><pre>import wandb</pre><pre><em># Your custom arguments defined here</em></pre><pre>args = …</pre><pre>wandb.init(config=args, project=”my-project”)</pre><pre>wandb.config[“more”] = “custom”</pre><pre>def training_loop():</pre><pre>while True:</pre><pre><em># Do some machine learning</em></pre><pre>epoch, loss, val_loss = …</pre><pre><em># Framework agnostic / custom metrics</em></pre><pre>wandb.log({“epoch”: epoch, “loss”: loss, “val_loss”: val_loss})</pre><p>Alternatively, we can<a href="https://docs.wandb.com/integrations/tensorboard"> integrate with Tensorboard</a> in one line:</p><pre>wandb.init(sync_tensorboard=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uq7spmogi_Zii4zA.png" /></figure><p>TensorBoard is a TensorFlow extension that allows us to easily monitor our model in a browser. To provide an interface from which we can watch the model’s process, TensorBoard also offers some options useful for debugging. For example, we can observe the distributions of the model’s weights and gradients during training. If we really want to dig into the model, TensorBoard offers a visual debugger. In this debugger, we can step through the execution of the TensorFlow model and examine every single value inside it. This is especially useful if we are working on complex models, such as variational auto-encoders, and are trying to understand why complex things break down.</p><h3>Conclusion</h3><p>We now have a substantial number of tools that will help us run actual machine learning projects. Making sure that the model works before deploying it is crucial and the failure to do so can cost us a lot of money. Hopefully, this blog post equips you well with practical techniques to make models resilient, generalizable, and easy to debug.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57c0829e85f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/six-ways-to-debug-a-machine-learning-model/six-ways-to-debug-a-machine-learning-model-57c0829e85f4">Six Ways to Debug a Machine Learning Model</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>