<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Machine Learning Use Cases for Risk Management</title>
	<atom:link href="https://www.relataly.com/category/use-case/risk-management/feed/" rel="self" type="application/rss+xml" />
	<link>https://www.relataly.com/category/use-case/risk-management/</link>
	<description>The Business AI Blog</description>
	<lastBuildDate>Sat, 27 May 2023 10:29:11 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>

<image>
	<url>https://www.relataly.com/wp-content/uploads/2023/04/cropped-AI-cat-Icon-White.png</url>
	<title>Machine Learning Use Cases for Risk Management</title>
	<link>https://www.relataly.com/category/use-case/risk-management/</link>
	<width>32</width>
	<height>32</height>
</image> 
<site xmlns="com-wordpress:feed-additions:1">175977316</site>	<item>
		<title>Tuning Model Hyperparameters with Grid Search at the Example of Training a Random Forest Classifier in Python</title>
		<link>https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/</link>
					<comments>https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Mon, 06 Jul 2020 21:16:52 +0000</pubDate>
				<category><![CDATA[Classification (two-class)]]></category>
		<category><![CDATA[Hyperparameter Tuning]]></category>
		<category><![CDATA[Insurance]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Random Decision Forests]]></category>
		<category><![CDATA[Risk Management]]></category>
		<category><![CDATA[Scikit-Learn]]></category>
		<category><![CDATA[Seaborn]]></category>
		<category><![CDATA[Intermediate Tutorials]]></category>
		<category><![CDATA[Random Forest Classification]]></category>
		<category><![CDATA[Supervised Learning]]></category>
		<category><![CDATA[Titanic Dataset]]></category>
		<category><![CDATA[Tuning Random Decision Forests]]></category>
		<guid isPermaLink="false">https://www.relataly.com/?p=2261</guid>

					<description><![CDATA[<p>Are you struggling to find the best hyperparameters for your machine learning model? With Python&#8217;s Scikit-learn library, you can use grid search to fine-tune your model and improve its performance. In this article, we&#8217;ll guide you through the process of hyperparameter tuning for a classification model, using a random decision forest that predicts the survival ... <a title="Tuning Model Hyperparameters with Grid Search at the Example of Training a Random Forest Classifier in Python" class="read-more" href="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/" aria-label="Read more about Tuning Model Hyperparameters with Grid Search at the Example of Training a Random Forest Classifier in Python">Read more</a></p>
<p>The post <a href="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/">Tuning Model Hyperparameters with Grid Search at the Example of Training a Random Forest Classifier in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Are you struggling to find the best hyperparameters for your machine learning model? With Python&#8217;s Scikit-learn library, you can use grid search to fine-tune your model and improve its performance. In this article, we&#8217;ll guide you through the process of hyperparameter tuning for a classification model, using a random decision forest that predicts the survival of Titanic passengers as an example.</p>



<p>We&#8217;ll start by explaining the concept of grid search and how it works. Then, we&#8217;ll dive into the development and optimization of the random decision forest using Python. By defining a parameter grid and feeding it to the grid search algorithm, we can explore all possible hyperparameter combinations and find the optimal configuration for our model.</p>



<p>Finally, we&#8217;ll compare the performance of different model configurations to determine the best one for our classification task. Whether you&#8217;re new to machine learning or looking to boost the performance of an existing model, this step-by-step guide to hyperparameter tuning with grid search will help you achieve better results. Let&#8217;s get started!</p>



<p>Also: <a href="https://www.relataly.com/multivariate-outlier-detection-using-isolation-forests-in-python-detecting-credit-card-fraud/4233/" target="_blank" rel="noreferrer noopener">Multivariate Anomaly Detection on Time-Series Data in Python</a></p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-large is-resized"><img fetchpriority="high" decoding="async" data-attachment-id="2353" data-permalink="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/image-7-5/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/07/image-7.png" data-orig-size="837,539" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-7" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/07/image-7.png" src="https://www.relataly.com/wp-content/uploads/2020/07/image-7.png" alt="Grid Search - parameter grid for hyperparameter tuning" class="wp-image-2353" width="386" height="248" srcset="https://www.relataly.com/wp-content/uploads/2020/07/image-7.png 837w, https://www.relataly.com/wp-content/uploads/2020/07/image-7.png 300w, https://www.relataly.com/wp-content/uploads/2020/07/image-7.png 768w, https://www.relataly.com/wp-content/uploads/2020/07/image-7.png 80w" sizes="(max-width: 386px) 100vw, 386px" /><figcaption class="wp-element-caption">Exemplary parameter grid for the tuning of a random decision forest with four hyperparameters</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">What are Hyperparameters?</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>Hyperparameters play a crucial role in the performance of a machine learning model. They are adjustable parameters that influence the model training process and control how a machine learning algorithm learns and how it behaves. </p>



<p>Unlike the internal parameters (coefficients, etc.) that the algorithm automatically optimizes during model training, hyperparameters are model characteristics (e.g., the number of estimators for an ensemble model) that we must set in advance. </p>



<p>Which hyperparameters are available, depends on the algorithm.  For example, a random decision forest model may have hyperparameters such as the number of trees and tree depth, while a neural network model may have hyperparameters such as the number of hidden layers and nodes in each layer. Finding the optimal configuration of hyperparameters can be a challenging task, as there is often no way to know in advance what the ideal values should be. </p>



<p>This requires experimentation with different hyperparameter settings, which can be time-consuming if done manually. Grid search is a useful tool for automating this process and efficiently finding the best hyperparameter configuration for a given model.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full is-resized"><img decoding="async" data-attachment-id="9871" data-permalink="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/picture2-min/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/10/Picture2-min.png" data-orig-size="696,472" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Picture2-min" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/10/Picture2-min.png" src="https://www.relataly.com/wp-content/uploads/2022/10/Picture2-min.png" alt="" class="wp-image-9871" width="385" height="260" srcset="https://www.relataly.com/wp-content/uploads/2022/10/Picture2-min.png 696w, https://www.relataly.com/wp-content/uploads/2022/10/Picture2-min.png 300w" sizes="(max-width: 385px) 100vw, 385px" /><figcaption class="wp-element-caption">Hyperparameters are the little screws that we can adjust to tune a predictive model.</figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading" id="h-efficient-hyperparameter-tuning-with-exhaustive-grid-search">Efficient Hyperparameter Tuning with Exhaustive&nbsp;Grid Search</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>When we train a machine learning model, it is usually unclear which hyperparameters lead to good results. While there are estimates and rules of thumb, there is often no way to avoid trying out hyperparameters in experiments. However, machine learning models often have several hyperparameters that affect the model&#8217;s performance in a nonlinear way.</p>



<p>We can use grid search to automate searching for optimal model hyperparameters. The search grid algorithm exhaustively generates models from parameter permutations of a grid of parameter values. Let&#8217;s take a look at how this works.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">Hyperparameter Tuning with Grid Search: How it Works</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The idea behind the grid search technique is quite simple. We have a model with parameters, and the challenge is to test various configurations until we are satisfied with the result. Grid search is exhaustive in that it tests all permutations of a parameter grid. The number of model variants results from the parameter grid and the specified parameters.</p>



<p>The grid search algorithm requires us to provide the following information:</p>



<ul class="wp-block-list">
<li>The hyperparameters that we want to configure (e.g., tree depth)</li>



<li>For each hyperparameter, a range of values (e.g., [50, 100, 150])</li>



<li>A performance metric so that the algorithm knows how to measure performance (e.g., accuracy for a classification model)</li>
</ul>



<p>For example, imagine we have a range of [16, 32, and 64] for n_estimators and a range of [8, 16, and 32] for max_depth. Then, the search grid will test 9 different parameter configurations.</p>



<h3 class="wp-block-heading">Early Stopping</h3>



<p>Running parameter optimization against an entire grid can be time-consuming, but there are ways to shorten the process. Depending on how much time you want to invest in the search process, you can test all combinations exhaustively or shorten the process with an early stopping logic. A stopping logic defines that the search ends early when a specific criterion is met. Such a criterion could be, for example, that newly trained models underperform the average performance of previously trained models by a certain value. In this case, the search stops and returns the best models found up to that point. When you define a large search grid with many parameters, defining an early stopping logic is recommended. </p>



<h3 class="wp-block-heading" id="h-strengths-and-weaknesses-of-grid-search">Strengths and Weaknesses of Grid Search</h3>



<p>The advantage of the grid search is that the algorithm automatically identifies the optimal parameter configuration from the parameter grid. However, the number of possible configurations increases exponentially with the number of values in the parameter grid. So, in practice, defining a sparse parameter grid or defining stopping criteria is essential.</p>



<p>Grid Search is only one of several techniques that can be used to tune the hyperparameters of a predictive model. Alternative techniques include  <a href="https://www.relataly.com/using-random-search-to-tune-the-hyperparameters-of-a-random-decision-forest-with-python/6875/" target="_blank" rel="noreferrer noopener">Random Search</a>. In contrast to Grid Search, Random Search is a none exhaustive hyperparameter-tuning technique, which randomly selects and tests specific configurations from a predefined search space. Further optimization techniques are Bayesian Search and Gradient Descent.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"><div class="wp-block-image">
<figure class="aligncenter size-large is-resized"><img decoding="async" data-attachment-id="2354" data-permalink="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/image-8-5/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/07/image-8.png" data-orig-size="384,196" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-8" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/07/image-8.png" src="https://www.relataly.com/wp-content/uploads/2020/07/image-8.png" alt="Grid Search - A search grid with two hyperparameters and three hyperparameter values" class="wp-image-2354" width="397" height="201"/><figcaption class="wp-element-caption">A parameter grid with two hyperparameters and respectively three hyperparameter values</figcaption></figure>
</div></div>
</div>



<h2 class="wp-block-heading">Evaluation Metrics</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>The question of which metric to optimize against inevitably arises when we talk about optimization. Generally, all common metrics available for classification or regression come into question.</p>



<p>Metrics for regression (<a href="https://www.relataly.com/regression-error-metrics-python/923/" target="_blank" rel="noreferrer noopener">more detailed description</a>)</p>



<ul class="wp-block-list">
<li>Mean Absolute Error (MAE) </li>



<li>Root Mean Squared Absolute Error (RMSAE) </li>



<li>Relative Squared Error (RSE).</li>
</ul>



<p>Metrics for classification (<a href="https://www.relataly.com/measuring-classification-performance-with-python-and-scikit-learn/846/" target="_blank" rel="noreferrer noopener">more detailed description</a>)</p>



<ul class="wp-block-list">
<li>Accuracy</li>



<li>Precision</li>



<li>F-1 Score</li>



<li>Recall</li>
</ul>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"></div>
</div>



<h2 class="wp-block-heading">Tuning the Hyperparameters of a Random Decision Forest Classifier in Python using Grid Search</h2>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow">
<p>Now that we have familiarized ourselves with the basic concept of hyperparameter tuning, let&#8217;s move on to the Python hands-on part! In this part, we will work with the Titanic dataset. We will apply the grid search optimization technique to a classification model. We will develop our Machine Learning model based on the Titanic dataset.</p>



<p>The sinking of the Titanic was one of the most catastrophic ship disasters, leading to more than 1500 casualties (The exact number is unknown due to several passengers being unregistered). The Titanic dataset contains a list of passengers with passenger information such as age, gender, cabin, ticket cost, etc., and whether they survived the Titanic sinking. The information about the passengers shows certain patterns that allow conclusions about the likelihood of the passengers surviving the accident. These data can be used to train a predictive model.</p>



<p>In the following, we will use the survival flag as a label and passenger information as input for a classification model. The goal is to predict whether a passenger will survive the Titanic sinking or not. The algorithm will be a random decision forest algorithm that classifies the passengers into two groups, survivors and non-survivors. Once we have trained a baseline model, we will apply grid search to optimize the hyperparameters of this model and select the best model.</p>
</div>
</div>



<p>The code is available on the GitHub repository.</p>



<div class="wp-block-group"><div class="wp-block-group__inner-container is-layout-flow wp-block-group-is-layout-flow">
<div class="wp-block-kadence-advancedbtn kb-buttons-wrap kb-btns_9836db-d0"><a class="kb-button kt-button button kb-btn_12cb2e-6a kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-tutorials/blob/master/11%20Hyperparamter%20Tuning/016%20Hyperparameter%20Tuning%20of%20Random%20Decision%20Forests%20using%20Grid%20Search.ipynb" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fe_eye kt-btn-icon-side-left"><svg viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg></span><span class="kt-btn-inner-text">View on GitHub </span></a>

<a class="kb-button kt-button button kb-btn_f9b732-8b kt-btn-size-standard kt-btn-width-type-full kb-btn-global-inherit  kt-btn-has-text-true kt-btn-has-svg-true  wp-block-button__link wp-block-kadence-singlebtn" href="https://github.com/flo7up/relataly-public-python-API-tutorials" target="_blank" rel="noreferrer noopener"><span class="kb-svg-icon-wrap kb-svg-icon-fa_github kt-btn-icon-side-left"><svg viewBox="0 0 496 512"  fill="currentColor" xmlns="http://www.w3.org/2000/svg"  aria-hidden="true"><path d="M165.9 397.4c0 2-2.3 3.6-5.2 3.6-3.3.3-5.6-1.3-5.6-3.6 0-2 2.3-3.6 5.2-3.6 3-.3 5.6 1.3 5.6 3.6zm-31.1-4.5c-.7 2 1.3 4.3 4.3 4.9 2.6 1 5.6 0 6.2-2s-1.3-4.3-4.3-5.2c-2.6-.7-5.5.3-6.2 2.3zm44.2-1.7c-2.9.7-4.9 2.6-4.6 4.9.3 2 2.9 3.3 5.9 2.6 2.9-.7 4.9-2.6 4.6-4.6-.3-1.9-3-3.2-5.9-2.9zM244.8 8C106.1 8 0 113.3 0 252c0 110.9 69.8 205.8 169.5 239.2 12.8 2.3 17.3-5.6 17.3-12.1 0-6.2-.3-40.4-.3-61.4 0 0-70 15-84.7-29.8 0 0-11.4-29.1-27.8-36.6 0 0-22.9-15.7 1.6-15.4 0 0 24.9 2 38.6 25.8 21.9 38.6 58.6 27.5 72.9 20.9 2.3-16 8.8-27.1 16-33.7-55.9-6.2-112.3-14.3-112.3-110.5 0-27.5 7.6-41.3 23.6-58.9-2.6-6.5-11.1-33.3 2.6-67.9 20.9-6.5 69 27 69 27 20-5.6 41.5-8.5 62.8-8.5s42.8 2.9 62.8 8.5c0 0 48.1-33.6 69-27 13.7 34.7 5.2 61.4 2.6 67.9 16 17.7 25.8 31.5 25.8 58.9 0 96.5-58.9 104.2-114.8 110.5 9.2 7.9 17 22.9 17 46.4 0 33.7-.3 75.4-.3 83.6 0 6.5 4.6 14.4 17.3 12.1C428.2 457.8 496 362.9 496 252 496 113.3 383.5 8 244.8 8zM97.2 352.9c-1.3 1-1 3.3.7 5.2 1.6 1.6 3.9 2.3 5.2 1 1.3-1 1-3.3-.7-5.2-1.6-1.6-3.9-2.3-5.2-1zm-10.8-8.1c-.7 1.3.3 2.9 2.3 3.9 1.6 1 3.6.7 4.3-.7.7-1.3-.3-2.9-2.3-3.9-2-.6-3.6-.3-4.3.7zm32.4 35.6c-1.6 1.3-1 4.3 1.3 6.2 2.3 2.3 5.2 2.6 6.5 1 1.3-1.3.7-4.3-1.3-6.2-2.2-2.3-5.2-2.6-6.5-1zm-11.4-14.7c-1.6 1-1.6 3.6 0 5.9 1.6 2.3 4.3 3.3 5.6 2.3 1.6-1.3 1.6-3.9 0-6.2-1.4-2.3-4-3.3-5.6-2z"/></svg></span><span class="kt-btn-inner-text">Relataly GitHub Repo </span></a></div>
</div></div>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%"><div class="wp-block-image">
<figure class="aligncenter is-resized"><img decoding="async" src="https://cdn.britannica.com/s:800x1000/72/153172-050-EB2F2D95/Titanic.jpg" alt="Operated by the White Star Line, RMS Titanic was the largest and most luxurious ocean liner of her time." width="357" height="227"/><figcaption class="wp-element-caption">Source: <em>The National Archives/Heritage-Images/Imagestate</em></figcaption></figure>
</div></div>
</div>



<h3 class="wp-block-heading" id="h-prerequisites">Prerequisites</h3>



<p>Before starting the coding part, make sure that you have set up your <a href="https://www.python.org/downloads/" target="_blank" rel="noreferrer noopener">Python 3</a> environment and required packages. If you don&#8217;t have a Python environment, follow&nbsp;<a href="https://www.relataly.com/anaconda-python-environment-machine-learning/1663/" target="_blank" rel="noreferrer noopener">this tutorial</a>&nbsp;to set up the&nbsp;<a href="https://www.anaconda.com/products/individual" target="_blank" rel="noreferrer noopener">Anaconda environment</a>.</p>



<p>Also, make sure you install all required packages. In this tutorial, we will be working with the following standard packages:&nbsp;</p>



<ul class="wp-block-list">
<li><em><a href="https://pandas.pydata.org/" target="_blank" rel="noreferrer noopener">pandas</a></em></li>



<li><em><a href="https://numpy.org/" target="_blank" rel="noreferrer noopener">NumPy</a></em></li>



<li><a href="https://docs.python.org/3/library/math.html" target="_blank" rel="noreferrer noopener">math</a></li>



<li><em><a href="https://matplotlib.org/" target="_blank" rel="noreferrer noopener">matplotlib</a></em></li>
</ul>



<p>In addition, we will be using the Python Machine Learning library <a href="https://scikit-learn.org/stable/" target="_blank" rel="noreferrer noopener">Scikit-learn</a> to implement the random forest and the grid search technique. </p>



<p>You can install packages using console commands:</p>



<ul class="wp-block-list">
<li><em>pip install &lt;package name&gt;</em></li>



<li><em>conda install &lt;package name&gt;</em>&nbsp;(if you are using the anaconda packet manager)</li>
</ul>



<h3 class="wp-block-heading" id="h-about-the-titanic-dataset">About the Titanic Dataset</h3>



<div class="wp-block-columns is-layout-flex wp-container-core-columns-is-layout-9d6595d7 wp-block-columns-is-layout-flex">
<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:66.66%">
<p>In this article, we will be working with the popular titanic dataset for classification. The Titanic dataset is a well-known dataset that contains information about the passengers on the Titanic, a British passenger liner that sank in the North Atlantic Ocean in 1912 after colliding with an iceberg. The dataset includes variables such as the passenger&#8217;s name, age, fare, and class, as well as whether or not the passenger survived.</p>



<p>The titanic dataset contains the following information on passengers of the titanic:</p>



<ul class="wp-block-list">
<li><strong>Survival</strong>: Survival 0 = No, 1 = Yes (Prediction Label)</li>



<li><strong>Pclass</strong>: Ticket class 1 = 1st, 2 = 2nd, 3 = 3rd</li>



<li><strong>Sex</strong>: Sex</li>



<li><strong>Age</strong>: Age in years</li>



<li><strong>SibSp</strong>: # of siblings/spouses aboard the Titanic</li>



<li><strong>Parch</strong>: # of parents/children aboard the Titanic</li>



<li><strong>Ticket</strong>: Ticket number</li>



<li><strong>Fare</strong>: Passenger fare</li>



<li><strong>Cabin</strong>: Cabin number</li>



<li><strong>Embarked</strong>: Port of Embarkation C = Cherbourg, Q = Queenstown, S = Southampton</li>
</ul>



<p>The Survival column contains the prediction label, which states whether a passenger survived the sinking of the Titanic or not.</p>



<p>You can download the titanic dataset from <a href="https://www.kaggle.com/c/titanic" target="_blank" rel="noreferrer noopener">the Kaggle website</a>. Once you have completed the download, you can place the dataset in the file path of your choice. Using the Kaggle Python environment, you can directly save the dataset into your Kaggle project.</p>
</div>



<div class="wp-block-column is-layout-flow wp-block-column-is-layout-flow" style="flex-basis:33.33%">
<figure class="wp-block-image size-full is-resized"><img decoding="async" data-attachment-id="7036" data-permalink="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/picture28/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/Picture28.png" data-orig-size="693,720" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="Picture28" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/Picture28.png" src="https://www.relataly.com/wp-content/uploads/2022/04/Picture28.png" alt="We can assume that the cabin location of the passengers had an impact on their chance to survive the sinking. Developing a machine learning model for prediction of titanic passenger survival and optimizing its hyperparameters using grid search" class="wp-image-7036" width="377" height="391" srcset="https://www.relataly.com/wp-content/uploads/2022/04/Picture28.png 693w, https://www.relataly.com/wp-content/uploads/2022/04/Picture28.png 289w" sizes="(max-width: 377px) 100vw, 377px" /><figcaption class="wp-element-caption">We can assume that the cabin location of the passengers had an impact on their chance of surviving the sinking. </figcaption></figure>
</div>
</div>



<h2 class="wp-block-heading">Step #1 Load the Titanic Data</h2>



<p>The following code will load the titanic data into our python project. If you have placed the data outside the path shown below, don&#8217;t forget to adjust the file path in the code.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}">import math 
import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt 
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
import seaborn as sns
from pandas.plotting import register_matplotlib_converters

# set file path
filepath = &quot;data/titanic-grid-search/&quot;

# Load train and test datasets
titanic_train_df = pd.read_csv(filepath + 'titanic-train.csv')
titanic_test_df = pd.read_csv(filepath + 'titanic-test.csv')
titanic_train_df.head()</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">	PassengerId	Survived	Pclass	Name							Sex	Age	SibSp	Parch	Ticket				Fare	Cabin	Embarked
0	1			0			3		Braund, Mr. Owen Harris			male	22.0	1	0	A/5 21171			7.2500	NaN		S
1	2			1			1		Cumings, Mrs. John Bradley ...	female	38.0	1	0	PC 17599			71.2833	C85		C
2	3			1			3		Heikkinen, Miss. Laina			female	26.0	0	0	STON/O2. 3101282	7.9250	NaN		S
3	4			1			1		Futrelle, Mrs. Jacques ...		female	35.0	1	0	113803				53.1000	C123	S
4	5			0			3		Allen, Mr. William Henry		male	35.0	0	0	373450				8.0500	NaN		S</pre></div>



<h3 class="wp-block-heading" id="h-step-2-preprocessing-and-exploring-the-data">Step #2 Preprocessing and Exploring the Data</h3>



<p>Before we can train a model, we preprocess the data: </p>



<ul class="wp-block-list">
<li>Firstly, we clean the missing values in the data and replace them with the mean. </li>



<li>Second, we transform categorical features (<em>Embarked </em>and <em>Sex</em>) into numeric values. In addition, we will delete some columns to reduce model complexity. </li>



<li>Finally, we delete the prediction label from the training dataset and place it into a separate dataset named y_df.</li>
</ul>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Define a function for preprocessing the train and test data 
def preprocess(df):
    
    # Delete some columns that we will not use
    new_df = df[df.columns[~df.columns.isin(['Cabin', 'PassengerId', 'Name', 'Ticket'])]].copy()
    
    # Replace missing values
    for i in new_df.select_dtypes(include=['int16', 'int32', 'int64', 'float16', 'float32', 'float64']).columns:
        new_df[i].fillna(new_df[i].mean(), inplace=True)
    new_df['Embarked'].fillna('C', inplace=True)
    
    # Decode categorical values as integer values
    new_df_b = new_df.copy()
    new_df_b['Sex'] = np.where(new_df_b['Sex']=='male', 0, 1) 
    
    cleanups = {&quot;Sex&quot;:     {&quot;m&quot;: 0, &quot;f&quot;: 1},
                &quot;Embarked&quot;: {&quot;S&quot;: 1, &quot;Q&quot;: 2, &quot;C&quot;: 3}}
    new_df_b.replace(cleanups, inplace=True)
    x = new_df_b.drop(columns=['Survived'])
    y = new_df_b['Survived']  
    
    return x, y

# Create the training dataset train_df and the label dataset
x_df, y_df = preprocess(train_df)
x_df.head()</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">		Pclass	Sex	Age		SibSp	Parch	Fare	Embarked
0		3		0	22.0	1		0		7.2500	1
1		1		1	38.0	1		0		71.2833	3
2		3		1	26.0	0		0		7.9250	1
3		1		1	35.0	1		0		53.1000	1
4		3		0	35.0	0		0		8.0500	1</pre></div>



<p>Let&#8217;s take a quick look at the data by creating paired plots for the columns of our data set. Pair plots help us to understand the relationships between pairs of variables in a dataset. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># # Create histograms for feature columns separated by prediction label value
df_plot = titanic_train_df.copy()

# class_columnname = 'Churn'
sns.pairplot(df_plot, hue=&quot;Survived&quot;, height=2.5, palette='muted')</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="6803" data-permalink="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/hyperparameter-tuning-random-decision-forests/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/04/hyperparameter-tuning-random-decision-forests.png" data-orig-size="1124,1062" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="hyperparameter-tuning-random-decision-forests" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/04/hyperparameter-tuning-random-decision-forests.png" src="https://www.relataly.com/wp-content/uploads/2022/04/hyperparameter-tuning-random-decision-forests-1024x968.png" alt="paired plot created with seaborn" class="wp-image-6803" width="768" height="726" srcset="https://www.relataly.com/wp-content/uploads/2022/04/hyperparameter-tuning-random-decision-forests.png 1024w, https://www.relataly.com/wp-content/uploads/2022/04/hyperparameter-tuning-random-decision-forests.png 300w, https://www.relataly.com/wp-content/uploads/2022/04/hyperparameter-tuning-random-decision-forests.png 768w, https://www.relataly.com/wp-content/uploads/2022/04/hyperparameter-tuning-random-decision-forests.png 1124w" sizes="(max-width: 768px) 100vw, 768px" /></figure>



<p>The histograms tell us various things. For example, most passengers were between 25 and 35 years old. In addition, we can see that most passengers had low-fare tickets, while some passengers had significantly more expensive tickets. </p>



<h3 class="wp-block-heading" id="h-step-3-splitting-the-data">Step #3 Splitting the Data</h3>



<p>Next, we will split the data set into training data (x_train, y_train) and test data (x_test, y_test) using a split ratio of 70/30.</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Split the data into x_train and y_train data sets
x_train, x_test, y_train, y_test = train_test_split(x_df, y_df, train_size=0.7, random_state=0)</pre></div>



<h3 class="wp-block-heading" id="h-step-4-building-a-single-random-forest-model">Step #4 Building a Single Random Forest Model</h3>



<p>After completing the preprocessing, we can train the first model. The model uses a random forest algorithm. The random forest algorithm has a large number of hyperparameters.</p>



<h4 class="wp-block-heading" id="h-4-1-about-the-random-forest-algorithm">4.1 About the Random Forest Algorithm</h4>



<p>A random forest is a robust predictive algorithm that can handle classification and regression tasks. As a so-called ensemble model, the random forest considers predictions from a group of several independent estimators. </p>



<p>Random decision forests have several hyperparameters that we can use to influence their behavior. However, not all of these hyperparameters have the same influence on model performance. Limiting the number of models by defining a sparse parameter grid is essential to reduce the amount of time needed to test the hyperparameters. </p>



<p>Therefore, we restrict the hyperparameters optimized by the grid search approach to the following two:</p>



<ul class="wp-block-list">
<li><strong>n_estimators</strong> determine the number of decision trees in the forest</li>



<li><strong>max_depth</strong> defines the maximum number of branches in each decision tree</li>
</ul>



<p>In the <a href="https://scikit-learn.org/stable/modules/generated/sklearn.ensemble.RandomForestClassifier.html?highlight=random%20forest#sklearn.ensemble.RandomForestClassifier" target="_blank" rel="noreferrer noopener">scikit-learn documentation</a>, you also find a full list of available hyperparameters. For the rest of these hyperparameters, we will use the default value defined by scikit-learn.</p>



<h4 class="wp-block-heading" id="h-4-2-implementing-a-random-forest-model">4.2 Implementing a Random Forest Model</h4>



<p>We train a simple baseline model and make a test prediction with the x_test dataset. Then we visualize the performance of the baseline model in a confusion matrix:</p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Train a single random forest classifier
clf = RandomForestClassifier(max_depth=2, random_state=0, n_estimators = 100)
clf.fit(x_train, y_train)
y_pred = clf.predict(x_test)

# Create a confusion matrix
cnf_matrix = confusion_matrix(y_test, y_pred)

# Create heatmap from the confusion matrix
%matplotlib inline
class_names=[False, True] # name  of classes
fig, ax = plt.subplots(figsize=(7, 6))
sns.heatmap(pd.DataFrame(cnf_matrix), annot=True, cmap=&quot;YlGnBu&quot;, fmt='g')
ax.xaxis.set_label_position(&quot;top&quot;)
plt.tight_layout()
plt.title('Confusion matrix')
plt.ylabel('Actual label')
plt.xlabel('Predicted label')
tick_marks = [0.5, 1.5]
plt.xticks(tick_marks, class_names)
plt.yticks(tick_marks, class_names)</pre></div>



<figure class="wp-block-image size-full"><img decoding="async" width="486" height="452" data-attachment-id="8471" data-permalink="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/output-1-2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2022/05/output-1.png" data-orig-size="486,452" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="output-1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2022/05/output-1.png" src="https://www.relataly.com/wp-content/uploads/2022/05/output-1.png" alt="Confusion matrix of the best-guess random forest model before hyperparameter tuning" class="wp-image-8471" srcset="https://www.relataly.com/wp-content/uploads/2022/05/output-1.png 486w, https://www.relataly.com/wp-content/uploads/2022/05/output-1.png 300w" sizes="(max-width: 486px) 100vw, 486px" /><figcaption class="wp-element-caption">Confusion matrix of the best-guess random forest model</figcaption></figure>



<p>Our best-guess model accurately predicted that 151 passengers would not survive. The dark-blue number in the top-left is the group of titanic passengers that did not survive the sinking, and our model classified them correctly as non-survivors. The green area below shows the passengers who survived the sinking and were correctly classified. The other sections show the number of times our model was wrong. </p>



<p>In total, these results correspond to a model accuracy of 80%. Considering that this was a best-guess model, these results are pretty good. However, we can further optimize these results by using the grid search approach for hyperparameter tuning.</p>



<h3 class="wp-block-heading" id="h-step-5-hyperparameter-tuning-a-classification-model-using-the-grid-search-technique">Step #5 Hyperparameter Tuning a Classification Model using the Grid Search Technique</h3>



<p>By comparing the performance of different model configurations, we can find the best set of hyperparameters that yields the highest accuracy. This approach is a powerful tool for fine-tuning machine learning models and improving their performance. So let&#8217;s get started and see if we can beat the results of our best-guess model using the grid search technique! </p>



<h4 class="wp-block-heading">Training and Tuning the Model</h4>



<p>Next, we will use the grid search technique to optimize a random decision forest model that predicts the survival of Titanic passengers. We&#8217;ll define a grid of hyperparameter values in Python and then use the Scikit-learn library to train and test the model with different hyperparameter configurations. First, we will define a parameter range:</p>



<ul class="wp-block-list">
<li>max_depth = [2, 8, 16]</li>



<li>n_estimators = [64, 128, 256]</li>
</ul>



<p>We leave the other parameters at their default value. In addition, we need to define against which metric we want the grid search algorithm to evaluate the model performance. Since we have no personal preference and our dataset is well-balanced, we choose the mean test score as the evaluation metric. Then we run the grid search algorithm. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Define Parameters
max_depth=[2, 8, 16]
n_estimators = [64, 128, 256]
param_grid = dict(max_depth=max_depth, n_estimators=n_estimators)

# Build the grid search
dfrst = RandomForestClassifier(n_estimators=n_estimators, max_depth=max_depth)
grid = GridSearchCV(estimator=dfrst, param_grid=param_grid, cv = 5)
grid_results = grid.fit(x_train, y_train)

# Summarize the results in a readable format
print(&quot;Best: {0}, using {1}&quot;.format(grid_results.cv_results_['mean_test_score'], grid_results.best_params_))
results_df = pd.DataFrame(grid_results.cv_results_)
results_df</pre></div>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:false,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;null&quot;,&quot;mime&quot;:&quot;text/plain&quot;,&quot;theme&quot;:&quot;3024-day&quot;,&quot;lineNumbers&quot;:false,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Plain Text&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;text&quot;}">Best: [0.79611613 0.78005161 0.79290323 0.81387097 0.82187097 0.81867097 
 0.78818065 0.78816774 0.78498065], using {'max_depth': 8, 'n_estimators': 128}
 
 	mean_fit_time	std_fit_time	mean_score_time	std_score_time	param_max_depth	param_n_estimators	params	split0_test_score				split1_test_score	split2_test_score	split3_test_score	split4_test_score	mean_test_score	std_test_score	rank_test_score
