<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrew Nguyen on Medium]]></title>
        <description><![CDATA[Stories by Andrew Nguyen on Medium]]></description>
        <link>https://medium.com/@andrewnguyen07?source=rss-b7da2b6ca9c2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iDPFCFvsrOdynw0CWtTBxw.jpeg</url>
            <title>Stories by Andrew Nguyen on Medium</title>
            <link>https://medium.com/@andrewnguyen07?source=rss-b7da2b6ca9c2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:14:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrewnguyen07/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Airbnb Price Prediction: Multilayer Perceptrons with TensorFlow’s Keras API]]></title>
            <link>https://medium.com/data-science/airbnb-price-prediction-multilayer-perceptrons-with-tensorflows-keras-api-9096e7d0c340?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9096e7d0c340</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Mon, 21 Sep 2020 11:48:26 GMT</pubDate>
            <atom:updated>2020-09-21T12:35:37.829Z</atom:updated>
            <content:encoded><![CDATA[<h4>This project is my very first step in Deep Learning field with Neural Networks using TensorFlow and Keras to develop a regression model that is able to make price prediction with MAE as low as possible.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aRJE8p9q4dO_lUfW" /><figcaption>Photo by <a href="https://unsplash.com/@tvick?utm_source=medium&amp;utm_medium=referral">Taylor Vick</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>Context</strong></h3><p>Deep Learning was an indigestible field when I first encountered it during my journey to, hopefully, becoming a Data Scientist. The reason why I initially and biasedly assumed its puzzling complexity was due to the underlying logic and mechanism of such field. However, after taking some time to absorb the great applicability of Deep Learning in general and Neural Networks in particular, I started to grow interest in leveraging it into solving Data Science problems.</p><p>Before jumping into the project, I would like to draw attention to <strong><em>the heated comparison between Machine Learning and Deep Learning </em></strong>that might have flashed through our mind, at least once. In essence, while Machine Learning uses algorithm to decode medium-to-large-scale data to make decisions, Deep Learning creates multi-layer neural networks that take longer time to train to produce higher-accuracy models.</p><p>If you’re keen to give the first shot with Deep Learning, feel free to check out the dataset publicly shared by Kaggle <a href="https://www.kaggle.com/stevezhenghp/airbnb-price-prediction">here</a> and follow the following content.</p><h3>1. Explantory Data Analysis (EDA)</h3><p><em>As a data analyst/data scientist, 70% of our time is and should be well spent on data cleaning and preparation before making it usable for modelling.</em></p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>df = pd.read_csv(&quot;airbnb-price-prediction.csv&quot;)</pre><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqCk-1OxdMnO8pUcI1Xwiw.png" /></figure><p><strong>NOTE</strong>: <em>As this article focuses on developing a neural network model, I will only go through the important actions in EDA but you can check out the full-fledged EDA in my Github repository at the end of the content.</em></p><p>What instantly struck me after loading the dataset is the “amenities” variable, which embeds unstructured values per each row. If it was structured as a JSON field, it would be easier for us to flatten it and parse each sub-variables into different columns. However, from my observation, the variable includes different items of amenities for each listing, so to make it more usable, I decided to <strong>format the values and consolidate the unique ones</strong> to calculate the percentage of amenities of each listing to the total:</p><pre>df.amenities = df.amenities.map(lambda x: &quot;|&quot;.join([i.replace(&quot;}&quot;, &quot;&quot;).replace(&quot;{&quot;, &quot;&quot;).replace(&#39;&quot;&#39;, &quot;&quot;) for i in x.split(&quot;,&quot;)])</pre><pre>df.amenities = df.amenities.map(lambda x: x.split(&quot;|&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*LB_ISOdynfn6Zw2LhKxILg.png" /><figcaption>df.map()</figcaption></figure><pre>amenities_list = list(np.unique(np.concatenate(df.amenities))[1:-2])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q2CvtWR11bZSXt0hO4rftQ.png" /><figcaption>np.unique()</figcaption></figure><pre>df[&#39;amenities_percentage&#39;] = df.amenities.apply(lambda x: len(x)/len(amenities_list)*100)</pre><p>Then, I proceeded to <strong>check whether there is null values</strong> to either remove or fill with actual values:</p><pre>df_new.isna().sum()</pre><pre>#Removing null values that would not help the modelling</pre><pre>df_new = df_new[df_new.bathrooms.notna()]<br>df_new = df_new[df_new.bedrooms.notna()]<br>df_new = df_new[df_new.beds.notna()]<br>df_new = df_new[df_new.host_since.notna()]</pre><pre>#Fill null values with actual values</pre><pre>df_new.host_response_rate = df_new.host_response_rate.fillna(&quot;0%&quot;)<br>df_new.review_scores_rating = df_new.review_scores_rating.fillna(0)</pre><p>Also, as we all might know well, outliers are relatively sensitive to the modelling process, so we should <strong>handle outliers </strong>(either remove or convert) carefully so that the model can learn the data more efficiently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*DzGTHdD7HXsQaSeFDcER8Q.png" /><figcaption>sns.boxplot(df_new.price)</figcaption></figure><p>Since price variable follows a Gaussian Distribution, we will create a function that removes the outliers that fall out of our fixed range:</p><pre>from numpy import mean<br>from numpy import std</pre><pre>def remove_outliers(x):<br>    data_mean = mean(x)<br>    data_std = std(x)<br>    cutoff = data_std*3<br>    lower = data_mean - cutoff<br>    upper = data_mean + cutoff<br>    return lower, upper</pre><pre>lower, upper = remove_outliers(df_new.price)</pre><pre>df_new = df_new.loc[(df_new.price &gt; lower) &amp; (df_new.price &lt; upper)]</pre><h3>2. Feature Engineering and Scaling</h3><p><em>Similar to machine learning’s modelling, feature engineering helps pre-process and convert the raw dataset to a more digestible one to train the model.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FagGZh_x1aLhcVsPVjR_HQ.png" /><figcaption>df.head()</figcaption></figure><p>Except those numeric variables, we need to transform the categorical ones that the model can understand and learn from. In short, we will apply different techniques for binary and multi-class variables: <strong>Label Encoder and OneHotEncoder</strong> respectively. However, it is imperative that we <strong><em>always split the dataset into train and test set </em></strong>before conducting any pre-processing steps, to avoid data leakage during the modelling.</p><pre>from sklearn.model_selection import train_test_split</pre><pre>x = df_new.iloc[:, 1:-1]<br>y = df_new.iloc[:, -1]</pre><pre>x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 42)</pre><p>Then, we import Label Encoder and OneHotEncoder for the transformation: fitting on the train set and transforming on both.</p><pre>from sklearn.preprocessing import LabelEncoder, OneHotEncoder</pre><pre><strong>#Binary variables</strong></pre><pre>le = LabelEncoder()</pre><pre>binary_var = [&#39;cleaning_fee&#39;, &#39;host_has_profile_pic&#39;, &#39;host_identity_verified&#39;, &#39;instant_bookable&#39;]</pre><pre>for i in binary_var:<br>    le.fit(x_train[i])<br>    x_train[i] = le.transform(x_train[i])<br>    x_test[i] = le.transform(x_test[i])</pre><pre><strong>#Multi-category variables</strong></pre><pre>oe = OneHotEncoder(sparse=False, handle_unknown = &#39;error&#39;)</pre><pre>oe.fit(x_train[[&#39;property_type&#39;, &#39;room_type&#39;, &#39;bed_type&#39;, &#39;cancellation_policy&#39;, &#39;city&#39;]])</pre><pre>#Transform the train set</pre><pre>multi = oe.transform(x_train[[&#39;property_type&#39;, &#39;room_type&#39;, &#39;bed_type&#39;, &#39;cancellation_policy&#39;, &#39;city&#39;]])<br>df_multi = pd.DataFrame(index = x_train.index, data=multi, columns=oe.get_feature_names([&#39;property_type&#39;, &#39;room_type&#39;, &#39;bed_type&#39;, &#39;cancellation_policy&#39;, &#39;city&#39;]))<br>x_train = pd.concat([x_train, df_multi], axis=1)<br>x_train.drop(columns=[&#39;property_type&#39;, &#39;room_type&#39;, &#39;bed_type&#39;, &#39;cancellation_policy&#39;, &#39;city&#39;], inplace=True)</pre><pre>#Transform the test set</pre><pre>multi_test = oe.transform(x_test[[&#39;property_type&#39;, &#39;room_type&#39;, &#39;bed_type&#39;, &#39;cancellation_policy&#39;, &#39;city&#39;]])<br>df_multi_test = pd.DataFrame(index = x_test.index, data=multi_test, columns=oe.get_feature_names([&#39;property_type&#39;, &#39;room_type&#39;, &#39;bed_type&#39;, &#39;cancellation_policy&#39;, &#39;city&#39;]))<br>x_test = pd.concat([x_test, df_multi_test], axis=1)<br>x_test.drop(columns=[&#39;property_type&#39;, &#39;room_type&#39;, &#39;bed_type&#39;, &#39;cancellation_policy&#39;, &#39;city&#39;], inplace=True)</pre><p>Besides, as each variable has a different range of data, we need to apply scaling to independent variables so that the model can learn the data faster and more efficiently. In this case, I chose <strong>MinMaxScaler</strong> to compress the data to the range of (0,1), which will be useful to the algorithms we will be using in the following section:</p><pre>from sklearn.preprocessing import MinMaxScaler</pre><pre>mn = MinMaxScaler()</pre><pre>x_train_scaled = pd.DataFrame(mn.fit_transform(x_train), columns = x_train.columns)<br>x_test_scaled = pd.DataFrame(mn.fit_transform(x_test), columns = x_test.columns)</pre><p>Alright, we are all set!</p><h3>3. Neural Network Modelling</h3><p><em>What is Neural Networks and why do we need to combine modelling and optimization concurrently?</em></p><p>Before jumping into what Neural Networks is, I would like to highlight the convention that we just don’t stop at modelling phase; rather, <strong><em>it’s a continuous procedure of building the model and testing different parameters </em></strong>that produce the model with the highest accuracy.</p><p>Back to the concept of Neural Networks, in short:</p><blockquote>A neural network is a series of algorithms that endeavours to recognize underlying relationships in a set of data through a process that mimics the way the human brain operates. — Investopedia.</blockquote><p>If you want a more deep-dive into the concept, please check out the series of videos by 3Blue1Brown <a href="https://www.youtube.com/watch?v=aircAruvnKk&amp;list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi">here</a> which provides a full-fledged explanation on the underlying items of a neural network.</p><p>In Deep learning, particularly Neural Networks, there are 3 common standard models that we use to make predictions: <strong>Multilayer Perceptrons (MLP)</strong>, <strong>Convolutional Neural Networks (CNN)</strong> and <strong>Recurrent Neural Networks (RNN)</strong>. For this project, I’ve started off with MLP to acquire the underlying concepts in deep learning, but please look out for my upcoming projects that tackles data science problems with a more advanced model.</p><p>So, what exactly is MLP and what does it do to make predictions?</p><p>By definitions,</p><blockquote>A Multilayer Perceptron model, or MLP for short, is a standard fully connected neural network model. It is <strong>comprised of layers of nodes</strong> where each node is connected to all outputs from the previous layer and the output of each node is connected to all inputs for nodes in the next layer. — Machinelearningmastery.com</blockquote><p>For easier visualization,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*HdgZYIbLq06G7Up8.png" /><figcaption>Image source: ResearchGate</figcaption></figure><p>TensorFlow and Keras is an open-source library that is able to perform various tasks in deep learning, namely regression and classification. Because of its complexity, several steps need to be followed:</p><ol><li>Define the model</li><li>Compile the model</li><li>Fit the model</li><li>Evaluate the model</li><li>Make a prediction</li></ol><p>To explain in more details, let’s have a look at the full-step implementation of an MLP model as below:</p><pre>from tensorflow.keras import Sequential<br>from tensorflow.keras.layers import Dense, Dropout<br>from tensorflow.keras.callbacks import EarlyStopping</pre><pre><strong>#Step1. Define the model</strong></pre><pre>model = Sequential()</pre><pre>model.add(Dense(16, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;, input_shape = (x_train_scaled.shape[1],)))<br>model.add(Dense(8, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;))<br>model.add(Dense(1))</pre><pre><strong>#Step2. Compile the model</strong></pre><pre>model.compile(optimizer = &#39;adam&#39;, loss = &#39;mse&#39;, metrics = &#39;mae&#39;)</pre><pre><strong>#Step3. Fit the model</strong></pre><pre>history = model.fit(x_train_scaled, y_train, validation_data=(x_test_scaled, y_test), epochs=50,batch_size=64, verbose=0)</pre><pre><strong>#Step4.1 Evaluate the model</strong></pre><pre>loss, mae = model.evaluate(x_test_scaled, y_test)</pre><pre><strong>#Step4.2 Plot the learning curve</strong></pre><pre>plt.plot(history.history[&#39;loss&#39;], label=&#39;train&#39;)<br>plt.plot(history.history[&#39;val_loss&#39;], label=&#39;val&#39;)<br>plt.show()</pre><p>(1) — Define the model:</p><ul><li><strong>Type of Model</strong>: we can choose either <strong>Sequential or Functional Model API </strong>from TensorFlow. While Sequential Model is the simplest model to implement where it provides a “sequential” path with layers after layers in a linear manner, Functional Model is a more complex and yet flexible model where we need to manually specify the input and output layers.</li><li><strong>Number of nodes</strong>: it depends on how complex you want your model to be. There’s no “one size fit all” option but rather we need to test and learn to see how many nodes per each layer produces the highest accuracy.</li><li><strong>Activation</strong>: for each node in each layer, the neural network calculates the weighted sum of the inputs (and adds a bias) then decides whether it should “activate” the node or not. This means the weighted sum should pass a certain threshold for the node to be “activated”. To find the bounds, we need to determine the activation function that helps define the upper and lower range of the bounds.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/0*PNlGpyWCRf1p8Bs0.gif" /><figcaption>Image source: StackExchange</figcaption></figure><ul><li><strong>Initializer</strong>: as seen from above, initializers help define the way to set the initial random weights (w) of the input layers. There are a number of different initializers that go well with different activation functions, which we will test in the following content.</li></ul><p>(2) — Compile the model:</p><ul><li><strong>Optimizer</strong>: optimizer helps change the attributes of the neural network (e.g. weights, learning rates, etc.) in order to reduce the losses of the model as much as possible. Similar to activation and initializer, there are a handful of optimizers that we should test out to find which produces the model with the highest accuracy.</li><li><strong>Loss</strong>: as the name tells, loss function indicates the method that the model uses to optimize towards in order to reduce the error. Technically, loss is used to calculate the gradients and gradients are used to update the weights of the neural network.</li><li><strong>Metrics</strong>: depending on the type of model we build (e.g. regression, classification), we will choose the relevant metric to evaluate how well the model is trained (e.g. MAE/MSE/RMSE for regression and Accuracy for classification)</li></ul><p>(3) — Fit the model:</p><ul><li><strong>Epochs</strong>: the number of epochs is the number of complete passes through the entire example in the training set. For example, if we set the number of epochs to 5, it means the training set will be looped 5 times before the model produces the final result.</li><li><strong>Batch_size</strong>: batch size is the number of samples in an epoch used to estimate model error before the model gets updated. For example, if we set the batch size to 32, it means 32 samples of the training set will be used to train the model and update the model. Then, the next 32 samples will be used until no samples are left in an epoch. The procedure will be repeated if we have more than 1 epoch.</li></ul><p>(4) — Evaluate the model:</p><ul><li><strong>.evaluate()</strong>: we will call this function on the test set to print out the error value as well as the metrics we want the model to optimize for.</li><li><strong>Learning curve</strong>: I suggest we should draw the learning curve for each model we test, as it’s important to see how the model is trained through each epoch and whether overfitting or underfitting occurs to the model.</li></ul><p>Alrighty, that’s all the core parameters that we should be familiar in neural networks. Now let’s print out the result and the learning curve of the 1st-trial model above.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FPToVwBoQy8qrsCcbUIgbw.png" /></figure><p>As seen, we achieved the MAE of 0.3356 with the setting of the above model. Let’s set this number as the benchmark and see if we can get a smaller MAE as we optimize the model.</p><h3>4. Neural Network Optimization</h3><p>A quick summary of all the optimization methods I will be using below for your reference:</p><ol><li>Neural Networks with Feature Selection (Correlation Heatmap/PCA)</li><li>Neural Networks with additional layers (increase model complexity)</li><li>Neural Networks with different optimizers</li><li>Neural Networks with higher epochs (Early Stopping)</li><li>Neural Networks with Regularization (DropOut and L1/L2)</li><li>Neural Networks with different activation and initializer</li><li>Neural Networks with smaller batch size</li></ol><p>For (1) method, I wanted to see if reducing the number of independent variables (features) or selecting the more important ones helps improve the model or not. Two options I relied on are Correlation Heatmap (manual selection) and PCA (machine-learned selection):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*Mvbt5PqLmv324A-6L80sCQ.png" /><figcaption>df.corr()</figcaption></figure><p>As you can see, not all features are highly correlated with the target variable (price) based on the colour scale. Therefore, I’ve selected only the variables that has better correlation with the target (highly positive/negative) but it seems that the model did not improve any better: MAE &gt; the benchmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zO6wd_weDtpAuIP4as8qAw.png" /><figcaption>Model with Correlation HeatMap: MAE = 0.3544 (&gt; benchmark = 0.3356)</figcaption></figure><p>With PCA, the model did not improve much either, but MAE of this model is better than that we manually selected the features:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bhxwuWN3KjLGTj9oXw80NQ.png" /><figcaption>Model with PCA: MAE = 0.3475 (&gt; benchmark = 0.3356)</figcaption></figure><p>For (2) method, I wanted to see if <strong>increasing model complexity by adding several additional layers</strong> would help decrease the MAE value or not.</p><pre>#Step1. Define the model4</pre><pre>model4 = Sequential()</pre><pre>model4.add(Dense(32, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;, input_shape = (x_train_scaled.shape[1],)))<br>model4.add(Dense(16, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;))<br>model4.add(Dense(8, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;))<br>model4.add(Dense(8, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;))<br>model4.add(Dense(1))</pre><pre>#Step2 - 4 follows the same as the 1st model</pre><p>If the 1st model has only 2 hidden layers with 16 and 8 nodes respectively, I added 2 additional layers on top of the existing and also increased the number of nodes. As below, the model has slightly improved compared to the above methods, but still not significant enough compared to the benchmark.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zZhqHpTQtdXA3l-MxnoO3g.png" /><figcaption>Additional hidden layers added: MAE = 0.3358 (&gt; benchmark = 0.3356)</figcaption></figure><p>For (3) method, I wanted to <strong>test a different optimizer</strong> other than the usual “adam” that is commonly recommended: “rmsprop”. No improvement was seen but it is remarkable that the model fluctuates often during the training (as you can see from the orange line — evaluation on the test set):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAAj_QrmAyfCu_WPySxMDg.png" /><figcaption>Model with optimizer = “rmsprop”: MAE= 0.3375 (&gt; benchmark = 0.3356)</figcaption></figure><p>For (4) method, the <strong>number of epochs</strong> might influence on the result of the model. If you’re familiar with machine learning, you will have the same concern as mine — “<em>How many epochs are enough to train the model?</em>” Frankly speaking, we can’t tell the exact number rather than test and learn. However, Keras comes up <strong>EarlyStopping</strong> which helps stop the model from further looping/training that might lead to overfitting.</p><p>For implementation, we just need to define the variable of EarlyStopping and set the “patience” as the threshold that the model will stop learning if passing:</p><pre>es = EarlyStopping(monitor = &#39;val_loss&#39;, patience=5)</pre><pre>history = model6.fit(x_train_scaled, y_train, validation_data=(x_test_scaled, y_test), epochs=200, batch_size=64, verbose=0, callbacks = [es])</pre><p>If you see above, I set monitor = ‘val_loss’ and patience = 5, meaning if the val_loss value (test set) is higher than loss value (train set) after 5 consecutive epochs, the model will stop learning. As below, the model stops at the 20+ epochs. This method not only <strong><em>prevents the model from overfitting</em></strong> but also <strong><em>improves the runtime </em></strong>of the model significantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HB33wWbdYykfR1GhH8-szw.png" /><figcaption>Model with EarlyStopping: MAE = 0.3371 (&gt; benchmark = 0.3356)</figcaption></figure><p>For (5) method, <strong>regularization</strong> is a technique that makes modifications to the model as it learns in order to generalize better. This is achieved by minimizing the out-of-sample test error as the model learns, which also helps reduce overfitting. You might have heard of “<strong>L1/L2 regularizer</strong>” in machine learning, which shrinks the features, but we also have another common regularizer in neural network — <strong>DropOut.</strong> Let’s see which performs better with our current dataset:</p><pre>#Step1. Define the model7</pre><pre>model7 = Sequential()</pre><pre>model7.add(Dense(32, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;, input_shape = (x_train_scaled.shape[1],)))<br>model7.add(Dense(16, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;))<br>model7.add(Dropout(0.3))<br>model7.add(Dense(8, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;))<br>model7.add(Dropout(0.3))<br>model7.add(Dense(8, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;))<br>model7.add(Dropout(0.3))<br>model7.add(Dense(1))</pre><pre>#Step 2 - 4 follows the same as the 1st model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pKs2bICRysu3pBOIOQGgWA.png" /><figcaption>Model with DropOut: MAE = 0.3660 (&gt; benchmark = 0.3356)</figcaption></figure><pre>#Step1. Define the model8</pre><pre>model8 = Sequential()</pre><pre>model8.add(Dense(32, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;, input_shape = (x_train_scaled.shape[1],)))<br>model8.add(Dense(16, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;, kernel_regularizer = &#39;l1&#39;))<br>model8.add(Dense(8, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;, kernel_regularizer = &#39;l1&#39;))<br>model8.add(Dense(8, activation = &#39;relu&#39;, kernel_initializer = &#39;he_normal&#39;, kernel_regularizer = &#39;l1&#39;))<br>model8.add(Dense(1))</pre><pre>#Step 2 - 4 follows the same as the 1st model</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aa3ON-odO5zPPGjUaTHqFA.png" /><figcaption>Model with L1 Regularizer: MAE = 0.3344 (&lt; benchmark = 0.3356)</figcaption></figure><p>Voila! Finally, the model has improved, even slightly significantly as compared to the 1st model thanks to L1 Regularizer!</p><p>For (6) method, testing <strong>different combinations of activations and initializers </strong>is a good and easy way to see if the model improves. Below are the common combinations used in practice:</p><ol><li>activation = ‘sigmoid’, kernel_initializer = ‘glorot_normal’</li><li>activation = ‘relu’, kernel_initializer = ‘he_uniform’</li></ol><p>However, with this dataset, no improvement is seen, so we can pass this method.</p><p>Moving to the last one, it is recommended to <strong>test smaller batch size</strong> as we optimize the model, since smaller batch size offers better regularizing effect/lower generalization error as well as improve the runtime.</p><p>Voila! That’s the end of this project — Airbnb Price Prediction with TensorFlow’s Keras API. I hope you find this article useful and easy to follow.</p><p>Do look out for my <strong>upcoming projects</strong> in Data Science and Machine Learning in the near future! In the meantime feel free to check out my Github here for the complete repository:</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9096e7d0c340" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/airbnb-price-prediction-multilayer-perceptrons-with-tensorflows-keras-api-9096e7d0c340">Airbnb Price Prediction: Multilayer Perceptrons with TensorFlow’s Keras API</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[E-commerce Sales Reporting: ERR Diagram, SQL Processing and Data Studio Dashboard]]></title>
            <link>https://medium.com/data-science/e-commerce-sales-reporting-err-diagram-sql-processing-and-data-studio-dashboard-2500e8f79af?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/2500e8f79af</guid>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[reporting]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[dashboard]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Sun, 23 Aug 2020 09:50:27 GMT</pubDate>
            <atom:updated>2020-08-23T13:40:56.858Z</atom:updated>
            <content:encoded><![CDATA[<h4>This project aims to walk you through how to leverage SQL in relationship mapping and data processing with multiple datasets, and to create an automated reporting dashboard with the help of Data Studio</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pjv6B3Qgw97XV03b" /><figcaption>Photo by <a href="https://unsplash.com/@blakewisz?utm_source=medium&amp;utm_medium=referral">Blake Wisz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>SQL</strong> is one of the essential languages that every data analyst should be familiar with in order to store, manipulate and retrieve data in a relational database. Indeed, there are a number of various Relational Database Management Systems (RDMS) that use SQL as their standard language, namely MySQL, Oracle, SQL Server, etc.</p><p>That being said, this project aims to boost my capability in using SQL to the max to <strong>explore and manipulate multiple datasets of an e-commerce company.</strong> It’s not just limited to data processing; I’ve decided to expand the scope of this project to scale the applicability of structured data to visualization by plugging into Data Studio to build a reporting dashboard.</p><p>If you’re keen, feel free to check out the dataset provided publicly <a href="https://www.kaggle.com/olistbr/brazilian-ecommerce?select=olist_order_payments_dataset.csv">here</a> at Kaggle. Below is a quick summary of the key highlights in this project:</p><ol><li>Dataset Relationship Mapping with ERR Diagram</li><li>SQL Processing to store data in a centralized database</li><li>Reporting Dashboard with Data Studio</li></ol><h3>1. Dataset Relationship Mapping</h3><p><em>How should we handle multiple datasets that share relationships with one another?</em></p><p>If you refer to the database provided by Kaggle, there are 7 to 8 separate datasets that represents an e-commerce sales report: order, customer, order_items, payment, delivery, etc. Prior to data processing, we need to identify the relationship of all datasets with one another to avoid mis-mapping that may result in data loss.</p><p>Take “order” and “customer” datasets as an example, one customer can have 0 or multiple orders (one customer_id for different order_id), but one order is only tied to one customer only (one order_id for one customer_id).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9AavAGTblK7Bj5KaO1HNDQ.png" /><figcaption>order dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*7kh0uTv70ugqEMjReF9p7w.png" /><figcaption>customer dataset</figcaption></figure><p>MySQL comes with the built-in function of building an ERR Diagram that allows us to map and draw the relationship of the datasets with one another visually. So what is ERR Diagram?</p><blockquote><strong>Entity Relationship Diagram</strong> (ER) displays the relationships of entity set stored in a database. In other words, we can say that ER diagrams help you to explain the logical structure of databases — <a href="https://www.guru99.com/er-diagram-tutorial-dbms.html">Guru99.com</a></blockquote><blockquote><strong>Enhanced Entity Relationship</strong> <strong>Diagram</strong> (EER) is basically an expanded upon version of ER diagrams. EER models are helpful tools for designing databases with high-level models. With their enhanced features, you can plan databases more thoroughly by delving into the properties and constraints with more precision — <a href="https://cacoo.com/blog/er-diagrams-vs-eer-diagrams-whats-the-difference/">Cacoo.com</a></blockquote><p>To provide a more visual example,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/0*K0jVSVJ7Clea3I3y.png" /><figcaption>Image credit: <a href="https://www.visual-paradigm.com/guide/data-modeling/what-is-entity-relationship-diagram/">https://www.visual-paradigm.com/guide/data-modeling/what-is-entity-relationship-diagram/</a></figcaption></figure><p>The relationships of the datasets to one another are represented by a system of notation called crow’s food notation as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/0*ObpJz15yoTphwpP7.png" /><figcaption>Image credit: <a href="https://cacoo.com/blog/er-diagrams-vs-eer-diagrams-whats-the-difference/">https://cacoo.com/blog/er-diagrams-vs-eer-diagrams-whats-the-difference/</a></figcaption></figure><p>Essentially, ERR Diagram helps us understand the relationship of the datasets better so that we can proceed with data processing more efficiently.</p><p>With this project, I have selected only 5 datasets for the sake of simplicity and the relationships can be easily understood as below ERR Diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*7Nex40rK1Vmih3lQLChF4Q.png" /></figure><ul><li>(1) customers and orders: 1 customer can have multiple orders, so the notation styling should be “one or many”.</li><li>(2) orders and order_items: 1 order can have multiple order_items, which is “one or many” again.</li><li>(3) orders and payment: 1 order can only have 1 payment, “one and only one” styling.</li><li>(4) order_items and products: similarly, 1 order item is tied to 1 product only, meaning “one and only one” styling.</li></ul><h3>2. SQL Processing</h3><p><em>What is SQL Processing and how does SQL help to convert raw data to a more structured and usable format?</em></p><p>For a formal definition of SQL processing,</p><blockquote><strong>SQL processing</strong> is the parsing, optimization, row source generation, and execution of a SQL statement. Depending on the statement, the database may omit some of these stages — <a href="https://docs.oracle.com/database/121/TGSQL/tgsql_sqlproc.htm#TGSQL176">Oracle</a></blockquote><p>Essentially, we import the raw database and manipulate the cross-table data to convert it into one (or many) structured database which is digestible and easy to understand and scale.</p><p>If you refer back to the ERR Diagram above, we are able to join all the datasets together into one database as a centralized hub for reference before conducting further manipulation. You can join and manipulate from one centralized hub, but I suggest to <strong>separate these steps</strong> as it’s easier to <strong>import future data into the workflow</strong> with the hub before processing it together with the existing data.</p><p>Moving to the joining process, as the relationship tells, <strong>JOIN</strong> (aka INNER JOIN) or <strong>LEFT JOIN </strong>can be used depending on how you want your structured database looks like. For JOIN syntax, it maps only the values that exist between 2 datasets and removes those that only appear in either. For LEFT JOIN, apart from mapping the connected values, it also includes the values from the “left” dataset that do not exist in the other.</p><p>In my datasets, I used <strong>JOIN</strong> for (1) to only take the values that exist in both datasets (customers and orders) while <strong>LEFT JOIN</strong> for (2), (3), and (4) to also return those values that do not appear in the other dataset. Reason being for LEFT JOIN in this case is to identify the “null” values that infer the missing information from the input data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-H1CiYgaNYL3zJ4bgaJjhw.png" /><figcaption>SQL query in MySQL</figcaption></figure><p>Some key highlights from the SQL statement:</p><ul><li>CREATE TABLE: this is to create a centralized database as a hub which I shared previously is necessary for future data input.</li><li>TIMESTAMPDIFF: this is to convert the timestamp-formatted values to our preferable time indicators (e.g. hours, minutes). In this case, I converted the raw values to “minutes” and then divide by 60 divided by 24 to acquire the number of days.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LCBttpV7SCX_8fwSLT0P4Q.png" /></figure><p>After creating a centralized raw database, I proceeded to convert the data into a more structured and usable format, namely:</p><ul><li>Timestamp columns (e.g. order_approved_at, order_delivered_carrier): for example, I want to calculate the number of days from approving the order to delivering it to the carrier.</li><li>Price columns (e.g. unit price, shipping fee): I want to calculate the total price per order</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3zhtayMcViXLLd8wisxYow.png" /></figure><p>The key highlight from this SQL Statement is <strong>GROUP BY</strong>. When selecting both text and aggregation (e.g. sum, subtract, multiply, etc.), we need to use GROUP BY to arrange identical data into groups. For example, we might have multiple order_ids with the same values, so grouping by order_ids to consolidate the total price from multiple order_ids into one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*da4iXlo_7Xyr__YlOiGFbg.png" /></figure><p>We can further drill down the database to generate the columns and values that align with our business objective.</p><h3>3. Data Studio Dashboard</h3><p><em>What is Data Studio and how does it help to build a visually engaging reporting dashboard?</em></p><p>After processing the database, we might want to interpret the data visually to conduct analysis and reporting. In fact, there is a variety of platforms that provide visualization services with the integration of relational database systems, namely Tableau, Datorama and Data Studio. In this case, I used Data Studio as it has the option of integrating with MySQL as well as is easy to use and conduct further processing in the dashboard which also uses SQL as the standard language.</p><p>I will not go into details of how to use the platform as it’s pretty straightforward and you should play around based on your needs: <a href="https://datastudio.google.com/">https://datastudio.google.com/</a>.</p><p>A quick snapshot of my reporting dashboard and key analysis highlights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*C9aka1Wn3zliD9vWS4hA1w.png" /></figure><ul><li>Total revenue (both gross and net) around $12–14M, but “tracked_gross_revenue” is only $500k, which infers there’s a vast amount of missing revenue that was not tracked properly in the input data.</li><li>Delivery process: while the average estimated delivery day is 23, the actual delivery day only takes 12 days. This explains why the delivery lags (difference between estimated and actual delivery days) is a negative number.</li><li>Approval to Delivery duration: it takes less than 1 day to approve the order, less than 3 days to ship the order to the carrier, and around 9 days for the order to reach the customers.</li><li>Product information: the average product name length is 6 characters, description length is 103, and the total quantity of photos in the e-com site is 27k.</li><li>Revenue over time: from 2016 to 2018, the revenue started to rise from March 2017 and continued to stabilize ever since.</li><li>Geo performance: the majority of revenue came from South America cities, but a positive trend was seen as the e-com site is widely used globally.</li><li>Product performance: within top 10 product categories, health &amp; beauty was the most purchased among all.</li><li>Payment type: credit card accounted for 74% of all payment types, indicating that this is the main method of payment.</li></ul><p>Voila! That’s the end of this project — E-commerce Sales Reporting. I hope you find this article useful and easy to follow.</p><p>Do look out for my <strong>upcoming projects</strong> in Data Science and Machine Learning in the near future! In the meantime feel free to check out my Github here for the complete repository:</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2500e8f79af" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/e-commerce-sales-reporting-err-diagram-sql-processing-and-data-studio-dashboard-2500e8f79af">E-commerce Sales Reporting: ERR Diagram, SQL Processing and Data Studio Dashboard</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Customer Segmentation: K-Means Clustering & A/B Testing]]></title>
            <link>https://medium.com/data-science/customer-segmentation-k-means-clustering-a-b-testing-bd26a94462dd?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd26a94462dd</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[k-means]]></category>
            <category><![CDATA[segmentation]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[clustering]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Sun, 16 Aug 2020 10:05:29 GMT</pubDate>
            <atom:updated>2020-08-16T11:34:53.902Z</atom:updated>
            <content:encoded><![CDATA[<h4>This project aims to study customer behaviours on digital platforms by grouping customers without any prior knowledge and conduct A/B Testing that helps boost business performance.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dkiQNjaQhr0CvmoE" /><figcaption>Photo by <a href="https://unsplash.com/@nicotitto?utm_source=medium&amp;utm_medium=referral">nrd</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Context</h3><p>I have been working in Advertising, specifically Digital Media and Performance, for nearly 3 years and customer behaviour analysis is one of the core concentrations in my day-to-day job. With the help of different analytics platforms (e.g. Google Analytics, Adobe Analytics), my life has been made easier than before since these platforms come with the built-in function of segmentation that analyses user behaviours across dimensions and metrics.</p><p>However, despite the convenience provided, I was hoping to <strong><em>leverage Machine Learning to do customer segmentation</em></strong> that can be <strong><em>scalable and applicable</em></strong> to other optimizations in Data Science (e.g. A/B Testing). Then, I came across the dataset provided by Google Analytics for a Kaggle competition and decided to use it for this project.</p><p>Feel free to check out the dataset <a href="https://www.kaggle.com/c/ga-customer-revenue-prediction/data">here</a> if you’re keen! Beware that the dataset has several sub-datasets and <strong><em>each has more than 900k rows</em></strong>!</p><h3>A. Explanatory Data Analysis (EDA)</h3><p><em>This always remain an essential step in every Data Science project to ensure the dataset is clean and properly pre-processed to be used for modelling.</em></p><p>First of all, let’s import all the necessary libraries and read the csv file:</p><pre>import pandas as pd<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import seaborn as sns</pre><pre>df_raw = pd.read_csv(&quot;google-analytics.csv&quot;)<br>df_raw.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1001/1*Ovon3QYB_zYcT_zDBdILig.png" /></figure><h4>1. Flatten JSON Fields</h4><p>As you can see, the raw dataset above is a bit “messy” and not digestible at all since some variables are formatted as JSON fields which compress different values of different sub-variables into one field. For example, for geoNetwork variable, we can tell that there are several sub-variables such as continent, subContinent, etc. that are grouped together.</p><p>Thanks to the help of a Kaggler, I was able to convert these variables to a more digestible ones by <strong>flattening those JSON fields</strong>:</p><pre>import os<br>import json<br>from pandas import json_normalize</pre><pre>def load_df(csv_path=&quot;google-analytics.csv&quot;, nrows=None):<br>    json_columns = [&#39;device&#39;, &#39;geoNetwork&#39;, &#39;totals&#39;, &#39;trafficSource&#39;]<br>    df = pd.read_csv(csv_path, converters={column: json.loads for column in json_columns},dtype={&#39;fullVisitorID&#39;:&#39;str&#39;}, nrows=nrows)<br>    for column in json_columns:<br>        column_converted = json_normalize(df[column])<br>        column_converted.columns = [f&quot;{column}_{subcolumn}&quot; for subcolumn in column_converted.columns]<br>        df = df.drop(column, axis=1).merge(column_converted, right_index=True, left_index=True)<br>    return df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*11ddVzt9cpYM5u09k89wJA.png" /></figure><p>After flattening those JSON fields, we are able to see a much cleaner dataset, especially those JSON variables split into sub-variables (e.g. device split into device_browser, device_browserVersion, etc.).</p><h4>2. Data Re-formatting &amp; Grouping</h4><p>For this project, I have chosen the variables that I believe have better impact or correlation to the user behaviours:</p><pre>df = df.loc[:,[&#39;channelGrouping&#39;, &#39;date&#39;, &#39;fullVisitorId&#39;, &#39;sessionId&#39;, &#39;visitId&#39;, &#39;visitNumber&#39;, &#39;device_browser&#39;, &#39;device_operatingSystem&#39;, &#39;device_isMobile&#39;, &#39;geoNetwork_country&#39;, &#39;trafficSource_source&#39;, &#39;totals_visits&#39;, &#39;totals_hits&#39;, &#39;totals_pageviews&#39;, &#39;totals_bounces&#39;, &#39;totals_transactionRevenue&#39;]]</pre><pre>df = df.fillna(value=0)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qsIFEOlOTbSBp9KzzoeuYg.png" /></figure><p>Moving on, as the new dataset has fewer variables which, however, vary in terms of data type, I took some time to analyze each and every variable to ensure the data is “clean enough” prior to modelling. Below are some quick examples of un-clean data to be cleaned:</p><pre><strong>#Format the values</strong><br>df.channelGrouping.unique()<br>df.channelGrouping = df.channelGrouping.replace(&quot;(Other)&quot;, &quot;Others&quot;)</pre><pre><strong>#Convert boolean type to string </strong><br>df.device_isMobile.unique()<br>df.device_isMobile = df.device_isMobile.astype(str)<br>df.loc[df.device_isMobile == &quot;False&quot;, &quot;device&quot;] = &quot;Desktop&quot;<br>df.loc[df.device_isMobile == &quot;True&quot;, &quot;device&quot;] = &quot;Mobile&quot;</pre><pre><strong>#Categorize similar values</strong></pre><pre>df[&#39;traffic_source&#39;] = df.trafficSource_source</pre><pre>main_traffic_source = [&quot;google&quot;,&quot;baidu&quot;,&quot;bing&quot;,&quot;yahoo&quot;,...., &quot;pinterest&quot;,&quot;yandex&quot;]</pre><pre>df.traffic_source[df.traffic_source.str.contains(&quot;google&quot;)] = &quot;google&quot;<br>df.traffic_source[df.traffic_source.str.contains(&quot;baidu&quot;)] = &quot;baidu&quot;<br>df.traffic_source[df.traffic_source.str.contains(&quot;bing&quot;)] = &quot;bing&quot;<br>df.traffic_source[df.traffic_source.str.contains(&quot;yahoo&quot;)] = &quot;yahoo&quot;<br>.....<br>df.traffic_source[~df.traffic_source.isin(main_traffic_source)] = &quot;Others&quot;</pre><p>After re-formatting, I found that fullVisitorID’s unique values are fewer than the total rows of the dataset, meaning there are multiple fullVisitorIDs that were recorded. Hence, I proceeded to group the variables by fullVisitorID and sort by Revenue:</p><pre>df_groupby = df.groupby([&#39;fullVisitorId&#39;, &#39;channelGrouping&#39;, &#39;geoNetwork_country&#39;, &#39;traffic_source&#39;, &#39;device&#39;, &#39;deviceBrowser&#39;, &#39;device_operatingSystem&#39;])<br>               .agg({&#39;totals_hits&#39;:&#39;sum&#39;, &#39;totals_pageviews&#39;:&#39;sum&#39;, &#39;totals_bounces&#39;:&#39;sum&#39;,&#39;totals_transactionRevenue&#39;:&#39;sum&#39;})<br>               .reset_index()</pre><pre>df_groupby = df_groupby.sort_values(by=&#39;totals_transactionRevenue&#39;, ascending=False).reset_index(drop=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K73Bejdl4hvn4__97U7C1w.png" /><figcaption>df.groupby() and df.sort_values()</figcaption></figure><h4>3. Outlier Handling</h4><p>The last step of any EDA process that cannot be overlooked is detecting and handling outliers of the dataset. The reason being is that outliers, especially those marginally extreme ones, impact the performance of a machine learning model, mostly negatively. That said, we need to either remove those outliers from the dataset or convert them (by mean or mode) to fit them to the range that the majority of the data points lie in:</p><pre><strong>#Seaborn Boxplot to see how far outliers lie compared to the rest<br></strong>sns.boxplot(df_groupby.totals_transactionRevenue)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*Q_pbMaXnmXN5ZafY9-Svow.png" /><figcaption>sns.boxplot()</figcaption></figure><p>As you can see, most of the data points in Revenue lie below USD200,000 and there’s only one extreme outlier that hits nearly USD600,000. If we don’t remove this outlier, the model also takes it into consideration that produces a less objective reflection.</p><p>So let’s go ahead and remove it, and please do so for other variables. Just a quick note, there are several methods of dealing with outliers (such as inter-quantiles). However, in my case, there’s only one so I just went ahead defining the range that I believe fits well:</p><pre>df_groupby = df_groupby.loc[df_groupby.totals_transactionRevenue &lt; 200000]</pre><h3>B. K-Means Clustering</h3><p><em>What is K-Means Clustering and how does it help with customer segmentation?</em></p><p>Clustering is the most well-known unsupervised learning technique that finds structure in unlabeled data by identifying similar groups/clusters, particularly with the helps of K-Means.</p><p>K-Means tries to address two questions: (1) K: <strong>the number of clusters</strong> (groups) we expect to find in the dataset and (2) Means: <strong>the average distance of data to each cluster center </strong>(centroid) which we try to minimize.</p><p>Also, one thing of note is that K-Means comes with several variations, typically :</p><ol><li><strong>init = ‘random’:</strong> that randomly selects the centroids of each cluster</li><li><strong>init = ‘k-means++’:</strong> that only selects the 1st centroid by randomness while other centroids to be placed as far away from the 1st as possible</li></ol><p>In this project, I’ll use the second option to ensure that each cluster is well-distinguished from one another:</p><pre>from sklearn.cluster import KMeans</pre><pre>data = df_groupby.iloc[:, 7:]</pre><pre>kmeans = KMeans(n_clusters=3, init=&quot;k-means++&quot;)<br>kmeans.fit(data)</pre><pre>labels = kmeans.predict(data)<br>labels = pd.DataFrame(data=labels, index = df_groupby.index, columns=[&quot;labels&quot;])</pre><p>Before applying the algorithm, we need to define “<strong>n_clusters</strong>” which is the number of groups we expect to get out of the modelling. In this case, I randomly put n_clusters = 3. Then, I went ahead visualizing how the dataset is grouped using 2 variables: Revenue and PageViews:</p><pre>plt.scatter(df_kmeans.totals_transactionRevenue[df_kmeans.labels == 0],df_kmeans.totals_pageviews[df_kmeans.labels == 0], c=&#39;blue&#39;)</pre><pre>plt.scatter(df_kmeans.totals_transactionRevenue[df_kmeans.labels == 1], df_kmeans.totals_pageviews[df_kmeans.labels == 1], c=&#39;green&#39;)</pre><pre>plt.scatter(df_kmeans.totals_transactionRevenue[df_kmeans.labels == 2], df_kmeans.totals_pageviews[df_kmeans.labels == 2], c=&#39;orange&#39;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/766/1*SyujnM2p83c4gawc_LS4bQ.png" /></figure><p>As you can see, the x-axis stands for the number of Revenue while y-axis for PageViews . After modelling, we can tell a certain degree of difference in 3 clusters. However, I was not sure whether 3 is the “right” number of clusters or not. That said, we can rely on the estimator of K-Means algorithm, <strong>inertia_</strong>, which is the distance from each sample to the centroid. In particular, we will compare the inertia of each cluster ranging from 1 to 10, in my case, and see which is the lowest and how far we should go:</p><pre>#Find the best number of clusters</pre><pre>num_clusters = [x for x in range(1,10)]<br>inertia = []</pre><pre>for i in num_clusters:<br>    model = KMeans(n_clusters = i, init=&quot;k-means++&quot;)<br>    model.fit(data)<br>    inertia.append(model.inertia_)<br>    <br>plt.plot(num_clusters, inertia)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*hr8jVNZuJ5pOzs93XYT5yw.png" /><figcaption>model.inertia_</figcaption></figure><p>From the chart above, inertia started to fall slowly since the 4th or 5th cluster, meaning that that’s the lowest inertia we can get, so I decided to go with “<strong>n_clusters=4</strong>”:</p><pre>plt.scatter(df_kmeans_n4.totals_pageviews[df_kmeans_n4.labels == 0], df_kmeans_n4.totals_transactionRevenue[df_kmeans_n4.labels == 0], c=&#39;blue&#39;)</pre><pre>plt.scatter(df_kmeans_n4.totals_pageviews[df_kmeans_n4.labels == 1],<br>df_kmeans_n4.totals_transactionRevenue[df_kmeans_n4.labels == 1], c=&#39;green&#39;)</pre><pre>plt.scatter(df_kmeans_n4.totals_pageviews[df_kmeans_n4.labels == 2],<br>df_kmeans_n4.totals_transactionRevenue[df_kmeans_n4.labels == 2], c=&#39;orange&#39;)</pre><pre>plt.scatter(df_kmeans_n4.totals_pageviews[df_kmeans_n4.labels == 3],<br>df_kmeans_n4.totals_transactionRevenue[df_kmeans_n4.labels == 3], c=&#39;red&#39;)</pre><pre>plt.xlabel(&quot;Page Views&quot;)<br>plt.ylabel(&quot;Revenue&quot;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*reSCo718L-Op-tSPsC5APQ.png" /><figcaption>Switch PageViews to x-axis and Revenue to y-axis</figcaption></figure><p>The clusters now look a lot more distinguishable from one another:</p><ol><li>Cluster 0 (Blue): high PageViews yet little-to-none Revenue</li><li>Cluster 1 (Red): medium PageViews, low Revenue</li><li>Cluster 2 (Orange): medium PageViews, medium Revenue</li><li>Cluster 4 (Green): unclear trend of PageViews, high Revenue</li></ol><p>Except for cluster 0 and 4 (unclear pattern), which are beyond our control, cluster 1 and 2 can tell a story here as they seem to share some similarities.</p><p>To understand which factor that might impact each cluster, I segmented each cluster by Channels, Device and Operating System:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F3laLX0sZyQtR1sBBjqKAQ.png" /><figcaption>Cluster 1</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOCu6UI0BnCl6uG1hkiiJw.png" /><figcaption>Cluster 2</figcaption></figure><p>As seen from above, in Cluster 1, Referral channel contributed the highest Revenue, followed by Direct and Organic Search. In contrast, it’s Direct that made the highest contribution in Cluster 2. Similarly, while Macintosh is the most dominating device in Cluster 1, it’s Windows in Cluster 2 that achieved higher revenue. The only similarity between 2 clusters is the Device Browser, which Chrome is widely used.</p><p>Voila! This further segmentation helps us tell which factor (in this case, Channel, Device Browser, Operating System) works better for each cluster, hence we can better evaluate our investment moving forward!</p><h3>C. A/B Testing through Hypothesis Testing</h3><p><em>What is A/B Testing and how can Hypothesis Testing come into place to complement the process?</em></p><p>A/B Testing is no stranger to those who work in Advertising and Media, since it’s one of the powerful techniques that help improve the performance with more cost efficiency. Particularly, A/B Testing divides the audience into 2 groups: Test vs Control. Then, we expose the ads/show a different design to the Test group only to see if there’s any significant discrepancy between 2 groups: exposed vs un-exposed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FVRja7u_j052UxCv.png" /><figcaption>Image credit: <a href="https://productcoalition.com/are-you-segmenting-your-a-b-test-results-c5512c6def65?gi=7b445e5ef457">https://productcoalition.com/are-you-segmenting-your-a-b-test-results-c5512c6def65?gi=7b445e5ef457</a></figcaption></figure><p>In Advertising, there are a number of different automatic tools in the market that can easily help do A/B Testing at one click. However, I still wanted to try a different method in Data Science that can do the same: <strong>Hypothesis Testing</strong>. The methodology is pretty much the same, as Hypothesis Testing compares the Null Hypothesis (H0) and Alternate Hypothesis (H1) and see if there’s any significant discrepancy between the two!</p><p><strong>Assume that </strong>I run a promotion campaign that exposes an ad to the Test group. Here’s a quick summary of steps that need to be followed to test the result with Hypothesis Testing:</p><ol><li>Sample Size Determination</li><li>Pre-requisite Requirements: Normality and Correlation Tests</li><li>Hypothesis Testing</li></ol><p><strong>For the 1st step</strong>, we can rely on Power Analysis which helps determine the sample size to draw from a population. Power Analysis requires 3 parameters: (1) effect size, (2) power and (3) alpha. If you are looking for details on how Power Analysis, please <strong><em>refer to an in-depth article</em></strong> <a href="https://medium.com/analytics-vidhya/exchange-rate-prediction-part-1-276b6cd5338">here</a> that I wrote some time ago.</p><p>Below is a quick note to each parameter for your quick understanding:</p><pre>#Effect Size: (expected mean - actual mean) / actual_std<br>effect_size = (280000 - df_group1_ab.revenue.mean())/df_group1_ab.revenue.std() #set expected mean to $350,000<br>print(effect_size)</pre><pre>#Power<br>power = 0.9 #the probability of rejecting the null hypothesis</pre><pre>#Alpha<br>alpha = 0.05 #the error rate</pre><p>After having 3 parameters ready, we use <strong>TTestPower()</strong> to determine the sample size:</p><pre>import statsmodels.stats.power as sms</pre><pre>n = sms.TTestPower().solve_power(effect_size=effect_size, power=power, alpha=alpha)</pre><pre>print(n)</pre><p>The result is 279, meaning we need to draw 279 data points from each group: Test and Control. As I don’t have real data, I used <strong>np.random.normal</strong> to generate a list of revenue data, in this case sample size = 279 for each group:</p><pre>#Take the samples out of each group: control vs test</pre><pre>control_sample = np.random.normal(control_rev.mean(), control_rev.std(), size=279)<br>test_sample = np.random.normal(test_rev.mean(), test_rev.std(), size=279)</pre><p><strong>Moving to the 2nd step</strong>, we need to ensure the samples are (1) normally distributed and (2) independent (not correlated). Again, if you want a refresh on the tests used in this step, refer to my article as above. In short, we are going to use (1) Shapiro as the normality test and (2) Pearson as the correlation test.</p><pre>#Step 2. Pre-requisite: Normality, Correlation</pre><pre>from scipy.stats import shapiro, pearsonr</pre><pre>stat1, p1 = shapiro(control_sample)<br>stat2, p2 = shapiro(test_sample)</pre><pre>print(p1, p2)</pre><pre>stat3, p3 = pearsonr(control_sample, test_sample)<br>print(p3)</pre><p>The p-value of Shapiro is 0.129 and 0.539 for Control and Test group respectively, which is &gt; 0.05. Hence, we don’t reject the null hypothesis and are able to say that 2 groups are normally distributed.</p><p>The p-value of Pearson is 0.98, which is &gt;0.05, meaning that 2 groups are independent from each other.</p><p><strong>Final step is here</strong>! As there are 2 variables to be tested against each other (Test vs Control group), we use T-Test to see if there’s any significant discrepancy in Revenue after running A/B Testing:</p><pre>#Step 3. Hypothesis Testing</pre><pre>from scipy.stats import ttest_ind</pre><pre>tstat, p4 = ttest_ind(control_sample, test_sample)<br>print(p4)</pre><p>The result is 0.35, which is &gt; 0.05. Hence, the A/B Test conducted indicates that the Test Group exposed to the ads doesn’t show any superiority over the Control Group with no ad exposure.</p><p>Voila! That’s the end of this project — Customer Segmentation &amp; A/B Testing! I hope you find this article useful and easy to follow.</p><p>Do look out for my <strong>upcoming projects</strong> in Data Science and Machine Learning in the near future! In the meantime feel free to check out my Github here for the complete repository:</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd26a94462dd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/customer-segmentation-k-means-clustering-a-b-testing-bd26a94462dd">Customer Segmentation: K-Means Clustering &amp; A/B Testing</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit Risk Management: Classification Models & Hyperparameter Tuning]]></title>
            <link>https://medium.com/data-science/credit-risk-management-classification-models-hyperparameter-tuning-d3785edd8371?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3785edd8371</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[crossvalidation]]></category>
            <category><![CDATA[hyperparameter-tuning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Mon, 10 Aug 2020 08:22:25 GMT</pubDate>
            <atom:updated>2020-08-10T13:07:06.287Z</atom:updated>
            <content:encoded><![CDATA[<p>The final part aims to walk you through the process of applying different classification algorithms on our transformed dataset as well as producing the best-performing model using Hyperparameter Tuning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSw-njRsFwVlqbTElIX8oQ.jpeg" /><figcaption>Image credit: <a href="https://unsplash.com/photos/w7ZyuGYNpRQ">https://unsplash.com/photos/w7ZyuGYNpRQ</a></figcaption></figure><p>As a reminder, this end-to-end project aims to solve a classification problem in Data Science, particularly in finance industry and is divided into 3 parts:</p><ol><li>Explanatory Data Analysis (EDA) &amp; Feature Engineering</li><li>Feature Scaling and Selection (Bonus: Imbalanced Data Handling)</li><li><strong>Machine Learning Modelling (Classification)</strong></li></ol><p>If you have missed the previous two parts, feel free to check them out <a href="https://towardsdatascience.com/credit-risk-management-eda-feature-engineering-81cc34efc428"><strong>here</strong></a><strong> </strong>and <a href="https://towardsdatascience.com/credit-risk-management-feature-scaling-selection-b734049867ea"><strong>here</strong></a> before going through the final part which leveraged their output in producing the best classification model.</p><h3>A. Classification Models</h3><p><em>Which algorithms should be used to build a model that addresses and solves a classification problem?</em></p><p>When it comes to classification, we have quite a handful of different algorithms to use unlike regression. To name some, Logistic Regression, K-Neighbors, SVC, Decision Tree and Random Forest are the top common and widely used algorithms to solve such problems.</p><p>Here’s a quick recap of what each algorithm does and how it distinguishes itself from the others:</p><ul><li><strong>Logistic Regression</strong>: this algorithm uses regression to <strong><em>predict the continuous probability</em></strong> of a data sample (from 0 to 1), then classifies that sample to the more probable target (either 0 or 1). However, it assumes a linear relationship between the the inputs and the target, which might not be a good choice if the dataset does not follow Gaussian Distribution.</li><li><strong>K-Neighbors</strong>: this algorithm assumes data points which are in close proximity to each other belong to the same class. Particularly, it classifies the target (either 0 or 1) of a data sample by <strong><em>a plurality vote of the neighbors</em></strong> which are close in distance to it.</li><li><strong>SVC</strong>: this algorithm makes classifications by <strong><em>defining a decision boundary</em> </strong>and then classify the data sample to the target (either 0 or 1) by seeing which side of the boundary it falls on. Essentially, the algorithm aims to maximize the distance between the decision boundary and points in each class to decrease the chance of false classification.</li><li><strong>Decision Tree</strong>: as the name tells, this algorithm <strong><em>splits the root of the tree </em></strong>(the entire dataset) into decision nodes, and each decision node will be split until no further node is splittable. Then, the algorithm classifies the data sample by sorting them down the tree from the root to the leaf/terminal node and seeing which target node it falls on.</li><li><strong>Random Forest</strong>: this algorithm is an ensemble technique developed from the Decision Tree, in which it involves many decision tree that work together. Particularly, the random forest gives that data sample to each of the decision trees and <strong><em>returns the most popular classification</em></strong> to assign the target to that data sample. This algorithm helps avoid overfitting which may occurs to Decision Tree, as it aggregates the classification from multiple trees instead of 1.</li></ul><p>Let’s see how they work with our dataset compared to one another:</p><pre>from sklearn.linear_model import LogisticRegression<br>from sklearn.neighbors import KNeighborsClassifier<br>from sklearn.svm import SVC<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.ensemble import RandomForestClassifier</pre><pre>classifiers = {<br>    &quot;LogisticRegression&quot; : LogisticRegression(),<br>    &quot;KNeighbors&quot; : KNeighborsClassifier(),<br>    &quot;SVC&quot; : SVC(),<br>    &quot;DecisionTree&quot; : DecisionTreeClassifier(),<br>    &quot;RandomForest&quot; : RandomForestClassifier()<br>}</pre><p>After importing the algorithms from sklearn, I <strong><em>created a dictionary which combines all algorithms into one place</em></strong>, so that it’s easier to apply them on the data at once, without the need to manually iterate each individually.</p><pre>#Compute the training score of each models</pre><pre>train_scores = []<br>test_scores = []</pre><pre>for key, classifier in classifiers.items():<br>    classifier.fit(x_a_train_rs_over_pca, y_a_train_over)<br>    train_score = round(classifier.score(x_a_train_rs_over_pca, y_a_train_over),2)<br>    train_scores.append(train_score)<br>    test_score = round(classifier.score(x_a_test_rs_over_pca, y_a_test_over),2)<br>    test_scores.append(test_score)</pre><pre>print(train_scores)<br>print(test_scores)</pre><p>After applying the algorithms on both train and test sets, it seems that Logistic Regression doesn’t work well for the dataset as the scores are relatively low (around 50%, which indicates that the model is not able to classify the target). This is quite understandable and somehow proves that our original dataset is not normally distributed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*eeyeLtwrmE-yuiS08oiBrA.png" /></figure><p>In contrast, Decision Tree and Random Forest produced a significantly high accuracy scores on the train sets (85%). Yet, it’s the otherwise for the test set when the scores are remarkably low (over 50%). Possible reasons that might explain the large gap is (1) overfitting the train set, (2) leaking target to the test set. However, after cross checking, it doesn’t seem as the case.</p><p>Hence, I decided to look into another scoring metric, <strong>Cross Validation Score, </strong>to see if there’s any difference. Basically, this technique splits the training set into n folds (default = 5), then fits the data on n-1 folds and score on the other fold. This process is repeated in n folds from which the average score will be calculated. Cross validation score <strong><em>brings a more objective analysis on how the models works</em></strong> as compared to the standard accuracy score.</p><pre>from sklearn.model_selection import cross_val_score</pre><pre>train_cross_scores = []<br>test_cross_scores = []</pre><pre>for key, classifier in classifiers.items():<br>    classifier.fit(x_a_train_rs_over_pca, y_a_train_over)<br>    train_score = cross_val_score(classifier, x_a_train_rs_over_pca, y_a_train_over, cv=5)<br>    train_cross_scores.append(round(train_score.mean(),2))<br>    test_score = cross_val_score(classifier, x_a_test_rs_over_pca, y_a_test_over, cv=5)<br>    test_cross_scores.append(round(test_score.mean(),2))<br>    <br>print(train_cross_scores)<br>print(test_cross_scores)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*Zf0hsW6HZYgJi9gH95neqQ.png" /></figure><p>As seen, the gap between the train and test scores was significantly bridged!</p><p>Since Random Forest model produced the highest cross validation score, we will test it against another score metric named <strong>ROC AUC Score</strong> as well as see how it performs on the <strong>ROC Curve</strong>.</p><p>Essentially, <strong>ROC Curve</strong> is a plot of the false positive rate (x-axis) versus the true positive rate (y-axis) within the threshold between 0 and 1 while <strong>AUC</strong> represents the degree or measure of separability (simply, the ability to distinguish the target).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*hMn9YQZ7eKTFTqkfzJ4FvA.png" /><figcaption>Image credit: <a href="https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5">https://towardsdatascience.com/understanding-auc-roc-curve-68b2303cc9c5</a></figcaption></figure><p>Below is a quick summary table of how to calculate <strong>FPR </strong>(the inversion of Specificity) and <strong>TPR</strong> (also known as Sensitivity):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpR4UVf513eZiGpdHajG6A.png" /><figcaption>Image credit: <a href="https://towardsdatascience.com/hackcvilleds-4636c6c1ba53">https://towardsdatascience.com/hackcvilleds-4636c6c1ba53</a></figcaption></figure><pre>from sklearn.model_selection import cross_val_predict<br>from sklearn.metrics import roc_curve<br>from sklearn.metrics import roc_auc_score</pre><pre>rf = RandomForestClassifier()<br>rf.fit(x_a_train_rs_over_pca, y_a_train_over)<br>rf_pred = cross_val_predict(rf, x_a_test_rs_over_pca, y_a_test_over, cv=5)<br>print(roc_auc_score(y_a_test_over, rf_pred))</pre><pre>#Plot the ROC Curve<br>fpr, tpr, _ = roc_curve(y_a_test_over, rf_pred)<br>plt.plot(fpr, tpr)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*sE6LXsW4SPBisEnf1WkXBg.png" /><figcaption>ROC Curve with ROC AUC Score = 76%</figcaption></figure><p>As I had proved that cross validation worked on this dataset, I then applied another cross validation technique called “<strong>cross_val_predict</strong>”, which follows similar methodology of splitting n-folds and predicting the value accordingly.</p><h3>B. Hyperparameter Tuning</h3><p><em>What is hyperparameter tuning and how does it help to improve the accuracy of the model?</em></p><p>After computing the model from the default estimators of each algorithm, I was hoping to see if further improvement could be made, which comes down to Hyperparameter Tuning. Essentially, this technique <strong><em>chooses a set of optimal estimators</em></strong> from each algorithm that (might) produces the highest accuracy score on the given dataset.</p><p>The reason why I put (might) in the definition is that for some cases, little to none improvement is seen depends on the dataset as well as the preparation done initially (plus it takes like forever to run). However, Hyperparameter Tuning should be taken into consideration with the hope of finding the best performing model.</p><pre>#Use GridSearchCV to find the best parameters</pre><pre>from sklearn.model_selection import GridSearchCV</pre><pre>#Logistic Regression<br>lr = LogisticRegression()<br>lr_params = {&quot;penalty&quot;: [&#39;l1&#39;, &#39;l2&#39;], &quot;C&quot;: [0.001, 0.01, 0.1, 1, 10, 100, 1000], &quot;solver&quot;: [&#39;newton-cg&#39;, &#39;lbfgs&#39;, &#39;liblinear&#39;, &#39;sag&#39;, &#39;saga&#39;]}<br>grid_logistic = GridSearchCV(lr, lr_params)<br>grid_logistic.fit(x_a_train_rs_over_pca, y_a_train_over)<br>lr_best = grid_logistic.best_estimator_</pre><pre>#KNearest Neighbors<br>knear = KNeighborsClassifier()<br>knear_params = {&quot;n_neighbors&quot;: list(range(2,7,1)), &quot;algorithm&quot;: [&#39;auto&#39;, &#39;ball_tree&#39;, &#39;kd_tree&#39;, &#39;brutle&#39;]}<br>grid_knear = GridSearchCV(knear, knear_params)<br>grid_knear.fit(x_a_train_rs_over_pca, y_a_train_over)<br>knear_best = grid_knear.best_estimator_</pre><pre>#SVC</pre><pre>svc = SVC()<br>svc_params = {&quot;C&quot;: [0.5, 0.7, 0.9, 1], &quot;kernel&quot;:[&#39;rbf&#39;, &#39;poly&#39;, &#39;sigmoid&#39;, &#39;linear&#39;]}<br>grid_svc = GridSearchCV(svc, svc_params)<br>grid_svc.fit(x_a_train_rs_over_pca, y_a_train_over)<br>svc_best = grid_svc.best_estimator_</pre><pre>#Decision Tree</pre><pre>tree = DecisionTreeClassifier()<br>tree_params = {&quot;criterion&quot;: [&#39;gini&#39;, &#39;entropy&#39;], &quot;max_depth&quot;:list(range(2,5,1)), &quot;min_samples_leaf&quot;:list(range(5,7,1))}<br>grid_tree = GridSearchCV(tree, tree_params)<br>grid_tree.fit(x_a_train_rs_over_pca, y_a_train_over)<br>tree_best = grid_tree.best_estimator_</pre><p><strong>GridSearchCV </strong>is the key to finding the set of optimal estimators in each algorithm, as it scrutinizes and combines different estimators to fit the dataset, then returns the best set among all.</p><p>One thing of note is that we have to remember by heart all available estimators of each algorithm to be able to use. For example, with Logistic Regression, we have a set of “penalty”, “C”, and “solver” which do not belong to other algorithms.</p><p>After finding the <strong>.best_estimator_</strong> of each algorithm, fit and predict the data using each algorithm with its best set. However, we need to compare the new scores against the original to determine if any improvement is seen or to continue fine-tuning the estimators again.</p><h3>Bonus: XGBoost and LightGBM</h3><p><em>What are XGBoost and LightGBM and how significantly better do these algorithms do compared to the traditional?</em></p><p>Apart from the common classification algorithms I’ve heard of, I also have known a couple of advanced algorithms which rooted from the traditional. In this case, <strong>XGBoost and LightGBM </strong>can be considered as <em>the successor of Decision and Random Forest. </em>Look at the below timeline for a better understanding of how these algorithms were developed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*mC_QcBQ-V4KdrUB1gy-2yQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/0*-zHaoqHQcj1l1lAP" /><figcaption>Image credit: <a href="https://www.slideshare.net/GabrielCyprianoSaca/xgboost-lightgbm">https://www.slideshare.net/GabrielCyprianoSaca/xgboost-lightgbm</a></figcaption></figure><p>I’m not going to go into details of how these algorithms differ mathematically, but in general, they are able to <strong><em>prune the decision trees better while handling missing values + avoid overfitting at the same time.</em></strong></p><pre>#XGBoost<br>import xgboost as xgb</pre><pre>xgb_model = xgb.XGBClassifier()<br>xgb_model.fit(x_a_train_rs_over_pca, y_a_train_over)<br>xgb_train_score = cross_val_score(xgb_model, x_a_train_rs_over_pca, y_a_train_over, cv=5)<br>xgb_test_score = cross_val_score(xgb_model, x_a_test_rs_over_pca, y_a_test_over, cv=5)</pre><pre>print(round(xgb_train_score.mean(),2))<br>print(round(xgb_test_score.mean(),2))</pre><pre>#LightGBM<br>import lightgbm as lgb</pre><pre>lgb_model = lgb.LGBMClassifier()<br>lgb_model.fit(x_a_train_rs_over_pca, y_a_train_over)<br>lgb_train_score = cross_val_score(lgb_model, x_a_train_rs_over_pca, y_a_train_over, cv=5)<br>lgb_test_score = cross_val_score(lgb_model, x_a_test_rs_over_pca, y_a_test_over, cv=5)</pre><pre>print(round(lgb_train_score.mean(),2))<br>print(round(lgb_test_score.mean(),2))</pre><p>After computing, the train and set scores of each model are 72% &amp; 73% (XGBoost) and 69% &amp; 72% (LightGBM), which is relatively the same as Random Forest model computed above. However, we are still able to make further optimisations via Hyperparameter Tuning for these advanced models, but beware that it might take forever since XGBoost and LightGBM have longer runtime due to the complexity of their algorithm.</p><p>Voila! That’s the wrap for this end-to-end project with regards to Classification! If you are keen to explore the entire code, feel free to check out my Github below:</p><p>Repository: <a href="https://github.com/andrewnguyen07/credit-risk-management">https://github.com/andrewnguyen07/credit-risk-management</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Follow my Medium to keep posted on future projects coming up soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3785edd8371" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/credit-risk-management-classification-models-hyperparameter-tuning-d3785edd8371">Credit Risk Management: Classification Models &amp; Hyperparameter Tuning</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit Risk Management: Feature Scaling & Selection]]></title>
            <link>https://medium.com/data-science/credit-risk-management-feature-scaling-selection-b734049867ea?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/b734049867ea</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[imbalanced-data]]></category>
            <category><![CDATA[feature-selection]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 10:16:00 GMT</pubDate>
            <atom:updated>2020-08-05T11:41:08.881Z</atom:updated>
            <content:encoded><![CDATA[<p>Following feature engineering, this part moves to the next step in the data preparation process: feature scaling and selection, which transforms the dataset to a more digestible one prior to modelling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wL7BP-A3YGzaEgGhk4hlWg.jpeg" /><figcaption>Image credit: <a href="https://unsplash.com/photos/JG35CpZLfVs">https://unsplash.com/photos/JG35CpZLfVs</a></figcaption></figure><p>As a reminder, this end-to-end project aims to solve a classification problem in Data Science, particularly in finance industry and is divided into 3 parts:</p><ol><li>Explanatory Data Analysis (EDA) &amp; Feature Engineering</li><li><strong>Feature Scaling and Selection (Bonus: Imbalanced Data Handling)</strong></li><li>Machine Learning Modelling (Classification)</li></ol><p>If you have missed the 1st part, feel free to check it out <a href="https://towardsdatascience.com/credit-risk-management-eda-feature-engineering-81cc34efc428"><strong>here</strong></a> before going through the 2nd part that follows here for a better context understanding.</p><h3>A. Feature Scaling</h3><p><em>What is feature scaling and why do we need it prior to modelling?</em></p><p>According to Wikipedia,</p><blockquote>Feature scaling is a method used to <strong>normalize</strong> the range of independent variables or features of data. In data processing, it is also known as data normalization and is generally performed during the data preprocessing step.</blockquote><p>If you recall from the 1st part, we have completed engineering all of our features on both datasets (A &amp; B) as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7T4dYhJh55OIAJatAiYVcQ.png" /><figcaption>Dataset A (encoded without target)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*E5MvNmHr6k3YAgM0.png" /><figcaption>Dataset B (encoded with target)</figcaption></figure><p>As seen above, data range and distribution among all features are relatively different from one another, not to mention some variables bearing with outliers. That being said, it is highly recommended that we apply feature scaling to the entire dataset consistently for the purpose of making it more digestible to machine learning algorithms.</p><p>In fact, there are a number of different methods in the market, but I will only focus on the three which I believe are relatively distinctive: <strong>StandardScaler</strong>, <strong>MinMaxScaler </strong>and<strong> RobustScaler</strong>. In brief,</p><ul><li><strong>StandardScaler</strong>: this method removes the mean and scales the data to unit variance (mean = 0 and standard deviation = 1). However, it is highly influenced by outliers, especially those marginally extreme ones which can spread the scaled data range to further than 1 standard deviation.</li><li><strong>MinMaxScaler</strong>: this method subtracts the minimum value in the feature and divides it by the range (which is the difference between the original maximum and minimum value). Essentially, it rescales the dataset to the range of 0 and 1. However, this method is relatively limited as it compress all data points to a narrow range and it doesn’t help much in the presence of outliers.</li><li><strong>RobustScaler</strong>: this method is based on percentiles, which subtracts the median and divides by the interquartile range (75% — 25%). It is generally more preferable than other two scalers since it is not greatly influenced by large marginal outliers if any.</li></ul><p>Let’s see how the three scalers differ in our dataset:</p><pre>from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler</pre><pre>#StandardScaler<br>x_a_train_ss = pd.DataFrame(StandardScaler().fit_transform(x_a_train), columns=x_a_train.columns)</pre><pre>#MinMaxScaler<br>x_a_train_mm = pd.DataFrame(MinMaxScaler().fit_transform(x_a_train), columns=x_a_train.columns)</pre><pre>#RobustScaler<br>x_a_train_rs = pd.DataFrame(RobustScaler().fit_transform(x_a_train), columns=x_a_train.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFDAFlzoz7RKGiBIN-gZ8w.png" /><figcaption>StandardScaler</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FR0o5MpFZ3VvCcr6oq8HxQ.png" /><figcaption>MinMaxScaler</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lP0FcW8yd4KjZnX1WzoOSA.png" /><figcaption>RobustScaler</figcaption></figure><p>As seen above, the scaled data range of RobustScaler looks more digestible than the other two scalers, which might help the machine learning algorithms push the processing runtime faster and more efficiently. However, this is my assumption prior to modelling, but we can put it on trials when it comes to that phase.</p><h3>B. Imbalanced Data Handling</h3><p><em>What is imbalanced data and how should we handle it?</em></p><p>In short, imbalanced datasets are those where there is a severe skew in the target distribution which might not be ideal for modelling. As a clearer example, let’s see if our dataset is imbalanced or not:</p><pre>a_target_0 = df_a[df_a.target == 0].target.count() / df_a.target.count()<br>a_target_1 = df_a[df_a.target == 1].target.count() / df_a.target.count()</pre><p>The result is that 76% of the data is classified as target 0 while the remaining 24% as target 1.</p><p>In fact, there’s no crystal clear benchmark that we should rely on to accurately determine whether our dataset is imbalanced or not. Some says that the ratio of 9:1 while others of 8:2, which indeed really depends on the nature of your dataset as well as the context/problem you are solving. In my case, I take the above result as imbalanced and will “resample” the dataset to make it relatively balanced.</p><p><strong><em>Just a disclaimer</em></strong>, all the pre-processing steps I have taken here do not mean that they are all must-do and positively impact the accuracy of our model later on. It rather implies that I was aiming to test all possible scenarios that might help improve my models.</p><p>Back to resampling, there are two common methodologies that we might have heard of: over-sampling and under-sampling. In brief,</p><ul><li><strong>Over-sampling</strong>: this method duplicates the samples from the minority class and add them to the dataset (training set).</li><li><strong>Under-sampling</strong>: this is the opposite to the above which deletes some samples from the majority class.</li></ul><p>Visually, you can imagine something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UiNxMJ5Go69XDHrQ.png" /><figcaption>Image credit: <a href="https://towardsdatascience.com/having-an-imbalanced-dataset-here-is-how-you-can-solve-it-1640568947eb">https://towardsdatascience.com/having-an-imbalanced-dataset-here-is-how-you-can-solve-it-1640568947eb</a></figcaption></figure><p>Let’s test both out:</p><pre># Under-sampling<br>from imblearn.under_sampling import RandomUnderSampler</pre><pre>undersample = RandomUnderSampler()</pre><pre>x_a_train_rs_under, y_a_train_under = undersample.fit_resample(x_a_train_rs, y_a_train)<br>print(Counter(y_a_train_under))</pre><pre># Over-sampling<br>from imblearn.over_sampling import SMOTE<br>from collections import Counter</pre><pre>oversample = SMOTE()</pre><pre>x_a_train_rs_over, y_a_train_over = oversample.fit_resample(x_a_train_rs, y_a_train)<br>print(Counter(y_a_train_over))</pre><p>For each methodology, there is a variety of options to resample your dataset, but I’ve chosen the most common one to execute, which is <strong>RandomUnderSampler </strong>(for under-sampling) and <strong>SMOTE</strong> (for over-sampling). The class distribution after resampling is:</p><ul><li>RandomUnderSampler: 0: 5814, 1: 5814</li><li>SMOTE: 1: 18324, 0: 18324</li></ul><p>Both has their pros and cons, but from the name suggests, RandomUnderSampler “randomly” selects data from the majority class to remove, which might result in information loss as not the entire dataset is taken into modelling. That said, I’ve opted for SMOTE instead.</p><h3>C. Feature Selection</h3><p><em>What is feature selection and what are the options available for our perusal?</em></p><p>In short, feature selection is the process of selecting the variables in the dataset which has great correlation to/ impact on the target variable. Particularly, when it comes to bigger dataset, we might face up to hundreds of features, some of which might not be relevant or even relates to the output. Hence, we need to conduct feature selection prior to modelling to achieve the highest accuracy.</p><p>Indeed, there are a handful of different techniques which can be grouped under two big categories: (1) <strong>Feature Selection</strong> and (2) <strong>Dimensionality Reduction</strong>. I believe the names sound really familiar to you, but essentially they are the same but the technique done for each is relatively different.</p><h4>1. Feature Selection</h4><p>If you are looking for a complete list of techniques, feel free to refer to <a href="https://www.analyticsvidhya.com/blog/2018/08/dimensionality-reduction-techniques-python/">this blog article</a> which lists down all possible methods for your trial. In this project, I will just apply two for the sake of simplicity: (a) <strong>Feature Importance</strong> and (b) <strong>Correlation Matrix</strong>.</p><p>For <strong>Feature Importance</strong>, as the name can tell, we will select the top features that have the highest correlation rate with the target variable (e.g. top 10 or 15, depending on the total number of features). Particularly, this technique deploys the attribute of ExtraTreeClassifier algorithm: <strong>feature_importances_</strong></p><pre>from sklearn.ensemble import ExtraTreesClassifier</pre><pre>fi = ExtraTreesClassifier()<br>fi_a = fi.fit(x_a_train_rs_over, y_a_train_over)</pre><pre>df_fi_a = pd.DataFrame(fi_a.feature_importances_,index=x_a_train_rs_over.columns)<br>df_fi_a.nlargest(10,df_fi_a.columns).plot(kind=&#39;barh&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Nz_TGbT4cjooiVDRawhvww.png" /><figcaption>.feature_importances_</figcaption></figure><p>As you can see, annual income is the most important feature, followed by age and year of employment. Indeed, it really depends on you on the number of features to be selected.</p><p>Moving on to the 2nd method of Feature Selection, a <strong>Correlation Matrix </strong>is a table showing the correlation coefficients between variables in the dataset. Essentially, the higher the numbers, the more correlated it is between any two variable.</p><p>Let’s see it more visually for better illustration:</p><pre>df_b_train_processed = pd.concat([x_b_train_rs_over, y_b_train_over], axis=1) #combine processed features with their target</pre><pre>cm_b = df_b_train_processed.corr()</pre><pre>print(cm_b.target.sort_values().tail(10))</pre><pre>plt.figure(figsize=(20,20))<br>sns.heatmap(cm_b, xticklabels=df_b_train_processed.columns, yticklabels=df_b_train_processed.columns,annot=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*rPtKPg-AtPemB3itzkQvFA.png" /><figcaption>df.corr()</figcaption></figure><p>As seen above, we only need to take into consideration the last column in the table, which is the correlation of all independent variables with the target. It looks that all features share similar coefficients with the target as of the same colour shade. This might be slightly different from (1) Feature Importance that we just ran above. However, there’s no definite right-wrong answer as each technique was designed and functions differently.</p><h4>2. Dimensionality Reduction</h4><p>Dimensionality Reduction is basically similar to Feature Selection, but it has its own technique. The common options that I often use can be grouped as Component-based (PCA) and Projection-based (t-SNE and UMAP).</p><ul><li><strong>Component-based (PCA)</strong>: as the name tells, it’s based off on the original features in the dataset which are transformed to a new set of variables that have better correlation with the target.</li><li><strong>Projection-based (t-SNE and UMAP)</strong>: the mathematical concept behind this technique is complicated, but in short, it refers to multi-dimensional data projected to a lower-dimensional space, which helps reduce the number of features in the dataset.</li></ul><p>Remember, feature scaling is required when using these techniques!</p><pre>from sklearn.decomposition import PCA</pre><pre>pca = PCA(.95)</pre><pre>pca_a_train = pca.fit(x_a_train_rs_over, y_a_train_over)<br>print(pca_a_train.n_components_)</pre><pre>plt.plot(np.cumsum(pca_a_train.explained_variance_ratio_))<br>plt.show()</pre><pre>x_a_train_rs_over_pca = pd.DataFrame(pca_a_train.transform(x_a_train_rs_over))<br>x_a_train_rs_over_pca.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*DKO_hRaYwgs_1Wib_sqGJA.png" /></figure><p>As for PCA, when I called the syntax, I set the explained variance of PCA to .95, which means that I was hoping to get the new set of variables that has 95% of variance from the original one. In this case, after we fit the training data to PCA, it is calculated that we only need 24 out of 46 features. Furthermore, looking at the explained_variance_ratio chart, the line stops increasing after 24 features, which could be the ideal number of features after PCA applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vSlIb1YZEem4aCawQzV3Rg.png" /><figcaption>pca.fit_transform()</figcaption></figure><p>As for projection-based, t-SNE works well for large dataset but it’s proven to have limitations, specifically low computing time and large-scale information loss while UMAP performs better in terms of runtime while preserving information.</p><p>In short, how UMAP works is that it first calculates the distance between the points in high dimensional space, projects them onto the low dimensional space, and calculates the distance between points in this low dimensional space. Then, it uses Stochastic Gradient Descent to minimize the difference between these distances.</p><pre>import umap</pre><pre>um = umap.UMAP(n_components=24)</pre><pre>umap_a_train = um.fit_transform(x_a_train_rs_over)<br>x_a_train_rs_over_umap = pd.DataFrame(umap_a_train)<br>x_a_train_rs_over_umap.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ms6Dni62nSnXFfRNmBs6-A.png" /><figcaption>umap.UMAP.fit_transform()</figcaption></figure><p>To compare between PCA and UMAP in terms of performance, it depends on the scale and the complex of our dataset so as to determine which to be utilized. However, for the sake of simplicity and better runtime, I’ve opted for PCA to be applied across datasets and leverage for the modelling phase.</p><p>Voila! We’re done with the 2nd part of this end-to-end project, with the concentration on Feature Scaling and Selection!</p><p>I do hope you find it informative and easy to follow, so feel free to leave comments here! Do look out for the 3rd final part of this project which utilizes all of the data preparation steps to apply <strong>Machine Learning algorithms</strong>.</p><p>In the meantime, let’s connect:</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b734049867ea" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/credit-risk-management-feature-scaling-selection-b734049867ea">Credit Risk Management: Feature Scaling &amp; Selection</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Credit Risk Management: EDA & Feature Engineering]]></title>
            <link>https://medium.com/data-science/credit-risk-management-eda-feature-engineering-81cc34efc428?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/81cc34efc428</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[feature-engineering]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[categorical-data]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Sun, 02 Aug 2020 12:33:12 GMT</pubDate>
            <atom:updated>2020-08-02T14:01:47.291Z</atom:updated>
            <content:encoded><![CDATA[<h4>This part starts off with how to clean and pre-process data using EDA and Feature Engineering techniques for a Classification problem, especially with and without touching the “target” variable.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f6req9MWPWXKHN-JjqQ6Cw.jpeg" /><figcaption>Image credit: <a href="https://unsplash.com/photos/g7NfqV6C074">https://unsplash.com/photos/g7NfqV6C074</a></figcaption></figure><h3>Context</h3><p><em>What are the common use cases in the financial industry that Data Science can be of great help to?</em></p><p>Credit Score Cards are one of the common risk control methods in the financial industry which uses personal information and transactional records to identify and evaluate the creditworthiness of existing and potential customers. There are a number of different use cases leveraging this measure such as loan management, credit card approval, credit limit extension, etc.</p><p>That said, this project’s applicability varies depending on the problem a financial institution is facing. The core engine which makes this project usable is the processing and transformation of input data to engender the output of high predictability from the existing/new input that best addresses the issues.</p><h3>Table of Contents</h3><p>This end-to-end project is divided into 3 parts:</p><ol><li>Explanatory Data Analysis (EDA) &amp; Feature Engineering</li><li>Feature Scaling and Selection (Bonus: Imbalanced Data Handling)</li><li>Machine Learning Modelling (Classification)</li></ol><p><strong><em>Note</em>:</strong> As the project aims to boost my capability in Data Science, in short for the sake of self-study and self-improvement, instead of only applying the best performing technique, the project will divide the dataset into 2 smaller sub-sets to test which produces a better result.</p><p>So let’s kick off with the 1st part of the project: EDA &amp; Feature Engineering</p><h3>A. Explanatory Data Analysis (EDA)</h3><p>Let’s import the necessary libraries and the two datasets:</p><pre>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><pre>application = pd.read_csv(&quot;application_record.csv&quot;)<br>credit = pd.read_csv(&quot;credit_record.csv&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*flhb3P3MPnYK3RKHtdKa7w.png" /><figcaption>Application dataset</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*uko-ZqALrZw4Pdhn4NET_w.png" /><figcaption>Credit dataset</figcaption></figure><p>As shared above, while the Application dataset provides all data points from the <strong><em>personal information</em></strong> submitted by the existing banking customers (e.g. id, gender, income, etc.), the Credit dataset maps each corresponding id with his/her<strong> <em>loan repayment status</em></strong> (e.g. X stands for no loan of the month, C for paid off and &gt;0 implying the number of payment-overdue months).</p><p>For better usability of the Credit information, I cleaned up the dataset by converting the “Status” columns to numeric as well as grouped it by Customer ID and the latest month:</p><pre>credit.status = credit.status.replace({&#39;X&#39;:-2, &#39;C&#39;: -1})<br>credit.status = credit.status.astype(&#39;int&#39;)<br>credit.status = credit.status.apply(lambda x:x+1) </pre><pre>credit_month = credit.groupby(&#39;id&#39;).months_balance.max().reset_index()</pre><pre>record = pd.merge(credit_month, credit, how=&quot;inner&quot;, on=[&quot;id&quot;, &quot;months_balance&quot;])</pre><pre>record.head()</pre><p>When all had been set, I then combined the newly processed dataset with the Application utilizing “inner merge”. On top of this, if you refer back to the original dataset, “Birth_date” and “Employment” are the number of days counted backwards from today, which is a bit difficult to understand initially. As such, I decided to convert these variables into positive numbers and years instead.</p><pre>df[&#39;age&#39;] = df.birth_date.apply(lambda x: round(x/-365,0))<br>df[&#39;year_of_employment&#39;] = df.employment.apply(lambda x: round(x/-365,0) if x&lt;0 else 0)</pre><pre>df = df.drop(columns=[&quot;birth_date&quot;,&quot;employment&quot;])</pre><p>Moving on, two highlights of every EDA that I suggest you to never ignore are (1) <strong><em>checking null values</em> </strong>and (2) <strong><em>handling outliers</em></strong>. The former ensures that we have a 100% clean dataset before processing and plugging into modelling while the latter helps avoid your dataset getting overly skewed as a result of marginally extreme outliers.</p><pre>df.isnull().sum()<br>df.occupation_type = df.occupation_type.fillna(&quot;Others&quot;)</pre><p>“Occupation Type” is the only variable that has null values (NaN), so I went ahead filling those values with “Others”.</p><p>Using <strong>df.describe</strong> and <strong>sns.boxplot</strong>, I was able to find out that “Annual Income” and “Fam Members” are two variables that have outliers in the dataset, visually as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*wGnh53YfDe9G9z6IB_-u4A.png" /></figure><p>To remove outliers, I wrote a function which can be easily applied across variables with similar issues at once:</p><pre>def remove_outlier(col):<br>    q25 = col.quantile(0.25)<br>    q75 = col.quantile(0.75)<br>    iqr = q75 - q25<br>    cutoff = iqr*1.5<br>    lower = q25 - cutoff<br>    upper = q75 + cutoff<br>    return lower, upper</pre><pre>#Remove outliers for Annual Income</pre><pre>lower_1, upper_1 = remove_outlier(df.annual_income)<br>df = df.loc[(df.annual_income &gt; lower_1) &amp; (df.annual_income &lt; upper_1)] </pre><pre>#Remove outliers for Fam Members</pre><pre>lower_2, upper_2 = remove_outlier(df.fam_members)<br>df = df.loc[(df.annual_fam_members &gt; lower_2) &amp; (df.fam_members &lt; upper_2)]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*Qsn2bDd6gUpcNJjkM7fZ3g.png" /></figure><p>We’re almost done with EDA, coming down to define the “target” variable, which you might have heard somewhere in most classification lessons.</p><p>Going back to the topic of this project, Credit Risk Management, we need to determine how we should handle the loan repayment status of the customers. With this dataset, I defined “target = 0” for those who didn’t have any loan or paid off that month while the remaining data, any overdue loan, was mapped to “target = 1”.</p><pre>df[&#39;target&#39;] = None<br>df.loc[df.status &lt; 1,&#39;target&#39;]=0<br>df.loc[df.status &gt;= 1,&#39;target&#39;]=1<br>df.target = pd.to_numeric(df.target)</pre><h3>B. Feature Engineering</h3><p><em>What is Feature Engineering and what does it do to help pre-process the data prior to modelling?</em></p><p>According to <a href="https://en.wikipedia.org/wiki/Feature_engineering">Wikipedia</a>,</p><blockquote>Feature engineering is the process of using domain knowledge to extract features from raw data via data mining techniques. These features can be used to improve the performance of machine learning algorithms.</blockquote><p>In fact, Feature Engineering requires not only domain knowledge but also the understanding of the dataset and the goal of achievement. Particularly, with our dataset, there are quite a number of different features, which we call as <strong>independent variables</strong>, which have the correlation with the repayment status, which is the <strong>target variable (0 or 1)</strong>. As such, in order to tune out an insightful and actionable model, we need to “engineer” those features by transforming existing and/or adding supporting data, which makes Feature Engineering different from EDA.</p><p>As I have mentioned from the beginning, we will never know which is a better approach until we test it. That being said, I decided to test out 2 scenarios, <strong>WITH </strong>and <strong>WITHOUT </strong>touching the target variable, and see if there is any significant difference in the result produced later on.</p><p>Before diving into the implementation, we should be aware that there is no “one-size-fit-all” technique for Feature Engineering as it depends on how you process your features. In this project, I leveraged “<strong>Category Encoding</strong>” in my dataset, since the majority of the data is categorical, which should be converted to numerical for easier processing in most machine learning models.</p><pre>df_a = df #for encoding without target<br>df_b = df #for encoding with target</pre><pre>x_a = df_a.iloc[:, 1:-1]<br>y_a = df_a.iloc[:, -1]</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>x_a_train, x_a_test, y_a_train, y_a_test = train_test_split(x_a, y_a, test_size=0.3, random_state=1)</pre><p>Two separate dataset were created for two scenarios, so that we are able to manipulate each dataset without fearing it getting mixed up.</p><p>Also, <strong>an important highlight to note </strong>before processing is that we are highly recommended to <strong>split the dataset </strong>to train and test sets to <strong>avoid data leakage</strong>. Essentially, if we split after processing, the data of the test set has been exposed, hence not being objective enough to compare against the train set in the modelling phase.</p><h3>1. Category Encoding WITHOUT Target</h3><p><em>Depending on the variable type, we will apply the suitable technique to each.</em></p><p>If you refer back to the dataset, there are 3 types of variable: (1) binary, (2) nominal and (3) continuous. While binary and continuous variables are pretty much self-explanatory, nominal variable refers to a group of different categories that has no intrinsic order to each other.</p><h4>1.1. Binary Variables</h4><p>For binary variables in our dataset (e.g. gender, car, property), we can choose either <strong>Label Encoder</strong> or <strong>Label Binarizer</strong> from sklearn library, which will <strong><em>map the original data to 0 or 1:</em></strong></p><pre>#Option 1: Label Encoder (applied to &gt;2 categories per variable)<br>from sklearn.preprocessing import LabelEncoder, LabelBinarizer</pre><pre>le = LabelEncoder()<br>gender_le = le.fit_transform(x_a_train.gender)</pre><pre>#Option 2: LabelBinarizer (applied to 2 categories per variable)</pre><pre>bn = LabelBinarizer()<br>gender_bn = np.array(x_a_train.gender).reshape(-1,1)<br>gender_bn = bn.fit_transform(gender_bn)</pre><h4>1.2. Nominal Variables</h4><p>Nominal variables (e.g. income type, education, family status, housing type, occupation type) are categorical which needs converting to numerical prior to modelling. Two common methods of encoding a category is (1) <strong>Dummy Encoding</strong> and (2) <strong>One Hot Encoder</strong>, which basically creates n columns as n unique categories within that variable and assigns 0 or 1 depending on the absence/presence of each category in each column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HpIj52gOqR-PS7MW.jpeg" /><figcaption>Image credit: <a href="https://deepai.org/machine-learning-glossary-and-terms/dummy-variable">https://deepai.org/machine-learning-glossary-and-terms/dummy-variable</a></figcaption></figure><p>The difference between these methods is that Dummy Encoding coverts into n-1 sub-variables while One Hot Encoder converts into n sub-variables.</p><pre>#Option 1: Dummy Encoding: kn - k variables</pre><pre>income_type_dummy = pd.get_dummies(x_a_train.income_type)</pre><pre>#Option 2: OneHotEcnoder: kn variables</pre><pre>from sklearn.preprocessing import OneHotEncoder</pre><pre>onehot = OneHotEncoder(sparse=False, drop=&#39;first&#39;, handle_unknown=&#39;error&#39;)</pre><pre>income_type_onehot = onehot.fit_transform(x_a_train.income_type.to_numpy().reshape(-1,1))<br>income_type_onehot = pd.DataFrame(income_type_onehot, columns=onehot.get_feature_names([&#39;income_type&#39;]))<br></pre><p>Dummy Encoding can easily be done via <strong>pd.get_dummies()</strong> as it’s a part of pandas library already. For One Hot Encoder, we need to import it from sklearn library and transform each variable, individually or all at the same time.</p><p>One Hot Encoder was designed to keep the consistency in the number of categories across train and test sets (e.g. handling categories that do not appear in either), so it’s more highly recommended than Dummy Encoding due to easier control with “<strong>handle_unknown= “error”</strong>”.</p><p>However, one of the drawbacks of One Hot Encoder is <strong>multicollinearity</strong>, which refers to variables or sub-variables highly linearly related to one another and hence reduces the accuracy of our models. This can be rectified or avoided by assigning the parameter of “<strong>drop= ‘first’</strong>” which helps remove one of the sub-variables after encoding.</p><h4>1.3. Continuous Variables</h4><p>Continuous variables<strong> </strong>are numeric variables that have an infinite number of values between any two values. Essentially, it takes forever to count! Let’s look at the distribution of each continuous variable in our data set visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yw5bCErenx716f-fcU5oAA.png" /></figure><p>The left figure illustrates the range of age of the customers while the right shows the distribution of different income buckets. Two of the common methods to handle this type of variable is (1) <strong>Fixed-width Binning</strong> and (2) <strong>Adaptive Binning</strong>. Particularly, the former creates sub-categories from the pre-defined bins (e.g. age — 10–20, 20–30, 30–40, etc) while the latter relies on the distribution of the data.</p><p>The pros and cons of Fixed-width Binning is that it’s <strong>easy and simple</strong> to encode the variable <strong>yet relatively subjective </strong>without taking into consideration the data itself. As such, I suggest opting for Adaptive Binning which closely looks at the data distribution. From what I observed, instead of converting into 2-bin categories, I decided to go for “<strong>quantiles</strong>” since the original distribution is widely ranged, <strong>after which Label Encoding was applied</strong>.</p><pre>#Convert each variable into 5 equal categories/each</pre><pre>x_a_train[&#39;age_binned&#39;] = pd.qcut(x_a_train.age, q=[0, .25, .50, .75, 1])<br>x_a_train[&#39;annual_income_binned&#39;] = pd.qcut(x_a_train.annual_income, q=[0, .25, .50, .75, 1])</pre><pre>#Apply Label Encoder to assign the label to each category without bias</pre><pre>x_a_train[&#39;age&#39;] = le.fit_transform(x_a_train[&#39;age_binned&#39;])<br>x_a_train[&#39;annual_income&#39;] = le.fit_transform(x_a_train[&#39;annual_income_binned&#39;])</pre><p>Tada! We have engineered all necessary variables without ever touching the target variable! Now, let’s move to the other prior to fitting each to the modelling phase.</p><h3>2. Category Encoding WITH Target</h3><p><em>As the correlation with the target variable is leveraged in this method, we should encode all independent variables in the same way for better objectivity.</em></p><p>Again, pre-requisite has to be followed: train_test_split before processing</p><pre>x_b = df_b.iloc[:, 1:-1]<br>y_b = df_b.iloc[:, -1]</pre><pre>from sklearn.model_selection import train_test_split</pre><pre>x_b_train, x_b_test, y_b_train, y_b_test = train_test_split(x_b, y_b, test_size=0.3, random_state=1)</pre><p>Among the techniques for category encoding with the involvement of the target, I found 3 common options which are widely used: (1) <strong>Weight-of-Evidence Encoder (WOE)</strong>, (2) <strong>Target Encoder</strong>, and (3) <strong>Leave-One-Out Encoder (LOO)</strong>.</p><p>In brief,</p><ul><li><strong>WOE Encoder</strong>: Weight-of-evidence encoding is a widely used technique in credit risk modelling which gets the maximum difference among the unique categories in each variable related to the target. This can be easily understood with its mathematical calculation as below — the natural log of % Good (in this case, target = 0) / % Bad (target = 1):</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VALE5SvAG5QNHLy9assbVg.png" /></figure><ul><li><strong>Target Encoder &amp; LOO Encoder</strong>: while the former method replaces a categorical value with the mean of the target variable across all rows in the dataset, the latter does the same but excludes the row itself. The reason being is to avoid direct target leakage from using too much information before modelling.</li></ul><pre>#Option 1: WOE Encoder<br>import category_encoders as ce</pre><pre>woe = ce.WOEEncoder()</pre><pre>def woe_encoder(col, target):<br>    for i in range(len(x_b_train.columns)):<br>        col.iloc[:,i] = woe.fit_transform(col, target)<br>    return col</pre><pre>df_woe_train = woe_encoder(x_b_train, y_b_train)<br></pre><pre>#Option 2: Target Encoder<br>from category_encoders import TargetEncoder</pre><pre>te = TargetEncoder()</pre><pre>def target_encoder(col, target):<br>    for i in range(len(x_b_train.columns)):<br>        col.iloc[:,i] = te.fit_transform(col, target)<br>    return col</pre><pre>df_te_train = target_encoder(x_b_train, y_b_train)</pre><p>After testing both methods, it seems that the newly encoded dataset between the two is not much of a difference to each other. Hence, I opted for the dataset with WOE Encoder for the following steps of this project. <strong>However</strong>, please test out on other datasets, which might produce a different result possibly due to different data distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHzXQ5JMvUbWlJ2xh3HwWw.png" /><figcaption>WOE Encoder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RUUowahFAvuaLx2M-KorYw.png" /><figcaption>Target Encoder</figcaption></figure><p>Voila! That’s a wrap for the 1st part of this project!</p><p>As shared above, the project was created as a repository of learning notes and highlights along the journey of improving my Data Science skillsets. Hence, I have tested out multiple methods per each section in order to find out the best performing technique for use moving forward.</p><p>Do look out for the next 2 parts which covers <strong>Feature Scaling/Selection</strong> and <strong>Machine Learning Modelling</strong>! In the meantime, let’s connect:</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81cc34efc428" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/credit-risk-management-eda-feature-engineering-81cc34efc428">Credit Risk Management: EDA &amp; Feature Engineering</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exchange Rate Prediction: Time Series Forecasting with ARIMA]]></title>
            <link>https://medium.com/data-science/exchange-rate-prediction-time-series-forecasting-with-arima-27260faafcdc?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/27260faafcdc</guid>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[stationary]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Sun, 31 May 2020 08:36:00 GMT</pubDate>
            <atom:updated>2020-05-31T14:45:30.473Z</atom:updated>
            <content:encoded><![CDATA[<h4>Utilizing the previous work with Regression, this final part aims to forecast future exchange rates using ARIMA, a machine learning algorithm that “predicts the future from the past”.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKcLHePKOSLThuMkzE0keg.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/6EnTPvPPL6I">https://unsplash.com/photos/6EnTPvPPL6I</a></figcaption></figure><p>Here comes the <strong>final part</strong> of my end-to-end project in Data Science. If you have followed or read the previous two parts, you might have known what to expect in this article. But if you haven’t, do not hesitate to check them out: <a href="https://medium.com/analytics-vidhya/exchange-rate-prediction-part-1-276b6cd5338"><strong>1st part</strong></a> and <a href="https://towardsdatascience.com/exchange-rate-prediction-machine-learning-with-5-regression-models-d7a3192531d"><strong>2nd part</strong></a>.</p><p>Here’s a summary of the entire structure of this project:</p><ul><li><strong>Part 1</strong>: Explanatory Data Analysis (EDA) &amp; Data Visualisation (Bonus: Hypothesis Testing)</li><li><strong>Part 2</strong>: Machine Learning with 4 Regression Models</li><li><strong>Part 3: Machine Learning (cont.) with ARIMA</strong></li></ul><p>With the first part paving the foundation for the analysis with data cleaning and visualization and the second employing Regression models to fit all data points, this final part will utilize them all to <strong>predict the future</strong> (in this case, AUD/USD exchange rates in 2020). In order to achieve so, prerequisites and process should be taken into account:</p><ol><li>Stationary Testing (ADF &amp; KPSS)</li><li>Autocorrelation (ACF) and Partial Autocorrelation (PACF)</li><li>ARIMA Forecast</li></ol><p>Let’s get started!</p><p>Before jumping in, you might wonder why we need to follow the mentioned structure before using ARIMA. If so, let’s briefly understand what ARIMA is and needs prior!</p><h3>0. ARIMA in a nutshell</h3><p><em>What does ARIMA stand for?</em></p><p>When it comes to forecasting a time series, we can choose either:</p><ul><li><strong>Univariate</strong>: if we believe the previous values of the time series are able to predict its future values</li><li><strong>Multi-Variate</strong>: if we use predictors OTHER THAN the series itself to predict the future values</li></ul><p>In this case, ARIMA stands for <em>‘AutoRegressive Integrated Moving Average’</em>, an algorithm originating from the belief that the <strong><em>past values of a time series can alone be used to predict future values</em></strong>.</p><p>To use ARIMA, we need to determine the values for its parameter: p, d, q</p><ul><li>p: the order of the AR term (AR: Auto-Regressive)</li><li>d: the number of differencing</li><li>q: the order of the MA term (MA: Moving Average)</li></ul><p>That’s pretty much all information needed for you to get acquainted with what’s coming below.</p><h3>1. Stationary Testing</h3><p><em>What is Stationary Testing and why do we need it?</em></p><p>ARIMA requires the dataset to be “<strong>stationary</strong>” in order for the model to produce accurate predictions. In a nutshell, stationary series, technically, does not vary over time. Particularly, parameters such as <strong>mean, variance, and covariance remain unchanged with time</strong>.</p><p>To illustrate it more visually engaging, let’s look at the charts below to see the difference between stationary and non-stationary data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ID13ocl51akBidzW.png" /><figcaption>Source: <a href="https://en.wikipedia.org/wiki/Stationary_process">https://en.wikipedia.org/wiki/Stationary_process</a></figcaption></figure><p>As you can see, it does not mean the dataset is “frozen” at any particular point of time. It does change, but its mean and variance remain the same as time shifts (chart 1). <strong>In contrast</strong>, if such unusual peaks or dips are seen (no clear patterns), it means the dataset and its statistical properties change over time (chart 2). It’s commonly known to be owing to trends or seasonality that intervene in the dataset.</p><p>If you want to dive in the difference between the two, mathematically, check out this article on Towards Data Science:</p><p><a href="https://towardsdatascience.com/stationarity-in-time-series-analysis-90c94f27322">Stationarity in time series analysis</a></p><p>Stationary data is important because it’s easier <strong>for the model to learn</strong> the pattern as well as <strong>for us to analyze and forecast</strong>, which has become a common assumption in most time series analysis.</p><p>Having said so, how do we know whether the dataset is stationary or not? First of all, we can rely on <strong>statistical testing</strong> to check the stationarity and if it’s not, we need to transform the data from non-stationary to stationary.</p><p><strong>ADF </strong>(Augmented Dickey-Fuller) and <strong>KPSS</strong> (Kwiatkowski-Phillips-Schmidt-Shin) are two common statistical tests for stationarity. The purpose of these two tests is technically the same, except for the technique used behind. Whereas <strong>ADF uses differencing</strong> to transform the dataset, <strong>KPSS removes the trend</strong> to make the data stationary. Therefore, it’s well advised to use both tests to ensure the expected outcomes.</p><p>However, one important to note is that the H0 (null hypothesis) and H1 (alternative hypothesis) of the two tests are the opposite to each other:</p><ul><li><strong>ADF:</strong> H0 states that the dataset is <strong>NOT</strong> stationary while H1 says it is.</li><li><strong>KPSS</strong>: H0 states that the dataset is stationary while H1 says it is<strong> NOT</strong>.</li></ul><pre>from statsmodels.tsa.stattools import adfuller</pre><pre>adf_test = adfuller(y_pred)<br>print(&#39;stat=%.3f, p=%.3f&#39; % adf_test[0:2])<br>if adf_test[1] &gt; 0.05:<br> print(&#39;Probably not Stationary&#39;)<br>else:<br> print(&#39;Probably Stationary&#39;)</pre><p>The result of ADF test: <strong>stat=-0.434, p=0.904— ‘Probably not Stationary’</strong></p><pre>from statsmodels.tsa.stattools import kpss</pre><pre>kpss_test = kpss(y_pred, nlags=&#39;auto&#39;)</pre><pre>print(&#39;stat=%.3f, p=%.3f&#39; % kpss_test[0:2])<br>if kpss_test[1] &gt; 0.05:<br>    print(&#39;Probably Stationary&#39;)<br>else:<br>    print(&#39;Probably not Stationary&#39;)</pre><p>The result of KPSS test: <strong>stat=0.692, p=0.014 — ‘Probably not Stationary’</strong></p><p>It turns out that the dataset is NOT stationary at all! Let’s see it visually:</p><pre>from statsmodels.tsa.seasonal import seasonal_decompose</pre><pre>y_pred_list = y_pred.tolist()<br>result = seasonal_decompose(y_pred_list, model=&#39;additive&#39;, period=1)</pre><pre>result.plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*1aqkGnOSxrvFGFsFtU5kfw.png" /></figure><p><strong>Seasonal_decompose </strong>tells us how our dataset looks in terms of trend, seasonal and residual. As you can see, the pattern between Observed and Trend is pretty similar to each other, implying that trend has intervened as the cause of non-stationary data.</p><p>Let’s make it stationary, again!!</p><pre>date = list(range(1,37))<br>date_fx = pd.DataFrame(zip(date, y_pred_list), columns=[&#39;Date&#39;, &#39;FX&#39;])</pre><pre>date_fx_log = np.log(date_fx)</pre><pre>date_fx_log_diff = date_fx_log - date_fx_log.shift(1)<br>date_fx_log_diff.dropna(inplace=True)</pre><pre>y_stationary = date_fx_log_diff.iloc[:,1]</pre><p>First of all, I replaced the actual date with a range of numbers from 1 to 36 (representing 36 months in our data), for the sake of simplicity. Then, to stabilize the dataset, I applied transformation into the original data with <strong>np.log</strong> (this can be done by different methods: power transform, square root or log transform). Finally, I used <strong>differencing</strong> to make the data stationary with <strong>.shift(1),</strong> which substracts every point in the dataset by the one that precedes it.</p><p>There we go, we have transformed the non-stationary predicted exchange rates (y_pred_list, as in the previous part) to the stationary one (y_stationary)!</p><p>Let’s double check with ADF and KPSS again!</p><pre>#a. ADF Test<br>adf_test_2 = adfuller(y_stationary)<br>print(&#39;stat=%.3f, p=%.3f&#39; % adf_test_2[0:2])<br>if adf_test_2[1] &gt; 0.05:<br> print(&#39;Probably not Stationary&#39;)<br>else:<br> print(&#39;Probably Stationary&#39;)</pre><pre>#b. KPSS Test<br>kpss_test_2 = kpss(y_stationary, nlags=&#39;auto&#39;)</pre><pre>print(&#39;stat=%.3f, p=%.3f&#39; % kpss_test_2[0:2])<br>if kpss_test_2[1] &gt; 0.05:<br>    print(&#39;Probably Stationary&#39;)<br>else:<br>    print(&#39;Probably not Stationary&#39;)</pre><p>The results are:</p><ul><li><strong>ADF:</strong> stat=-5.316, p=0.000, Probably Stationary</li><li><strong>KPSS</strong>: stat=0.192, p=0.100, Probably Stationary</li></ul><p>YAY!</p><h3>2. Autocorrelation (ACF) and Partial Autocorrelation (PACF)</h3><p><em>What is ACF and PACF and how do they relate to ARIMA?</em></p><p>After making the dataset stationary, we move on to the 2nd step of the process: determining the <strong>p, d, q</strong> for the ARIMA model. This can be done by looking at ACF and PACF plots!</p><p>According to <a href="https://machinelearningmastery.com/gentle-introduction-autocorrelation-partial-autocorrelation/">Machine Learning Mastery</a>,</p><blockquote>These are plots that graphically summarize the strength of a relationship with an observation in a time series with observations at prior time steps.</blockquote><p>This exactly aligns with one of the steps we have done previously: <strong>differencing with .shift(1)</strong>! If you recall, we have employed shift as the way to subtract the current value by its preceding one to make the data stationary. Indeed, ACF and PACF can do more than just differencing!</p><p>Let’s plot them out:</p><pre>from statsmodels.graphics.tsaplots import plot_acf, plot_pacf</pre><pre>date_fx_log_diff = date_fx_log_diff.values.reshape(-1)</pre><pre>plot_acf(date_fx_log_diff, lags=50)<br>plot_pacf(date_fx_log_diff, lags=50)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*fL9qy2M_Jdwzd7zoB657Ng.png" /></figure><p>Based on the shape and the pattern of ACF and PACF, we can determine the p (AR term) and q (MA term) for the ARIMA model. If you want to dive into it, check out these articles <a href="https://support.minitab.com/en-us/minitab/18/help-and-how-to/modeling-statistics/time-series/how-to/autocorrelation/interpret-the-results/autocorrelation-function-acf/">here</a> and <a href="https://support.minitab.com/en-us/minitab/18/help-and-how-to/modeling-statistics/time-series/how-to/partial-autocorrelation/interpret-the-results/partial-autocorrelation-function-pacf/">here</a>. Essentially, the number of significant lags in the charts “delivers the message”, in this case the values of p &amp; q.</p><p>As you can see in ACF plot, a large spike is seen in lag 1, followed by 2 or 3 more lags and all of them are deemed significant as they lie above the “limit threshold” or “significance line” (the blue area). Likewise, in the PACF plot, a large spike is seen in lage 1, followed by another in lag 3. So what does it all imply?</p><p>To me, this finding is a key to testing which combination of (p, d, q) brings out the best result for our ARIMA model, in which p can be found in ACF and q in PACF. So what <strong><em>result</em></strong> is it, specifically? It’s AIC.</p><blockquote>The Akaike Information Critera (AIC) is a widely used measure of a statistical model. It basically quantifies 1) the goodness of fit, and 2) the simplicity/parsimony, of the model into a single statistic. — Abbas Keshvani, <a href="https://coolstatsblog.com/2013/08/14/using-aic-to-test-arima-models-2/">Coolstatsblog</a></blockquote><p>Generally, the lower the AIC is, the better. Let’s move to part 3 to find out which combination brings the lowest AIC!</p><h3>3. ARIMA Forecasting</h3><p><em>Let’s plug in the values of p, d, q to our ARIMA model!</em></p><p>As I explained earlier, the number of significant lags in the ACF and PACF plots can be translated into the corresponding p &amp; q. Let’s see how ARIMA looks with the following values:</p><ul><li>p = 3 as 3 significant lags in ACF</li><li>d = 1 as computed in .shift(1)</li><li>q =2 as 2 significant lags in PACF</li></ul><pre>from statsmodels.tsa.arima_model import ARIMA</pre><pre>y = date_fx_log.iloc[:, 1]</pre><pre>model_arima = ARIMA(y, (3,1,2))<br>model_arima_fit = model_arima.fit()<br>print(model_arima_fit.summary())</pre><p>First of all, we imported ARIMA from Statsmodels library and extracted y from the transformed dataset. Then, we fit ARIMA model with the above values of (p, d, q) and called <strong>.summary()</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*zueKl95wxV2IYXiBj-aEmQ.png" /></figure><p>As much complicated as it looks, we just have to focus on two metrics in the table: AIC and p-value (P&gt;|z|).</p><ul><li>AIC = -183.227, which we will test against another combination of p, d, q to see if it’s the lowest value or not.</li><li>With p = 3, the model returns 3 different p-values for each AR in different lines. While the first two’s <strong>p-values &lt;0.05</strong> (which is ideally recommendable), the AR.L3’s is above 0.05. This means that there might actually be 2 significant lags in the ACF plot.</li></ul><p>Based on the finding, let’s test out another combination of (p, d, q) = (2,1,2):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4zFIIw7Vaw_xjyxk-tlglw.png" /></figure><p>In this case, the AIC (-183.096) does not improve compared to the first model’s AIC (-183.227). Furthermore, the p-values of AR.L1 (the 1st p) and MA.L1 (the 1st q) are &gt;0.05, which indicates that we might only need p=1 and q=1. Let’s test this out with (p, d, q) = (1, 1, 1):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPOf6AW8r5O3e67gzAaanw.png" /></figure><p>Bingo! The AIC has improved quite a lot as it’s the best value so far after three trials (lowest AIC and all p-values &lt;0.05).</p><p>Okay, this process has been a bit too manual and time-consuming. How about we use <strong>iteration with a for loop</strong> and see which combination (p, d, q) brings out the lowest AIC?</p><pre>import itertools</pre><pre>p = range(1, 4)<br>d = range(1, 2)<br>q = range(1, 3)</pre><pre>pdq = list(itertools.product(p, d, q))</pre><pre>aics = []<br>params = []</pre><pre>for param in pdq:<br>    model = ARIMA(y, order=param)<br>    model_fit = model.fit()<br>    aic = model_fit.aic<br>    aics.append(aic)<br>    params.append(param)</pre><pre>combo = list(zip(aics, params))<br>combo.sort()</pre><pre>combo_array = np.array(combo)<br>print(combo_array)</pre><p>As seen in the above, I created different ranges for p, d and q corresponding with the ACF and PACF plots:</p><ul><li>p = range(1, 4): as 3 lags are seen in ACF</li><li>d = range(1, 2): as we need at least 1 differencing to make the data stationary</li><li>q = range(1, 3): as 2 lags are seen in PACF</li></ul><p>Then, I used <strong>itertools.product()</strong> to generate different combinations from the given values. Finally, I applied a<strong> for loop</strong> and fit the ARIMA model with each combination generated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*jJsI96CWWG220kE4sCD7Tg.png" /></figure><p>So there you go, the lowest AIC is -185.892 from the (p, d, q) of (1, 1, 1), which is the same as the latest trial above!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPOf6AW8r5O3e67gzAaanw.png" /></figure><p>Finally, the very last step of all, forecasting:</p><pre>pred = model_arima_fit.forecast(12, alpha=0.05)[0]<br>print(pred)</pre><pre>model_arima_fit.plot_predict(1,42)</pre><p>Just a quick note, <strong>.forecast()</strong> includes <strong>the number of values</strong> which we need to forecast (in this case, 12 months in 2020 following the dataset period) and <strong>alpha=0.05</strong> as 95% confidence interval. plot_predict(1, 42) as (start, end) of the entire dataset of forecast (in this case, 1 as the 1st month, 01/2017, and 2 as the last month, 12/2020).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*fycP6prWcEVR5Dg621yEwQ.png" /></figure><p>Regarding the matchability of our y-value (orange) and the forecast (blue), it doesn’t look bad! In fact, if you recall from the chart with Polynomial Regression, the forecast (blue) perfectly matches the line that we’ve discovered!</p><p>Tadah! We nearly get to the end of the project, which we have forecasted the exchange rates in 2020. If you print the predicted values, it might look odd to you:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*IbYJct1SDG8zf-lfnC7zwQ.png" /></figure><p>That’s because the predicted values originated from the dataset which <strong>had been log-transformed</strong> before running this model! Simply revert the values with the help of <strong>exponential function</strong>, which is the inverse of log.</p><pre>pred = np.exp(pred)<br>forecast = pred.tolist()</pre><pre>fx_2020 = np.array(list(zip(month_year_future, forecast)))<br>print(fx_2020)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*W4CkjOhMh2o20Y8ngSNTdg.png" /></figure><p>Perfect! Let’s visualize it as a whole, from 2017 to 2020!</p><pre>x_merge = [&#39;2019-12&#39;, &#39;2020-01&#39;]<br>y_merge = [y_pred[-1], forecast[0]]</pre><pre>plt.figure(figsize=(14,6))<br>plt.scatter(month_year, y_fx, alpha=0.4)<br>plt.plot(month_year, y_fx_predict, color=&#39;b&#39;)<br>plt.plot(month_year, y_fx_predict_2, color=&#39;r&#39;)<br>plt.plot(month_year, y_fx_predict_3, color=&#39;g&#39;)<br>plt.plot(month_year, y_pred, color=&#39;black&#39;)<br>plt.plot(x_merge, y_merge, color=&#39;y&#39;)<br>plt.plot(month_year_future, forecast, color=&#39;y&#39;)<br>plt.legend([&#39;1var&#39;, &#39;2var&#39;, &#39;3var&#39;, &#39;3var with Poly&#39;, &#39;Forecast&#39;])<br>plt.title(&quot;Linear Regression: AUD/USD Exchange Rate (3 var: Interest Rate, GDP &amp; UER)&quot;)<br>plt.xlabel(&quot;Month-Year&quot;)<br>plt.ylabel(&quot;Exchange Rate&quot;)<br>plt.xticks(fontsize=5)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iR0cTWHUv3TjWJyg2q08xw.png" /></figure><p>Voila!!!</p><p>That’s the end of this project — Exchange Rate Prediction! Despite a lot information to absorb, I do hope you find the entire series (<a href="https://medium.com/analytics-vidhya/exchange-rate-prediction-part-1-276b6cd5338"><strong>part 1</strong></a>, <a href="https://towardsdatascience.com/exchange-rate-prediction-machine-learning-with-5-regression-models-d7a3192531d"><strong>part 2</strong></a>, and final part here) helpful and informative!</p><p>Do look out for my <strong>upcoming projects</strong> in Data Science and Machine Learning in the near future! In the meantime, give me a clap if you find this helpful and feel free to check out my Github here for the complete repository:</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27260faafcdc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exchange-rate-prediction-time-series-forecasting-with-arima-27260faafcdc">Exchange Rate Prediction: Time Series Forecasting with ARIMA</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exchange Rate Prediction: Machine Learning with 5 Regression Models]]></title>
            <link>https://medium.com/data-science/exchange-rate-prediction-machine-learning-with-5-regression-models-d7a3192531d?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7a3192531d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[regularization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[linear-regression]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Fri, 29 May 2020 12:31:01 GMT</pubDate>
            <atom:updated>2020-05-30T03:18:25.163Z</atom:updated>
            <content:encoded><![CDATA[<h4>Following data cleaning and visualisation, this part deploys Machine Learning to find the best line that fits all data points, as the preparation for the prediction in the final part.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nO79OeVwblOJkr6XyupheA.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/7JoXNRbx6Qg">https://unsplash.com/photos/7JoXNRbx6Qg</a></figcaption></figure><p>If you have missed my <strong>1st part</strong> on this end-to-end project about Exchange Rate Prediction, feel free to check it out <a href="https://medium.com/analytics-vidhya/exchange-rate-prediction-part-1-276b6cd5338"><strong>here</strong></a><strong>.</strong></p><p>As a recap, this project aims to analyze the historical pattern of exchange rates across different country currencies against USD and therefore to forecast the values in 2020. In order to bring out the best model, I have divided the project into 3 parts which, I hope, will possibly cover what is needed for the prediction:</p><ol><li><strong>Part 1</strong>: Explanatory Data Analysis (EDA) &amp; Data Visualisation (Bonus: Hypothesis Testing)</li><li><strong>Part 2: Machine Learning with 4 Regression Models</strong></li><li><strong>Part 3:</strong> Machine Learning (cont.) with ARIMA</li></ol><p>Today, I will bring you through the 2nd part which deploys Machine Learning with the aim of <strong>finding the line that best fits </strong>the pattern of exchange rates over the years. That being said, Linear Regression would seemingly be the right model or, at least, the foundation for our analysis. Beyond it, I have also tested out other linear regression models before deciding which to use for the forecasting (part 3):</p><ul><li>Linear Regression</li><li>Multiple Linear Regression</li><li>Polynomial Regression</li><li>Ridge Regression (L2 Regularization)</li><li>Lasso Regression (L1 Regularization)</li></ul><p>Let’s get started!</p><p>According to Investopedia, there are 3 common ways to forecast exchange rates: Purchasing Power Parity (PPP), Relative Economic Strength, and Econometric Model. Among the three, I decided to go with the third as it involves a multitude of factors that affect currency movements.</p><p><a href="https://www.investopedia.com/articles/forex/11/4-ways-to-forecast-exchange-rates.asp">Learn 3 Common Ways to Forecast Currency Exchange Rates</a></p><blockquote>“The factors used in econometric models are typically based on economic theory, but <strong>any variable</strong> <strong>can be added</strong> if it is <strong>believed to significantly influence</strong> the exchange rate.” — Investopedia, by Joseph Nguyen.</blockquote><p>This method greatly aligns with the direction that employs “any independent variable” that is influential on the dependent variable — linear regression. Therefore, the factors I wanted to test out are <strong>interest rate differential</strong>, <strong>GDP growth rates</strong>, and <strong>income growth rate</strong>, sequentially yet accumulatively. For this project, I used the exchange rate of AUD/USD for the analysis.</p><h3>1. Linear Regression</h3><p>Let’s kick off our Linear Regression model with one independent variable: <strong>Interest Rate Differential</strong>. If you are keen to explore, please refer to this <a href="https://forexop.com/swaps/AUDUSD/">data source</a>.</p><pre>ir_df = pd.read_csv(&quot;aud usd interest carry trade.csv&quot;)<br>ir_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*ToYzrypGkouFCCKEClM0og.png" /></figure><p>Above is the table of interest rate differential of AUD/USD from 2017 to 2019. If you want to know more what “long carry” and “short carry” are, check out this article on Investopedia about <a href="https://www.investopedia.com/terms/c/currencycarrytrade.asp">Carry Trade</a> and another on FXCM about <a href="https://www.fxcm.com/markets/insights/interest-rate-carry-trades/">Interest-Rate Carry Trade</a>. In short,</p><blockquote>Interest-rate carry trades are a form of arbitrage, in which someone makes use of the difference that exists between two markets in order to turn a profit.</blockquote><p>As such, let’s transform this data for the analysis (in this case, I used Long Carry Interest Rate):</p><pre>x_ir = ir_df[&#39;Long Carry&#39;].astype(str)<br>x_ir = x_ir.replace({&#39;%&#39;:&#39;&#39;}, regex = True)<br>x_ir = x_ir.astype(float)<br>x_ir = np.array(x_ir).reshape(-1,1)</pre><pre>aud_usd_fx = df_groupby_aud[(df_groupby_aud[&#39;month_year&#39;] &gt;= &#39;2017-01&#39;) &amp; (df_groupby_aud[&#39;month_year&#39;] &lt;=&#39;2019-12&#39;)].reset_index(drop=True)<br>aud_usd = aud_usd_fx[&#39;AUD_USD&#39;]</pre><pre>y_fx = aud_usd</pre><p>Here, <strong>x_ir</strong> refers to the independent variable that affects our exchange rate. For easier use, I removed the “%” from the numbers with <strong>regex replace</strong>, and converted them to float. As 2D array data is required in the regression model, we need to convert our 1D x_ir to 2D by using <strong>.reshape(-1, 1). </strong>And if you recall from the 1st part, we have cleaned up the entire dataset, so it’s now easier for us to pick up the AUD/USD data (y_fx) as the dependent variable.</p><p>Please note that I only used a short period of time (from 2017 to 2019, 36 months) in this project for the sake of simplicity.</p><p>There you go, let’s run our 1st machine learning model by importing<strong> </strong>relevant functions from<strong> Scikit-learn</strong> library!</p><pre>from sklearn.model_selection import train_test_split<br>from sklearn.linear_model import LinearRegression</pre><p>As you might have known, in order to test the accuracy of our model, we are advised to split the dataset into training and testing sets. Essentially, we train the model on the training set and then predict the values with the testing set.</p><pre>x_train, x_test, y_train, y_test = train_test_split(x_ir, y_fx, train_size=0.8, test_size=0.2, random_state=1)</pre><pre>model = LinearRegression()<br>model.fit(x_train, y_train)<br>y_predict = model.predict(x_test)</pre><pre>print(model.score(x_train, y_train))<br>print(model.score(x_test, y_test))</pre><p>Here, I split the data into 80% training and 20% test, meaning that the model will learn the pattern by 80% training data, and then predict the y values with 20% testing data. <strong>.score()</strong> tells us the percentage of a dependent variable (exchange rate) being explained by the independent variable (interest rate differential) or as we know, <strong>R-squared</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*pkczz9rEnsJb-EijeFG2BA.png" /></figure><p>As you can see, the percentage between training and testing data is pretty much close, meaning that the accuracy of the model is relatively good.</p><p>However, from my observation, the size of the dataset is relatively small (n=36 as we only cover 2017 to 2019), I wanted to see whether I’m able to NOT split the data into training and testing sets or not, for the sake of simplicity.</p><pre>model = LinearRegression()<br>model.fit(x_ir, y_fx)<br>y_fx_predict = model.predict(x_ir)</pre><pre>print(model.score(x_ir, y_fx))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*V8kDME6N1bMwHBz63XEL2g.png" /></figure><p>The difference in the R-squared between split and no-split is minimal, probably due to the small dataset size. Hence, I will <strong>NOT</strong> split the data and use the entire dataset.</p><p>Let’s see how well our model does in creating the “best-fit” line:</p><pre>month_year = aud_usd_fx[&#39;month_year&#39;]<br>month_year = month_year.astype(str)</pre><pre>plt.figure(figsize=(12,6))<br>plt.scatter(month_year, y_fx, alpha=0.4)<br>plt.plot(month_year, y_fx_predict)<br>plt.title(&quot;Linear Regression: AUD/USD Exchange Rate (1 var: Interest Rate)&quot;)<br>plt.xlabel(&quot;Month-Year&quot;)<br>plt.ylabel(&quot;Exchange Rate&quot;)<br>plt.xticks(fontsize=4)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDSCqGjgtixIs_6a7vCtKg.png" /></figure><p>Combined with the R-squared, the line seems to be able to portray the exchange rate to some extent (R-squared is 72%). Let’s add another variable to see how far our R-squared improves, with Multiple Linear Regression.</p><h3>2. Multiple Linear Regression</h3><p>As shared from the beginning of the article, we are able to add additional variables to the model as long as they are influential on the dependent variable. This leads us to the second Linear Regression model, which includes <strong>more than 1 independent variable</strong>.</p><p>Let’s add <strong>GDP Growth Rate</strong> to our dataset, which can be found from <a href="https://fred.stlouisfed.org/">this domain</a>.</p><pre>aus_gdp = pd.read_csv(&quot;AUS GDP.csv&quot;)<br>usa_gdp = pd.read_csv(&quot;USA GDP.csv&quot;)</pre><pre>aus_gdp = aus_gdp.rename(columns={&#39;GDP&#39;: &#39;AUS_GDP&#39;})<br>aus_usa_gdp = pd.merge(aus_gdp, usa_gdp, on=&quot;month_year&quot;, how=&quot;inner&quot;)<br>aus_usa_gdp = aus_usa_gdp.rename(columns={&#39;GDP&#39;: &#39;USA_GDP&#39;})<br>aus_usa_gdp[&#39;GDP_diff&#39;] = aus_usa_gdp[&#39;AUS_GDP&#39;] - aus_usa_gdp[&#39;USA_GDP&#39;]</pre><pre>aus_usa_gdp_20172019 = aus_usa_gdp[(aus_usa_gdp[&#39;month_year&#39;] &gt;= &#39;2017-01&#39;) &amp; (aus_usa_gdp[&#39;month_year&#39;] &lt;=&#39;2019-12&#39;)].reset_index(drop=True)</pre><pre>gdp_diff = [&quot;%.4f&quot; %num for num in aus_usa_gdp_20172019[&#39;GDP_diff&#39;]]</pre><p>After loading the data, I applied EDA to clean up and extracted <strong>gdp_diff </strong>from the dataframe to a list, so as to combine with <strong>x_ir</strong> variable for our Multiple Linear Regression.</p><pre>x_ir_gdp = np.array(list(zip(x_ir, gdp_diff)))<br>x_ir_gdp = x_ir_gdp.astype(np.float)</pre><pre>model.fit(x_ir_gdp, y_fx)<br>y_fx_predict_2 = model.predict(x_ir_gdp)</pre><pre>print(model.score(x_ir_gdp, y_fx))</pre><p>After adding another variable to the model, R-squared has improved quite significantly, from 72% to 87.2%. Let’s compare it visually against the first line we created:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zujdHWj4ivYFyGv29BUNbw.png" /></figure><p>Looks good, right! Okay, let’s try adding another independent variable to our model, <strong>Consumer Price Index (CPI). </strong>Again, the dataset can be found from <a href="https://fred.stlouisfed.org/">this domain</a>.</p><pre>cpi = pd.read_csv(&quot;aus usa cpi difference.csv&quot;)</pre><pre>cpi_diff = cpi[&#39;CPI_diff&#39;]</pre><pre>x_ir_gdp_cpi = np.array(list(zip(x_ir, gdp_diff, cpi_diff)))<br>x_ir_gdp_cpi = x_ir_gdp_cpi.astype(np.float)</pre><pre>model.fit(x_ir_gdp_cpi, y_fx)<br>y_fx_predict_4 = model.predict(x_ir_gdp_cpi)</pre><pre>print(model.score(x_ir_gdp_cpi, y_fx))</pre><p>This time, R-squared increased really slightly, from 87.2% to 87.3%. This means CPI does not significantly affect the movement of exchange rate nor help improve our model. Visually, there’s no difference either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D961H4RCVX1naDmb4ibVVw.png" /></figure><p>Let’s replace CPI variable with another, Unemployment Rate (UER) and see whether this improves our model or not.</p><pre>unemployment_rate = pd.read_csv(&quot;aus usa unemployment rate.csv&quot;)</pre><pre>unemployment_rate[&#39;uer_diff&#39;] = unemployment_rate[&#39;aus_unemployment rate&#39;] - unemployment_rate[&#39;usa_unemployment rate&#39;]<br>uer_diff_all = unemployment_rate[&#39;uer_diff&#39;]</pre><pre>uer_diff = [&quot;%.4f&quot; % num for num in uer_diff_all]</pre><pre>x_ir_gdp_uer = np.array(list(zip(x_ir, gdp_diff, uer_diff)))<br>x_ir_gdp_uer = x_ir_gdp_uer.astype(np.float)</pre><pre>model.fit(x_ir_gdp_uer, y_fx)<br>y_fx_predict_3 = model.predict(x_ir_gdp_uer)</pre><pre>print(model.score(x_ir_gdp_uer, y_fx))</pre><p>Okay, R-squared has improved a bit better, from 87.2% to 88.9%. Not too bad, statistically and visually. You can continue to add some more variables to the model, but be careful with <strong>overfitting</strong>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eP2ddK3o8lCJyIQWXZ2xUw.png" /></figure><p>For me, instead of adding more independent variables, I decided to test out another regression model to find a better-fit line: Polynomial Regression.</p><h3>3. Polynomial Regression</h3><p>What is Polynomial Regression? It’s still one kind of Linear Regression but a much more “adaptable” version.</p><p>Traditionally, Linear Regression aims to find the best linear line that fits all your data points, which might not always be the case. Therefore, Polynomial Regression acts as another form that draws the line from coordinates (x, y) with <strong><em>y modeled as the nth degree polynomial</em></strong>.</p><p>Let’s import the function from Sciki-learn library and build our model:</p><pre>from sklearn.preprocessing import PolynomialFeatures</pre><pre>poly = PolynomialFeatures(degree=4)</pre><pre>x_poly = poly.fit_transform(x_ir_gdp_uer)</pre><pre>model_poly = LinearRegression()<br>model_poly.fit(x_poly, y_fx)<br>y_pred = model_poly.predict(x_poly)</pre><pre>print(model_poly.score(x_poly, y_fx))</pre><p>The only difference in the function between Linear and Polynomial Regression is the <strong>degree</strong> parameter. Before getting to the result, let me briefly explain: <strong>.fit_transform()</strong> is to convert your independent variables from linearly to polynomially. The rest of the function stays the same.</p><p>Here, I randomly selected the degree of 4 and R-squared is nearly perfect: 99.9%! You may want to see it visually?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z_HqHGFmTa1DxyDSa-9MaA.png" /></figure><p>The black line represents the fit that Polynomial Regression found with the degree of 4. How amazing? But the question is: “Which degree is the best, to <strong>neither overfit nor underfit</strong> the data?”</p><p>We know that we aim to find <strong>R-squared</strong> as high as possible, as it well explains the fact that the dependent variable (exchange rate) is affected by the independent variable(s). Apart from it, there is another metric that is able to evaluate the accuracy of our model: <strong>Mean Squared Error (MSE).</strong></p><p>To find the best degree, I decided to test a range of degrees, from 1 to 10 on our model separately with<strong> a for loop </strong>and visualize it:</p><pre>from sklearn.metrics import mean_squared_error</pre><pre>r_squared_list = []<br>mse_list = []<br>a = range(1,10,1)</pre><pre>for i in a:<br>    poly = PolynomialFeatures(degree=i)<br>    x_poly = poly.fit_transform(x_ir_gdp_uer)<br>    <br>    model_poly = LinearRegression()<br>    model_poly.fit(x_poly, y_fx)<br>    y_pred = model_poly.predict(x_poly)<br>    <br>    r_squared = model_poly.score(x_poly, y_fx)<br>    mse = mean_squared_error(y_pred, y_fx)<br>    <br>    r_squared_list.append(r_squared)<br>    mse_list.append(mse)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ysbJvtai3OaV7tZGcJjq_Q.png" /></figure><p>As you can see in both charts, as the line increases from degrees of 1 to 4, the R-Squared and MSE improve significantly (the higher the better for R-Squared, the lower the better for MSE). However, it peaks at degree of 4 and no further improvement is seen since the degree of 5. This means that degree of 4 brings out the best accuracy score for our model! So let’s stick with 4 then!</p><p>Yay! We finally got the line that best fits the exchange rate over the years, thanks to Polynomial Regression!</p><h3>4. &amp; 5. Ridge Regression &amp; Lasso Regression</h3><p>These final two are my latest experiment in the “ecosystem” of linear regression models as I have heard about somewhere before. Oh yes, it regards L1 &amp; L2 Regularisation! As such, I wanted to test out these two models in my project as well to see how they perform against the above models.</p><p>However, before jumping into them, let’s quickly point out the origin of these models, <strong>Regularisation</strong>, and the roles they play against what we might commonly know about Linear Regression.</p><p>It all started with <strong>Overfitting</strong>. In a nutshell, overfitting occurs when a machine learning model is too tailored to a certain dataset (especially with too many independent variables/features) and hence unable to generalise to other datasets. Hence, <strong>regularisation</strong> was introduced to prevent this phenomenon. Essentially, what regularisation does is:</p><ul><li>Reduce the complexity of the model while maintaining the number of independent variables/features</li><li>Technically, reduce the magnitude of the coefficients as penalty term to the loss function</li></ul><p>If you want to deep dive into how it works, mathematically, check out this article on <a href="https://towardsdatascience.com/intuitions-on-l1-and-l2-regularisation-235f2db4c261">Towards Data Science</a> for more details.</p><p>Ridge Regression and Lasso Regression were developed from this concept of Regularisation. The only difference between the two is:</p><ul><li><strong>Ridge Regression</strong> uses L2 Regularisation technique, which shrinks the coefficients to zero, but <strong>NOT absolute zero</strong></li><li><strong>Lasso Regression</strong> uses L1 Regularisation technique, which shrinks the coefficients to <strong>absolute zero</strong></li></ul><p>This is because Ridge keeps all variables/features <strong><em>while</em></strong> Lasso only keeps the important ones that matter, hence voted as the variable/feature selection technique when our dataset has TOO MANY variables/features.</p><p>Okay, back to our dataset!</p><p>Even though our model does not have too many variables (in this case, 3), I still wanted to see how Ridge and Lasso Regression perform on my dataset.</p><pre>from sklearn.linear_model import Ridge, Lasso</pre><pre>ridge = Ridge(alpha=0.001)<br>ridge.fit(x_ir_gdp_uer, y_fx)</pre><pre>y_fx_ridge = ridge.predict(x_ir_gdp_uer)<br>print(ridge.score(x_ir_gdp_uer, y_fx))</pre><pre>lasso = Lasso(alpha=0.001)<br>lasso.fit(x_ir_gdp_uer, y_fx)</pre><pre>y_fx_lasso = lasso.predict(x_ir_gdp_uer)<br>print(lasso.score(x_ir_gdp_uer, y_fx))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwa17SGtblMLrEyfw6Lg2A.png" /></figure><p>R-Squared of Ridge is 88% while of Lasso is 87%. Not too bad when we compare these numbers with our Multiple Linear Regression (88.9%). This proves that overfitting does not occur to our model!</p><p>WOW! That’s a wrap for the 2nd part of this project! Too much to absorb, isn’t it? But I do hope you have found this article informative and actionable.</p><p>In short, we have <strong>found the line that best fits our dataset</strong>, greatly explaining the pattern of exchange rates over the years! What’s next?</p><p>Again, do look out for the <strong>final part</strong> of my project which will cover <strong>how I forecasted the exchange rates of 2020 </strong>using the regression line we have just discovered. In the meantime, give me a clap if you find this helpful and feel free to check out my Github here for the complete repository:</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7a3192531d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/exchange-rate-prediction-machine-learning-with-5-regression-models-d7a3192531d">Exchange Rate Prediction: Machine Learning with 5 Regression Models</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exchange Rate Prediction (part 1)]]></title>
            <link>https://medium.com/analytics-vidhya/exchange-rate-prediction-part-1-276b6cd5338?source=rss-b7da2b6ca9c2------2</link>
            <guid isPermaLink="false">https://medium.com/p/276b6cd5338</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[hypothesis-testing]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andrew Nguyen]]></dc:creator>
            <pubDate>Mon, 25 May 2020 12:23:19 GMT</pubDate>
            <atom:updated>2020-05-31T10:38:54.864Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exchange Rate Prediction (Part 1): EDA &amp; Data Visualisation</h3><h4>This part is a kick-off to Data Science using EDA to clean and structure the visibility of the dataset, followed by visualization and hypothesis testing.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fAhaD8B9dXy4NoD5bqB47g.jpeg" /><figcaption>Source: <a href="https://unsplash.com/photos/2VMcpbUR6w8">https://unsplash.com/photos/2VMcpbUR6w8</a></figcaption></figure><p>Just some <strong>disclaimers</strong> before diving in:</p><p>1. This project is one of the series built and developed with the aim of improving my Data Science skillsets in the long run, both technical and analytical.<br>2. However, I’m not formally trained or with a higher degree in data science. This is all self-learning ranging from online courses, medium reads to everyday practice.</p><p>Hence, your feedback is greatly appreciated!</p><h3>Table of Content</h3><p>Let’s get started! This is an end-to-end project divided into 3 parts and covering the following sections:</p><ol><li><strong>Part 1</strong>: Explanatory Data Analysis (EDA) &amp; Data Visualisation (Bonus: Hypothesis Testing)</li><li><strong>Part 2:</strong> Machine Learning with 4 Regression Models</li><li><strong>Part 3:</strong> Machine Learning (cont.) with ARIMA</li></ol><p>As a kick-off, this article will cover the 1st part of the project, so stay tuned for the other two in the coming days! If you’d like to see the entire repository, scroll down the end to see my Github link ;)</p><h3>Introduction</h3><p>Exchange Rate is one of the daily topics that captures everyone’s attention, especially in the current Covid-19 situation where the global economy is severely affected. Therefore, I’m highly interested in analyzing the exchange rate pattern in the past so as to be able to forecast the value in the future. If you are as keen as I am, you can access this dataset <a href="https://www.kaggle.com/brunotly/foreign-exchange-rates-per-dollar-20002019">here</a> from Kaggle for your own exploration.</p><h3>A. Explanatory Data Analysis (EDA)</h3><p>First, let’s import two fundamental Python libraries, Pandas and Numpy and read the data:</p><pre>import pandas as pd<br>import numpy as np</pre><pre>df = pd.read_csv(&quot;Foreign_Exchange_Rates.csv&quot;)</pre><p>To briefly understand our dataset, use <strong>df.head()</strong> to see the first 5 rows, <strong>df.columns</strong> to see the variables:</p><pre>df.head()<br>print(df.columns)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c6-7sBhil4sucSWUOr_KKw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzceFnIE50QADB2uzd9fQA.png" /></figure><p>At first glance, I see an unusual variable named “Unnamed:0”, which should be removed.</p><pre>df = df.drop(columns=df.columns[0])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xdbas5ytta59rNQR2Ehm5w.png" /></figure><p>Next, the column names seem too confusing and difficult to call later, so I will standardize them to “Country Currency/USD” (e.g. AUD/USD).</p><pre>new_col_names = [&#39;Time Series&#39;, &#39;aud&#39;, &#39;eur&#39;, &#39;nzd&#39;, &#39;gbp&#39;, &#39;brl&#39;, &#39;cnd&#39;, &#39;cny&#39;, &#39;hkd&#39;, &#39;idr&#39;, &#39;krw&#39;, &#39;mxn&#39;, &#39;zar&#39;, &#39;sgd&#39;, &#39;dkk&#39;, &#39;jpy&#39;, &#39;myr&#39;, &#39;nok&#39;, &#39;sek&#39;, &#39;lkr&#39;, &#39;chf&#39;, &#39;twd&#39;, &#39;thb&#39;]</pre><pre>df.columns = new_col_names</pre><pre>df.columns = map(str.upper, df.columns)<br>df.rename(columns=lambda x:x+&#39;_USD&#39;, inplace=True)<br>df.rename(columns={&#39;TIME SERIES_USD&#39;:&#39;Time Series&#39;}, inplace=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QLjC096NdEfXCqa-4KqQfg.png" /></figure><p>As you can see, I created a new list with new country currency codes, capitalized them, and added “_USD” to each column name. There you go, a fresher dataset to look at!</p><p>Looking through the entire dataset again, there are some unusual values named “ND”. So I replaced them with “NaN” values by <strong>np.nan</strong> and then drop all “NaN” values at one go. If no “NaN” value is found using <strong>df.isna().sum()</strong>, we are good to go!</p><pre>df = df.replace(&#39;ND&#39;, np.nan)<br>df = df.dropna().reset_index(drop=True)<br>df.isna().sum()</pre><h3>B. Data Visualisation</h3><p>Let’s look at the dataset in a more visually engaging format!</p><p>First, we need to make sure that the values are numeric instead of objects by calling <strong>df.dtypes</strong> and <strong>pd.to_numeric</strong> for type conversion.</p><pre>df.dtypes</pre><pre>for col in df.columns[1:]:<br>    df[col] = pd.to_numeric(df[col], errors=&#39;coerce&#39;)</pre><p>Use a <strong>for loop</strong> to apply the change to all columns at once instead of repeating the process all over again. <strong>Errors</strong> parameter in the function can be set to “ignore” (return invalid values as is) or “coerce” (return invalid values as NaN).</p><p>As the date format is currently YYYY-MM-DD, which is relatively packed when it comes to charts, I will add another column formatted as YYYY-MM and use it in replacement.</p><pre>df[&#39;Time Series&#39;] = pd.to_datetime(df[&#39;Time Series&#39;])<br>df[&#39;month&#39;] = df[&#39;Time Series&#39;].dt.month<br>df[&#39;year&#39;] = df[&#39;Time Series&#39;].dt.year<br>df[&#39;month_year&#39;] = df[&#39;Time Series&#39;].dt.to_period(&#39;M&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XZqpRJUG83KtQ_SPUODLpA.png" /></figure><p><strong>pd.to_datetime</strong> to convert the values from object to datetime, then we extract the month and year with <strong>.dt.month </strong>and <strong>.dt.year</strong>. Finally, we created a new column called “month_year” using <strong>.dt.to_period(‘M’)</strong>. You can refer to this <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DatetimeIndex.to_period.html">documentation</a> for full details.</p><p>Let’s visualise the exchange rate of AUD/USD for simplicity first.</p><pre>df[&#39;AUD_USD&#39;].count()</pre><p>By using <strong>.count()</strong>, we know that there are <strong>5k+ values</strong> for each column. That’s a huge number! So instead, we will take the average rate of each month, assuming the mean represents the entire month. Groupby to the rescue!</p><pre>df_groupby_aud = df.groupby(&#39;month_year&#39;).AUD_USD.mean().reset_index()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*cA_TFG_P4YL70c3YhNdt7w.png" /></figure><p>Let&#39;s import Matplotlib library for our first visual chart!</p><pre>from matplotlib import pyplot as plt</pre><pre>x = df_groupby_aud[&#39;month_year&#39;].astype(str)<br>y = df_groupby_aud[&#39;AUD_USD&#39;]</pre><pre>plt.figure(figsize=(8,4))<br>plt.plot(x, y)<br>plt.title(&quot;Exchange Rate: AUD/USD&quot;)<br>plt.xlabel(&quot;Month&quot;)<br>plt.ylabel(&quot;Exchange Rate&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gT5lFh0EP-1hzDTsfqVfAQ.png" /></figure><p>Okay, we now can see the pattern for AUD/USD. Let’s upgrade our chart with more than one exchange rate.</p><pre>groupby_all = df.groupby(&#39;month_year&#39;).apply(lambda x: pd.Series<br>           ({<br>              &#39;AUD_mean&#39;: x[&#39;AUD_USD&#39;].mean(),<br>              &#39;EUR_mean&#39;: x[&#39;EUR_USD&#39;].mean(),<br>              &#39;NZD_mean&#39;: x[&#39;NZD_USD&#39;].mean(),<br>              &#39;SGD_mean&#39;: x[&#39;SGD_USD&#39;].mean(),<br>              &#39;GBP_mean&#39;: x[&#39;GBP_USD&#39;].mean(),<br>              &#39;JPY_mean&#39;: x[&#39;JPY_USD&#39;].mean(),<br>              &#39;CHF_mean&#39;: x[&#39;CHF_USD&#39;].mean()<br>                                             })).reset_index()</pre><pre>groupby_all = pd.DataFrame(groupby_all)</pre><pre>groupby_all[&#39;USD_mean&#39;] = [1 for i in range(240)]<br>groupby_all.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Nz7DnRZeNejKMUAHl5vlA.png" /></figure><p>In order to do groupby for multiple columns, we use <strong>lambda</strong> to apply a function to a Series of columns (in this case, <strong>.mean()</strong>), then convert back to DataFrame for easier use.</p><p>The reason why I created a column of USD_mean and added a value of 1 is to illustrate the difference of all exchange rates against the baseline visually. <strong>List comprehension</strong> is the easiest way to create such list.</p><pre>y_all = groupby_all[[&#39;AUD_mean&#39;, &#39;EUR_mean&#39;, &#39;NZD_mean&#39;, &#39;SGD_mean&#39;, &#39;GBP_mean&#39;, &#39;CHF_mean&#39;,&#39;USD_mean&#39;]]<br>labels = [&quot;AUD_mean&quot;, &quot;EUR_mean&quot;, &quot;NZD_mean&quot;, &quot;SGD_mean&quot;, &quot;GBP_mean&quot;, &quot;CHF_mean&quot;, &quot;USD_mean&quot;]<br>x_ticks = list(range(1, 240, 12))<br>x_ticklabels = [x for x in range(2000, 2021)]</pre><pre>plt.figure(figsize=(20,10))<br>ax = plt.subplot()</pre><pre>plt.plot(x, y_all)<br>ax.set_xticks(x_ticks)<br>ax.set_xticklabels(x_ticklabels)<br>plt.legend(labels)<br>plt.title(&quot;Exchange Rate: Top Countries/USD&quot;)<br>plt.xlabel(&quot;Year&quot;)<br>plt.ylabel(&quot;Exchange Rate&quot;)</pre><pre>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/993/1*MvCIIbQrjgBOZ7wbyqZ5Lg.png" /></figure><p>Here you are!! It is seen that the pattern of all exchange rates against USD baseline is pretty much the same. Such peak is seen between the year of 2008 and 2010, which can be explained by the Great Recession in 2008.</p><p>Apart from Matplotlib, there are several other libraries for visualisation such as <strong>Plotly or Bokeh</strong>, which provide more options for interaction. If you are keen to explore, check out my Github at the end for the full code. Here’s a brief chart using Bokeh:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*hMNUw_aIrgXUVw9Uhy_luw.png" /></figure><h3>C. Hypothesis Testing</h3><p>To be completely honest, I’m still struggling with tons of different elements, theories, and functions behind Hypothesis Testing.</p><p>That’s why I decided to practice a bit in this project by asking myself whether <strong>these variables in the dataset are different from one another</strong> or not.</p><p>Let’s use AUD_mean and SGD_mean for this example. The reason I used these two variables is that I see <strong>a relative difference in the chart</strong> above. So this test is to <strong>reassure or refute</strong> the assumption I was having.</p><p><strong>H0 (Null Hypothesis)</strong>: The mean of AUD is the same as that of SGD.<br><strong>H1 (Alternative Hypothesis)</strong>: The mean of AUD is significantly different from that of SGD.</p><p>However, before conducting a hypothesis testing, there are some prerequisites and process we need to be aware of:</p><ol><li>Take the sample dataset out of each population</li><li>Test the normality of each sample set and the correlation of two</li><li>Select the right hypothesis test to use</li></ol><p>For the 1. task, the question is “how much data should we take out of each population?”. If you recall, we have more than 5k+ values (the population) of each variable. To do sample sizing, we can rely on <strong>Power Analysis.</strong></p><p>But first, let’s prepare the datasets of this section:</p><pre>aud_sgd = df.loc[:,[&#39;AUD_USD&#39;, &#39;SGD_USD&#39;]]</pre><pre>aud = np.array(aud_sgd.iloc[:,0])<br>sgd = np.array(aud_sgd.iloc[:,1])</pre><p>Then, we import the <strong>statsmodels </strong>library to conduct Power Analysis:</p><pre>import statsmodels.stats.power as sms</pre><pre>n = sms.TTestPower().solve_power(effect_size=0.3, power=0.9, alpha=0.05)</pre><pre>print(n)</pre><p>For full detail, please refer to this documentation <a href="https://www.statsmodels.org/stable/generated/statsmodels.stats.power.TTestIndPower.solve_power.html">here</a>. In short, <strong>TTestPower</strong> is a statistical power calculation for paired sample t-test. We know these variables are paired (or connected to some extent) since they are divided by USD exchange rate. <strong>.solve_power()</strong> is a function which includes 3 core parameters: effect size, power and alpha (aka significance level):</p><ol><li><strong>Effect size</strong>: in layman’s term, it refers to the difference between the two groups (e.g. the mean difference of two groups) divided by the standard deviation of one of the groups. In case there is not enough data for calculation, we can use the effect size from the range of 0.3 to 0.8 when testing normality later to find the best effect size.</li><li><strong>Power</strong>: is the probability that we will reject the null hypothesis when we should. It is generally accepted that power should be 0.8 or 0.9, depending on how great you want your chance of finding a significant difference is.</li><li><strong>Alpha:</strong> is the error rate we are willing to accept, often set at 0.05 or 0.01. In brief, an alpha 0f 0.05 means we are willing to accept that there is a 5% chance that our results are due to chance/randomness.</li></ol><p>If my explanation seems a bit difficult to grasp, I recommend you to look at different materials to really understand the concept, and one of those is this document <a href="http://meera.snre.umich.edu/power-analysis-statistical-significance-effect-size">here</a>.</p><p>After running the Power Analysis, we found that the sample size for each variable is 118. Then, we use this number to randomly generate the sample set from each population:</p><pre>aud_sample = np.random.choice(aud, size=118)<br>sgd_sample = np.random.choice(sgd, size=118)</pre><p>Step 1 is done!</p><p>Move on to step 2, we need to test the normality of each sample set and the correlation of the two. In brief, it is required that two sample sets are<strong> normally distributed</strong> and <strong>not correlated</strong> with each other.</p><pre>from scipy.stats import shapiro, pearsonr</pre><pre>stat, p1 = shapiro(aud_sample)<br>stat, p2 = shapiro(sgd_sample)<br>print(p1)<br>print(p2)</pre><pre>stat, p3 = pearsonr(aud_sample, sgd_sample)<br>print(p3)</pre><p>For details of H0 and H1 of each test, refer to this quick <a href="https://machinelearningmastery.com/statistical-hypothesis-tests-in-python-cheat-sheet/">cheat sheet</a>.</p><p>Back to our example, if we use the effect size of 0.3, the result indicates “not normally distributed”. As I increased the effect size and finally reached 0.8 (sample size is 18), the sample sets are normally distributed to be used for Hypothesis Testing. For Pearson test, they are independent from each other.</p><pre>from scipy.stats import ttest_ind<br>tstat, pval = ttest_ind(aud_sample, sgd_sample)<br>print(pval)</pre><p>Finally, let’s import scipy library for Hypothesis Testing. The answer we are looking for is whether the means of AUD and SGD sample sets are equal or not. If pval &lt;0.05, we can reject the null hypothesis saying that they are different.</p><p>However, it turned out that my assumption from the chart that their means are different has been rejected, as the pval &gt;0.05!</p><p>Well, that’s a wrap for the 1st part of this project! Phew, a long read indeed?!</p><p>I hope you do enjoy my 1st Medium article and feel free to leave a comment here or on my Github! Do look out for <strong>my next 2 parts</strong> with regards to <strong>Machine Learning</strong> to see <strong>how I computed the predicted exchange rates for 2020!</strong></p><p>Let’s connect!</p><p>Github: <a href="https://github.com/andrewnguyen07">https://github.com/andrewnguyen07</a><br>LinkedIn: <a href="http://www.linkedin.com/in/andrewnguyen07">www.linkedin.com/in/andrewnguyen07</a></p><p>Thanks!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=276b6cd5338" width="1" height="1" alt=""><hr><p><a href="https://medium.com/analytics-vidhya/exchange-rate-prediction-part-1-276b6cd5338">Exchange Rate Prediction (part 1)</a> was originally published in <a href="https://medium.com/analytics-vidhya">Analytics Vidhya</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>