<?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 Akhila Seneviratne on Medium]]></title>
        <description><![CDATA[Stories by Akhila Seneviratne on Medium]]></description>
        <link>https://medium.com/@akhilaseneviratne?source=rss-b0aac68b5a71------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-VyN0XFU4d71RfbuUtApDw.jpeg</url>
            <title>Stories by Akhila Seneviratne on Medium</title>
            <link>https://medium.com/@akhilaseneviratne?source=rss-b0aac68b5a71------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:04:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@akhilaseneviratne/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[To Subscribe or not to Subscribe?]]></title>
            <link>https://akhilaseneviratne.medium.com/to-subscribe-or-not-to-subscribe-887114a41756?source=rss-b0aac68b5a71------2</link>
            <guid isPermaLink="false">https://medium.com/p/887114a41756</guid>
            <category><![CDATA[support-vector-machine]]></category>
            <category><![CDATA[banking]]></category>
            <dc:creator><![CDATA[Akhila Seneviratne]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 16:04:56 GMT</pubDate>
            <atom:updated>2021-06-21T19:12:20.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Support Vector Machine (SVM) with Kernels tutorial using Banking data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kNHBCRex9wmcjqy5" /><figcaption>Photo by <a href="https://unsplash.com/@spanic?utm_source=medium&amp;utm_medium=referral">Damir Spanic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Support Vector Machines are a branch in Machine Learning which has several applications in solving real world problems. In an example where there is a dataset and you are expected to do Binary Classification, it is very much like plotting a graph and drawing a single line to divide the different classes.</p><p>Let’s find the answer!</p><h4>What you need</h4><p>To start this exercise, we will need a few tools. Install Python programming language and set your environment variables correctly in order to proceed with the next steps. Then you must install Jupyter Notebook and download this dataset which consists of banking data from a Portuguese bank.</p><p><a href="https://archive.ics.uci.edu/ml/datasets/bank+marketing#">https://archive.ics.uci.edu/ml/datasets/bank+marketing#</a></p><p>Now let’s proceed with the following steps before cleaning our data.</p><p>If not used before, it is essential to install scipy, pandas, sklearn,imblearn, matplotlib and seaborn using pip. These are useful libraries to be used.</p><p>Import pandas library as below and load the csv file from the storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*bwypL5u7yna53SxEA8QgZQ.png" /><figcaption>load dataset</figcaption></figure><h4>Data Preprocessing</h4><p>We need to ensure that the data we are using is free from missing values and outliers that will make us calculate messy test results.</p><h4>1.) Removing Missing values</h4><p>If we use the head() function, we can see the data below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*zjbDSIPqfdkYye5xoRfQfg.png" /></figure><p>Sometimes there maybe instances where there are empty value cells such as null or NaN. These must be removed as below but first we need to check if there are any null values using df.isnull().any() but this dataset doesn’t have any null values.</p><p>As we have no missing values to remove, we can proceed with removing the outliers if there are any.</p><h4>2.) Removing Outliers</h4><p>Outliers are very large or very small values that appear infrequently and outside a boxplot range. These out of range values may be errors and we must remove them so that we can get more accurate predictions and have less variations among the available features.</p><p>To get a basic idea of the outliers, we use the boxplot() function. This must be used in each they are not very clear but we can visualize individual boxplots. Below is an example for one boxplot (campaign column).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*n9s_YQMTwmOKheSBF4xvAA.png" /></figure><p>So it is understandable that these can be calculation errors and therefore we must remove them as the following using a row by deletion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*74OtQv3u94BiQ3AU-5CJ3Q.png" /></figure><p>Now we will get a boxplot as seen above. There are still outliers but we only delete the ones that are significant and not continuous as seen above. In fact it is the only boxplot that will show a significant outlier since it has been specified that duration column should be dropped for accurate predictions.</p><p>Now we have a ‘cleaner’ dataset. Let’s move onto the standardization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*Tl4FF0ggtH-GR1vGoF2zBg.png" /></figure><h4>Feature Transformation</h4><p>Here we look at plotting histograms and QQ plots in order to understand the distribution of our data. Then we apply transformation codes to change the distribution of the data if it is right skewed or left skewed. Skewness results in long tails where there is fewer data in that range. This will cause errors in predictions because there are not enough values in the tail range.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/1*CE-qxV2xtmz3wq5bFTizhg.png" /></figure><p>As seen above, there are several histograms that have significant gaps in the distribution but are also skewed. We can easily transform age and campaign which is right skewed. We need to import scipy and matplotlib libraries for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*jyV7wPrhNQTeBkfpmk4-cA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*jca8TCEv4agEjQ5H3qlvuA.jpeg" /><figcaption>Histogram and QQ plot of age column</figcaption></figure><p>The age column is right skewed. For this we use a square root transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*oDMv_uCyRxFUJDjhKR0TMQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*VXm-RfhMgE1DZnY0jxj3wA.jpeg" /><figcaption>Histogram and QQ plot of campaign column</figcaption></figure><p>The campaign column is right skewed. For this we use a logarithmic transformation by using square root.</p><pre>import numpy as np<br>from sklearn.preprocessing import FunctionTransformer</pre><pre>data = df.copy()</pre><pre># create the function transformer object with logarithm transformation<br>log_transformer = FunctionTransformer(np.sqrt, validate=True) #Right skew<br>square_transformer = FunctionTransformer(np.square, validate=True) #left skew</pre><pre># apply the transformation to your data<br>data_age = log_transformer.transform(data[[‘age’]])<br>data_previous = log_transformer.transform(data[[‘previous’]])<br>data_campaign = log_transformer.transform(data[[‘campaign’]])<br>data_nr = square_transformer.transform(data[[‘nr_employed’]])</pre><pre>data[‘age’]=data_age<br>data[‘previous’]=data_previous<br>data[‘campaign’]=data_campaign<br>data[‘nr_employed’]=data_nr</pre><p>We import numpy and FunctionTransformer. By creating two transformations, square root transformation for right skew and square transformation for left skew, we plus in the relevant columns to be transformed and assign it back to the data dataframe. If you run hist() again, you will see a result as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*gGiMBDwn_fpLqQ1Uplv4iQ.jpeg" /><figcaption>Histograms after starnderdization</figcaption></figure><p>We can see a small change in the shape because of the standardization. Next we move onto scaling the numerical columns.</p><h4>Scaling</h4><p>Scaling is also known as z score normalisation. We are normalising the values to the standard deviation so that it will provide more accurate results in the later steps.</p><pre>#feature scaling<br>from sklearn.preprocessing import StandardScaler</pre><pre>numerical_df = data.select_dtypes(include=np.number)<br>categorical_df = data.select_dtypes(exclude=np.number)</pre><pre># create the scaler object<br>scaler = StandardScaler()</pre><pre>data_scaled = pd.DataFrame(numerical_df, columns=numerical_df.columns)<br># fit the scaler to the data<br>scaler.fit(data_scaled)</pre><pre>train_scaled = scaler.transform(data_scaled)<br>df_scale = pd.DataFrame(train_scaled, columns=numerical_df.columns) #include column so name appears<br>df_scale.describe()</pre><p>We import StandardScaler to perform scaling. We will only select columns that have continuous data. Once we fit the new data into the scaler model and convert it to a dataframe, we end up with values as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*itMs06AMgBXLAgXh9TwBDw.jpeg" /><figcaption>Standardized Data</figcaption></figure><p>After standardizing the numerical data, we need to concatenate the categorical data and drop the null value row, otherwise this will cause an error in the step where we perform Principal Component Analysis.</p><pre>df_scaled = pd.concat([df_scale,categorical_df], axis = 1)<br>df_scaled=df_scaled.dropna(axis=0)<br>df_scaled.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*hO920jh2Fno2PKaFkqIgNQ.jpeg" /><figcaption>Concatenated data</figcaption></figure><h4>Feature Coding</h4><p>The categorical columns need to be coded in a way so that they can be used for principal component analysis. String values cannot be used.</p><pre>#feature coding before SEABORN matrix</pre><pre>df_scaled[‘job’] = df_scaled[‘job’].astype(‘category’).cat.codes<br>df_scaled[‘marital’].astype(‘category’).cat.codes<br>df_scaled[‘education’].astype(‘category’).cat.codes<br>df_scaled[‘default’].astype(‘category’).cat.codes<br>df_scaled[‘housing’].astype(‘category’).cat.codes<br>df_scaled[‘loan’] = df_scaled[‘loan’].astype(‘category’).cat.codes<br>df_scaled[‘contact’].astype(‘category’).cat.codes<br>df_scaled[‘month’] = df_scaled[‘month’].astype(‘category’).cat.codes<br>df_scaled[‘day_of_week’].astype(‘category’).cat.codes<br>df_scaled[‘pdays’] = df_scaled[‘pdays’].astype(‘category’).cat.codes<br>df_scaled[‘poutcome’].astype(‘category’).cat.codes<br>df_scaled[‘y’] = df_scaled[‘y’].astype(‘category’).cat.codes</pre><p>We change the datatype to int for all the columns by using cat.codes and now we move onto the Correlation Matrix.</p><h4>Correlation Matrix</h4><p>Correlations are how well variables affect the behaviour of other variables. This gives us some understanding as to which variables are dependent and independent.</p><pre>#seaborn heatmaps for correlation<br>import seaborn as sns</pre><pre>df_corr = df_scaled.copy()</pre><pre>#removing features that are not highly correlated with target but with other variables<br>df_corr = df_corr.drop(columns[‘emp_var_rate’,’euribor3m’,’cons_price_idx’])<br>corr_mat = df_corr.corr()<br>plt.figure(figsize=(16,10))<br>sns.heatmap(corr_mat, annot = True)</pre><pre>plt.title(“Correlation matrix of Banking data”)<br>plt.xlabel(“Banking features”)<br>plt.ylabel(“Banking features”)<br>plt.show()</pre><p>We need to import the seaborn library. We copy the scaled dataframe and we apply the above functions to create the correlation matrix table. I have removed several features that have a very high correlation to each other but don’t have a high correlation with our target variable. These must be removed to give a fair prediction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*W1FLuhBjoO9tuSv1Sj1S3g.jpeg" /></figure><p>This colour coded heatmap you see above indicates the correlations of each variables. Theoretically speaking, you need values that are close to +1 or -1 in order to consider it as a strong correlation. We can also see values that close to -0.5 but we can ignore these features as it is not a very strong correlation.</p><h4>Principal Component Analysis</h4><p>Now we do the Principal Component Analysis since we have some idea about the variables that are dependent and independent.</p><pre>#Principle component analysis<br>from sklearn.decomposition import PCA</pre><pre>numerical_df = df_corr.select_dtypes(include=np.number)<br>categorical_df = df_corr.select_dtypes(exclude=np.number)</pre><pre>features = numerical_df.columns<br> <br>X = df_corr.loc[:, features].values<br>Y = df_corr.loc[:,[‘y’]].values</pre><pre>X = StandardScaler().fit_transform(X)<br>pca = PCA(n_components=15) #n_components=5<br>X_pca = pca.fit_transform(X) </pre><pre>principalDf = pd.DataFrame(data = X_pca)<br>principalDf.head(10)</pre><p>We import PCA and we list the features to be reduced in PCA and we exclude y column because it is the target variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*lvrr6aW_M0MHtIHzxI8IXQ.jpeg" /></figure><p>As seen above, we get 15 columns shown in the explained ratio variance, we get an array and the total is approximately 95%, which means that we have extracted the significant features that have the most variance to the machine learning model. These are the features that will give us significant results.</p><pre>finalDf = pd.concat([principalDf, df_scaled[[‘y’]]], axis = 1)<br>finalDf=finalDf.dropna()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*iAnXNGGKo5qFYJKEmHEUyA.jpeg" /></figure><p>We need to add back the y column so we concatenate the dataframe components and get a result as above. We have almost reached the last step which is building the machine learning model. Again, we use the dropna() function to remove NaN values (otherwise the model won’t work).</p><h4>Class Imbalance</h4><p>Class Imbalance is when we have a very significant difference in the distribution of the target variable. These heavily affects prediction models because one output will be significantly low and will be sampled very unevenly. Therefore we must try to replicate rows in order to balance the yes and no output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*_qwLXAutRUU634vrYb3mlw.jpeg" /></figure><pre>#Removing classs imbalance<br>from imblearn.over_sampling import SMOTE<br>from sklearn.model_selection import train_test_split</pre><pre>y_true = finalDf[‘y’]<br>X = finalDf.drop(‘y’, axis=1)</pre><pre>os = SMOTE(random_state=0)<br>X_class_train, X_test, y_class_train, y_test = train_test_split(X, y_true, test_size=0.2, random_state=0)<br>columns = X_class_train.columns</pre><pre>data_X, data_y = os.fit_resample(X_class_train, y_class_train)</pre><pre>smoted_X = pd.DataFrame(data=data_X,columns=columns )<br>smoted_y= pd.DataFrame(data=data_y,columns=[‘y’])</pre><p>We then assign variables to train and test each for X and Y. We use a 80 to 20 ratio to split the training and test data. We should install imblearn and import SMOTE to resample our dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*4uwhjfEwZFxIh_CLIspmwQ.jpeg" /></figure><p>This is the output we get that shows the balanced output classes of the training dataset. We do not do this for the testing dataset because we had enough training to the 80% of the training dataset and would try to give a better accuracy as compared to not using SMOTE.</p><h4><strong>Support Vector Machine with Kernel</strong></h4><p>This is where the predictions happen. We must import the relevant sklearn libraries in order to use svm. In this example we can see that the SVC which is SVM with Kernels having different parameters called kernel, which is the kernel type and C, gamma variables that are to be changed according to the dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/649/1*aWqOhy373y5JhPJ-FDOWfw.jpeg" /></figure><p>By using and rbf kernel and setting C=1 and gamma=0.5, we get an accuracy of 92% for 0 labels and 39% for 1 labels. Below is a confusion matrix which shows how the category labels are predicted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*zzTjJQTxLWNeb_3uDPPXZQ.jpeg" /></figure><p>We need to keep in mind that results can vary depending on the test split. By trying different combinations, it was found that having a linear kernel regardless of the C and Gamma values will give a 54% accuracy for the 1 labels but the model takes a very long time to train. For rbf, using C=100 and Gamma =0.1 gives a good prediction result of 39% accuracy, 46% recall and 40% f-score. This is better than the result shown but these values differ from the dataset split. Usually the best accuracy level is between 50–60%.</p><h4>Conclusion</h4><p>Using Python and Jupyter Notebook, assisted by many useful libraries, we were able to use Support Vector Machine with Kernels to predict the target variable, if the customer is going to subscribe to the bank offer or not. Test results were average but given the imbalance of data, we can conclude that the prediction model did a fair job in predicting the output.</p><p>The Python code that was used to do all the steps is given below.</p><p><a href="https://colab.research.google.com/drive/1VG5L1Y5sgnwaDiO8lfLXcA65XX0HqmEW?usp=sharing">https://colab.research.google.com/drive/1VG5L1Y5sgnwaDiO8lfLXcA65XX0HqmEW?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=887114a41756" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bergs and Bullets: The Bias Behind Hidden Data]]></title>
            <link>https://akhilaseneviratne.medium.com/bergs-and-bullets-the-bias-behind-hidden-data-e210be1c91e0?source=rss-b0aac68b5a71------2</link>
            <guid isPermaLink="false">https://medium.com/p/e210be1c91e0</guid>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[survivorship-bias]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Akhila Seneviratne]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 17:26:57 GMT</pubDate>
            <atom:updated>2021-07-25T04:37:24.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*GEAX3iyVsOF-Nphyh3Zl3Q.jpeg" /><figcaption>The tip of the Icerberg</figcaption></figure><h4>The Survivorship Bias in Data and other things you should consider before arriving at conclusions</h4><p>I am very sure that many readers are familiar with the phrase “seeing the tip of the Iceberg”. We often see things that are only visible to the naked eye but tend to forget about what we don’t see, just like an iceberg where we only see the 10% of what’s floating on water.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c6L7Wiv1kOydGxrq" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering RAEng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>An Internet Meme</h4><p>The below image you see is a meme I came across on Social Media recently. You might know the story behind it if you are a history or engineering enthusiast. What’s does this plane have red dots and what happened to the survey (also the name of the plane)?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*-8Sd6zFQApx-T8a83qJwYA.jpeg" /><figcaption>Survivorship Bias Meme</figcaption></figure><p>Digging into the history of it and just a little bit of the statistical aspect of it, it made a lot of sense and there are so many implications and practical uses of this concept. It’s called the Survivorship Bias. This is the logical error in focusing only on people or things that made it past the selection process and ignoring the ones that don’t. Coming back to the meme, this means that no student filled the online survey and the conclusion is that no one had issues!</p><p>It happened so during WWII where a Hungarian Statistician Abraham Wald, concluded that they have been examining the damaged planes wrong. The main fault here is that they have only been examining the planes that returned to the hanger (survived) and the data that shows the bullet impacts (red dots) clearly did not give an accurate picture about the planes that didn’t return.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/452/1*N5dCOI6ftLzem1oqMVqqVw.gif" /><figcaption>Freddie Mercury- “Another One Bites The Dust”</figcaption></figure><p>Ward suggested that they were making a big mistake in where they were adding more armor so he stressed the importance of adding more armor in places that DON’T have red dots because that’s where the planes that didn’t survive were probably hit . Eventually this became a breakthrough in Operational Research and even have business applications as well.</p><h3>What can we learn from this?</h3><h3>Practical</h3><p>There a a lot of practical lessons like don’t only learn important life lessons from the most successful people in the world and to learn from those who failed as well. Or studying about the most successful companies in the world and ignoring those who failed. This bias leads to conclusions that maybe wrong such as a majority of successful people had these traits or the successful companies all had something in common and we only focus on them, the survivors of the selection bias.</p><p>If a surviving plane can give the wrong data, imagine about the data that you are using for a university research? The story on Survivorship Bias was just part of this story. Now I wish to dive in what I really wanted to talk about!</p><h4>Understanding your Dataset</h4><p>Whether you are using a Dataset which you downloaded from <a href="https://www.kaggle.com/">Kaggle</a> or it’s collected using your own research, there are many ways the data can be misleading if we do not look at the ‘bigger picture’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mhXXTDWZCN_hfJJ-" /><figcaption>Photo by <a href="https://unsplash.com/@nci?utm_source=medium&amp;utm_medium=referral">National Cancer Institute</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A big mistake many people make is not understanding the background of the dataset. You can’t evaluate medical data without having some sort of knowledge in medical aspects or supermarket data without knowing how sales operate. This helps us to question the data more and arrive at better conclusions, rather than taking the data as it it.</p><h4>Why and How?</h4><p>There are no hard and fast rules when it comes to ways of understanding your dataset but if you take time to understand about the data by asking, how it is collected, general practices and most preferably, industry specific knowledge (this is where Business Analysts are most helpful) so that we can find interesting patterns and tackle the unusual numbers.</p><h4>Missing Values</h4><p>This can be a pain if we are having too many missing values. DO NOT make the mistake of dropping down values without knowing what caused them.</p><p>If there is a column that has too many missing values, it is best to drop the column, rather than the rows. If there are only a few missing values, we can use certain estimations and fill the missing values. The following link by <a href="https://medium.com/u/3d8bf96a415f">Satyam Kumar</a> will give you a better understanding on how its done.</p><p><a href="https://towardsdatascience.com/7-ways-to-handle-missing-values-in-machine-learning-1a6326adf79e">https://towardsdatascience.com/7-ways-to-handle-missing-values-in-machine-learning-1a6326adf79e</a></p><h4>Outliers</h4><p>These are the abnormally high or low values of a particular column. Think of pressure being 0 or body temperature above 50 degrees. These are impossible numbers that would ruin predictions and these must be removed. We use box plots to identify these values within the quartile range and we only remove the values that have a very significant difference to the other high/low values.</p><h4>Skewness of Data</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f2xRCa1i3q3c1WNI" /><figcaption>Photo by <a href="https://unsplash.com/@lukechesser?utm_source=medium&amp;utm_medium=referral">Luke Chesser</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Skewed data is where the normal distribution of your data is more towards the left or right side, which is a result of having too many or too less data within a particular range. We need to apply different transformation methods in order to normalize the data so that it is able to give more accurate predictions when using Machine Learning models.</p><h4>Conclusion</h4><p>As much as we tend to have our own biases in perception, we should not let that happen to the data we are trying to understand. The Survivorship Bias will lead you to the wrong conclusions. Keep asking How and Why questions. Be open minded. Think beyond the numbers and what you see because after all, Data Science is about what you don’t see!</p><blockquote>References</blockquote><ul><li><a href="https://towardsdatascience.com/survivorship-bias-in-data-science-and-machine-learning-4581419b3bca">Survivorship bias in Data Science and Machine Learning</a></li><li><a href="https://towardsdatascience.com/data-science-sometimes-the-absent-data-is-the-best-data-ae2fe8b78db1">Survivor Bias: Missing data can be the best data</a></li><li><a href="https://dataschool.com/misrepresenting-data/survivorship-bias/">Survivorship Bias</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e210be1c91e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting Humidity with Temperature Using Machine Learning]]></title>
            <link>https://akhilaseneviratne.medium.com/test-bef9c3a93f42?source=rss-b0aac68b5a71------2</link>
            <guid isPermaLink="false">https://medium.com/p/bef9c3a93f42</guid>
            <dc:creator><![CDATA[Akhila Seneviratne]]></dc:creator>
            <pubDate>Fri, 28 May 2021 10:39:39 GMT</pubDate>
            <atom:updated>2021-05-29T07:32:30.320Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Python tutorial to understand the relationship between Humidity and Temperature to using Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8ae2sdECFJHFax77GIyCg.jpeg" /><figcaption>sunnyday.jpg</figcaption></figure><p>Machine Learning has many applications in solving real world problems. Are these days feeling too warm for you? Is there a relationship between Humidity and Temperature?</p><p>Let’s find the answer!</p><h4>What you need</h4><p>To start this exercise, we will need a few tools. You must install Python programming language and set your environment variables correctly in order to proceed with the next steps. Then you must install Jupyter Notebook and download this dataset which consists of weather data.</p><p><a href="https://www.kaggle.com/budincsevity/szegedweather?select=weatherHistory.csv">https://www.kaggle.com/budincsevity/szegedweather?select=weatherHistory.csv</a></p><p>Now let’s proceed with the following steps before cleaning our data.</p><p>If not used before, it is essential to install scipy, pandas, sklearn, matplotlib and seaborn using pip. These are useful libraries to be used.</p><p>Import pandas library as below and load the csv file from the storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*k6UHDQWcHkb9-GBfpB2Wpw.png" /><figcaption>Pandas loading</figcaption></figure><h4>Data Preprocessing</h4><p>We need to ensure that the data we are using is free from missing values and outliers that will make us calculate messy test results.</p><h4>1.) Removing Missing values</h4><p>If we use the head() function, we can see the data below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*JoWdlD4T1HMoaGsd_GQorg.png" /><figcaption>Head Values</figcaption></figure><p>Sometimes there maybe instances where there are empty value cells such as null or NaN. These must be removed as below but first we need to check if there are any null values using the isnull() function combined with any().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*irwjxNDT9gNoceUlRdIBTw.png" /><figcaption>Null values</figcaption></figure><p>We can clearly see that only Precip Type has null values. If we use</p><p>df[‘Precip Type’].value_counts()</p><p>we get only Rain, Snow and of course null. Because rain is more than snow, we can replace the null values with rain as below but later in this tutorial, you will see that this particular column will not be very useful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*BEMHyCgOQAFGNwE0oPNCQA.png" /><figcaption>No Null Values</figcaption></figure><p>Once we have successfully removed the null values, we can remove the outliers if there are any.</p><h4>2.) Removing Outliers</h4><p>Outliers are very large or very small values that appear infrequently and outside a boxplot range. These out of range values may be errors and we must remove them so that we can get more accurate predictions and have less variations among the available features.</p><p>To get a basic idea of the outliers, we use the boxplot() function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*8PsjQW91ekCCqbhKAhsMzQ.png" /><figcaption>boxplots</figcaption></figure><p>As seen above, they are not very clear but we can visualize individual boxplots. Below is an example for one boxplot (Pressure column).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*UktKClTFaACTTSSNIKakog.png" /></figure><p>As seen above, there is an outlier where 0 is a very unnatural value (we’re all gonna die!!!)</p><p>So it is understandable that these can be calculation errors and therefore we must remove them as the following using a row by deletion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*81lmUsfw7Amgv4YghqoPxQ.png" /></figure><p>Now we will get a boxplot as seen above. There are still outliers but we only delete the ones that are significant and not continuous as seen above. Further we repeat the same process for the Humidity and Windspeed columns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*5CwZl9UlUomj2WdebwGbbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*doIH60K_NEVFK2wDYPVjyQ.png" /></figure><p>Now we have a ‘cleaner’ dataset. Let’s move onto the standardization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*-GaC8oZPGO0P_yqXNv3pPg.png" /><figcaption>Dataset after cleaning</figcaption></figure><h4>Feature Transformation</h4><p>Here we look at plotting histograms and QQ plots in order to understand the distribution of our data. Then we apply transformation codes to change the distribution of the data if it is right skewed or left skewed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*98ejx20-sIGszLdhoLXWUg.png" /><figcaption>histograms</figcaption></figure><p>As seen above, there are 2 histograms that are significantly skewed after using hist(). They are Humidity which is left skewed and Wind Speed which is right skewed. We need to transform these two features. We need to import scipy and matplotlib libraries for this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/725/1*PokLVLOhyTAnBTBPDWxXYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*8BKDk-q_hHxYi0_e6Tn-6g.png" /><figcaption>QQ plot and Histogram for Wind Speed</figcaption></figure><p>The Wind Speed feature is right skewed. For this we use a logarithmic transformation by using the log transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*P0AIjdr604whEH-goH2SPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*EY30vkuQQMuHLk54BS2qvg.png" /><figcaption>QQ plot and Histogram for Humidity</figcaption></figure><p>The Humidity feature is left skewed. For this we use a logarithmic transformation by using the exp transformation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*GOubIk0LBvcsl85C48twkw.png" /></figure><p>We import numpy and FunctionTransformer. It is best to drop the Loud Cover column since it only consists of 0s and this will create an error in the next step if not removed in this step.</p><p>With a new variable named data, we replace all the 0s with NaN using numpy. Then we will drop the NaN values with dropna() function. If we don’t remove Loud Cover, we will end up with an empty table since all rows will be deleted.</p><p>By creating two transformations, log transformation for right skew and exp transformation for left skew, we plus in the relevant columns to be transformed and assign it back to the data dataframe. If you run hist() again, you will see a result as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*WpWfh71-CnYURAwtM3SxnQ.png" /></figure><p>We can see a small change in the shape because of the standardization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/694/1*7slVtCyGM5_bDXibwxDJkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*_YDYxTbrcb67xAmYg8WhiQ.png" /><figcaption>Histograms after Standardization</figcaption></figure><h4>Feature Coding</h4><p>This dataset has one variable that can be used to demonstrate feature coding in order to give a numerical value to a discrete feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*fYWnEz3V6o3UQ5tH2dJ8SA.png" /><figcaption>Feature coding for precip type</figcaption></figure><p>As clearly seen above, we can assign a dummy values for Precip Type and if it is rain, we get a 1–0 combination while it would be vice versa for snow.</p><h4>Scaling</h4><p>Scaling is also known as z score normalisation. We are normalising the values to the standard deviation so that it will provide more accurate results in the later steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*rmqR0f6BNHdXh0Yw7o7rMQ.png" /><figcaption>feature scaling</figcaption></figure><p>We import StandardScaler to perform scaling. We will only select columns that have continuous data. Once we fit the new data into the scaler model and convert it to a dataframe, we end up with values as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*3uxpF0ssl768VQgG11Kr6Q.png" /><figcaption>Features after scaling</figcaption></figure><p>We don not need string data values and now we are only left with a dataframe of floating point values and all of the values are normalised, adjusted to their mean values and standard deviation. This will be use for Principal Component Analysis to follow.</p><h4>Correlation Matrix</h4><p>Correlations are how well variables affect the behaviour of other variables. This leads us to the case study question, does humidity have a relationship with temperature. Let’s solve this question once and for all!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*QNF2u-NvqC-o6DhgS1jSKQ.png" /><figcaption>seaborn plotting</figcaption></figure><p>We need to import the seaborn library. We copy the scaled dataframe and we apply the above functions to create the correlation matrix table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*KHqeooFyK7G7EtS2ulrU5Q.png" /><figcaption>Correlation Matrix</figcaption></figure><p>This colour coded heatmap you see above indicates the correlations of each variables. Theoretically speaking, you need values that are close to +1 or -1 in order to consider it as a strong correlation. We can also see values that are higher than -0.6 so we may consider it, even though the range -0.7 to -1 comes under the strong positively correlated range. Humidity shows a -0.6 plus correlation with temperature and apparent temperature, so we conclude that there is a relationship between the variables.</p><p>Furthermore, Temperature and Apparent Temperature have a +0.99 correlation which is very strong. This means that both variables should not be paired into the machine learning model but Apparent Temperature is what we want to predict so that will be our target variable. All other variables can be considered as significantly independent.</p><h4>Principal Component Analysis</h4><p>Now we do the Principal Component Analysis since we have some idea about the variables that are dependent and independent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*bDs6b_xBpDpTn1gcnOM8FQ.png" /><figcaption>PCA code</figcaption></figure><p>We import PCA and we list the features to be reduced in PCA and we exclude Apparent temperature because it is the target column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*Jhmk9qJxIosKEzI0ukiOyw.png" /></figure><p>As seen above, we get 6 columns and further by using the explained ratio variance, we get an array and the total is approximately 99, which means that we have extracted the significant features that have the most variance to the machine learning model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*-e1EjK8fEihDmXl1nCfeEQ.png" /><figcaption>Dataset before Regression</figcaption></figure><p>We need to add back the Apparent Temperature column so we concatenate the dataframe components and get a result as above. We have almost reached the last step which is building the machine learning model. Again, we use the dropna() function to remove NaN values (otherwise the model won’t work).</p><h4>Regression Model</h4><p>Regression Model is a supervised Machine learning technique because we are comparing the inputs and predicted inputs that are generated using regression functions (line of best fit).</p><p>We import the relevant libraries from sklearn and we use the pop() function to include only Apparent Temperature values for Y and all the other columns except humidity to X.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*gXj_Pb960y9DbpwRoga2ew.png" /><figcaption>Training Data</figcaption></figure><p>We then assign variables to train and test each for X and Y. We use a 80 to 20 ratio to split the training and test data. To have an idea of what kind of data will be going as the input, we use head() for the train_X variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*0zaaulym-WjWEI3ysEXtug.png" /><figcaption>Model Evaluation</figcaption></figure><p>Once we use the LinearRegression() function and fit the training data, we make a prediction variable by assigning the test_X data and get the accuracy of our model as compared to the test_Y data.</p><p>In the end, we get a mean square error of <strong>0.01</strong> and a score of <strong>99%</strong> which is very good.</p><h4>Conclusion</h4><p>Using Python and Jupyter Notebook, assisted by many useful libraries, we were able to find that Humidity and Temperature have a relationship and develop a machine learning model to predict Apparent Temperature.</p><p>The Python code that was used to do all the steps is given below.</p><p><a href="https://colab.research.google.com/drive/1GmbFaw27nmzRhF_g3cMKT_v7GsfWdsGw?usp=sharing">https://colab.research.google.com/drive/1GmbFaw27nmzRhF_g3cMKT_v7GsfWdsGw?usp=sharing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bef9c3a93f42" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>