0	0.057045		0.001108		0.005001		0.000001		2				64					{'max_depth': 2, 'n_estimators': 64}	0.824				0.800				0.784				0.774194			0.798387		0.796116	0.016883	4
1	0.112051		0.002088		0.009490		0.000775		2				128					{'max_depth': 2, 'n_estimators': 128}	0.760				0.824				0.784				0.750000			0.782258		0.780052	0.025523	9
2	0.221600		0.003740		0.016487		0.000448		2				256					{'max_depth': 2, 'n_estimators': 256}	0.792				0.824				0.784				0.774194			0.790323		0.792903	0.016756	5
3	0.061998		0.001410		0.005801		0.000400		8				64					{'max_depth': 8, 'n_estimators': 64}	0.784				0.824				0.792				0.806452			0.862903		0.813871	0.028044	3
4	0.122886		0.002652		0.009587		0.000480		8				128					{'max_depth': 8, 'n_estimators': 128}	0.784				0.848				0.808				0.806452			0.862903		0.821871	0.029089	1
5	0.250295		0.007654		0.018557		0.000836		8				256					{'max_depth': 8, 'n_estimators': 256}	0.800				0.824				0.800				0.806452			0.862903		0.818671	0.023797	2
6	0.065602		0.000505		0.005800		0.000399		16				64					{'max_depth': 16, 'n_estimators': 64}	0.736				0.808				0.784				0.766129			0.846774		0.788181	0.037557	6
7	0.127662		0.003297		0.008600		0.004080		16				128					{'max_depth': 16, 'n_estimators': 128}	0.752				0.800				0.784				0.758065			0.846774		0.788168	0.034078	7
8	0.259617		0.003121		0.018873		0.000537		16				256					{'max_depth': 16, 'n_estimators': 256}	0.752				0.784				0.776				0.766129			0.846774		0.784981	0.032690	8</pre></div>



