<?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 Deepa Pandit on Medium]]></title>
        <description><![CDATA[Stories by Deepa Pandit on Medium]]></description>
        <link>https://medium.com/@deepapandithu?source=rss-2f7a5857f7cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*cdkskAwP2PzXyZE6</url>
            <title>Stories by Deepa Pandit on Medium</title>
            <link>https://medium.com/@deepapandithu?source=rss-2f7a5857f7cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 12:52:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deepapandithu/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[Machine Learning for Wine Lovers: Building a Classification Model for Wine Quality — Part 2]]></title>
            <link>https://medium.com/@deepapandithu/machine-learning-for-wine-lovers-building-a-classification-model-for-wine-quality-part-2-699335478a54?source=rss-2f7a5857f7cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/699335478a54</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[classification-algorithms]]></category>
            <category><![CDATA[wine-quality-prediction]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Deepa Pandit]]></dc:creator>
            <pubDate>Thu, 14 Sep 2023 18:04:01 GMT</pubDate>
            <atom:updated>2023-09-14T18:21:05.044Z</atom:updated>
            <content:encoded><![CDATA[<h3>Machine Learning for Wine Lovers: Building a Classification Model for Wine Quality — Part 2</h3><p>This is the second part of the project on wine quality where I take you through the steps to build a machine learning model that can predict the quality of wine using different classification algorithms.</p><p>Please also refer <a href="https://medium.com/@deepapandithu/a-data-science-approach-to-wine-tasting-exploring-the-wine-quality-dataset-part-1-4469c078cf5c?source=your_stories_page-------------------------------------"><em>A Data Science Approach to Wine Tasting: Exploring the Wine Quality Dataset — Part 1</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kY9q_fs4b6foktBZ" /><figcaption>Photo by <a href="https://unsplash.com/@albertvincentwu?utm_source=medium&amp;utm_medium=referral">Albert Vincent Wu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>EDA recap</strong></h4><p>The EDA of the Wine quality dataset has given us enough insights into the data that will enable us to now build our Machine Learning model. To recap,</p><ul><li>There were originally 13 columns and 6497 rows. The ‘type’ column consisted of the 2 types of wines, Red and White. This column was one- hot encoded into two columns ‘Red’ and ‘White’ using <br>get_dummies( ) with values set as 0 (absence) and 1 (presence).</li><li>The ‘type’ column was dropped to minimise redundancy.</li><li>Missing values were found in the dataset, but they were too few to affect the analysis, so they were removed.</li><li>The resultant dataset consisted 14 columns and 6463 rows.</li></ul><h4><strong>Target Variable</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*KM6vr5641NAZcJ8m__D5RA.jpeg" /></figure><p>The target variable is the ‘quality’ column which has values from 3 to 9 in ordinal progression. That is, 3 in this dataset will be the lowest quality , while 9 is purportedly the highest quality.</p><p>Most of the wines have a quality of 5 or 6, and very few have a quality of 3 or 9. The data is highly imbalanced which can make it hard to compare or measure the quality of different wines.</p><h4><strong>Binarizing the quality column</strong></h4><p>In the Machine Learning Classification problem, our goal is to assign a binary output to each input. For example, to classify whether a wine is good or not based on its features. To do this, it would be necessary to binarize the quality column in the dataset, which contains numerical ratings from 1 to 10. By binarizing the quality column, the problem can be simplified to be able to use classification algorithms that require a binary output.</p><p>However, quality ratings in the dataset are not objective or universal measures of good or bad wine quality. They may depend on various factors such as personal preferences, food pairings, or cultural backgrounds.</p><p>Therefore, it would be useful to choose a reasonable threshold for binarizing the quality column that reflects our specific application and domain knowledge. In this case, I decided to keep the threshold at 5 and label any wine with a quality rating above 5 as “high” quality and any wine below 5 as “low” quality. This is purely my own choice and it may not be suitable for other purposes or contexts.</p><p>The dataset then looks like this, with a new column called ‘quality_binary’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*jk1qMJBVClfVQLz3xAJgFw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*566esM5fOEhCA6-jhjAYdQ.png" /><figcaption>Number of wines in each category</figcaption></figure><p>With the number of wines in category 1 are 4091 and category 0 are 2372, the data is still imbalanced.</p><p><strong>Coping with imbalanced data</strong></p><p>Imbalanced data is a common problem in machine learning classification. There are several tactics that can be used to combat this issue. One of the most effective methods is to use tree-based models such as decision trees, random forests, or gradient boosted trees. These models can handle imbalanced data well because they can split the data based on different criteria and create subgroups that are more balanced. They can also capture complex interactions and non-linear relationships among the features.</p><p><strong>X, y ,Train Test Split</strong></p><p>In machine learning, ‘X’ and ‘y’ are used to represent the input features and target variable, respectively.</p><p><strong>X</strong> contains the input features of the dataset. Each row represents a sample, and each column represents a feature.</p><p><strong>y</strong> contains the target variable of the dataset. It represents the output or label that will be used to predict using the input features.</p><p>To apply classification, the data is split into training set and a testing set. The training set is used to train the model, while the testing set is used to evaluate its performance.</p><p><strong>Preprocessing</strong></p><p><strong><em>Feature scaling</em></strong></p><p>The wine quality dataset contains both numeric and categorical features. The categorical feature has already been one-hot encoded so it is only the numeric features so forth. The numeric features include metrics from objective tests such as acidity levels, pH values, and alcohol content, while the target variable is a numerical score based on sensory data.</p><p>In this project I have used the Feature Scaling as the first step. Since the data contains different numerical parameters for each feature, feature scaling transforms the input features to a common scale to ensure that they have similar ranges. This can help to improve the performance of some machine learning algorithms, such as those that use distance-based metrics as in classification.</p><p>Here I am setting a variable ‘scaler’ to MinMaxScaler() to scale the features. I am using this scaler since the numeric features are not guaranteed to follow a normal distribution. It will also prevent distortion of the dataset. One can also use Robust scaler as there quite a few columns with outliers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*a00aWl6ytAAfz4MRpxclSw.jpeg" /></figure><p><strong><em>Principle Component Analysis</em></strong></p><p>In the next step, I apply PCA. In machine learning, PCA is a technique used to reduce the complexity of a dataset by identifying the most important features in the data and combining them into a smaller set of features. This can help to improve the performance of the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/206/1*j7m0CL5qEIQIDfhZFeqhcg.jpeg" /></figure><p>Here the pca is set with n_components =0.9. This is a way of telling the algorithm to keep enough principal components to explain 90% of the variance in the data. In other words, we are selecting the minimum number of principal components that capture most of the information in the data.</p><h3><strong>Model Training</strong></h3><p>I will now train each model using a different classifier, and we can check the efficacy of each and select the best model.</p><p>The <strong>make_pipeline </strong>function from the <strong>sklearn.pipeline</strong> module is used to create the pipeline object, which can be used to apply a sequence of transformations to the data, such as scaling, PCA, and the Classifier.</p><p>The <strong>fit method</strong> is used to fit the full pipeline to the training data while the score method is used to check the score of the full pipeline on the training data. The score represents the accuracy of the model on the training data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*UAUTs9UYPcELKeSCq4Bwtg.jpeg" /><figcaption>Pipeline</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*SXgSzQD2dXjjUAaSWHNX0Q.jpeg" /><figcaption>Target Variable prediction</figcaption></figure><p>In this example, X_test represents the input features of the test data, while log_y_pred represents the predicted target variable. You can compare the predicted target variable with the actual target variable to evaluate the performance of the model.</p><p><strong>Evaluating the model</strong></p><p>We can apply various metrics to evaluate the performance of a machine learning model, such as accuracy, precision, recall and F1-score.</p><ul><li><strong>Accuracy</strong> measures the proportion of correct predictions out of the total number of predictions.</li><li><strong>Precision</strong> measures the proportion of true positives out of the total number of predicted positives.</li><li><strong>Recall</strong> measures the proportion of true positives out of the total number of actual positives.</li><li><strong>F1-score</strong> is the harmonic mean of precision and recall.</li></ul><p>We can get all these scores for the machine learning model using classification_report from sklearn.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/493/1*AKaof4KtS87WolDQbcmfug.jpeg" /><figcaption>Classification report</figcaption></figure><p>In this case, the model has an overall accuracy of 0.96, which means that it correctly predicts the class of 96% of the instances. The precision and recall for class 0 are 0.96 and 0.93, respectively, while the precision and recall for class 1 are 0.96 and 0.98, respectively. The F1-score for class 0 is 0.95, while the F1-score for class 1 is 0.97.</p><p><strong>Other Classifiers</strong></p><p>The pipeline method can be used to train the dataset using other classifiers like Decision tree, Random Forest, K-Nearest Neighbors (knn), Support Vector Classifier (SVC) and Gradient boosting. You can create a pipeline object using make_pipeline module and specify the sequence of transformations and the classifier to be used in the pipeline.</p><h4><strong>Best models</strong></h4><p>Here is a comparison of the accuracy of different machine learning models on the wine quality dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/193/1*2GC3ixvLo4Fp8uAY7V4aFg.jpeg" /><figcaption>best_models comparison</figcaption></figure><p>The <strong>random_forest</strong> and <strong>SVC</strong> classifiers achieved the highest accuracy, with a score of 97.58%. The <strong>knn</strong> model came a close second with 97.16%.</p><p>The <strong>logistic_regression</strong> classifier achieved an accuracy of 95.98%, while the <strong>decision_tree</strong> and <strong>gradient_boosting</strong> classifiers achieved accuracies of 94.38% and 96.91%, respectively.</p><p>In general, <strong>random_forest</strong>,<strong> knn</strong> and <strong>SVC</strong> classifiers are known for their ability to handle complex datasets and can be effective at capturing non-linear relationships between the features and the target variable.</p><p>On the other hand,<strong> logistic_regression</strong> may not be as effective at handling complex datasets or capturing non-linear relationships between the features and the target variable.</p><p>The accuracy of a machine learning classifier depends on several factors, including the quality and quantity of the training data, the choice of algorithm, and the hyperparameters used to train the model. The classifiers in my training model are using default hyperparameters. Performance of the models could be improved further by tuning the hyperparameters.</p><h4><strong>Concluding thoughts</strong></h4><p>In conclusion, this project has combined EDA with machine learning model training, to gain valuable insights into the wine quality dataset and identified several classifiers that can predict wine quality with high accuracy.</p><p>The whole code is available on <a href="https://github.com/deepacoder/machine_learning/blob/main/winequality_prediction_ML.ipynb">machine_learning/winequality_prediction_ML.ipynb at main · deepacoder/machine_learning (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=699335478a54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Data Science Approach to Wine Tasting: Exploring the Wine Quality Dataset— Part 1]]></title>
            <link>https://medium.com/@deepapandithu/a-data-science-approach-to-wine-tasting-exploring-the-wine-quality-dataset-part-1-4469c078cf5c?source=rss-2f7a5857f7cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/4469c078cf5c</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[wine-quality-prediction]]></category>
            <category><![CDATA[classification]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Deepa Pandit]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 15:08:05 GMT</pubDate>
            <atom:updated>2023-09-14T20:38:06.090Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Data Science Approach to Wine Tasting: Exploring the Wine Quality Dataset -Part 1</h3><p>This is a classic Machine Learning project using a dataset that enumerates wine features of red and white wines, and a target variable denoting “Quality”. I have divided this article into 2 parts , Part 1 will cover the EDA of the dataset, and Part 2- will cover the Classification project steps.</p><p>Please also refer <a href="https://medium.com/@deepapandithu/machine-learning-for-wine-lovers-building-a-classification-model-for-wine-quality-part-2-699335478a54"><em>Machine Learning for Wine Lovers: Building a Classification Model for Wine Quality — Part 2 | by Deepa Pandit | Sep, 2023 | Medium</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXfER5uPkKNysuMnjwx0TA.png" /></figure><h3>The Dataset</h3><p>The wine quality dataset was created by Paulo Cortez and his colleagues from the University of Minho, Portugal. The wines covered in the dataset are from the Vinho Verde region of Portugal. The goal of creating this dataset was to model wine quality based on the physicochemical features and sensory tests while exploring the potential of machine learning techniques for this task.</p><p>The physicochemical tests measured various properties of the wines, such as acidity, alcohol, pH, etc. The sensory tests assigned a quality score to each wine sample, from 0 (very bad) to 10 (very good). The aim of this paper was to use machine learning techniques to predict wine quality based on the physicochemical features. The utility of such a model would be seen as beneficial to wine certification entities, wine producers and consumers as well as professional or hobby wine tasters.</p><p><strong>Classification or Regression ?</strong></p><p>According to the creators of the dataset, the data can be used for both classification and regression tasks, depending on how the quality score is treated. If the quality score is considered as a discrete variable, then it is a classification task. If the quality score is considered as a continuous variable, then it is a regression task. In this project, I have used the quality score as finite and applied Classification techniques.</p><p><strong>What does the data reveal?</strong></p><p>Applying the pandas tool .info() reveals the features of the data:</p><ol><li>It consists 13 columns and 6497 rows.</li><li>The ‘type’ column is categorical denoting two types of wines, Red and White.</li><li>The ‘quality’ column is ordinal indicating intrinsic value in the number values.</li><li>The other 11 columns are numerical consisting of float and integers.</li><li>There are some null columns in the dataset, probably information lost in processing, but not significant enough to influence the data.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*6FfkFv_j36lGtgxvk8Qjng.png" /><figcaption>Data snapshot</figcaption></figure><p><strong>Data preparation</strong></p><p>I have dropped the null columns in this dataset, and proceeded to one-hot encode the ‘type’ column from a categorical to a numerical variable using the get_dummies() method.</p><p>As a result, two new columns are created for ‘red’ and ‘wine’ with indicating presence (1) or absence (0) of the type of wine in the column. The ‘type’ column is dropped as it is unnecessary for further analysis. We can drop the ‘type’ column because it does not add any new information to the data set. <a href="https://www.geeksforgeeks.org/wine-quality-prediction-machine-learning/">Moreover, dropping the type column can help to avoid multicollinearity, which is a problem that occurs when two or more variables are highly correlated and can affect the accuracy and stability of the model</a>.</p><h4><strong>Data distribution and bivariate analysis.</strong></h4><p><em>Data distribution</em></p><p>Data distribution can help to identify the shape, center, spread, and outliers of a variable. It can also help to determine the type of distribution, such as normal, skewed, or bimodal. Knowing the distribution of a variable can help to choose the appropriate statistical tests and models for analysis or inference.</p><ol><li>In this dataset, the variables “fixed acidity”, “volatile acidity”, “citric acid”, “residual sugar”, “chlorides”, “free sulfur dioxide”, “total sulfur dioxide”, “density”, and “sulphates” are all <strong>right-skewed</strong>, meaning that they have a long tail on the right side and most of the values are concentrated on the left side. This indicates that these variables have some outliers or extreme values that are much higher than the rest of the data.</li><li>The variable “pH” is approximately <strong>symmetric</strong>, meaning that it has a bell-shaped curve and the values are evenly distributed around the center. This indicates that this variable follows a normal distribution, which is a common assumption for many statistical tests and models.</li><li>The variable “alcohol” is <strong>left-skewed</strong>, meaning that it has a long tail on the left side and most of the values are concentrated on the right side. This indicates that this variable has some outliers or extreme values that are much lower than the rest of the data.</li><li>The variable “quality” contains values ranging from 3 to 9, with higher values indicating better quality. Most wines are in the generic quality value between 5 and 7, with most wines containing a rating of 6.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/490/1*mlrDdBDa9QuW7Pl8C73b2A.png" /></figure><p>Lets take a look at the distribution of each feature in the data:</p><ul><li>Fixed acidity : This is the sum of the organic acids that are present in wine, mainly tartaric, malic, citric and succinic acids. These acids contribute to the taste, color, and stability of the wine. The average level of fixed acidity in wine ranges from 4 to 12 grams per liter (g/L), depending on the grape variety and the climate. The data is within the average range.</li><li>Volatile acidity : This refers to the amount of acetic acid that is produced by bacteria or yeast during fermentation or aging. Acetic acid contributes to the level of pungency and sourness. The average level of volatile acidity in wine should ideally be less than 0.4 g/L. Volatile acidity is considered a wine fault when it exceeds the sensory threshold of 0.6 to 0.9 g/L for red wines and 0.5 to 0.7 g/L for white wines. Our data has wines exceeding these thresholds.</li><li>Citric acid: The plot shows wines with 0 amount of CA, however CA is not very important to wine quality, as it is only present in small amounts in grapes and is mostly consumed by bacteria during fermentation.</li><li>Residual sugar : This is an important component of wine, as it balances out the sourness caused by acids and enhances the taste of wine. The level of sugars balanced by acidity makes the wine dry, off-dry, sweet and so forth. This visual helps understanding this perfectly. <a href="https://grape-to-glass.com/index.php/sugar-in-wine/">Sugar in Wine — Grape to Glass (grape-to-glass.com)</a>. Our dataset has wines that range from bone-dry, dry to sweet.</li><li>Chlorides : Chlorides are not very important to wine quality, as they are usually present in low levels and do not have a significant impact on the taste, color, or stability of the wine.</li><li>Free and Total Sulfur dioxides : Important in wine as they add freshness and crispness to wine.</li><li>density: The mean density in the dataset is 0.99, which makes the wines in the ideal range of density.</li><li>pH : A very important factor contributing to wine quality as it affects the acidity of wine. Highly acidic wines with a pH value of less than 3 need other features to balance it out, while the ideal range for wines remains 3.2 to 3.4 with the right amount of acidity. Beyond this value, wines become less acidic and may need additives to increase robustness. There are some highly acidic and less acidic wines in the dataset.</li><li>Sulfates : Wines with lower acidity need more sulfates than higher acidity wines. At pH 3.6 and above, wines are much less stable, and sulfates are necessary for shelf-life.</li><li>Alcohol : The mean alcohol level is 10.4 which is moderately low alcohol content for wines. The average alcohol content of wine ranges from 11% to 13% ABV, but some wines can have as low as 5.5% ABV (such as Moscato d’Asti) or as high as 23% ABV (such as fortified wines like Port or Sherry). The alcohol content of wine is not a direct indicator of its quality, but rather a result of various factors such as the style of wine, the quality level, the climate where the grapes grow, and the winemaking decisions. Different wines have different optimal alcohol levels depending on their grape variety, acidity, sweetness, tannin, and balance. Some wines may taste better with higher alcohol, while others may benefit from lower alcohol.</li></ul><p><strong><em>Bivariate analysis</em></strong></p><p>It is useful to make a bivariate analysis of the data that examines the relationship between two variables. For example, to understand the relationship between alcohol content and quality, a bivariate analysis can point out correlation, causation and distribution of mean and medians of features across each quality value.</p><p>The following boxplots and scatterplots show how the quality of wine varies with each of its physicochemical properties. We can draw some important inferences from these graphs, such as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_mjFAeRnHwCQwEgEaU5aw.png" /></figure><ol><li>7–9 quality wines have a lower volatile acidity which is desirable in a good quality wine.</li><li>Mean Residual sugar is very low and most wines lie in the range of 8.1, which indicates the presence of largely dry wines.</li><li>Density is ideal among more than 75% of the wines.</li><li>pH levels are within the range of ideal of 3.2 and 3.6, barring outliers. Quality 5 ,6 and 7 wines with outliers of pH values beyond 3.6 consequently shows the presence of higher sulphate content to add acidity.</li><li>7 -9 quality wines show higher contents of alcohol, though it is still low alcohol level for wine in general.</li></ol><p><strong>My insights from the dataset</strong></p><p>It is generally accepted among Sommeliers that there is not just one or two features or factors that contribute to the quality of wine. The wine quality dataset is based on the subjective evaluation of wine experts, who rated the wines on a scale from 0 to 10 based on sensory attributes such as appearance, aroma, flavor, and mouthfeel. The quality ordinals do not necessarily reflect the objective quality of the wines, as different people may have different preferences and expectations for wine.</p><p>The dataset can help us understand how the physicochemical properties of wine affect its sensory attributes, such as appearance, aroma, flavor, and mouthfeel.</p><p>It can certainly help wine growers and producers to determine the choice of procedures to use to create a certain type of wine.</p><p>It can also enable us to create a classification or predictive model that can recommend wines that match different types of cuisines.</p><p>Therefore, the wine quality dataset does not convey the absolute or universal quality of the wines, but rather the relative or perceived quality of the wines according to a specific group of experts.</p><p><strong><em>Acknowledgments:</em></strong></p><p>The following resources were referred in writing this article :</p><ol><li><a href="https://archive.ics.uci.edu/dataset/186/wine+quality">Wine Quality — UCI Machine Learning Repository</a></li><li><a href="https://www.geeksforgeeks.org/wine-quality-prediction-machine-learning/">Wine Quality Prediction — Machine Learning — GeeksforGeeks</a></li><li><a href="https://towardsdatascience.com/red-wine-quality-prediction-using-regression-modeling-and-machine-learning-7a3e2c3e1f46">Red Wine Quality Prediction Using Regression Modeling and Machine Learning | by Dexter Nguyen | Towards Data Science</a></li><li><a href="https://www.sciencedirect.com/topics/food-science/wine-quality">Wine Quality — an overview | ScienceDirect Topics</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4469c078cf5c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recommender System : User Collaborative filtering]]></title>
            <link>https://medium.com/@deepapandithu/recommender-system-user-collaborative-filtering-37613f0c6a9?source=rss-2f7a5857f7cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/37613f0c6a9</guid>
            <category><![CDATA[recommender-systems]]></category>
            <category><![CDATA[movielens]]></category>
            <category><![CDATA[jupyter-notebook]]></category>
            <category><![CDATA[collaborative-filtering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Deepa Pandit]]></dc:creator>
            <pubDate>Fri, 07 Jul 2023 19:06:51 GMT</pubDate>
            <atom:updated>2023-07-09T13:20:40.521Z</atom:updated>
            <content:encoded><![CDATA[<h3>Recommender System : User based Collaborative filtering</h3><p>by Deepa Pandit</p><p>This week I decided to delve into Recommender Systems. Not just because Netflix/Amazon Prime/Hulu have in recent years dominated our audio/visual consumption spectrum but for a more mundane reason as to practice Python coding. What better way than to unwrap the Recommender System while honing coding skills. In this code, and article I’ve focussed on the User-user, or Collaborative filtering method. So lets get to it.</p><h3>Recommenders : the backbone of streaming platforms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*lFjE05nGmWyeexXOFOyxyQ.jpeg" /><figcaption>Image : Netflix</figcaption></figure><p>When you sign into your entertainment provider like Netflix, you are likely to see rows of shows and movies with suggestions such as Continue Watching, Trending Now, Award-Winning Comedies, You might also like etc. This is Netflix’s Recommender algorithm at work to provide the most personalised, recommendations tailored to fit the user’s preferences.</p><p>At Data Science Bootcamp, I got to understand the nuances of what drives the streaming giants. A branch of Machine Learning, a Recommender System is a system that seeks to predict or filter preferences according to the user’s choices.</p><p>In this article, I provide insight into the Recommender System with a focus on Collaborative filtering. While Collaborative filtering models are used to make predictions, the goal here is to make recommendations to users based on their past behaviour and the behaviour of similar users through ratings. However, it does not make future rating predictions.</p><h3>The Pioneers</h3><p>Interestingly, the first Recommender System called Grundy was created by a woman, a Computer Science pro -Elaine Rich in 1979. Grundy system was programmed to recommend books. The system gathered some data of the user by asking specific questions and assigned stereotypes depending on her answers. This in turn would cultivate a list of book recommendations to fit the user’s choices. <a href="https://www.cs.utexas.edu/~ear/CogSci.pdf">This is a very exciting prospect especially for women breaking into STEM, and I urge you to read Rich’s thesis</a>.</p><p>Recommender Systems gained from further developments and parallel improvements through the years. Prof John Riedl from the Department of Computer Science at the University of Minnesota, is considered the pioneer in the field of Recommender Systems, through the research lab he set up called GroupLens in 1992. They developed the system for news whose key component was a user-user collaborative filtering model.</p><p>That brings us to the topic of this article. To bring the technical jargon to perspective, here is a picture to convey the essence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jol4IGdsMcq5g8CBv5XkMg.png" /><figcaption>Credits: WBS Coding School</figcaption></figure><p>As you can see, there are several ways to construct a Recommender System, but I am going to focus on the User based Collaborative filtering for this article. <a href="https://www.geeksforgeeks.org/user-based-collaborative-filtering/">User-based collaborative filtering is a technique used to predict the items that a user might like on the basis of ratings given to that item by other users who have similar taste with that of the target user</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*cufyV16I8Cxlx4B7k98MzQ.jpeg" /><figcaption>Credits:Own image</figcaption></figure><p>The workflow of a collaborative filtering system is depicted above for a streaming platform:</p><ol><li>User 1 has watched the Comedies A, B, C, D and rated it according to her interests.</li><li>User 2 has most probably also watched inter alia the same comedies as well and provided his preferences in the rating system.</li><li>User 3 is browsing for recommendations and based on the history of their choices, t<a href="https://en.wikipedia.org/wiki/Collaborative_filtering">he system matches this user’s ratings against any other users’ and finds the people with most “similar” tastes</a> i.e. in this scenario User 1 and User 2.</li><li>Accordingly, the system recommends Comedy D to User 3 as they are most likely to watch and like it.</li></ol><p>Now, we shall look at the Code that will generate the likely recommendations based on the above principle.</p><h3>The code</h3><p>The Code has been implemented in a Jupyter Notebook. The dataset used is the <a href="https://grouplens.org/datasets/movielens/100k/">Movielens100K</a>, containing more than 100K ratings of 9742 movies rated by 610 users between March 29, 1996 and September 24, 2018.</p><pre>#Keep relevant columns<br>movies_ratings_df = movies_ratings_df[[&#39;movieId&#39;,&#39;userId&#39;,&#39;movie_name&#39;,&#39;year&#39;,<br>&#39;genres&#39;, &#39;rating&#39;]]<br>movies_ratings_df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*fY35M99H1VvYtd2exgELYg.jpeg" /></figure><p>The ratings dataset has 10 unique ratings which are 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0. Movies are a subjective product, evidently users could give the same movie any rating based on their viewing preferences. Plus, some movies contain more number of ratings than others. We will therefore take the average ratings of the movies into consideration as this would give a more accurate representation of the average rating than the actual ratings of different users. Taking the mean rating would handle the impact of outliers which would otherwise skew the overall ratings.</p><h3>Popular Movies based on Average ratings</h3><p>Here we are taking the average ratings of movies based on the number of ratings and limiting it to only those movies which have registered more than a 100 ratings. This will ensure only movies with higher ratings given by reasonable number of users will be considered.</p><pre># Take the aggregate ratings<br>avg_ratings = movies_ratings_df.groupby(&#39;movie_name&#39;).agg(avg_rating = (&#39;rating&#39;, &#39;mean&#39;),<br>                                                number_of_ratings = (&#39;rating&#39;, &#39;count&#39;)).reset_index()<br><br># Keep the movies with over 100 ratings<br>avg_ratings100 = avg_ratings[avg_ratings[&#39;number_of_ratings&#39;]&gt;100]                   </pre><p>The first row of our streaming app would showcasing the Top most popular movies based on average ratings would look like this:</p><figure><img alt="Credits:own" src="https://cdn-images-1.medium.com/max/960/1*gnuft0zKVaic0foiT3tDTw.jpeg" /></figure><pre>#Lets see the movies that have a higher rating and most number of user ratings<br>avg_ratings = movies_ratings_df.groupby(&#39;movie_name&#39;).agg(avg_rating = (&#39;rating&#39;, &#39;mean&#39;),<br>                                                number_of_ratings = (&#39;rating&#39;, &#39;count&#39;)).reset_index()<br><br># Keep the movies with over 100 ratings<br>avg_ratings100 = avg_ratings[avg_ratings[&#39;number_of_ratings&#39;]&gt;100]<br><br># Check popular movies<br>avg_ratings100.sort_values(by=&#39;number_of_ratings&#39;, ascending=False).head()<br>                    <br>     movie_name                   avg_rating             number_of_ratings<br>3060 forrest gump                 4.16                     329<br>7325 shawshank redemption the     4.42                     317<br>6623 pulp fiction                 4.19                     307<br>7412 silence of the lambs the     4.16                     279<br>5321 matrix the                   4.19                     278</pre><p>As we have now the data with the average ratings of movies with more than 100 ratings, we can merge the main dataframe movies_ratings_df with the avg_ratings100.</p><pre>merged_df = pd.merge(movies_ratings_df, avg_ratings100[[&#39;movie_name&#39;]], on=&#39;movie_name&#39;, how=&#39;inner&#39;)</pre><p>An inner join returns only the rows that have matching values in both dataframes. In other words, it returns the intersection of the two dataframes. The resulting dataframe will only contain rows where the movie_name column is present in both movies_ratings_df and avg_ratings100.</p><h3><strong>User-Item Matrix</strong></h3><p>In the dataframe containing movies and ratings, we are mainly interested in the userId, movie_name and the corresponding ratings. To get a better view of the essential information we shall transform the data into a user-item matrix . This would also make it efficient to compute similarity between users based on their ratings.</p><p>The merged_df is now transformed into a matrix using <em>pivot</em>. The resultant movies_ratings_pivot table shows the ratings given by each user for each movie title. The rows represent the user IDs, the columns represent the movie titles, and the values represent the ratings given by each user for each movie title.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*wsUymUKUhHHwfwwAmuDl5w.jpeg" /></figure><h3><strong>Computing Similarity : Cosine Similarity</strong></h3><p>Cosine similarity is a popular metric used in Collaborative filtering to find similar users and recommend movies based on their preferences.</p><p>In the context of Collaborative Filtering, users can use cosine similarity to measure how similar their preferences are to other users preferences. Chances are you might like the same movies in the selection.</p><p>Users can be represented as vectors in an n-dimensional space, where n is the number of items we have. The cosine similarity is calculated by measuring the angle between these vectors.</p><p>If:-</p><ul><li>the angle is small i.e &lt; 90 degrees i.e cosine similarity of 1 = movies or users preferences are very similar</li><li>the angle is large i.e &gt; 90 degrees i.e cosine similarity is -1 = movies or users preferences are very different</li><li>If the angle is 90 degrees i.e cosine similarity of 0 would mean the two vectors are orthogonal (perpendicular) to each other. This means that they have no similarity at all.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OBF64z5Equwu6bfC.png" /><figcaption>pic credit: WBS Coding School</figcaption></figure><p>So now we shall consider the Cosine similarity of the given matrix between users based on their ratings of the movies and convert it into a Pandas dataframe.</p><pre># Calculate the cosine similarity matrix of users<br>similarity_matrix = cosine_similarity(movies_ratings_pivot)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*g6QK9V8RVQDto2Q_caEKvg.jpeg" /></figure><h3><strong>Get Similar Users</strong></h3><p>We need a target user to be able to find similar users. We therefore create a variable called <strong>select_userid</strong> and choose the target user. The supporting code for this article uses <strong>userId 5.</strong></p><p>Then we create a weight matrix which takes the weighted average of similarities between a user and other users. The weight matrix is used to give more importance to users who provide more frequent ratings than others when calculating the average similarity.</p><pre>select_userid = 5<br>similarities = similarity_matrix_df[select_userid].drop(select_userid)<br>weights = similarities/similarities.sum()</pre><p>In order to be able to recommend a movie to the <em>select_userid</em>, we need to round up some<em> similar_users </em>to gauge their tendency to rate a particular movie a certain way. In order to do this: -</p><pre>#num of silimar users<br>n =10 <br>#set a threshold for similarity<br>user_similarity_threshold =  0.5<br># Get top n similar users<br>similar_users = similarity_matrix_df[similarity_matrix_df[select_userid]&gt;user_similarity_threshold][select_userid].sort_values(ascending=False)[:n]</pre><ul><li>We can set the number of similar users to retrieve to 10.</li><li>We then need to establish a similarity threshold, to say 0.5. This means that only users with a <em>similarity score</em> greater than 0.5 will be considered.</li><li>We can then write a code to retrieve the top n similar users based on the similarity threshold. The userIds in the similarity_matrix_df where the similarity score is greater than the threshold are filtered by rows. It then selects only the column corresponding to the userId and sorts the resulting series in descending order. Finally, it selects only the top n similar users.</li></ul><p>Based on this code, the top similar users are :</p><pre>The similar users for user 5 are userId<br>5      1.000000<br>470    0.703033<br>117    0.684129<br>40     0.681779<br>142    0.672452<br>109    0.661853<br>565    0.655640<br>455    0.654090<br>38     0.652586<br>229    0.651689</pre><h3><strong>Movies Watched by select_userid 5</strong></h3><p>With the information we now have, the next logical step would be to find what movies have already been watched by select_userid 5, so the same may not be recommended.</p><p>With the code below, we will get the movies watched by select_userid 5 and limit them to those rated 3 and above. It would be safe to say, 5 would not want to watch bad movies, so lets not recommend such movies.</p><p>Here, we have a list of 23 movies watched by select_userId 5, which the recommender system MUST NOT recommend to the select_userid.</p><pre>watched_movies = movies_ratings_pivot.loc[movies_ratings_pivot.index== select_userid, movies_ratings_pivot.loc[select_userid,:]&gt;=3]<br>Index([&#39;ace ventura  pet detective&#39;, &#39;aladdin&#39;, &#39;apollo 13&#39;, &#39;babe&#39;, &#39;batman&#39;,<br>       &#39;batman forever&#39;, &#39;beauty and the beast&#39;, &#39;braveheart&#39;,<br>       &#39;clear and present danger&#39;, &#39;clueless&#39;, &#39;dances with wolves&#39;, &#39;fargo&#39;,<br>       &#39;fugitive  the&#39;, &#39;interview with the vampire  the vampire chronicles&#39;,<br>       &#39;lion king  the&#39;, &#39;mask  the&#39;, &#39;pretty woman&#39;, &#39;pulp fiction&#39;,<br>       &#39;schindler s list&#39;, &#39;shawshank redemption  the&#39;,<br>       &#39;terminator 2  judgment day&#39;, &#39;toy story&#39;, &#39;usual suspects  the&#39;],<br>      dtype=&#39;object&#39;, name=&#39;movie_name&#39;)</pre><h3>Movies not watched by select_userid</h3><p>We now have our selection of similar users and the list of movies watched by select_userid. However, we are interested in recommending movies to the select_userid that they have not watched(‘movies_not_watched’).</p><p>We shall therefore filter the movies that have not been rated by the select_userid as an indicator of unwatched movies.</p><p>The code selects all the movies that have been watched by the users EXCEPT for select_userid. The resulting pivot shows the ratings given by each user for these movies, except select_userid. A value of 0 indicates that the user has not watched the movie.</p><pre>#movies not watched by select_userid 5 <br>not_watched_movies = movies_ratings_pivot.loc[movies_ratings_pivot.index!= select_userid, movies_ratings_pivot.loc[select_userid,:]==5]</pre><h3><strong>Recommendations based on Weighted Averages</strong></h3><p>Based on the rating preferences of similar users of movies_not_watched, we will calculate a weighted average.</p><p>Weighted averages are used in collaborative filtering to combine and weigh the preferences of similar users. A weighted average accounts for the relative contribution, or weight, of the things being averaged, while a simple average does not. <strong>Therefore, it gives more value to those similar_users who provide ratings relatively more number of times in the dataset.</strong></p><p>In the code below, we are calculating the weighted averages of the not_watched_movies for the select_userid. The similarities between the select_userid are used as weights in this calculation.</p><pre>similarities = similarity_matrix_df[select_userid].drop(select_userid)<br>weights = similarities/similarities.sum()<br>weighted_averages = pd.DataFrame(not_watched_movies.T.dot(weights.to_numpy()), columns=[&quot;weighted_avg&quot;])</pre><p>Based on the weighted averages approach, the top 10 movie recommendations for select_userid would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*jV_m16Dw_SDXgLevQKwQ7g.jpeg" /></figure><h3>Recommendations based on Similarity Score</h3><p>Another approach would be to arrive at the recommendations using similarity scores between the most similar users in relation to the select_userid. The ratings of these similar users are then used to make recommendations for the select_userid.</p><p><strong>The similarity score is used as a measure to afford more importance to the ratings given by users who are more similar to the target user.</strong></p><p>The top 10 movie recommendations for select_userid would look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/1*w4-V3P8PmKl-8vSs_H3T0g.jpeg" /></figure><h3><strong>This or That?</strong></h3><p>As both the above approaches are based on two entirely different algorithms, the movies recommended are varied though there are a few common movies.</p><p>The number of movies in the weighted averages and similarity scores may also differ because the two methods use different criteria to select movies. The weighted average approach selects all the not-watched movies for the select_userid, while the similarity score approach selects only those movies that have been rated by similar users.</p><h3>Final thoughts</h3><p>Both the similarity score approach and the weighted average approach have their own advantages and disadvantages. The similarity score approach is simpler and easier to implement than the weighted average approach. The weighted average approach can provide more accurate recommendations than the similarity score approach. However, both approaches need a considerable number of users to make observations based on number of ratings or measure of similarity.</p><p>You can checkout the whole <a href="https://github.com/deepacoder/collaborativefiltering">code here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37613f0c6a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predicting e-scooter demand and movement : A journey through Data Engineering process for Data…]]></title>
            <link>https://medium.com/@deepapandithu/predicting-e-scooter-demand-and-movement-a-journey-through-data-engineering-process-for-data-6b59eda90148?source=rss-2f7a5857f7cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b59eda90148</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[automated-pipelines]]></category>
            <category><![CDATA[flight-api]]></category>
            <category><![CDATA[weather-api]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Deepa Pandit]]></dc:creator>
            <pubDate>Mon, 22 May 2023 19:20:01 GMT</pubDate>
            <atom:updated>2023-05-22T19:20:01.674Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Predicting e-scooter demand and movement : A journey through Data Engineering process for Data Science beginners</strong></h3><p>By Deepa Pandit, this is an original article.</p><p><em>The goal of this project is to assemble and automate a data pipeline in a virtual destination, that way provide usability of this automation to Gans to get the desired data at any point in time. This will involve performing ETL operations and eventually storing the data in a database in the cloud. If this sounds intimidating, the </em><a href="https://www.wbscodingschool.com/data-science-bootcamp-part-time/?utm_term=wbs%20coding%20school&amp;utm_campaign=DE+%7C+Brand&amp;utm_source=adwords&amp;utm_medium=ppc&amp;hsa_acc=1582954711&amp;hsa_cam=8841345998&amp;hsa_grp=92772141007&amp;hsa_ad=501195315359&amp;hsa_src=g&amp;hsa_tgt=kwd-857797241471&amp;hsa_kw=wbs%20coding%20school&amp;hsa_mt=e&amp;hsa_net=adwords&amp;hsa_ver=3&amp;gad=1&amp;gclid=CjwKCAjwpayjBhAnEiwA-7enaxQyLyROCncY1vMgLO_bHYyYFcr3j0ttDCyU2_bUtT-HPo0aQQ509hoCj98QAvD_BwE"><em>Data Science Bootcamp </em></a><em>equips the aspiring data scientist with the required skills to navigate the project.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OrdN8GksA6S5bLeV" /><figcaption>Photo by <a href="https://unsplash.com/ja/@vhowkins?utm_source=medium&amp;utm_medium=referral">Victoria Howkins</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The most exciting part of the Data Science Bootcamp is the opportunity of working on projects that reflect real world business scenarios. The project on e-scooter sharing business developed by Gans, a make-believe start-up company provided the platform to learn and hone skills in aspects of Data Engineering.</p><p>Project Scenario : We are introduced to Gans, a fictional start-up Company, that is in the process of breaking into the micromobility market with e-scooters. Micromobility refers to a range of small, lightweight vehicles operating at speeds typically below 25 km/h (15 mph) and driven by users personally. Micromobility devices typically include bicycles, e-bikes, electric scooters. According to Gans, the goal ahead is for operations to reach the most populous cities all around the world. In each city, the company would like to have hundreds of e-scooters parked in the streets and allow users to rent them by the minute.</p><p>As a new entrant into an increasingly competitive market, Gans needs some insights to predict e-scooter movement so as to make informed business decisions.</p><p>Some of the problems that Gans foresees are related to mundane but relevant aspects like topography, gauging the number of people who could be potential consumers, weather and flight schedules!</p><p>The Task ahead<em> </em>: As stated in the project goal, we will help Gans get the data it needs regarding weather, cities, and flights; store it in an automated pipeline so that they can retrieve any information as per their needs.</p><h3><strong>Assembling the relevant data</strong></h3><ol><li><strong>Collect data through Web scraping</strong></li></ol><p>The first step is to collect data. Zero in on what is essential. As the Company is seeking to enter into markets across various cities, especially tourist hubs a good approach would be to get basic information of such cities. For this project, I chose cities in Germany such as Berlin, Hamburg, Munich to name a few which are popular among students, backpackers and for short business trips. The method I used to extract this information is Web-Scraping.</p><p>Web scraping is a totally legal way to mine information available on websites such as Wikipedia. To scrap and extract any information from the internet, you’ll probably need to go through three stages: Fetching HTML, Obtaining HTML Tree, then Extracting information from the tree.</p><p>For the project, I used</p><ul><li>The Requests library to fetch the HTML from the relevant wikipedia URL, e.g the wiki page of the city Berlin</li><li>BeautifulSoup to parse and extract the HTML Tree , thereby accessing Tags and texts within the tree</li><li>Python code in Colab and Jupyter Notebook to organize the extracted Data</li></ul><p>An HTML professional would probably glide through this step, but as a novice I relied on some basic tools to get the information I need. Referring to the BeautifulSoup documentation is indeed helpful.</p><p>Here are some of the ways I used to get relevant city statistics, like city name, country, coordinates, area and population. These details are stored in the ‘infobox’ on the right side in a wiki page. When you open the desired Wikipedia page of a particular city, e.g Berlin. Right-click anywhere on the page to select inspect. Here, you can find the adjacent HTML code, containing the infobox data such as ids, selectors, href, class, div, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hr8PmDjuHHrcmgLbSQHsiA.png" /></figure><p>Now to start the scraping, we shall deploy the required tools in the Google Colab.</p><pre>url = &quot;https://en.wikipedia.org/wiki/Berlin&quot;<br>response = requests.get(url)<br>response.status_code<br>200 (== request has succeeded!)<br>soup = BeautifulSoup(response.content, &quot;html.parser&quot;)</pre><p>To get the the city_name from the page:</p><pre>city_tag = soup.h1.string<br>city_tag<br>&#39;Berlin&#39;</pre><p>The h1 tag in html indicates the heading. Another way to obtain the same is by .select and get_text().</p><pre>country_name = soup.select(&quot;.infobox-data&quot;)[0].get_text()<br>&#39;Germany&#39;.<br>latitude = soup.select(&quot;.latitude&quot;)[0].get_text()<br>&#39;52°31′12″N&#39;</pre><p>If you are interested in the entire code, you may look it up <a href="https://github.com/deepacoder/webscraping">here. </a>This is a straightforward and simple approach to retrieve information. However, there are many constraints and limitations in web scraping,as Wiki pages may vary in information and HTML code structure, so one code may not fit all. In the same breath, scraped data may become redundant in case of updates to the main wiki page.</p><p><strong>2. Collect data through APIs</strong>:</p><p>The next section of data extraction uses APIs, which stands for Application Programming Interfaces. As explained by Pedro Preguiro in his article “<a href="https://realpython.com/python-api/#:~:text=API%20stands%20for%20application%20programming,in%20many%20forms%20or%20shapes."><em>Python &amp; APIs: A Winning Combo for Reading Public Data</em></a><em>”,</em></p><p>“ In essence, an API acts as a communication layer, or as the name says, an interface, that allows different systems to talk to each other without having to understand exactly what each other does.”</p><p>In this context, we can say that the system the data engineer is working with, setting up the code is an application that is establishing a communication wire with the system storing the data.</p><p>For this project, API requests for data were made on two platforms : Open Weather for weather forecast, and AeroData for flight information. Access is easy, by setting up an account respectively with the user information. Be careful when using the API. With a free account, permitted access through an API Key allows the user to make a specified number of calls.</p><p><strong>2.1 Weather data</strong></p><p>The use of e-scooters would be optimal under suitable weather conditions. With the Open Weather online service , we are allowed to access minute-by-minute hyperlocal weather forecast for any location. To make an API call on Open Weather,</p><ol><li>Set up an account verified by email id, whereby you receive an alphanumeric API Key</li><li>Select API, where there are a variety of types of data which can be selected from. For this project, the 5 Day / 3 Hour Forecast was used. This API doc provides the URL to make the desired API call.</li><li>Specific parameters to be included in the URL are provided in the documentation thereunder. Here, I chose the city name , and to receive values in metric units. The URL looks like this: “http://api.openweathermap.org/data/2.5/forecast?q=&quot;+city+&quot;&amp;appid=&quot;+API_key+&quot;&amp;units=metric&quot;</li><li>The API call generates a response in JSON format, that is Java Script Object Notation. For easy readability of the JSON response, the URL can be loaded on a viewer like jsonviewer.stack.hu. A small extract of a JSON response is shown here for example.</li></ol><pre>:<br>&quot;weather&quot;: [<br>        {<br>          &quot;id&quot;: 500,<br>          &quot;main&quot;: &quot;Rain&quot;,<br>          &quot;description&quot;: &quot;light rain&quot;,<br>          &quot;icon&quot;: &quot;10d&quot;<br>        }</pre><p>As you can see, this is a set of nested dictionaries including list elements and looks mighty complicated. We shall therefore use the .json() function in our code, which is part of the requests library. It converts the JSON response into a python dictionary object, which is convenient to manipulate in a Google Colab or Jupyter Notebook.</p><p>The python dictionary object is still an eye sore and what we need to do is, flatten this multilayered structure and to get from here to a structured, table-like dataframe, that is easy to use. This can be easily executed with the “ .json_normalize()” function from pandas.</p><p>However, sometimes the output can be difficult to understand. The normalised dataframe could contain columns , where each element is a dictionary or a list.</p><p>If the code is pd.json_normalize(weather,[‘list’]) it will flatten the list elements json, which means that the “weather” element is a list containing a dictionary within a list. Confusing, yes? It was for me and it took me several attempts. I decided to <a href="https://github.com/deepacoder/weatherapi">do it this way</a> which gave me the desired result, a dataframe (after data cleaning) that looked like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*6ll5R9W873UYkPhin49-yg.png" /></figure><p>Automating the process of taking the weather data of several cities at a time is done through a Python function. This will enable the system to make API calls of a list of cities and automatically generate an organized, neat and interactive structure for us.</p><p><strong>2.2 Flight data</strong></p><p>Now that we are familiar with APIs and JSON files, we will proceed to set up the aviation data API for our application. A partly free and fast service provider in this regard is AerodataBox. Managed through the RapidAPI platform, <a href="https://aerodatabox.com/">AeroDataBox</a> offers a wide range of travel APIs that can be easily integrated into applications. Again, always remember to economize your API calls as there is only a limited number. If you exceed the limit, the data will show up as an error.</p><p>An account can be set up on the RapidAPI website from a verified email account. We then subscribe to the <a href="https://rapidapi.com/aedbx-aedbx/api/aerodatabox/">AeroDataBox</a> API on a freemium. This directs us to the landing page where we work on getting the data which contains 3 sections : Choose the endpoint, Documentation and Code Snippets. The best thing about this platform is that RapidAPI provides the Code in Python ready to use. The steps involved in this process are ➖</p><ol><li>choose the URL endpoint we want to get. Since we are interested in the arrivals in a particular city, we choose the endpoint as Flight API &gt; FIDS/Schedules: Airport departures and arrivals.</li><li>Fill out the needed parameters in the Documentation section correctly, and then click Test Endpoint.</li><li>If successful, in Code Snippets, the Results will generate the 200 Success response along with the JSON file with the data. We then go to Code Snippets, select ‘Python → Requests’ as programming language in the dropdown box. Voila! The code has been generated. It will look like this :</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hM4jIasFNxyK4PEdj7XlbQ.png" /></figure><p>The purpose of finding flight information of arrivals is to equip Gans with enough population statistics from these arrivals and prepare their logistical response in terms of availability of e-scooters at that time at the given airport. Therefore, the code should incorporate this requirement and prepare the data fetching parameters with the future date and time. Remember, the API has some limitations, as it can only turn data for 12 hours.</p><p><em>ICAO information</em></p><p>From the snapshot above, you can see that the documentation gives us an option to choose the airport identifier by way of ICAO. This is the airport code or location indicator, a four-letter code designating airports around the world defined by the International Civil Aviation Organization. This is a catch, as the correct ICAO Code would need to be entered for the city you are looking for. I did a simple search on Google for the airports I needed. My final dataframe looked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*XJWib2DmkpzVQazJAtynZQ.png" /></figure><h3><strong>B. Storing the data</strong></h3><p>We have all this information now, and the power to get more with just a code. But well, where does one store all this data? As you can see, a single city can divulge tons of data on each parameter. MySQL Workbench is used for creating the database to store all this information. In your Mysql instance, under your local host, you create a schema with tables modelled as Relational Database using SQL in the script. It is important to keep the column names consistent between each dataframe and the equivalent table created on MySql to be able to send the data from the environment storing your Python codes to the MySql Database.</p><p><strong><em>B.1 Store data on a local MySQL instance</em></strong></p><p>The next important step after we have created the database model in the MySql Workbench, is to test that the connection between Python and MySQL is established by setting up the database locally on the computer. In this process we will use SQL Alchemy, a library that facilitates the communication between Python programs and databases. WIth this connection, data can be transferred with ease from the Python environment to the Mysql Workbench.</p><p><strong><em>B.2 Moving the data to a Cloud Instance</em></strong></p><p>For businesses to store a gamut of data, applications and even servers , cloud is the way to go. In order to set up the Cloud pipeline, we used the Amazon Relational Database Service ( RDS) from the largest public cloud provider: Amazon Web Services (AWS). It is a limited option if to be used cost-free, so this was more of a learning platform. The process is best followed by the guidance in the AWS documentation, as it involves various intricacies.</p><p>Once the RDS is set up on the AWS instance, we can proceed to create the Lambda Functions. Not to be confused with Python Lambda , this is a namesake serverless compute service that runs your code in response to events and automatically manages the underlying compute resources for you. These events may include changes in state or an update, such as ingesting a date to retrieve flight information or weather update.</p><p>And thus we move our scripts , which are right now collecting data from API calls from our computers local instance to the AWS Cloud.</p><p><strong><em>B.3 Automate the pipeline</em></strong></p><p>The last step in the entire process is automating the pipeline. Our lambda functions are not being executed as of now, however they will run only when we schedule the trigger event by defining the time and intervals.</p><h3><strong>Concluding thoughts</strong></h3><p>As a Data Science beginner, the process of Data Engineering is an important skill to hone. While many steps are challenging and require hours of perseverance the results are indeed quite satisfying. In the larger picture, Data engineering and automation of data are a crucial component of success especially for start ups like Gans. By enabling startups to collect, store, and analyse large amounts of data, data engineering allows startups to make data-driven decisions, make better use of their data, understand their customers, and stay ahead of the competition.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b59eda90148" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>