<p>The list above is an overview of the tested model configurations, ranked by their prediction scores. Model number five achieved the best results. The parameters of this model are a maximum depth of 8 and several estimators of 256. </p>



<h4 class="wp-block-heading">Model Evaluation</h4>



<p>We select the best model and use it to predict the test data set. We visualize the results in another confusion matrix. </p>



<div class="wp-block-codemirror-blocks-code-block code-block"><pre class="CodeMirror" data-setting="{&quot;showPanel&quot;:true,&quot;languageLabel&quot;:false,&quot;fullScreenButton&quot;:true,&quot;copyButton&quot;:true,&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text/x-python&quot;,&quot;theme&quot;:&quot;monokai&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:true,&quot;readOnly&quot;:true,&quot;fileName&quot;:&quot;&quot;,&quot;language&quot;:&quot;Python&quot;,&quot;maxHeight&quot;:&quot;400px&quot;,&quot;modeName&quot;:&quot;python&quot;}"># Extract the best decision forest 
best_clf = grid_results.best_estimator_
y_pred = best_clf.predict(x_test)

# Create a confusion matrix
cnf_matrix = confusion_matrix(y_test, y_pred)

# Create heatmap from the confusion matrix
%matplotlib inline
class_names=[False, True] # name  of classes
fig, ax = plt.subplots(figsize=(7, 6))
sns.heatmap(pd.DataFrame(cnf_matrix), annot=True, cmap=&quot;YlGnBu&quot;, fmt='g')
ax.xaxis.set_label_position(&quot;top&quot;)
plt.tight_layout()
plt.title('Confusion matrix')
plt.ylabel('Actual label')
plt.xlabel('Predicted label')
tick_marks = [0.5, 1.5]
plt.xticks(tick_marks, class_names)
plt.yticks(tick_marks, class_names)</pre></div>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="2297" data-permalink="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/image-5-5/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/07/image-5.png" data-orig-size="486,452" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image-5" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/07/image-5.png" src="https://www.relataly.com/wp-content/uploads/2020/07/image-5.png" alt="confusion matrix on the best model returned by the grid search hyperparameter tuning approach in Python" class="wp-image-2297" width="529" height="491" srcset="https://www.relataly.com/wp-content/uploads/2020/07/image-5.png 486w, https://www.relataly.com/wp-content/uploads/2020/07/image-5.png 300w" sizes="(max-width: 529px) 100vw, 529px" /><figcaption class="wp-element-caption">Confusion matrix of the best grid search model</figcaption></figure>



<p>The confusion matrix shows the best model results from the grid search technique. The result is an overall model accuracy of 83,5 %, which shows that the best grid search model outperforms our initial best guess model. This optimal model has correctly classified that 148 passengers would not survive and 76 passengers would survive. In 44 cases, the model was wrong.</p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>This article has shown how we can use grid Search in Python to efficiently search for the optimal hyperparameter configuration of a machine learning model. In the conceptual part, you learned about hyperparameters and how to use grid search to try out all permutations of a predefined parameter grid. </p>



<p>In the hands-on part of this article, we developed a random decision forest that predicts the survival of Titanic passengers using Python and scikit-learn. The grid search technique applies not only to classification models but can also be used to optimize the performance of regression models. First, we developed a baseline model with best-guess parameters. Subsequently, we defined a parameter grid and used the grid search technique to tune the hyperparameters of the random decision forest. In this way, we quickly identified a configuration that outperforms our initial baseline model. In this way, we have demonstrated how Gid Search can help optimize the classification model parameters. </p>



<p>I hope this article was helpful. I am always interested to learn and improve. So, if you have any questions or suggestions, please write them in the comments. </p>



<h2 class="wp-block-heading">Sources and Further Reading</h2>



<div style="display: inline-block;">
  <iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=3030181162&amp;asins=3030181162&amp;linkId=669e46025028259138fbb5ccec12dfbe&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1999579577&amp;asins=1999579577&amp;linkId=91d862698bf9010ff4c09539e4c49bf4&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1839217715&amp;asins=1839217715&amp;linkId=356ba074068849ff54393f527190825d&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
<iframe sandbox="allow-popups allow-scripts allow-modals allow-forms allow-same-origin" style="width:120px;height:240px;" marginwidth="0" marginheight="0" scrolling="no" frameborder="0" src="//ws-eu.amazon-adsystem.com/widgets/q?ServiceVersion=20070822&amp;OneJS=1&amp;Operation=GetAdHtml&amp;MarketPlace=DE&amp;source=ss&amp;ref=as_ss_li_til&amp;ad_type=product_link&amp;tracking_id=flo7up-21&amp;language=de_DE&amp;marketplace=amazon&amp;region=DE&amp;placement=1492032646&amp;asins=1492032646&amp;linkId=2214804dd039e7103577abd08722abac&amp;show_border=true&amp;link_opens_in_new_window=true"></iframe>
</div>



<p class="has-contrast-2-color has-base-3-background-color has-text-color has-background"><em>The links above to Amazon are affiliate links. By buying through these links, you support the Relataly.com blog and help to cover the hosting costs. Using the links does not affect the price.</em></p>



<p></p>
<p>The post <a href="https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/">Tuning Model Hyperparameters with Grid Search at the Example of Training a Random Forest Classifier in Python</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/hyperparameter-tuning-with-grid-search/2261/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">2261</post-id>	</item>
		<item>
		<title>Flight Delay Prediction using Azure Machine Learning</title>
		<link>https://www.relataly.com/predict-flight-delays-azure/57/</link>
					<comments>https://www.relataly.com/predict-flight-delays-azure/57/#comments</comments>
		
		<dc:creator><![CDATA[Florian Follonier]]></dc:creator>
		<pubDate>Tue, 15 Oct 2019 18:10:23 +0000</pubDate>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[Azure Machine Learning]]></category>
		<category><![CDATA[Classification (two-class)]]></category>
		<category><![CDATA[Decision Trees]]></category>
		<category><![CDATA[Logistics]]></category>
		<category><![CDATA[Machine Learning]]></category>
		<category><![CDATA[Risk Management]]></category>
		<category><![CDATA[Use Cases]]></category>
		<category><![CDATA[AI in Logistics]]></category>
		<category><![CDATA[Beginner Tutorials]]></category>
		<category><![CDATA[Classic Machine Learning]]></category>
		<category><![CDATA[Data Pipelines]]></category>
		<category><![CDATA[Supervised Learning]]></category>
		<guid isPermaLink="false">http://www.relataly.com/?p=57</guid>

					<description><![CDATA[<p>If you travel a lot, you&#8217;ve probably already experienced this &#8211; you&#8217;re in a hurry on your way to the airport trying to catch a flight, only to find out that your flight is delayed. Wasn&#8217;t it great to know when a flight will be delayed in advance? We can use past flight delay data ... <a title="Flight Delay Prediction using Azure Machine Learning" class="read-more" href="https://www.relataly.com/predict-flight-delays-azure/57/" aria-label="Read more about Flight Delay Prediction using Azure Machine Learning">Read more</a></p>
<p>The post <a href="https://www.relataly.com/predict-flight-delays-azure/57/">Flight Delay Prediction using Azure Machine Learning</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></description>
										<content:encoded><![CDATA[
<p id="h-if-you-travel-a-lot-you-ve-probably-already-experienced-this-you-re-in-a-total-hurry-on-your-way-to-the-airport-trying-to-catch-a-flight-only-to-find-out-at-the-airport-that-your-flight-is-delayed-anyway-wasn-t-it-great-to-know-in-advance-when-a-flight-is-going-to-be-delayed-this-would-make-travelling-more-relaxed-well-there-is-a-solution-and-it-is-based-on-machine-learning-we-can-use-past-data-on-delayed-flights-to-develop-a-classification-model-that-predicts-flight-delays-more-specifically-we-speak-of-a-statistical-model-that-calculates-the-probability-of-a-certain-flight-being-delayed-or-on-time-in-this-blog-post-on-flight-delay-prediction-i-show-how-to-develop-a-prediction-model-in-the-azure-ml-studio-classic-workbench-that-predicts-whether-a-flight-will-be-more-or-less-than-30-minutes-late-all-you-need-is-a-microsoft-live-account-and-about-30-40-minutes-of-your-time">If you travel a lot, you&#8217;ve probably already experienced this &#8211; you&#8217;re in a hurry on your way to the airport trying to catch a flight, only to find out that your flight is delayed. Wasn&#8217;t it great to know when a flight will be delayed in advance? We can use past flight delay data to develop a classification model that predicts whether a flight will be on time or delayed in the future. This tutorial shows how this works by creating a flight-delay prediction model&nbsp;in the Azure Machine Learning Studio workbench. </p>



<p id="h-if-you-travel-a-lot-you-ve-probably-already-experienced-this-you-re-in-a-total-hurry-on-your-way-to-the-airport-trying-to-catch-a-flight-only-to-find-out-at-the-airport-that-your-flight-is-delayed-anyway-wasn-t-it-great-to-know-in-advance-when-a-flight-is-going-to-be-delayed-this-would-make-travelling-more-relaxed-well-there-is-a-solution-and-it-is-based-on-machine-learning-we-can-use-past-data-on-delayed-flights-to-develop-a-classification-model-that-predicts-flight-delays-more-specifically-we-speak-of-a-statistical-model-that-calculates-the-probability-of-a-certain-flight-being-delayed-or-on-time-in-this-blog-post-on-flight-delay-prediction-i-show-how-to-develop-a-prediction-model-in-the-azure-ml-studio-classic-workbench-that-predicts-whether-a-flight-will-be-more-or-less-than-30-minutes-late-all-you-need-is-a-microsoft-live-account-and-about-30-40-minutes-of-your-time">The model uses a <a href="https://www.relataly.com/category/machine-learning-algorithms/decision-trees/" target="_blank" rel="noreferrer noopener">decision tree algorithm</a> to predict whether a flight will be more or less than 30 minutes late. In this approach, the algorithm searches for patterns in the data of past flight connections and applies these patterns to classify flights into two classes: delayed and not delayed. Travel service providers use similar models to warn customers when a flight is likely to be delayed.</p>



<h2 class="wp-block-heading">What is Flight Delay Prediction?</h2>



<p>Flight delay prediction is the use of data and analytics to forecast whether a flight is likely to be delayed. This information can be used by airlines, airports, and passengers to plan and prepare for potential delays and to make informed decisions about travel plans. Models for predicting flight punctuality typically consider a range of factors, including historical data on past flight delays, weather conditions, the performance of the airline and the specific aircraft involved, and other relevant information. Machine learning algorithms are often used to analyze and process this data, and to generate predictions about the likelihood and duration of flight delays. These predictions can be made in real-time, as the flight is in progress, or in advance, based on the scheduled departure time and other factors.</p>



<h2 class="wp-block-heading">Developing a Flight Prediction Model in Azure Machine Learning</h2>



<p>In the following hands-on tutorial, we will develop a flight prediction model in Azure Machine Learning. To develop the  model, we will carry out the following steps:</p>



<ol class="wp-block-list">
<li><strong>Gather and prepare the data:</strong> We will load data on past flights, including information on their departure and arrival times, the airlines and aircraft involved, the airports and routes, and other relevant factors. This data needs to be cleaned and preprocessed to remove any errors or inconsistencies and to format it in a way that can be used by the machine learning model.</li>



<li><strong>Explore and analyze the data: </strong>This involves using tools and techniques, such as data visualization and statistical analysis, to understand the patterns and trends in the data and to identify any factors that may be associated with flight delays. </li>



<li><strong>Train a machine learning algorithm: </strong>We train a decision forest algorithm on the data to learn the patterns and relationships that exist in the data. </li>



<li><strong>Evaluate the model: </strong>We test our trained model on a separate set of data to see how accurately it can predict flight delays. This can be done using a range of metrics, such as accuracy, precision, and recall, to measure the performance of the model and to identify any areas for improvement.</li>



<li><strong>Deploy and use the model:</strong> We don&#8217;t cover this step explicitly. However, we broadly discuss how we could deploy the model into production. </li>
</ol>



<h2 class="wp-block-heading">Prerequisites: Signing Up for a Free Azure Account</h2>



<p>In order to use the azure machine learning studio, you require access to a valid Azure subscription. Don&#8217;t worry, you can sign up for a free Azure account that offers beginners a sufficient number of credits. Simply follow these steps:</p>



<ol class="wp-block-list">
<li>Go to the Azure website (<a href="https://azure.microsoft.com/" target="_blank" rel="noreferrer noopener">https://azure.microsoft.com/</a>).</li>



<li>Click on the &#8220;Try azure for free&#8221; button in the middle of the page. Then select &#8220;start free&#8221; on the next page.</li>



<li>Enter your email address and password, and create a new Microsoft account, if you don&#8217;t already have one.</li>



<li>Follow the on-screen instructions to complete the sign-up process, including verifying your email address and phone number.</li>



<li>Once your account has been created, you can log in to the Azure portal (<a href="https://portal.azure.com/" target="_blank" rel="noreferrer noopener">https://portal.azure.com/</a>) using your Microsoft account credentials.</li>



<li>From the Azure portal, you can access a range of services and resources, including machine learning, data analytics, and other cloud-based tools and services.</li>
</ol>



<p>Note that the free Azure account includes a limited amount of free credit and services, which you can use to try out Azure and learn more about its capabilities. Once your free credit has been used up, you can choose to upgrade to a paid subscription to continue using Azure.</p>



<h3 class="wp-block-heading" id="h-step-1-access-microsoft-azure-machine-learning-studio">Step #1 Access Microsoft Azure Machine Learning Studio</h3>



<p>This article uses Microsoft&#8217;s data science workbench Azure Machine Learning Studio (classic). There is also a new version of the Machine Learning Studio available, which provides more functionality but works in a similar way. The classic workbench provides comprehensive functions such as creating data pipelines, training and testing machine learning models, and publishing trained models as a web service via an API. </p>



<p>The studio is available via free trial access. You can create a free test account (8h valid) via &#8220;Sign up here&#8221; on <a href="https://azure.microsoft.com/de-de/services/machine-learning-studio/" target="_blank" rel="noreferrer noopener">Azure Machine Learning</a> <a href="https://azure.microsoft.com/de-de/services/machine-learning-studio/" target="_blank" rel="noreferrer noopener">Studio</a> or log in with an existing Microsoft Live account. After the successful login, you will see the experiments section: </p>



<figure class="wp-block-image is-resized"><img decoding="async" data-attachment-id="59" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/image-2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2019/10/image.png" data-orig-size="1452,675" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="image" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2019/10/image.png" src="http://www.relataly.com/wp-content/uploads/2019/10/image-1024x476.png" alt="Welcome Screen in Azure ML Studio Classic" class="wp-image-59" width="768" height="357" srcset="https://www.relataly.com/wp-content/uploads/2019/10/image.png 1024w, https://www.relataly.com/wp-content/uploads/2019/10/image.png 300w, https://www.relataly.com/wp-content/uploads/2019/10/image.png 768w, https://www.relataly.com/wp-content/uploads/2019/10/image.png 1452w" sizes="(max-width: 768px) 100vw, 768px" /><figcaption class="wp-element-caption">Experiments section of the Azure Machine Learning Studio </figcaption></figure>



<h3 class="wp-block-heading" id="h-step-2-importing-training-data-into-azure-ml">Step #2 Importing Training Data into Azure ML</h3>



<p>This tutorial will work with the CSV dataset <a href="http://www.relataly.com/wp-content/uploads/2019/10/FlightDelayData.csv">FlightDelayData.csv</a></p>



<p>After downloading the dataset, you can import it into Azure Machine Learning Studio. Navigate to &#8220;Experiments&#8221; and click on &#8220;+ New&#8221; at the bottom left. On the following page, select &#8220;Dataset&#8221; on the left and then &#8220;Upload Local File.&#8221; Select the file FlightDelayData and confirm the upload. </p>



<figure class="wp-block-image size-large is-resized"><a href="https://ipt.jiveon.com/servlet/JiveServlet/showImage/38-1690-65776/pastedImage_1.png"><img decoding="async" data-attachment-id="1109" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/prediction1/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2019/10/prediction1.png" data-orig-size="2004,956" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="prediction1" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2019/10/prediction1.png" src="https://www.relataly.com/wp-content/uploads/2019/10/prediction1-1024x488.png" alt="Uploading a new dataset" class="wp-image-1109" width="768" height="366" srcset="https://www.relataly.com/wp-content/uploads/2019/10/prediction1.png 1024w, https://www.relataly.com/wp-content/uploads/2019/10/prediction1.png 300w, https://www.relataly.com/wp-content/uploads/2019/10/prediction1.png 768w, https://www.relataly.com/wp-content/uploads/2019/10/prediction1.png 1536w, https://www.relataly.com/wp-content/uploads/2019/10/prediction1.png 2004w" sizes="(max-width: 768px) 100vw, 768px" /></a><figcaption class="wp-element-caption">Uploading a new dataset</figcaption></figure>



<p>Confirm the dialog to access the experiment workspace. Here, you will find a list of different modules (highlighted in light blue) to the left of the workspace. The modules provide all central functions in Azure Machine Learning Studio, such as transforming and exploring the data and using them in machine learning.</p>



<figure class="wp-block-image size-large is-resized"><a href="https://ipt.jiveon.com/servlet/JiveServlet/showImage/38-1690-65777/pastedImage_3.png"><img decoding="async" data-attachment-id="1110" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/prediction2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/prediction2.png" data-orig-size="1128,617" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="prediction2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/prediction2.png" src="https://www.relataly.com/wp-content/uploads/2020/05/prediction2-1024x560.png" alt="The modul tab of Azure ML" class="wp-image-1110" width="768" height="420" srcset="https://www.relataly.com/wp-content/uploads/2020/05/prediction2.png 1024w, https://www.relataly.com/wp-content/uploads/2020/05/prediction2.png 300w, https://www.relataly.com/wp-content/uploads/2020/05/prediction2.png 768w, https://www.relataly.com/wp-content/uploads/2020/05/prediction2.png 1128w" sizes="(max-width: 768px) 100vw, 768px" /></a><figcaption class="wp-element-caption">The module tab of Azure Machine Learning</figcaption></figure>



<h3 class="wp-block-heading" id="h-step-3-exploring-the-data">Step #3 Exploring the Data</h3>



<p>Now that the data set is available in Azure Machine Learning, we will prepare it for its use in our flight delay prediction model. First, we will drag and drop the FlightDelayData dataset from &#8220;Saved Datasets&#8221; into the grey workspace of the experiment. Next, we will visualize the data by right-clicking on FlightDelayData &#8211;&gt; &#8220;dataset&#8221; &#8211;&gt; &#8220;Visualize&#8221; in the grey work area. </p>



<p>Clicking on the individual columns will give you an overview of the data sets&#8217; characteristics and distribution. In the upper left corner, you can see that the dataset contains 135970 entries for flight connections. Each entry or line represents one flight. All flights took place in 2013. Furthermore, the data includes the departure and arrival locations of flights, time and day of departure and arrival, the airline, and the deviation from the planned take-off and landing time.  </p>



<h3 class="wp-block-heading" id="h-step-4-creating-a-data-pipeline">Step #4 Creating a Data Pipeline</h3>



<p>Before we can train the model, we need to split the data into two parts: train and test. We will use the first part of the data to train the Machine Learning model and the second to evaluate its predictions. This approach is known as supervised learning. Search for the &#8220;Split Data module&#8221; in the search list on the left and drag and drop it into the grey workspace to split the data. After this, you can connect the two modules by clicking on the output of the data set (FlightDelayData) and dragging it to the input of the &#8220;Split Data module&#8221; (see screenshot). </p>



<p> Next, we configure the Split Data module. Click on the module and make the following settings on the right side under &#8220;Properties&#8221;: Fraction of rows in the first output dataset: 0.7&nbsp;and Random seed: 123. </p>



<p>In this way, we divide the data randomly in a 70/30 ratio. You can leave the others as they are. </p>



<figure class="wp-block-image size-large is-resized"><a href="https://ipt.jiveon.com/servlet/JiveServlet/showImage/38-1690-65779/pastedImage_1.png"><img decoding="async" data-attachment-id="1112" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/prediction3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/prediction3.png" data-orig-size="628,354" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="prediction3" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/prediction3.png" src="https://www.relataly.com/wp-content/uploads/2020/05/prediction3.png" alt="Splitting the data into train and test" class="wp-image-1112" width="758" height="428" srcset="https://www.relataly.com/wp-content/uploads/2020/05/prediction3.png 628w, https://www.relataly.com/wp-content/uploads/2020/05/prediction3.png 300w" sizes="(max-width: 758px) 100vw, 758px" /></a><figcaption class="wp-element-caption">Splitting the data into train and test</figcaption></figure>



<p>(In practice, the compilation and preparation of the data are much more complex. I have already carried out some steps in advance.)</p>



<h3 class="wp-block-heading" id="h-step-5-creating-a-classification-model">Step #5 Creating a Classification Model</h3>



<p>Now we will create a classification model. Therefore, we will pull further models into the grey area of the workbench. Our model will use a boosted decision tree classifier. We can use this algorithm by dragging the module &#8220;Two-Class Boosted Decision Tree&#8221; into the grey workspace below the other modules. You can leave the settings of the module unchanged. </p>



<p>Next, we select the module &#8220;Train Model&#8221; and drag it into the grey workspace under the other modules. In the workspace, connect the output of the &#8220;Two-Class Boosted Decision Tree&#8221; module to the left input of the &#8220;Train Model&#8221; module.</p>



<p>Remember, we want to predict whether flights will be more or less than 15 minutes late. Select &#8220;Train Model&#8221; in the grey workspace and click on &#8220;Launch Column Selector&#8221; under Properties on the right. In the Column Selector, enter &#8220;ArrDel15&#8221; under &#8220;Column Name&#8221;. This column contains the so-called &#8220;prediction label,&#8221; which is the information on whether flights were more or less than 15 minutes late. Don&#8217;t forget to connect the left output of the Split Data module to the right input of the Train Model. </p>



<p>To evaluate the model&#8217;s predictions later, we will add a &#8220;Score Model.&#8221; We do this by selecting the module &#8220;Score Model&#8221; and dragging it into the workspace below the other modules. Finally, we need to create two connections. First, connect the left input of the &#8220;Score Model&#8221; with the left output of the &#8220;Train Model.&#8221; Second, connect the input node on the right of the &#8220;Score Model&#8221; to the output on the right of &#8220;Split Data,&#8221; which is the 30% of the original data set we use to test the model. </p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="1129" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/pastedimage_31/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_31.png" data-orig-size="705,361" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="pastedImage_31" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_31.png" src="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_31.png" alt="Selecting the prediction label" class="wp-image-1129" width="882" height="452" srcset="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_31.png 705w, https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_31.png 300w" sizes="(max-width: 882px) 100vw, 882px" /><figcaption class="wp-element-caption">Selecting the prediction label</figcaption></figure>



<h3 class="wp-block-heading" id="h-step-6-training-the-model">Step #6 Training the Model</h3>



<p>Before we can train the model, we add the module &#8220;Evaluate Model&#8221; by searching it in the module tab and dragging it into the workspace. Finally, we connect the (left) input of the &#8220;Evaluate Model&#8221; with the output of the &#8220;Score Model.&#8221; </p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="1133" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/pastedimage_22/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_22.png" data-orig-size="620,325" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="pastedImage_22" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_22.png" src="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_22.png" alt="" class="wp-image-1133" width="769" height="404" srcset="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_22.png 620w, https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_22.png 300w" sizes="(max-width: 769px) 100vw, 769px" /><figcaption class="wp-element-caption">Creating a machine learning model</figcaption></figure>



<p>Once we have created the data transformation pipelines, we are ready to train the model. Start the training process by clicking the &#8220;Run button&#8221; in the dark bar at the bottom. It may take a few minutes until the process has finished. Meanwhile, you can monitor the processing progress by the green checkmarks shown on the modules.</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="1132" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/pastedimage_2-2/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_2-2.png" data-orig-size="620,541" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="pastedImage_2-2" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_2-2.png" src="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_2-2.png" alt="Model after successfull training" class="wp-image-1132" width="617" height="539" srcset="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_2-2.png 620w, https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_2-2.png 300w" sizes="(max-width: 617px) 100vw, 617px" /><figcaption class="wp-element-caption">Model after successful training</figcaption></figure>



<h3 class="wp-block-heading" id="h-step-7-evaluating-model-performance">Step #7 Evaluating Model Performance </h3>



<p>So far, we have built a statistical model for flight delay prediction. Of course, we want to know how often our model is right or wrong with the predictions. Evaluating the performance of prediction models is thus an essential step in their development. To evaluate the model performance, right-click on &#8220;Evaluate Model&#8221; -> &#8220;Evaluation results&#8221; -> &#8220;Visualize.&#8221; Below you will find the <em>receiver operating characteristic</em> (ROC) of the trained model:</p>



<figure class="wp-block-image size-large is-resized"><img decoding="async" data-attachment-id="1134" data-permalink="https://www.relataly.com/predict-flight-delays-azure/57/pastedimage_3/#main" data-orig-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_3.png" data-orig-size="619,564" data-comments-opened="1" data-image-meta="{&quot;aperture&quot;:&quot;0&quot;,&quot;credit&quot;:&quot;&quot;,&quot;camera&quot;:&quot;&quot;,&quot;caption&quot;:&quot;&quot;,&quot;created_timestamp&quot;:&quot;0&quot;,&quot;copyright&quot;:&quot;&quot;,&quot;focal_length&quot;:&quot;0&quot;,&quot;iso&quot;:&quot;0&quot;,&quot;shutter_speed&quot;:&quot;0&quot;,&quot;title&quot;:&quot;&quot;,&quot;orientation&quot;:&quot;0&quot;}" data-image-title="pastedImage_3" data-image-description="" data-image-caption="" data-large-file="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_3.png" src="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_3.png" alt="ROC Curve and Results of the Flight Prediction Classifier" class="wp-image-1134" width="464" height="423" srcset="https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_3.png 619w, https://www.relataly.com/wp-content/uploads/2020/05/pastedImage_3.png 300w" sizes="(max-width: 464px) 100vw, 464px" /><figcaption class="wp-element-caption">Metrics used to evaluate the performance of a classification model</figcaption></figure>



<p>Let&#8217;s look at the different metrics at the bottom. </p>



<ul class="wp-block-list">
<li>The test data set contains 40791 flights, 30% of the original data.</li>



<li>The model correctly predicted for 2098 flights that, they would have more than 15 delays (true positives). </li>



<li>The model was wrong in 1310 cases (false positives).</li>



<li>According to the model&#8217;s prediction, six thousand eight hundred twenty-five flights were more than 15 minutes delayed (false negatives). </li>



<li>The model was correct in 30558 cases, estimating that these flights will have less than 15 minutes delays. </li>



<li>Overall, the model is correct in about 80% of the cases (Accuracy = 0.801).</li>
</ul>



<p>Finally, we look at the ROC curve. The curve illustrates the reliability of the model depending on the prediction threshold. The larger the area under the curve, the better the prediction model. The curve is sloped upwards and lies above the grey line, which means that the model works better than random assumptions. The gray diagonal line corresponds to a 50% chance to lie correctly, i.e., easy to guess. With a perfect correct model for every flight, the area would be 1.0. </p>



<h3 class="wp-block-heading">Step #8 Deploying the Model as a Web Service</h3>



<p>Now that we have our model available, of course, we would like to make it accessible to others. Let&#8217;s quickly discuss how we could deploy our model as a web service from the designer.</p>



<p>We won&#8217;t go into too much detail here and will only cover the basic steps for deploying a model. To deploy a machine learning pipeline in Azure Machine Learning, you need to convert the training pipeline into an inference pipeline. The pipeline can process prediction requests in real time or in batch mode. Deploying the model from the designer involves removing the training components, such as the Train Model and Split Data modules, and adding web service inputs and outputs to handle user requests. When you create an inference pipeline, azure ml stores the trained model as a Dataset component in the component palette. From there, you can access it under &#8220;My Datasets.&#8221; The saved trained model is then added to the pipeline, along with the web service input and output components. These components define the points where user data enters the pipeline and where the pipeline returns the results. Once you have deployed the model, other applications and systems can access it via a REST API.</p>



<h2 class="wp-block-heading" id="h-summary">Summary</h2>



<p>We have created a flight delay prediction model in Azure Machine Learning Studio in this article. The model can predict with 80% certainty whether flights on specific routes will be more or less than 15 minutes late. This can help airlines, airports, and passengers to plan and prepare for potential delays and to make informed decisions about travel plans. We have also discussed how we can use the studio designer to deploy our model as web services to provide predictions in real-time or batch mode.</p>



<p>The prediction model is only the first version and still offers room for optimization. One option to further improve the model would be to add features such as the weather, the aircraft type, etc. Another option would be to test different algorithms and hyperparameters. </p>



<p>I hope this article was helpful. If you have remarks or questions, please write them in the comments.</p>
<p>The post <a href="https://www.relataly.com/predict-flight-delays-azure/57/">Flight Delay Prediction using Azure Machine Learning</a> appeared first on <a href="https://www.relataly.com">relataly.com</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://www.relataly.com/predict-flight-delays-azure/57/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">57</post-id>	</item>
	</channel>
</rss>
