<?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 Alvaro Matsuda on Medium]]></title>
        <description><![CDATA[Stories by Alvaro Matsuda on Medium]]></description>
        <link>https://medium.com/@kazumatsuda?source=rss-326bb903f729------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cAzCLsUo1G-3jFxTjw-Nrw.png</url>
            <title>Stories by Alvaro Matsuda on Medium</title>
            <link>https://medium.com/@kazumatsuda?source=rss-326bb903f729------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 01:23:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kazumatsuda/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[Building complex ML pipelines]]></title>
            <link>https://ai.plainenglish.io/building-complex-ml-pipelines-6c742b0e7e9f?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c742b0e7e9f</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 13:01:41 GMT</pubDate>
            <atom:updated>2023-10-27T00:49:42.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building Complex ML Pipelines</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jBW29PwpkLmYSe-g" /><figcaption>Photo by <a href="https://unsplash.com/@danfreemanphoto?utm_source=medium&amp;utm_medium=referral">Dan Freeman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>A machine learning project have several steps to build the final model from preprocessing data, feature engineering, feature selection to training the model and making it ready to make predictions. Each one of these steps have their own complexity and sometimes your code can be unorganized and messy. Even worse than that, you can make a big methodology mistake in leaking data to your training dataset. For instance, when you encode or rescale you data before splitting into train, test and validation datasets.</p><p>To make your code more organized, readable and to prevent data leakage we can use the Pipeline from scikit-learn. However, when trying to build a more complex pipeline that integrate encondings, rescalers, feature engineering and balancing your data (in case of a classification model) from other packages such as imbalanced-learn and feature-engine, scikit-learn’s Pipeline cannot handle then properly. To solve this problem, we can use the imbalanced-learn Pipeline instead.</p><p>In this article, we’ll explore how to build this “complex pipeline” using three libraries — <a href="https://scikit-learn.org/stable/index.html">scikit-learn</a>, <a href="https://imbalanced-learn.org/stable/index.html">imbalanced-learn</a>, and <a href="https://feature-engine.trainindata.com/en/latest/index.html">feature-engine</a> — to construct robust and efficient ML pipelines. In addition, I will show how to use pipeline in cross-validation and how to access parameters from the steps of the pipeline to fine-tune them.</p><p>You can check the notebook with the code here:</p><p><a href="https://colab.research.google.com/drive/1CZ8mGWlY_zEJOpokZBSNvZPrtg1iHcAb">Google Colaboratory</a></p><h3>The dataset</h3><p>The data that we are going to use is the breast cancer dataset that we can load directly from sklearn with some minor changes. I selected just a few columns for the sake of simplicity and added 2 categorical features so that we have categorical features to be treated.</p><pre># Importing Pandas and Numpy<br>import pandas as pd<br>import numpy as np<br>from sklearn.datasets import load_breast_cancer<br><br># Loading breast cancer dataset from Sklearn<br>data = load_breast_cancer(as_frame=True).frame<br><br># Selecting just a few columns<br>df_base_table = data.iloc[:, :10].copy()<br><br># Adding Target column<br>df_base_table[&#39;target&#39;] = data[&#39;target&#39;]<br><br># List of cities to create city column<br>cities_list = [&#39;sao paulo&#39;, &#39;rio de janeiro&#39;, &#39;brasilia&#39;, &#39;salvador&#39;, &#39;fortaleza&#39; ,&#39;curitiba&#39;, &#39;cuiaba&#39;, &#39;goiania&#39;, &#39;manaus&#39;, &#39;palmas&#39;, &#39;vitoria&#39;, &#39;aracaju&#39;]<br><br># Setting seed for reproducibility<br>rng = np.random.default_rng(seed=42)<br><br># Create city column assigning cities to each row<br>df_base_table[&#39;city&#39;] = rng.choice(cities_list, size=df_base_table.shape[0])<br><br># Creating column of tumor size (categorical)<br>df_base_table[&#39;tumor size&#39;] = rng.choice([&#39;large&#39;, &#39;medium&#39;, &#39;small&#39;], size=df_base_table.shape[0])<br><br>df_base_table.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PepfbtgvrzDN9bDKGrNh_A.png" /></figure><p>It is binary classification dataset where the target is to identify if cells captured in the image are malignant or benign. The target variable is encode as malignant = 0 and benign = 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*qaNFBWt4gEcS1_lY37T6tA.png" /></figure><p>As the image above shows, we have 62.7% of the dataset that are benign and 37.3% that are malignant. Even though the dataset is not very imbalanced, for the sake of the example in this article we are going to apply a oversample technique to balance it to 50%/50%.</p><h3>Pipeline Steps Overview</h3><p>Before we get into any code, here is the purpose of the pipeline according to the sklearn documentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*Zy9Ms3KwsZAnbhR54etMQg.png" /><figcaption>source: <a href="https://scikit-learn.org/stable/modules/compose.html#pipeline-chaining-estimators">sklearn documentation</a>.</figcaption></figure><p>Now let’s visualize the steps that we are going to include in the pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*mmF5SlDXYIwzMpdGL9PAwQ.png" /><figcaption>Source: <a href="https://scikit-learn.org/stable/modules/compose.html#pipeline-chaining-estimators">sklearn documentation</a></figcaption></figure><p>Let’s break it down in parts:</p><ol><li>In the first set of steps we are dropping unnecessary features that we might have identified in our dataset.</li><li>In the second set of steps we are treating missing values.</li><li>Next, we are rescaling/encoding our data.</li><li>In the fourth set of steps we are doing feature selection</li><li>In the fifth set we are oversampling our data</li><li>And finally we have our model that will be trained with the transformed data.</li></ol><p><strong>Side Note: </strong>All the preprocessing steps of imputing missing value, rescalers and encoders were done without much consideration of what type of technique is best to each feature. The intent of this article is to show you how you can build a Pipeline with all these steps.</p><h3>Building the Pipeline</h3><p>Now that we know what we are going to do and the dataset, let’s see how to build the Pipeline using Scikit-Learn, Imbalanced-Learn and Feature-Engine libraries.</p><p>But first of all we need to split our dataset into train and test.</p><pre># Importing train_test_split function<br>from sklearn.model_selection import train_test_split<br><br># Splitting<br>X = df_base_table.drop(columns=[&#39;target&#39;])<br>y = df_base_table[&#39;target&#39;]<br><br>X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)</pre><p>After splitting our data we can build our Pipeline object with all the steps that we want to apply.</p><pre># ================================================================<br># Step 1. Importing libraries<br># ================================================================<br>from sklearn.preprocessing import MinMaxScaler, StandardScaler<br>from sklearn.tree import DecisionTreeClassifier<br>from sklearn.feature_selection import SelectKBest<br><br>from imblearn.pipeline import Pipeline<br>from imblearn.over_sampling import RandomOverSampler<br><br>from feature_engine.wrappers import SklearnTransformerWrapper<br>from feature_engine.imputation import ArbitraryNumberImputer, CategoricalImputer<br>from feature_engine.selection import DropFeatures, DropCorrelatedFeatures<br>from feature_engine.encoding import OneHotEncoder, CountFrequencyEncoder<br><br># ================================================================<br># Step 2. Separate columns to apply different preprocesses<br># ================================================================<br># Columns to drop<br>cols_to_drop = [<br>    &#39;mean fractal dimension&#39;<br>]<br><br># 2. Columns to fillna = 0<br>cols_fillna_0 = [<br>    &#39;mean symmetry&#39;<br>]<br><br># Columns to fillna = 1<br>cols_fillna_1 = [<br>    &#39;mean radius&#39;<br>]<br><br># Columns to fillna = -1<br>cols_fillna_neg999 = [<br>    &#39;mean perimeter&#39;<br>]<br><br># Columns to fillna = &quot;missing&quot;<br>cols_fillna_missing = [<br>    &#39;city&#39;,<br>    &#39;tumor size&#39;,<br>]<br><br># Columns to apply OneHotEncoding<br>cols_ohe = [<br>    &#39;tumor size&#39;<br>]<br><br># Columns to apply FrequencyEncoder<br>cols_freq_encode = [<br>    &#39;city&#39;<br>]<br><br># Columns to rescale with MinMaxScaler<br>cols_minmax = [<br>    &#39;mean radius&#39;,<br>    &#39;mean texture&#39;,<br>    &#39;mean perimeter&#39;,<br>    &#39;mean area&#39;,<br>]<br><br># Columns to apply StandardScaler<br>cols_std_scaler = [<br>    &#39;mean smoothness&#39;,<br>    &#39;mean compactness&#39;,<br>    &#39;mean concavity&#39;,<br>    &#39;mean concave points&#39;,<br>    &#39;mean symmetry&#39;,<br>]<br><br><br># ==============================================<br># Step 3. Building Pipeline with preprocess steps, oversample and model<br># ==============================================<br>preprocess_steps = [<br>    (&#39;drop_cols&#39;, DropFeatures(features_to_drop=cols_to_drop)),<br>    (&#39;fillna_0&#39;, ArbitraryNumberImputer(variables=cols_fillna_0, arbitrary_number=0)),<br>    (&#39;fillna_1&#39;, ArbitraryNumberImputer(variables=cols_fillna_1, arbitrary_number=1)),<br>    (&#39;fillna_neg999&#39;, ArbitraryNumberImputer(variables=cols_fillna_neg999, arbitrary_number=-999)),<br>    (&#39;fillna_missing&#39;, CategoricalImputer(variables=cols_fillna_missing, fill_value=&#39;missing&#39;)),<br>    (&#39;ohe&#39;, OneHotEncoder(variables=cols_ohe)),<br>    (&#39;freq_encode&#39;, CountFrequencyEncoder(variables=cols_freq_encode, encoding_method=&#39;frequency&#39;)),<br>    (&#39;minmax_scaler&#39;, SklearnTransformerWrapper(MinMaxScaler(), variables=cols_minmax)),<br>    (&#39;std_scaler&#39;, SklearnTransformerWrapper(StandardScaler(), variables=cols_std_scaler)),<br>    (&#39;drop_corr_feat&#39;, DropCorrelatedFeatures(method=&#39;pearson&#39;, threshold=0.8)),<br>    (&#39;feature_selection&#39;, SelectKBest(k=5)),<br>    (&#39;oversampling&#39;, RandomOverSampler(sampling_strategy=&#39;minority&#39;, random_state=42)),<br>    (&#39;decision_tree&#39;, DecisionTreeClassifier(max_depth=5, min_samples_split=10, random_state=42))<br>]<br><br># ==============================================<br># Step 4. Building Pipeline with preprocess steps, oversample and model<br># ==============================================<br>complex_pipeline = Pipeline(steps=preprocess_steps)</pre><p>Let’s break the code down to a better understanding:</p><p><strong>Step 1.</strong> We are just importing libraries that we are going to use</p><p><strong>Step 2.</strong> Each column will have different preprocess. Therefore, we create lists of column names for each preprocess to be applied to those columns.</p><p><strong>Step 3.</strong> Create a list with all the preprocessing steps that will be added in the pipeline</p><p><strong>Step 4.</strong> Build the Pipeline object with all the preprocess that are in the <em>preprocess_steps</em> list</p><p>If we print the <em>complex_pipeline </em>we get the overview of the steps in the pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*DhKtQzYs06eGMjLSq5fnGw.png" /></figure><p>Now that we have our pipeline object done, we can fit and predict just as we would with a sklearn model.</p><pre># Training the model with all the steps of the pipeline<br>complex_pipeline.fit(X_train, y_train)<br><br># Making predictions<br>y_pred = complex_pipeline.predict(X_test)<br>y_pred_proba = complex_pipeline.predict_proba(X_test)</pre><p>When we fit the entire pipeline with our train dataset, we are setting all the internal parameters of each step fitted to our train dataset. For instance, the standard scaler will have the mean and standard deviation stored of each variables passed to it according to the data of the train dataset and then, when we predict, it will apply the standard scaler — through transform method — to the test dataset.</p><p>It makes easier to fit and predict as we just have to call it once instead of calling fit and transform for each step before passing it to the model.</p><h3>Cross-Validation with Pipeline</h3><p>Another benefit of the pipeline is when we want to cross-validate our model. It will ensure that for each kfold split it will fit to the train folds and will apply transform/predict to the validation fold, avoiding data leakage in the process. The image below illustrate it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*5Jq57prdg8K6LGFgujH6eA.png" /></figure><p>The code below show how to cross-validade with pipeline:</p><pre># Importing Library<br>from sklearn.model_selection import cross_validate<br><br># Calculating Cross-Validation metrics<br>cv_metrics = cross_validate(<br>    estimator=complex_pipeline,<br>    X=X_train,<br>    y=y_train,<br>    scoring=[&#39;accuracy&#39;, &#39;precision&#39;, &#39;recall&#39;, &#39;f1&#39;, &#39;roc_auc&#39;],<br>    cv=5,<br>)<br><br># Constructing DataFrame of the averages of the metrics from Cross-Validation<br>df_cv_metrics = pd.DataFrame({<br>    &#39;accuracy&#39;: [cv_metrics[&#39;test_accuracy&#39;].mean()],<br>    &#39;precision&#39;: [cv_metrics[&#39;test_precision&#39;].mean()],<br>    &#39;recall&#39;: [cv_metrics[&#39;test_recall&#39;].mean()],<br>    &#39;f1&#39;: [cv_metrics[&#39;test_f1&#39;].mean()],<br>    &#39;roc_auc&#39;: [cv_metrics[&#39;test_roc_auc&#39;].mean()],<br>})<br><br>df_cv_metrics</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*wtWxPeTqOKkhaTZSUgzpSA.png" /></figure><p>To use the pipeline in cross-validation is as simple as passing it to the estimator parameter, just like as if you were passing a sklearn model with your X_train and y_train dataset.</p><h3>Fine-tunning with Pipeline</h3><p>The Pipeline object has a special way to access parameters from each step inside the pipeline. According to their documentation you can access parameters using “<em>estimator__parameter” </em>where the estimator is the name you gave for the step and parameter is the name of the parameter of said estimator. For instance, we named the SelectKBest estimator as “feature_selection” and we can access the “k” parameter like this: “feature_selection__k”.</p><p>To fine tune with Pipeline we can define a dictionary with the search space for each parameter of each estimator through this method. After that, we can pass this dictionary and the pipeline inside the RandomizedSearchCV or GridSearchCV as shown below.</p><pre># Importing RandomizedSearchCV from Sklearn<br>from sklearn.model_selection import RandomizedSearchCV<br><br># Dict with parameters distribution<br>param_distributions_dict = {<br>    &#39;feature_selection__transformer__k&#39;: [5, 7, 9],<br>    &#39;decision_tree__max_depth&#39;: [3, 5, 7],<br>    &#39;decision_tree__min_samples_split&#39;: [2, 5, 10],<br>    &#39;decision_tree__min_samples_leaf&#39;: [1, 5, 10]<br>    }<br><br># Instantiating random_search object<br>random_search = RandomizedSearchCV(<br>    estimator=complex_pipeline,<br>    param_distributions=param_distributions_dict,<br>    scoring=&#39;f1&#39;,<br>    cv=5,<br>    random_state=42,<br>    verbose=2<br>)<br><br># Fine tunning<br>random_search.fit(X_train, y_train)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/683/1*nuM5KGbIn7yFolsm9FEurw.png" /></figure><p>With the “best_estimator_” attribute we can get the Pipeline with the best parameters found for each estimator. Finally, we can use it to make predictions on the test dataset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*czaGy34FknCUYFBH_Tz5Gg.png" /></figure><h3>Conclusion</h3><p>In this article I showed how we can build a complex Pipeline object including preprocessing the data (handling missing value, scaling/encoding), feature_selection, balancing the data and the model. Building Pipelines this way helps us to encapsulate all the data manipulation and the final model in one object, thus making it more convenience because we have to call fit and transform/predict only once instead of calling it for each preprocessing step. Another benefit of using Pipelines is that it helps to prevent leaking data to your test/validation dataset, making it more reliable.</p><p>The exemple in this article may seem simple, but the goal was to show how to build the pipeline with all this different data manipulation so that you can adapt it to your use case. I encourage you to check the three libraries shown here to explore what they can offer. I hope this article was useful and if you have any question let me know.</p><h3>In Plain English</h3><p><em>Thank you for being a part of our community! Before you go:</em></p><ul><li><em>Be sure to </em><strong><em>clap</em></strong><em> and </em><strong><em>follow</em></strong><em> the writer! 👏</em></li><li><em>You can find even more content at </em><a href="https://plainenglish.io/"><strong><em>PlainEnglish.io</em></strong></a><strong><em> 🚀</em></strong></li><li><em>Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. 🗞️</em></li><li><em>Follow us: </em><a href="https://twitter.com/inPlainEngHQ"><strong><em>Twitter</em></strong></a><strong><em>(X</em></strong>), <a href="https://www.linkedin.com/company/inplainenglish/"><strong><em>LinkedIn</em></strong></a>, <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong><em>YouTube</em></strong></a>, <a href="https://discord.gg/in-plain-english-709094664682340443"><strong><em>Discord</em></strong></a><strong><em>.</em></strong></li><li><em>Check out our other platforms: </em><a href="https://stackademic.com/"><strong><em>Stackademic</em></strong></a>, <a href="https://cofeed.app/"><strong><em>CoFeed</em></strong></a>, <a href="https://venturemagazine.net/"><strong><em>Venture</em></strong></a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c742b0e7e9f" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/building-complex-ml-pipelines-6c742b0e7e9f">Building complex ML pipelines</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spatial Clustering]]></title>
            <link>https://kazumatsuda.medium.com/spatial-clustering-fa2ea5d035a3?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa2ea5d035a3</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[cluster-analysis]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Tue, 20 Jun 2023 13:01:02 GMT</pubDate>
            <atom:updated>2023-06-20T13:01:02.392Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QhlAlkWCWe4jVJKv" /><figcaption>Photo by <a href="https://unsplash.com/@amerour?utm_source=medium&amp;utm_medium=referral">Antoine Merour</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Spatial clustering is a valuable technique that can be used in various fields such as urban planning, ecology, and data analysis. It helps us identify patterns, group similar data points together, and gain insights into spatial distributions. In this article, we will explore how to perform spatial clustering using, scikit-learn, Geopandas and H3, a spatial indexing library developed by Uber with code example.</p><h3>Why Spatial Clustering?</h3><p>Spatial clustering involves dividing a dataset into groups based on their spatial proximity. It helps us understand the underlying structures and relationships within spatial data. For instance, in urban planning, spatial clustering can identify areas with similar characteristics like population density, land use patterns, or socioeconomic factors. This information is crucial for making informed decisions and developing targeted strategies</p><h3>Introduction to H3 library</h3><p>The H3 library, developed by Uber Technologies, is a powerful geospatial indexing and analytics library. It utilizes a hexagonal hierarchical spatial grid system to efficiently index and analyze geospatial data. By converting geographic coordinates into H3 indexes, the library facilitates tasks such as spatial indexing, point-in-polygon operations, proximity searches, aggregation, spatial joins and<strong> spatial clustering</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*Ou4zJP9sfqz2vDQmFzXe3Q.png" /></figure><p>There are other types of spatial indexing that use squares (eg. S2 from Google) and triangles. However, hexagons have some interesting properties that the others don’t.</p><p>Triangles and squares have neighbors with different distances, whereas hexagons have neighbors with same distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*m79Mr--Z7Nm1i5aJOrvGOA.jpeg" /><figcaption>Source: <a href="https://h3geo.org/docs/highlights/aggregation">https://h3geo.org/docs/highlights/aggregation</a></figcaption></figure><p>Hexagons have the property of expanding rings of neighbors approximating circles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/399/1*EbKtaA2nZ4HNllKNVkLzkw.jpeg" /><figcaption>Source: <a href="https://h3geo.org/docs/highlights/aggregation">https://h3geo.org/docs/highlights/aggregation</a></figcaption></figure><h3>Case Study</h3><p>For a better understanding of what spatial clustering can bring when analysing data, let’s imagine a hypothetical case.</p><blockquote>Imagine that we want to open a new store in a city and for that we have to map regions with the biggest sales potential.</blockquote><p>As a data scientist we can use spatial clustering to identify regions with the biggest sales potential. We can go further and after identifying the best cluster to our case we can prioritize and rank the regions within that cluster using weighted average.</p><p>To build the solution, we are going to use the brazilian census tract data of São Paulo city produced by IBGE that contains information of monthly income, population count and count of housing units. We are going to use only these three variables to make it simple.</p><p>To build the solution we are going to follow these steps:</p><ol><li>Preprocess data: aggregate census tract data into H3’s hexagons</li><li>Prepare data for modeling: rescale data</li><li>Build cluster model.</li><li>Analyse results.</li></ol><p>Now that we know what we want to do, let’s get to the code.</p><p>You can get access to the notebook of with the code here:</p><p><a href="https://colab.research.google.com/drive/1QS3wEo7ygjpekt092eub7H0VfppI3nng?usp=sharing">Google Colaboratory</a></p><h3>Preprocess Data</h3><p>The first step of our solution is to aggregate census tract data into H3’s hexagons. We can think of this aggregation as a way to “normalize” spatial data. One of the problem of census tract is that it comes with different sizes and shapes, making it difficult to make a fair comparison between them. With H3 hexagons we can solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*zAmumP0VC7qZG11J2DZ1yQ.jpeg" /><figcaption>Map with census tract shapes.</figcaption></figure><p>So let’s see how this aggregation is done.</p><p>First we import necessary libraries and load the census tract data</p><pre># Importing necessary libraries<br>import pandas as pd<br>import numpy as np<br><br>import geopandas as gpd<br>import h3<br>import folium<br>from shapely.geometry import Polygon, Point, mapping, LineString<br>from libpysal import weights<br><br>from sklearn.cluster import AgglomerativeClustering<br>from sklearn.preprocessing import MinMaxScaler<br>from feature_engine.wrappers import SklearnTransformerWrapper<br><br># Display all columns from dataframe<br>pd.set_option(&#39;display.max_columns&#39;, None)<br><br># Supress scietific notation<br>pd.set_option(&#39;display.float_format&#39;, lambda x: &#39;%.5f&#39; % x)</pre><pre># File path<br>SP_CENSUS_TRACT_FILE_PATH = r&#39;https://github.com/AlvaroMatsuda/Spatial_Clustering/blob/main/databases/brazilian_census_tract.geojson?raw=true&#39;<br><br># Loading data<br>df_census_tract = gpd.GeoDataFrame.from_file(SP_CENSUS_TRACT_FILE_PATH)<br><br>df_census_tract.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8K_L86AttR1D0p5a690bRA.png" /><figcaption>Output of the above code snippet.</figcaption></figure><p>Now we have to build the hexagons polygons covering São Paulo city. There are three steps to build the hexagons:</p><ul><li><strong>STEP 01:</strong> Get hexagon’s indexes that are contained inside census tract polygons.</li><li><strong>STEP 02: </strong>Convert from bigger aperture to a smaller aperture (see comment below).</li><li><strong>STEP 03:</strong> Create hexagons Polygon from hexagon’s indexes.</li></ul><pre># ========================<br># STEP 01<br># ========================<br><br># Initial Aperture size<br>INITIAL_APERTURE_SIZE = 10<br><br># Final Aperture size<br>FINAL_APERTURE_SIZE = 8<br><br># Empty list to be populated with hexagon&#39;s indexes<br>hex_list = []<br><br># Iterate over census tract geometries to get hexagon&#39;s indexes<br>for n,g in enumerate(df_census_tract[&#39;geometry&#39;].explode(ignore_index=True)):<br><br>    # Get GeoJson from geometry<br>    temp  = mapping(g)<br><br>    # Get coordinates of geometry from the GeoJson<br>    temp[&#39;coordinates&#39;]=[[[j[1],j[0]] for j in i] for i in temp[&#39;coordinates&#39;]]  <br><br>    # Fills the polygon with hexagons that are contained by the GeoJSON-like data structure.<br>    hex_list.extend(h3.polyfill(geojson=temp, res=INITIAL_APERTURE_SIZE))<br><br># ========================<br># STEP 02<br># ========================<br><br># Column name with the aperture size<br>initial_hex_col = &#39;hex{}&#39;.format(INITIAL_APERTURE_SIZE)<br>final_hex_col = &#39;hex{}&#39;.format(FINAL_APERTURE_SIZE)<br><br># Creating DataFrame with hexagon&#39;s indexes<br>df_hex = gpd.GeoDataFrame(hex_list,columns=[initial_hex_col])<br><br># Convert to aperture 8<br>df_hex[final_hex_col] = df_hex[initial_hex_col].apply(lambda x: h3.h3_to_parent(x, 8))<br><br># Dropping columns with original aperture<br>df_hex.drop(columns=[initial_hex_col], inplace=True)<br><br># ========================<br># STEP 03<br># ========================<br># Creating Hexagon polygons based on Hexagons indexes<br>df_hex[&#39;hex_polygon&#39;] = df_hex[final_hex_col].apply(lambda x: Polygon(h3.h3_to_geo_boundary(x, geo_json=True)))<br><br># Setting GeoDataFrame Geometry<br>df_hex.set_geometry(&#39;hex_polygon&#39;, crs=df_census_tract.crs, inplace=True)<br><br># Drop Duplicated hexagons caused when we converted aperture<br>df_hex.drop_duplicates(inplace=True)<br><br>df_hex.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*lGSbb6dKo6Ylz8te7fgnwQ.png" /><figcaption>Output of the code snippet.</figcaption></figure><pre># Creating a Folium Map object<br>m = folium.Map(location=[-23.568865965761308, -46.629872859184125], zoom_start=12, tiles=&#39;OpenStreetMap&#39;, crs=&#39;EPSG3857&#39;, width=&#39;70%&#39;, height=&#39;70%&#39;)<br><br># Adding census tract layer to the map<br>df_census_tract.explore(m=m)<br><br># Adding hexagons layer to the map<br>df_hex.explore(m=m, style_kwds={&#39;fillOpacity&#39;: 0.0, &#39;color&#39;: &#39;#CE2020&#39;})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZxd9ivaoKn_N1_XAy0HBQ.png" /><figcaption>Map with hexagons covering São Paulo city.</figcaption></figure><p>There is a trick in the code to solve a problem with polyfill function from H3 that is related to the step 02. If we polyfill the census tract directly with the aperture that we want, we get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BayHctR2LlzaA-0J0utWCQ.png" /><figcaption>Map demonstrating issue with polyfill function.</figcaption></figure><p>As you can see, there are areas where the hexagons don’t fully cover all census tract. To solve this problem, we need to get the indexes of a bigger aperture and them convert it to a smaller aperture. The aperture controls the resolution of the hexagons. We can think of it as being the scale or, in other words, the size of the hexagon. Bigger aperture means smaller hexagons.</p><p>With the hexagons constructed, we have to aggregate census tract data to the hexagons dataframe. To calculate total population that lives in a hexagon we have to sum the population of all census tract that are within it. However, as we can see on the images above, some census tracts intersects more than one hexagon. In those cases, I considered a portion of the data stored in the census tract according to the proportion of the area inside each hexagon.</p><pre># Calculating the area of each census tract<br>df_census_tract[&#39;area_census_tract&#39;] = (<br>    df_census_tract<br>    .to_crs(crs=3857)<br>    .area<br>    )<br><br># Overlaying census tracts that intersects each hexagon<br>df_agg = (<br>    df_hex<br>    .to_crs(crs=3857)<br>    .overlay(df_census_tract.to_crs(crs=3857))<br>    )<br><br># Calculating the area of overlayed cencus tract<br>df_agg[&#39;area_overlayed&#39;] = df_agg.area<br><br># Calculating the proportion of the area for each overlayed tract<br>df_agg[&#39;area_prop&#39;] = df_agg[&#39;area_overlayed&#39;] / df_agg[&#39;area_census_tract&#39;]<br><br><br># Calculating pop_count, total_monthly_income and housing_count proportional to the area inside the hexagons<br>df_agg = (<br>    df_agg<br>    .assign(prop_pop_count=lambda x: round(x[&#39;pop_count&#39;] * x[&#39;area_prop&#39;]))<br>    .assign(prop_total_monthly_income=lambda x: round(x[&#39;total_monthly_income&#39;] * x[&#39;area_prop&#39;]))<br>    .assign(prop_housing_count=lambda x: round(x[&#39;housing_count&#39;] * x[&#39;area_prop&#39;]))<br>    )<br><br># Aggregating census tract and summing the proportion variables<br>df_agg = (<br>    df_agg[[<br>    &#39;hex8&#39;, &#39;prop_pop_count&#39;, &#39;prop_total_monthly_income&#39;, &#39;prop_housing_count&#39;<br>    ]]<br>    .groupby([&#39;hex8&#39;])<br>    .sum()<br>    .reset_index()<br>    )<br><br># Creating Hexagon polygons based on Hexagons indexes<br>df_agg[&#39;hex_polygon&#39;] = df_agg[&#39;hex8&#39;].apply(lambda x: Polygon(h3.h3_to_geo_boundary(x, geo_json=True)))<br><br># Setting GeoDataFrame Geometry<br>df_agg = gpd.GeoDataFrame(df_agg, crs=df_census_tract.crs, geometry=&#39;hex_polygon&#39;) <br><br>df_agg.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*QKQYY6AN9kExBhlb_dZm6g.png" /><figcaption>Output of the above code snippet.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EwvAM_XstmcNaTtTJfZRBQ.png" /></figure><p>That is all for the aggregation. Now that we “normalized” spatial data, we are set to build a cluster model.</p><h3>Clustering</h3><p>Before we feed our data into a cluster model, first we need to rescale the value of the features, since clustering algorithms are based on distance of data points.</p><pre># Columns to be rescaled<br>cluster_variables = [<br>    &#39;prop_pop_count&#39;,<br>    &#39;prop_total_monthly_income&#39;,<br>    &#39;prop_housing_count&#39;<br>]<br><br># Pipeline with MinMaxRescaler to rescale variables<br>pipe = Pipeline(<br>    steps=[<br>        (&#39;rescaler&#39;, SklearnTransformerWrapper(MinMaxScaler(), variables=cluster_variables))<br>    ]<br>)<br><br># rescaled DataFrame<br>df_rescaled = pipe.fit_transform(df_agg)<br>df_rescaled = df_rescaled[cluster_variables]</pre><p>After rescaling we can train a cluster model. I am going to use Hierarquical clustering algorithm and build two models:</p><ol><li>The first will be with no proximity constrain.</li><li>The second with proximity constrain.</li></ol><p>The intent of this is to show the possibilities and the different results of these two different approaches.</p><pre># Instantiate model without proximity constrain<br>cluster_wo_constrain = AgglomerativeClustering(n_clusters=5)<br><br># Fit Model<br>cluster_wo_constrain.fit(df_rescaled)<br><br># Cluster labels<br>cluster_wo_constrain.labels_<br><br># Adding cluster column with cluster labels<br>df_agg[&#39;clusters_wo_constrain&#39;] = cluster_wo_constrain.labels_<br><br>df_agg[&#39;clusters_wo_constrain&#39;] = df_agg[&#39;clusters_wo_constrain&#39;].astype(str)<br><br>df_agg.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hsqkxEQDGaylYqKC4Q-V8Q.png" /><figcaption>Output of the above code snippet.</figcaption></figure><pre># Plotting the result of the cluster without constrain<br>df_agg.explore(<br>    column=&#39;clusters_wo_constrain&#39;,<br>    cmap=&#39;tab10&#39;,<br>    width=&#39;70%&#39;,<br>    height=&#39;70%&#39;,<br>    style_kwds={&#39;fillOpacity&#39;: 1.0, &#39;opacity&#39;: 0.0}<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVnP4SRALGH2d7kBfEA7nQ.png" /><figcaption>Map with the result of the cluster without proximity constrain.</figcaption></figure><p>To build the cluster with proximity constrain, first we need to build a spatial weights matrix that indicates which hexagons are neighbors of each other. After that we can use the <strong>connectivity </strong>parameter of the model and pass the spatial weight matrix as the constrain rule.</p><pre># Building spatial weights to be used as the proximity constrain<br>w = weights.contiguity.Queen.from_dataframe(df_agg)<br><br># Instantiate model with proximity constrain<br>cluster_w_constrain = AgglomerativeClustering(<br>    n_clusters=5,<br>    connectivity=w.sparse<br>)<br><br># Fit Model<br>cluster_w_constrain.fit(df_rescaled)<br><br># Cluster labels<br>cluster_w_constrain.labels_<br><br># Adding cluster column with cluster labels<br>df_agg[&#39;clusters_w_constrain&#39;] = cluster_w_constrain.labels_<br><br>df_agg[&#39;clusters_w_constrain&#39;] = df_agg[&#39;clusters_w_constrain&#39;].astype(str)<br><br>df_agg.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zgUnrDNoxpYgj5_wwnnE3A.png" /><figcaption>Output of the above code snippet.</figcaption></figure><pre># Plotting the result of the cluster with constrain<br>df_agg.explore(<br>    column=&#39;clusters_w_constrain&#39;,<br>    cmap=&#39;tab10&#39;,<br>    width=&#39;80%&#39;,<br>    height=&#39;80%&#39;,<br>    style_kwds={&#39;fillOpacity&#39;: 1.0, &#39;opacity&#39;: 0.0}<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTb2dv_LKjq8-afVwfdc_Q.png" /><figcaption>Map with the result of the cluster with proximity constrain.</figcaption></figure><p>As we can see, when we added the proximity constrain, all members of a cluster are connected, as opposed to the cluster without the constrain, where there are members of every cluster everywhere. Sometimes, when working with spatial data, it is desired that clusters have these constrains forming a uniform spatial cluster.</p><p>In our problem that is no need to add the constrain, as we just want to identify the regions with the best opportunities to open a new store.</p><h3>Cluster Profiling</h3><p>Now we can analyse the profile of each cluster and identify the cluster which contain hexagons with the biggest sales potential based on the three variables.</p><p>To do that we can calculate the average of all three variables for each cluster.</p><pre># Making clusters profile<br>clusters_profile = (<br>    df_agg<br>    .groupby(&#39;clusters_wo_constrain&#39;)<br>    .agg(<br>        mean_pop=(&#39;prop_pop_count&#39;, &#39;mean&#39;),<br>        mean_income=(&#39;prop_total_monthly_income&#39;, &#39;mean&#39;),<br>        mean_housing=(&#39;prop_housing_count&#39;, &#39;mean&#39;),<br>        )<br>    .reset_index()<br>    .sort_values(by=[&#39;mean_pop&#39;,&#39;mean_income&#39;, &#39;mean_housing&#39;], ascending=False)<br>    )<br><br>clusters_profile</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*rfz-DgJB--4qo9tByTqZ8A.png" /><figcaption>Output of the above code snippet.</figcaption></figure><p>Analysing the profile, we can identify that cluster 3 has the highest monthly income and population averages, which indicate that these regions have a lot of potential customers with high income.</p><p>After identifying the best cluster, we can rank the hexagons within the cluster 3 using weighted average.</p><pre># Separating only hexagons of cluster 3<br>cluster3 = df_agg[df_agg[&#39;clusters_wo_constrain&#39;] == &#39;3&#39;]<br><br># Weights for each variable<br>pop_weight = 0.5<br>income_weight = 0.4<br>housing_weight = 0.1<br><br># Calculating weighted Average<br>cluster3[&#39;weighted_avg&#39;] = (<br>    cluster3<br>    .apply(lambda x: (x[&#39;prop_pop_count&#39;] * pop_weight) + (x[&#39;prop_total_monthly_income&#39;] * income_weight) + (x[&#39;prop_housing_count&#39;] * housing_weight), axis=1)<br>)<br><br># Ranking hexagons according to the weighted average<br>cluster3[&#39;hex_rank&#39;] = (<br>    cluster3[&#39;weighted_avg&#39;]<br>    .rank(method=&#39;first&#39;, ascending=False)<br>    )<br><br>cluster3.sort_values(&#39;hex_rank&#39;, ascending=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*idwZ3Sg8UJwh0zrqS1gxOg.png" /></figure><pre># Plotting ranked hexagons<br>cluster3.explore(<br>    column=&#39;hex_rank&#39;,<br>    cmap=&#39;gray&#39;,<br>    height=&#39;80%&#39;,<br>    width=&#39;80%&#39;,<br>    style_kwds={&#39;fillOpacity&#39;: 0.7, &#39;opacity&#39;: 1.0, &#39;color&#39;: &#39;#000000&#39;}<br>    )</pre><figure><img alt="Map with ranked hexagons." src="https://cdn-images-1.medium.com/max/1024/1*ZJ85dvxKy1ixIOFS33JoHQ.png" /><figcaption>Map with ranked hexagons.</figcaption></figure><p>The map above show the hexagons ranked according to the calculated weighted average. Darker the color, higher the rank. With this, we could prioritize a deeper analysis on the higher ranked hexagons to make the decision of where to open a new store.</p><h3>Conclusion</h3><p>In this article we explored the power of spatial clustering using Uber’s H3 library as a way to “normalize” spatial data. We learned how to index our spatial data using H3, perform spatial clustering using Hierarquical Clustering algorithm with and without spatial constrain and their different results and lastly we have identifyed the cluster with the biggest potential and ranked the hexagons within this cluster to have a list of priorization.</p><p>Experiment with different clustering algorithms, appertures, and visualizations to gain a deeper understanding of your data and make informed decisions based on spatial patterns.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa2ea5d035a3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP (Part 2): Feature Extraction]]></title>
            <link>https://kazumatsuda.medium.com/nlp-part-2-feature-extraction-d8f0d20d09f1?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8f0d20d09f1</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[feature-extraction]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Wed, 10 May 2023 13:17:18 GMT</pubDate>
            <atom:updated>2023-05-10T13:17:18.685Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7bzVmS4qQPW5RVWZ" /><figcaption>Photo by <a href="https://unsplash.com/@tot87?utm_source=medium&amp;utm_medium=referral">Piotr Łaskawski</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Continuing on my previus post, in this second part I will focus on techniques of feature extraction for text data. Feature extraction are techniques that encode text data into numerical data such that machine learning models can interpret it.</p><p>Techniques covered:</p><ul><li>Bag of words (BoW);</li><li>Term Frequency Inverse Document Frequency (TF-IDF);</li><li>n-grams.</li></ul><p>If you haven’t read the first part yet, I highly recommend that you read it first as I am going to use the code done there.</p><p><a href="https://kazumatsuda.medium.com/nlp-preprocessing-text-data-part-1-b4641af2a5af">NLP: Preprocessing text data (Part 1)</a></p><p>Link to the notebook with the code for this post:</p><p><a href="https://github.com/AlvaroMatsuda/Sentiment_Analysis/blob/main/notebook/sentiment_analysis_part2.ipynb">Sentiment_Analysis/sentiment_analysis_part2.ipynb at main · AlvaroMatsuda/Sentiment_Analysis</a></p><h3>Bag of Words (BoW)</h3><p>Bag of words are one of the most popular feature extraction techniques. BoW is a technique that represents words as their occurance within a document. It is similar to one hot encoding in that each word in the vocabulary is a feature and it indicates whether that word occurs in the document or not (1 or 0).</p><p>After this brief explanation of BoW, I will show how to build it with code examples. There are three main steps to build a BoW:</p><ol><li>select our text data from where we are going to build the vocabulary;</li><li>generate vocabulary;</li><li>vectorize the document according to the vocabulary.</li></ol><p><em>OBS: I will continue to use the code of the first part as our text data is already preprocessed.</em></p><p>To build our Bag of Words we are going to use the CountVectorizer from Sklearn. We can do all three steps mentioned above inside the function.</p><pre># Importing CountVectorizer from Sklearn<br>from sklearn.feature_extraction.text import CountVectorizer<br><br># Getting only the reviews preprocessed with lemmatization<br>corpus_lem = df[&#39;review_pp_lem&#39;]<br><br># Instantiate CountVectorizer object<br>vectorizer = CountVectorizer()<br><br># Generate Bag of Words<br>bow = vectorizer.fit_transform(corpus_lem)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*3yZzMxpFdJojbKcX5W1z-w.png" /><figcaption>Shape comparison of bow object and the corpus_lem object.</figcaption></figure><p>We can see that it generated a parse matrix with 61,594 rows (the number of reviews in our dataset), and 28,034 columns, each one representing one word in the vocabulary created and the values are 0 or 1 indicating whether that word occurs in the review or not.</p><p>To make it easier to understand, let’s look how we can interpret it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*km3wX76fbmKtJtMjrdBvqQ.png" /></figure><p>The first code snippet of the image above, shows us how the <em>bow </em>object represent the reviews. Each column is referred to a word in the vocabulary and if a word is in the review it will have a value of 1 otherwise it will have value of 0. In the second code snippet I selected only words that are in either of the two sampled reviews. In the third code snippet I printed the text of both reviews to exemplify how bag of words encode text to number.</p><p>One thing to keep in mind about Bag of Words is that it does not care about the order of words or their context. It simply tells if a word is in the review or not. Another thing is that, as we can see from the shape of the <em>bow </em>object, it creates sparsity. We went from 1 column containing the text of the reviews to 28,034 columns.</p><h3>TF-IDF</h3><p>Term Frequency-Inverse Document Frequency is a statistical mearure that evaluate how relevant a word is to a document in a collection of documents. We can think of it as a weight of the importance of a word within a document compared to the entire corpus.</p><p>The formula behind it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/0*DADr73OO_JF5GawA.PNG" /><figcaption>Source: <a href="https://padhaitime.com/Natural-Language-Processing/TF-IDF">https://padhaitime.com/Natural-Language-Processing/TF-IDF</a></figcaption></figure><p>To have a better understanding of what it does, let’s say that we have three news articles with the following titles:</p><ol><li>What critics are saying about Guardians of the Galaxy Vol 3;</li><li>Six records that could be broken at the 2023 Oscar;</li><li>Marvel boss reveals how Fantastic Four will differ from old versions.</li></ol><p>Probably the words “movie”, “actor/actress”, “performance” will be very common among all three articles, thus it has little to say about each individual article, whereas “Torch” and “Invisible” probably will be very common only on the last article about Fantastic Four. In this example, the words “movie”, “actor/actress”, “performance” would have a small TF-IDF value and “Torch” and “Invisible” would have a high value.</p><p>Let’s see how to implement TF-IDF.</p><pre># Importing TfidfVectorizer from Sklearn<br>from sklearn.feature_extraction.text import TfidfVectorizer<br><br># Instantiating TfidfVectorizer object<br>tfidfvec = TfidfVectorizer()<br><br># Generating TF-IDF with the first 100 reviews<br>tfidf = tfidfvec.fit_transform(corpus_lem[:100])<br><br># Getting the first ten reviews decoded by the TF-IDF<br>example_tfidf = pd.DataFrame(tfidf[0:10].toarray(), columns=tfidfvec.get_feature_names_out())<br><br>example_tfidf</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1gVgQk1Y3J4y2vXUQsy_5g.png" /><figcaption>Output of the code snippet.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VOhxm-FKzOj_pdLbiUUkJg.png" /></figure><p>We can see that TF-IDF gives us a float number instead of only 0 and 1 generated by Bag of Words. Higher numbers generated by TF-IDF indicates that the word is frequent within a single document and is rare on the rest of documents. In our example, the word “app” appears in more documents than the word “audio”.</p><p>TF-IDF share the same problems that Bag of Words has, that being the context of words are not considered, it creates sparsity according to the size of the vocabulary. However, TF-IDF gives a bit more information to a machine learning model in that it gives the importance of a word as a weight instead of just indicating whether a word accurs in a document or not.</p><h3>N-grams</h3><p>We can think of N-grams as a sequence of “n” words that occurs in a document. For instance, a 1-gram (Unigram) is a sequence of only on word (the bag of words is a Unigram). A 2-gram (Bigram) is a sequence of two words and so on.</p><p>Let’s apply n-gram to a simple sentence:</p><p>“I really love chocolate ice cream.”</p><ul><li><strong>Unigram</strong>: [“I”, “really”, “love”, “chocolate”, “ice”, “cream”]</li><li><strong>Bigram</strong>: [“I really”, “really love”, “love chocolate”, “chocolate ice”, “ice cream”]</li><li><strong>Trigram</strong>: [“I really love”, “really love chocolate”, “love chocolate ice”, “chocolate ice cream”]</li></ul><p>One advantage of N-grams over bag of words and TF-IDF is that the context of words are considered. However, it does not consider the part of speech of words. Since N-grams does not encode the words itself, it only organizes them, we can use it in conjunction with either Bag of Words and TF-IDF.</p><p>On the functions that we used before (CountVectorizer and TfidfVectorizer) we can use a parameter called <em>ngram_range</em> and specify how we want to use n-grams and create the Bag of N-grams.</p><pre># Importing CountVectorizer from Sklearn<br>from sklearn.feature_extraction.text import CountVectorizer<br><br># Getting only the reviews preprocessed with lemmatization<br>corpus_lem = df[&#39;review_pp_lem&#39;]<br><br># Instantiate CountVectorizer object<br>vectorizer = CountVectorizer(ngram_range=(2, 2)) # Bigram<br><br># Generate Bag of Words<br>bongram = vectorizer.fit_transform(corpus_lem)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*g1CZfFuavb1wbxtMIiwZBA.png" /><figcaption>Shape comparison of bongram object and the corpus_lem object.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5lcEXUpv8th5RLCw7usgFw.png" /></figure><p>Notice how n-grams explode in dimension. It created 328.380 pair of words. There are ways to address this problem through the use of the <em>max_df, min_df </em>and <em>max_features </em>parameters from the CountVectorizer function. We can notice that the representation of words is the same as Bag of Words, the only difference being that in Bag of N-grams the features are pair of words instead of a single word.</p><h3>Conclusion</h3><p>We saw three techniques to extract features from text and after we apply one of them, we are set to feed the data into a machine learning model. From our review example, we still need to work on the data because we created a sparce matrix. One way to address it is by using said parameters from CountVectorizer function, as mentioned before.</p><p>The purpose of this post is to show how to apply these feature extraction techniques and hopefully have a bit more understanding behind what each technique does.</p><h3>About me</h3><p>I am a geographer currently working as a data scientist. For that reason, I am interested in data science and specially in spatial data science.</p><p>Follow me for more content. I will write a post every month about data science concepts and techniques, spatial data science and GIS (Geographic Information System).</p><h3>References</h3><ul><li><a href="https://medium.com/turing-talks/introdu%C3%A7%C3%A3o-a-bag-of-words-e-tf-idf-43a128151ce9">Introdução a Bag of Words e TF-IDF</a></li><li><a href="https://www.analyticsvidhya.com/blog/2022/05/a-complete-guide-on-feature-extraction-techniques/">A Complete Guide on Feature Extraction Techniques</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8f0d20d09f1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP: Preprocessing text data (Part 1)]]></title>
            <link>https://kazumatsuda.medium.com/nlp-preprocessing-text-data-part-1-b4641af2a5af?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4641af2a5af</guid>
            <category><![CDATA[text-mining]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 13:02:12 GMT</pubDate>
            <atom:updated>2023-05-03T01:06:16.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>NLP (Part 1): Preprocessing text data</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IjHv84tt0hgcnDU2" /><figcaption>Photo by <a href="https://unsplash.com/es/@issaphotography?utm_source=medium&amp;utm_medium=referral">Clarissa Watson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Text is everywhere and it can give us many insights about a company, product and service. However, extracting such insights is not an easy task. Text data is an unstructured data and, as the name suggest, we have to process it to a more “structured” form to be able to analyse and extract meaningful information. This is especially fundamental when we want to feed this data to a machine learning model.</p><p>I will write about text preprocessing in two parts. In this first part, I will cover some of the techniques necessary to process text data, mainly normalizing text and removing unwanted words and characters.</p><p>Techniques covered:</p><ul><li>Tokenization;</li><li>Removing punctuation;</li><li>Lower casing;</li><li>Removing stopwords;</li><li>Stemming;</li><li>Lemmatization.</li></ul><p>You can check the notebook with the code in my <a href="https://github.com/AlvaroMatsuda/Sentiment_Analysis/blob/main/notebook/sentiment_analysis.ipynb">github</a>.</p><h3>The Dataset</h3><p>First, let’s take a look at the dataset.</p><pre># Importing<br>import pandas as pd<br><br># Loading Dataset<br>df = pd.read_csv(r&#39;https://github.com/AlvaroMatsuda/Sentiment_Analysis/blob/main/data/reviews.csv?raw=true&#39;)<br>df</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*SrueAYaI9dK0LBEG9pyDIA.png" /><figcaption>Print of the dataframe.</figcaption></figure><p>We can observe that there are five columns:</p><ul><li><strong>Time_submitted</strong>: indicating the date and time of the submitted review;</li><li><strong>Review</strong>: column containing the text review;</li><li><strong>Rating</strong>: The rating given by the customer. Ranges from 1 to 5;</li><li><strong>Total_thumbsup</strong>: The number of thumbsup reaction of the review;</li><li><strong>Reply</strong>: The text containg the reply from spotify.</li></ul><p>We are interested only on the <strong>Review </strong>column.</p><h3>Tokenization</h3><p>Tokenization is a technique that most often decompose a sentence into words, but we can decompose into single letters if we want. The result of this decomposition is called tokens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*Kk5z1-YtbFnyaWLQka1u1A.png" /><figcaption>A single sentence.</figcaption></figure><pre># Importing<br>from nltk.tokenize import word_tokenize<br><br># Tokenizing a single review<br>tokens = word_tokenize(sentence)<br>tokens</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/123/1*X8V3eFpSw2hm1UwxxuQQWA.png" /><figcaption>Output of the above snippet.</figcaption></figure><pre># Tokenizing all rows from dataframe<br>review_tokens = df[&#39;Review&#39;].apply(word_tokenize)<br>review_tokens</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*ADqQtdYuoF0Mmwzr5Q8xCw.png" /><figcaption>All reviews tokenized.</figcaption></figure><p>We can see that there are some characters, such as (<strong>,.``)</strong> that depending on the use case is not ideal to have. For example, for sentiment analysis, these special character does not have any meaningful information if the review is positive or negative. In other cases like text generator models, these special characters can be important.</p><p>Next we are going to remove these special characters to show how it is done.</p><h3>Removing Punctuation</h3><p>Removing punctuation is quite simple. Inside the string module of python we have the following method that has all punctuations mapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*AG1P8n-z7Xre83dJDcaHJg.png" /></figure><p>We are going to use it to map all punctuations to use into the translate function of a string.</p><pre># Imports<br>import string<br><br># Creating translator object<br>translator = str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation)<br><br># Removing punctuation from sentence<br>punct_removed = sentence.translate(translator)<br><br># Printing sentence with and without punctuation<br>punct_removed, sentence</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*Y_AFvE0Xanw0ePfZJpakWA.png" /><figcaption>Output of the code above.</figcaption></figure><pre># Removing punctuation of all rows<br>reviews_punct_removed = df[&#39;Review&#39;].apply(lambda x: x.translate(str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation)))<br>reviews_punct_removed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*zEwXPBHgYRNVnCGyg-w91A.png" /></figure><h3>Lower Casing</h3><p>Another important step is to lower case our text. For example, “Great” and “great” would be considered two different words.</p><pre># Lower Casing all rows<br>reviews_lower = df[&#39;Review&#39;].str.lower()<br>reviews_lower</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*VUetUI6hKxLLbjN5n-Vg3A.png" /></figure><h3>Removing Stop Words</h3><p>Stop words are common words in a language. They are very common in text that they have no value in the meaning of the text. The most common words are:</p><ul><li><strong>preposition</strong>: in, at, for, by, etc;</li><li><strong>determiners</strong>: the, a, this, that, my, etc.</li></ul><p>These stop words are already mapped and is called stop list. Every language have a stop list and it can vary from list to list. We can even customize the stop list adding or removing words from the list.</p><p>It is worth mentioning that in some cases stop words are important, for instance, in text generator models.</p><pre># Importing<br>from nltk.corpus import stopwords<br><br># Getting list of english stopwords<br>ENG_STOPWORDS = stopwords.words(&#39;english&#39;)<br><br># Removing stopwords from all rows<br>review_wo_stopwords = df[&#39;Review&#39;].apply(lambda review: &#39; &#39;.join([word for word in review.split() if word not in ENG_STOPWORDS]))<br>review_wo_stopwords</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*6pdxyiAnTx8Lgjjjewd0rQ.png" /><figcaption>Reviews without stopwords.</figcaption></figure><pre># Comparing sentence with and without stepwords<br>df[&#39;Review&#39;][0], review_wo_stopwords[0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*wOi6Fd9_3Y-lS0m2_sOWBQ.png" /><figcaption>Comparing sentence with and without stopwords.</figcaption></figure><h3>Stemming</h3><p>Stemming is the process of transforming the word into its root. It does not account for the part of speech that the word belongs and the result can generate a word that does not exist.</p><pre># Importing<br>from nltk.stem.porter import PorterStemmer<br><br># Stemmer object<br>stemmer = PorterStemmer()<br><br># List of words to be stemmed<br>list_words = [&#39;study&#39;, &#39;studied&#39;, &#39;studying&#39;, &#39;studies&#39;]<br><br># Result of words stemmed<br>[stemmer.stem(word) for word in list_words]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*LHNcv9uKSu89P3ilqCtNlg.png" /><figcaption>Output of the above snippet.</figcaption></figure><p>As we can see, the stemming generated the word “<em>studi</em>” which does not exist, but is the root of the word study.</p><pre># Stemming all rows<br>review_stemmed = df[&#39;Review&#39;].apply(lambda x: &#39; &#39;.join(stemmer.stem(word) for word in x.split()))<br>review_stemmed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*on6qLBPEfD-wtJJitL1eEg.png" /><figcaption>Output of the above snippet.</figcaption></figure><h3>Lemmatization</h3><p>Lemmatization is the process of transforming a word into its lemma. Lemmatization takes into account the part of speech of each word and it returns an existing word.</p><pre># Importing<br>from nltk.stem import WordNetLemmatizer<br><br># Lemmatizer object<br>lemmatizer = WordNetLemmatizer()<br><br># List of words to be stemmed<br>list_words = [&#39;study&#39;, &#39;studied&#39;, &#39;studying&#39;, &#39;studies&#39;]<br><br># Result of words lemmatized<br>[lemmatizer.lemmatize(word) for word in list_words]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*789KGSYBDLjShJ6i3KnIpw.png" /><figcaption>Output of the above snippet.</figcaption></figure><pre># Lemmatization on all rows<br>review_lemmed = df[&#39;Review&#39;].apply(lambda x: &#39; &#39;.join(lemmatizer.lemmatize(word) for word in x.split()))<br>review_lemmed</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*ivoB39T7NRBHNrjA0dmgzQ.png" /><figcaption>Output of the above snippet.</figcaption></figure><h3>Lemmatization x Stemming</h3><p>How to decide which do we use? In general, lemmatization is used when we need to generate an understandable output, like chatbot and text generator models. On the other hand, we use stemming when we do not need and understandable output. The general meaning of the word is enough for the model. Stemming is most used for sentiment analysis and spam classification.</p><h3><strong>Full code</strong></h3><pre># Importing <br>import pandas as pd<br>from nltk.tokenize import word_tokenize<br>import string<br>from nltk.corpus import stopwords<br>from nltk.stem.porter import PorterStemmer<br>from nltk.stem import WordNetLemmatizer<br><br># Loading Dataset<br>df = pd.read_csv(r&#39;C:\Users\AlvaroMatsuda\OneDrive - DHAUZ\Área de Trabalho\Kazu_Files\Curso_FIA\Deep_Learning\Projeto_aula_deep_learning\base_dados\reviews.csv&#39;)<br><br># Removing punctuation of all rows<br>df[&#39;review_pp&#39;] = df[&#39;Review&#39;].apply(lambda x: x.translate(str.maketrans(&#39;&#39;, &#39;&#39;, string.punctuation)))<br><br># Lower Casing all rows<br>df[&#39;review_pp&#39;] = df[&#39;review_pp&#39;].str.lower()<br><br># Getting list of english stopwords<br>ENG_STOPWORDS = stopwords.words(&#39;english&#39;)<br><br># Removing stopwords from all rows<br>df[&#39;review_pp&#39;] = df[&#39;review_pp&#39;].apply(lambda review: &#39; &#39;.join([word for word in review.split() if word not in ENG_STOPWORDS]))<br><br># Stemmer object<br>stemmer = PorterStemmer()<br><br># Stemming all rows<br>df[&#39;review_pp_stem&#39;] = df[&#39;review_pp&#39;].apply(lambda x: &#39; &#39;.join(stemmer.stem(word) for word in x.split()))<br><br># Lemmatizer object<br>lemmatizer = WordNetLemmatizer()<br><br># Lemmatization on all rows<br>df[&#39;review_pp_lem&#39;] = df[&#39;review_pp&#39;].apply(lambda x: &#39; &#39;.join(lemmatizer.lemmatize(word) for word in x.split()))<br><br># Tokenizing reviews<br>tokens_lem = df[&#39;review_pp_lem&#39;].apply(word_tokenize)<br>tokens_stem = df[&#39;review_pp_stem&#39;].apply(word_tokenize)</pre><h3>Conclusion</h3><p>In this first post, it was showed some techniques to prepare text data, removing special characters, punctuation, stopwords and normalizing the text (lower casing, stemming and lemmatizing).</p><p>On the next post, I will continue to preprocess the same dataset. There, it will be shown techniques on how to represent these tokens into numeric data. This transformation is needed because machine learning can’t interpret text data.</p><h3>About me</h3><p>I am a geographer currently working as a data scientist. For that reason, I am interested in data science and specially in spatial data science.</p><p>Follow me for more content. I will write a post every month about data science concepts and techniques, spatial data science and GIS (Geographic Information System).</p><h3>References:</h3><p><a href="https://www.kaggle.com/code/sudalairajkumar/getting-started-with-text-preprocessing">Getting started with Text Preprocessing</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4641af2a5af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploratory Spatial Data Analysis (ESDA): Spatial Autocorrelation]]></title>
            <link>https://kazumatsuda.medium.com/exploratory-spatial-data-analysis-esda-spatial-autocorrelation-71b5782c19d6?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/71b5782c19d6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[geographic-information]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Wed, 08 Mar 2023 13:01:31 GMT</pubDate>
            <atom:updated>2023-03-21T02:29:02.665Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TRBej6WF-tSndZ_a" /><figcaption>Photo by <a href="https://unsplash.com/@nasa?utm_source=medium&amp;utm_medium=referral">NASA</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>In data science, an EDA (Exploratory Data Analysis) is a fundamental step of a project. It gives you better understanding of the data you are working with. It helps to identify outliers and extract insights through hypothesis testing. However, the methods applied to a regular EDA does not consider the spatial component of the data.</p><p>The ESDA (Exploratory Spatial Data Analysis) comes to answer questions that the regular EDA cannot. For example, with ESDA we can answer whether a variable (a phenomenon) happens at random in space or if they follow a spatial pattern. Another analysis we can do with ESDA is to identify if a variable is spatially clustered or not and if so, where they are clustered.</p><p>The spatial autocorrelation analyse if a given variable (phenomenon) occurs at random in space or if the location where it occurs have a bit of information about the value of the variable.</p><blockquote>Spatial autocorrelation can be defined as the “absence of spatial randomness”. (<a href="https://geographicdata.science/book/notebooks/06_spatial_autocorrelation.html#:~:text=absence%20of%20spatial%20randomness">Sergio J. Rey, Dani Arribas-Bel and Levi J. Wolf.</a>)</blockquote><p>There are two types of spatial autocorrelation:</p><ul><li>Global spatial autocorrelation</li><li>Local spatial autocorrelation</li></ul><p>I will get into more details of both global and local spatial autocorrelation and how to do them with code example. You can download the notebook with the code <a href="https://drive.google.com/uc?export=download&amp;id=1c5UEW2fszYvvTet06kLI7UZ1nSmO5f6z"><strong>here</strong> </a>to follow along.</p><p>But before we get into how to do it, let’s get familiar with the dataset we are going to work.</p><h3>The dataset</h3><p>We are going to use the census tract of São Paulo city, Brazil. It has information of population count and total monthly income contained in each tract.</p><p>Before we take a look at the dataset, let’s import the necessary libraries:</p><pre># Importing Libraries<br><br>import pandas as pd<br>import geopandas as gpd<br>import numpy as np<br>from pysal.lib import weights<br>from splot.libpysal import plot_spatial_weights<br>from esda.moran import Moran, Moran_Local<br>from splot.esda import moran_scatterplot, plot_local_autocorrelation, lisa_cluster<br>import matplotlib.pyplot as plt<br>import folium<br>import matplotlib.colors as colors<br><br><br>import warnings<br>warnings.filterwarnings(&quot;ignore&quot;)</pre><pre># Loading data<br>census_tract_sp = gpd.GeoDataFrame.from_file(r&#39;https://github.com/AlvaroMatsuda/medium_posts/blob/main/spatial_autocorrelation/data/census_tract_sp.geojson?raw=true&#39;)<br>census_tract_sp.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DRTV7vJdSQhsHfQM21Vgag.png" /></figure><pre># Fillna of pop_count and total_monthly_income<br>census_tract_sp[&#39;total_monthly_income&#39;].fillna(0, inplace=True)<br>census_tract_sp[&#39;pop_count&#39;].fillna(0, inplace=True)</pre><pre># Plotting choropleth map of pop_count column<br>census_tract_sp.explore(<br>    tiles=&#39;cartodbpositron&#39;,<br>    column=&#39;pop_count&#39;,<br>    height=&#39;60%&#39;,<br>    width=&#39;60%&#39;,<br>    scheme=&#39;naturalbreaks&#39;,<br>    cmap=&#39;Oranges&#39;,<br>    style_kwds={<br>        &#39;stroke&#39;: True,<br>        &#39;edgecolor&#39;: &#39;k&#39;,<br>        &#39;linewidth&#39;: 0.03,<br>        &#39;fillOpacity&#39;: 1<br>        },<br>    legend_kwds={<br>        &#39;colorbar&#39;: False,<br>        &#39;fmt&#39;: &#39;{:.0f}&#39;<br>        }<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*klyfxIiGCij1WTrkeX45HA.png" /><figcaption>Choropleth map of pop_count column.</figcaption></figure><pre># Plotting choropleth map of total_monthly_income column<br>census_tract_sp.explore(<br>    tiles=&#39;cartodbpositron&#39;,<br>    column=&#39;total_monthly_income&#39;,<br>    height=&#39;60%&#39;,<br>    width=&#39;60%&#39;,<br>    scheme=&#39;naturalbreaks&#39;,<br>    cmap=&#39;Oranges&#39;,<br>    style_kwds={<br>        &#39;stroke&#39;: True,<br>        &#39;edgecolor&#39;: &#39;k&#39;,<br>        &#39;linewidth&#39;: 0.03,<br>        &#39;fillOpacity&#39;: 1<br>        },<br>    legend_kwds={<br>        &#39;colorbar&#39;: False,<br>        &#39;fmt&#39;: &#39;{:.0f}&#39;<br>        }<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*MGc68knqVo0Wi31wikAWsg.png" /><figcaption>Choropleth map of total_monthly_income column.</figcaption></figure><p>Can we tell by looking at these two choropleth maps that <em>pop_count</em> and <em>total_monthly_income </em>are spatially clustered? Looking at <em>pop_count </em>map, is hard to say for sure if values are spatially clustered. On the other hand, <em>total_monthly_income </em>map seems to be more clustered. But, can we assure that it is clustered just by looking at the choropleth map? It is hard to tell.</p><p>So, we want be sure if values of <em>pop_count </em>and <em>total_monthly_income </em>variables are geographically clustered or not and where clusters occurs, if any.</p><h3>Spatial Weights and Spatial Lag</h3><p>To do spatial autocorrelation analysis, first we have to define two things in our dataset:</p><ul><li>Spatial weights</li><li>Spatial lag</li></ul><p>In summary, spatial weights is an operation that define the neighbors of each tract. There are many ways that we can define the neighbors, such as distance based, contiguity based and block based. I am not going to get into the details of it. In our case, we are going to use the contiguity based spatial weights, to be more precise the queen contiguity.</p><pre># Building spatial weights object<br>w = weights.contiguity.Queen.from_dataframe(census_tract_sp)<br><br># Plotting to visualize spatial weights<br>plot_spatial_weights(w, census_tract_sp);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*Aee1mfMbZMWap5TQi2-6rw.png" /></figure><p>The code above builds the weight object (w) which stores information of neighbors and weights assigned for each neighbors.</p><p>Below we can see which tract are neighbors of which. The key is referenced to the index of the tract and the values are indexes corresponding to tracts that are neighbors of the key tract index.</p><pre># Transforming weights into binary (if it&#39;s 1 = is neighbor, 0 = not neighbor)<br>w.transform = &quot;B&quot;<br><br># Showing neighbors indexes<br>w.neighbors</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*HL40m6bW_8W4KUGnxjkaKA.png" /></figure><p>The key “0” reference to the index 0 of the GeoDataFrame and the indexes [1, 450, 456, 429, 431] are all neighbors of the index 0.</p><p>The next code snippet show the weights assigned for each neighbor.</p><pre># Showing weights<br>w.weights</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*p7XFkf2zLFPUV8ewGybDuA.png" /></figure><p>In our case we are going to use the binary weights. But depending on the case, we can use different transformations to standardize weights.</p><p>After constructing the weight matrix, we have to calculate the spatial lag of variables we are interested. Spatial lag takes into account the weights assigned for each neighbor and multiply that by the value of the variable. After that, it sum the resulting values of all neighbors. In other words, it is the “local average” of a variable for each observation, considering the neighborhood.</p><pre># Calculating Spatial Lag<br>census_tract_sp[&#39;w_pop_count&#39;] = weights.lag_spatial(w, census_tract_sp[&#39;pop_count&#39;])<br>census_tract_sp[&#39;w_total_monthly_income&#39;] = weights.lag_spatial(w, census_tract_sp[&#39;total_monthly_income&#39;])<br><br>census_tract_sp[[&#39;id&#39;, &#39;pop_count&#39;, &#39;w_pop_count&#39;, &#39;total_monthly_income&#39;, &#39;w_total_monthly_income&#39;]].head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*VfrRIknDx9UGWAqDRH_irw.png" /></figure><p>In our case, since we used a binary weight the <em>w_pop_count </em>column is the sum of <em>pop_count</em> of all neighbors for each index. For example, the index 0 of the GeoDataFrame has these indexes as neighbors: [1, 450, 456, 429, 431]. So, if we sum the <em>pop_count </em>column of these rows we will get the value 1,876.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/777/1*kwuJNQiDjS7oibi1j3xzWA.png" /></figure><p>Now that we calculated the spatial lag for both variables we are interested, we are set to do spatial autocorrelation.</p><h3>Global Spatial Autocorrelation</h3><p>The global spatial autocorrelation helps us to answer questions like:</p><ul><li>Do variable values follow a spatial pattern?</li><li>Are similar values closer to other similar values than we would expect from pure chance?</li></ul><p>In other words, global spatial autocorrelation tells us if similar values of a given variable are clustered in space compared to what we would expect by pure chance (randomness). It gives an overview of our entire dataset, therefore it does not tell where those clusters are.</p><p>For continuous variable, we can use Moran’s I statistic for global spatial autocorrelation. The Moran’s I statistic is just like an analysis of autocorrelated variables. That is, the Moran’s I statistic ranges from -1 to 1 and it indicates if the variable is spatially clustered, dispersed or random. Positive values indicates that similar values of the variable are spatially closer (clustered), negative value indicates that the neighbors tend to have very different values (dispersed) and values close to 0 indicates that there are no correlation between location and the value of the variable (random). In other words, it tells us if the variable is spatially correlated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*tDf59zy6IcL0w3hOmNnxtA.png" /><figcaption>Result of Moran’s I statistic.</figcaption></figure><p>In our case the result of the Global Moran’s I statistic is 0.2425. What does this mean? Alone, it gives us the notion that the <em>pop_count </em>values is spatially positive correlated. However, only with this measure we can’t tell if we can be certain that the variable is spatially clustered. To be certain of that, we can calculate the p-value to test if the result of Moran’s statistic is significant or not. The null hypothesis of Moran’s I is that the values are randomly distributed in space.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*FExG-9aZyU2qsJJ8liYrqQ.png" /></figure><p>With a p-value of 0.001 we can reject the null hypothesis, therefore we can assume that the variable is not randomly distributed in space and with the value of the Moran’s I statistic we can tell that it have positive correlation.</p><p>We can use the Moran’s I scatterplot to help visualize the correlation.</p><pre># Plotting Moran&#39;s I scatter plot<br>moran_scatterplot(moran);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*Ykhv6G0W5G4IIdgLcw2ZXQ.png" /><figcaption>Moran’s I scatterplot.</figcaption></figure><p>The values in the x and y axis are in standard deviation. The x axis (Attribute) is referenced to the <em>pop_count </em>variable (pop count of each tract) and the y axis (Spatial Lag) is referenced to the <em>w_pop_count</em> variable (pop count of the neighbors for each tract). Looking at the plot we can analyse that as the x axis gets higher, so does the y axis in general. In other words, when <em>pop_count </em>is high in a tract, its neighbors also tend to have high values.</p><p>Now we are certain that the <em>pop_count </em>variable is spatially clustered, although the correlation is not that strong. Let’s do the same for <em>total_mothly_income</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*skYaKs6wscAqQVkqRLKBDg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*YyujBrloWDFdcF9rYDFyJg.png" /></figure><p>We can see that the <em>total_monthly_income </em>has higher Moran’s I value than <em>pop_count</em>, which means that <em>total_monthly_income </em>is more spatially clustered.</p><p>In summary, this is what the global spatial autocorrelation can tell us. It gives a general idea whether our data is spatially clustered, dispersed or random. Additionally, we can test if the data is spatially random distributed or not through the p-value. However, it does not indicate where the data is clustered or dispersed. That is where local spatial autocorrelation comes in. It can show us where the data is clustered.</p><h3>Local Spatial Autocorrelation</h3><p>As mentioned before, local spatial autocorrelation helps to identify where clusters are in a map. It achieve this by focusing on the relationship between each observarion and its neighbors.</p><p>For this LISA (Local Indicators of Spatial Association) is used. Basically, LISA is constructed based on the Moran’s scatterplot we did before. It divide the plot in 4 quadrants according to the relationship of observation and its neighbors:</p><ul><li>high value with high value neighbors (HH);</li><li>low value with low value neighbors (LL);</li><li>high value with low value neighbors (HL);</li><li>low value with high value neighbors (LH).</li></ul><pre># Local Moran&#39;s I<br>pop_count_local_moran = Moran_Local(y_pop_count, w)<br><br># Plotting Local Moran&#39;s I scatterplot of pop_count<br>fig, ax = moran_scatterplot(pop_count_local_moran, p=0.05);<br><br>plt.text(1.95, 1, &#39;HH&#39;, fontsize=25)<br>plt.text(1.95, -1.0, &#39;HL&#39;, fontsize=25)<br>plt.text(-1.5, 1, &#39;LH&#39;, fontsize=25)<br>plt.text(-1.5, -1, &#39;LL&#39;, fontsize=25)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*dJDL30T2KAjIL5F7V8y1dw.png" /><figcaption>Moran local scatterplot.</figcaption></figure><p>One thing that Local Moran’s I also do, is that it calculates the statistical significance (p-value) of each relationship. So, in the scatterplot we can see that there are grey dots. These grey dots are observations that doesn’t have statistical significance in the relationship of values of the observed tract value and the neighbohood weighted value. In other word, these values could be generated randomly and they are not unusual enough values to be considered statistically significant.</p><p>We can plot the map with the Local Moran’s I classification to identify where clusters are.</p><pre># creating column with local_moran classification<br>census_tract_sp[&#39;pop_count_local_moran&#39;] = pop_count_local_moran.q<br><br># Dict to map local moran&#39;s classification codes<br>local_moran_classification = {1: &#39;HH&#39;, 2: &#39;LH&#39;, 3: &#39;LL&#39;, 4: &#39;HL&#39;}<br><br># Mapping local moran&#39;s classification codes<br>census_tract_sp[&#39;pop_count_local_moran&#39;] = census_tract_sp[&#39;pop_count_local_moran&#39;].map(local_moran_classification)<br><br># p-value for each observation/neighbor pair<br>census_tract_sp[&#39;pop_count_local_moran_p_sim&#39;] = pop_count_local_moran.p_sim<br><br># If p-value &gt; 0.05 it is not statistical significant<br>census_tract_sp[&#39;pop_count_local_moran&#39;] = np.where(census_tract_sp[&#39;pop_count_local_moran_p_sim&#39;] &gt; 0.05, &#39;ns&#39;, census_tract_sp[&#39;pop_count_local_moran&#39;])<br><br>census_tract_sp.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z2CqIlpnCP3SW95mjXI0Mg.png" /></figure><pre># Plotting Local Moran&#39;s I classification map of pop_count column<br>census_tract_sp.explore(<br>    tiles=&#39;cartodbpositron&#39;,<br>    column=&#39;pop_count_local_moran&#39;,<br>    height=&#39;70%&#39;,<br>    width=&#39;70%&#39;,<br>    cmap=[<br>    &#39;#D7191C&#39;, # Red<br>    &#39;#FDAE61&#39;, # Orange<br>    &#39;#ABD9E9&#39;, # Light Blue<br>    &#39;#2C7BB6&#39;, # Blue<br>    &#39;#D3D3D3&#39;  # Grey<br>    ],<br>    style_kwds={<br>        &#39;stroke&#39;: True,<br>        &#39;edgecolor&#39;: &#39;k&#39;,<br>        &#39;linewidth&#39;: 0.03,<br>        &#39;fillOpacity&#39;: 1<br>        <br>        },<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tQU_N7FBvKc4iXEAGpxBGQ.png" /><figcaption>Map with Local Moran’s I classification for pop_count column.</figcaption></figure><p>We can see that the southern, northern and the central regions have clusters of low-low (LL) values of the <em>pop_count </em>column. Besides that, it is hard to identify any other cluster. Now, let’s do the same for <em>total_monthly_income</em> column.</p><pre># Local Moran&#39;s I<br>total_monthly_income_local_moran = Moran_Local(y_total_monthly_income, w)<br><br># Plotting Local Moran&#39;s I scatterplot of pop_count<br>fig, ax = moran_scatterplot(total_monthly_income_local_moran, p=0.05);<br><br>plt.text(1.95, 1, &#39;HH&#39;, fontsize=25)<br>plt.text(1.95, -1.0, &#39;HL&#39;, fontsize=25)<br>plt.text(-1.5, 1, &#39;LH&#39;, fontsize=25)<br>plt.text(-1.5, -1, &#39;LL&#39;, fontsize=25)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*BaVphPDuKPQXKFPnSvtm5A.png" /><figcaption>Moran local scatterplot.</figcaption></figure><pre># creating column with local_moran classification<br>census_tract_sp[&#39;total_monthly_income_local_moran&#39;] = total_monthly_income_local_moran.q<br><br># Dict to map local moran&#39;s classification codes<br>local_moran_classification = {1: &#39;HH&#39;, 2: &#39;LH&#39;, 3: &#39;LL&#39;, 4: &#39;HL&#39;}<br><br># Mapping local moran&#39;s classification codes<br>census_tract_sp[&#39;total_monthly_income_local_moran&#39;] = census_tract_sp[&#39;total_monthly_income_local_moran&#39;].map(local_moran_classification)<br><br># p-value for each observation/neighbor pair<br>census_tract_sp[&#39;total_monthly_income_local_moran_p_sim&#39;] = total_monthly_income_local_moran.p_sim<br><br># If p-value &gt; 0.05 it is not statistical significant<br>census_tract_sp[&#39;total_monthly_income_local_moran&#39;] = np.where(census_tract_sp[&#39;total_monthly_income_local_moran_p_sim&#39;] &gt; 0.05, &#39;ns&#39;, census_tract_sp[&#39;total_monthly_income_local_moran&#39;])<br><br># Plotting Local Moran&#39;s I classification map of pop_count column<br>census_tract_sp.explore(<br>    tiles=&#39;cartodbpositron&#39;,<br>    column=&#39;total_monthly_income_local_moran&#39;,<br>    height=&#39;70%&#39;,<br>    width=&#39;70%&#39;,<br>    cmap=[<br>    &#39;#D7191C&#39;, # Red<br>    &#39;#FDAE61&#39;, # Orange<br>    &#39;#ABD9E9&#39;, # Light Blue<br>    &#39;#2C7BB6&#39;, # Blue<br>    &#39;#D3D3D3&#39;  # Grey<br>    ],<br>    style_kwds={<br>        &#39;stroke&#39;: True,<br>        &#39;edgecolor&#39;: &#39;k&#39;,<br>        &#39;linewidth&#39;: 0.03,<br>        &#39;fillOpacity&#39;: 1<br>        <br>        },<br>    )</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2k4GmF9p-nLm-SwoqrvTw.png" /><figcaption>Map with Local Moran’s I classification for total_monthly_income column.</figcaption></figure><p>Compared to the classification of <em>pop_count</em>, <em>total_monthly_income </em>is more clustered, as it was analysed by the global autocorrelation. We can see that the northern, southern and the eastern regions have clusters of low-low (LL) values, whereas the central region has cluster of high-high (HH) values .</p><h3>Conclusion</h3><p>In this post, I showed you how to incorporate the spatial component in a EDA, turning it into a ESDA (Exploratoy Spatial Data Analysis). It gives us an idea of where variables are clustered in space and whether the relation between the observation and its neighbors are statistically significant. In other words, it tests if values of a variable is correlated by the location (neighbors) of where it happen.</p><p>Doing this kind of analysis can bring some insights of the problem we are dealing with.</p><h4>About me</h4><p>I am a geographer currently working as a data scientist. For that reason, I am an advocate of spatial data science.</p><p>Follow me for more content. I will write a post every month about data science concepts and techniques, spatial data science and GIS (Geographic Information System).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71b5782c19d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aggregating information of two overlaying GeoDataFrames using GeoPandas with code example]]></title>
            <link>https://kazumatsuda.medium.com/aggregating-information-of-two-overlaying-geodataframes-using-geopandas-with-code-example-dcee1df74e0e?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/dcee1df74e0e</guid>
            <category><![CDATA[geographic-information]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[geopandas]]></category>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Tue, 07 Feb 2023 13:01:18 GMT</pubDate>
            <atom:updated>2023-03-21T02:30:13.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*K0BKrpxg46xCVj4U2UT_5g.jpeg" /></figure><h3>Introduction</h3><p>In this post I will show how to aggregate information from two different GeoDataFrames (layers) using GeoPandas. I will show one of many ways that we can do that with code example. But first, let’s see a situation when we might need to do this kind of operation.</p><p>Obs 01: The notebook and data used in this post are available at my <a href="https://github.com/AlvaroMatsuda/medium_posts/tree/main/spatial%20aggregation">Github </a>page. If you want, you can follow this post along with the notebook.</p><p>Obs 02: If you want to display the notebook on your browser, use this <a href="https://nbviewer.org/github/AlvaroMatsuda/medium_posts/blob/main/spatial%20aggregation/notebook/spatial_aggregation.ipynb">link </a>instead.</p><h3>The Problem</h3><p>Let’s say that you work for Carrefour in São Paulo city and you want to know how many people lives within 1 km of distance for all stores from São Paulo city and the total monthly income. With that information, you want to prioritize marketing campaign for stores with highest monthly income per capita.</p><p>We have a dataframe containing information of location of all stores in São Paulo city. We are going to extract the population count and total monthly income from Brazil census tract produced by IBGE.</p><p>Now that we know what we want to achieve and where to get data, we have to get our hand-on the code and do some data preparation before we can extract informations we want.</p><h3>Data Preparation</h3><p>As I mentioned above, I have collected information of the location of Carrefour’s stores in São Paulo city.</p><pre># Importing libraries<br>import pandas as pd<br>import numpy as np<br>import geopandas as gpd<br>import folium<br><br># Loading Carrefour Store data<br>df_carrefour = pd.read_excel(r&#39;https://github.com/AlvaroMatsuda/medium_posts/blob/main/spatial%20aggregation/data/carrefour_stores_latlong.xlsx?raw=true&#39;)<br>df_carrefour.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldmULAq2OP0gaKl4JH2tJw.png" /></figure><p>This dataframe is a Pandas DataFrame object that we will convert it into a GeoPandas GeoDataFrame object. For that, we have to extract the WKT (Well Known Text) that stores the spatial information from <em>lat </em>and <em>long </em>columns. After that, we will create a radius buffer of 1 km for each store.</p><pre># Converting Pandas DataFrame into GeoPandas GeoDataFrame<br><br># Construct geometry Column from lat and long coordinates using geopandas<br>geometry = gpd.points_from_xy(df_carrefour[&#39;long&#39;], df_carrefour[&#39;lat&#39;], crs=&quot;EPSG:4979&quot;)<br><br># Adding new column with the geometry<br>df_carrefour[&#39;geometry&#39;] = geometry<br><br># Constructing GeoDataFrame<br>gdf_carrefour = gpd.GeoDataFrame(df_carrefour, geometry=df_carrefour[&#39;geometry&#39;])<br>gdf_carrefour.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypnnLPJ4tlDHW35DMkCpEA.png" /><figcaption>GeoDataFrame with the geometry column</figcaption></figure><p>With the GeoDataFrame object we can use the explore() method to plot the map with the location of Carrefour stores:</p><pre># Plotting the map to visualize<br>gdf_carrefour.explore()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8lAlF_grY7b8HZ_vIIezmw.png" /><figcaption>The blue dots are Carrefour stores.</figcaption></figure><p>Now, we have to create the buffer of 1 km for each store.</p><pre># Creating radius buffer<br># Converting CRS to a meter based CRS<br>gdf_carrefour.to_crs(crs=3857, inplace=True) <br><br># Creating 1km buffer column with WKT geometry<br>gdf_carrefour[&#39;buffer_geom&#39;] = gdf_carrefour.buffer(1000.0) <br><br># Converting back to original CRS<br>gdf_carrefour.to_crs(crs=4979, inplace=True) <br><br># Setting the geometry column to the buffer geometry<br>gdf_carrefour.set_geometry(&quot;buffer_geom&quot;, inplace=True)<br><br>gdf_carrefour.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O2gkrHfz7b5TX0DdM3088g.png" /><figcaption>Carrefour Store GeoDataFrame with 1km_buffer_geom column.</figcaption></figure><pre># Plotting the map to visualize<br>gdf_carrefour.explore()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOQY4JXF8wybuvrfbcH9Lw.png" /><figcaption>Map with 1 km buffer for each Carrefour Store</figcaption></figure><p>That is all the preparation for the Carrefour store dataframe. Now we have to prepare the census tract data.</p><p>Before we start the preparation for the census tract data, I have to mention that the data we need for this problem comes in 3 different files:</p><ol><li>Census tract shapes (polygons)</li><li>csv file with information of population count</li><li>csv file with information of income</li></ol><p>To get started, we load the census tract shapes/polygons:</p><pre># Loading Brazilian census tract data<br>census_tract_shapes = gpd.GeoDataFrame.from_file(r&#39;/vsicurl/https://raw.githubusercontent.com/AlvaroMatsuda/medium_posts/main/spatial%20aggregation/data/setor_censitario_sp_2010.shp&#39;)<br><br># Setting the CRS<br>census_tract_shapes = census_tract_shapes.to_crs(&#39;EPSG:4979&#39;)<br><br># Filtering to get only shapes from São Paulo city<br>sp_census_tract_shapes = census_tract_shapes.loc[census_tract_shapes[&#39;NM_MUNICIP&#39;] == &#39;SÃO PAULO&#39;]<br><br>sp_census_tract_shapes.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KF41iGhLwDb0ROLF2T7G_g.png" /><figcaption>The shapefile already comes with the geometry column and we load it directly from GeoPandas.</figcaption></figure><pre># Plottin the map to visualize<br>sp_census_tract_shapes.explore()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJHYi1rKXzPAl6p-ia0d2w.png" /><figcaption>Map with São Paulo census tract shapes</figcaption></figure><p>As I said before, the census tract polygons do not come with information of population and monthly income. These informations come in separate files. Therefore, we have to load each of them:</p><pre># Loading total Monthly Income dataframe<br># The column that holds the total monthly income is: V003<br>total_monthly_income_df = pd.read_csv(r&#39;https://github.com/AlvaroMatsuda/medium_posts/blob/main/spatial%20aggregation/data/DomicilioRenda_SP1.csv?raw=true&#39;, sep=&#39;;&#39;, encoding=&#39;latin1&#39;)<br><br># Converting Column &quot;Cod_setor&quot; from int to str<br>total_monthly_income_df[&#39;Cod_setor&#39;] = total_monthly_income_df[&#39;Cod_setor&#39;].astype(&#39;str&#39;)<br><br>total_monthly_income_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*1X2RGvTchXBOPhPt31Clxg.png" /><figcaption>Dataframe of total monthly income (V003 column).</figcaption></figure><pre># Loading population dataframe<br># The column that holds the population count is: V002<br>population_df = pd.read_csv(r&#39;https://github.com/AlvaroMatsuda/medium_posts/blob/main/spatial%20aggregation/data/Pessoa11_SP1.csv?raw=true&#39;, sep=&#39;;&#39;, encoding=&#39;latin1&#39;)<br><br># Converting Column &quot;Cod_setor&quot; from int to str<br>population_df[&#39;Cod_setor&#39;] = population_df[&#39;Cod_setor&#39;].astype(&#39;str&#39;)<br><br>population_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gr8sW9IUwwaG5Jh_KbqMKw.png" /><figcaption>Dataframe of population (V002 column).</figcaption></figure><p>All dataframes have one column in common, that being the tract code “<em>Cod_setor</em>” and “<em>CD_GEOCODI</em>”. We are going to join these dataframes on this column as the key to get the information we need on the dataframe containing the shapes/polygons.</p><pre># Joining shape dataframe with population and total_monthly_income dataframes<br>sp_census_tract = (<br>    sp_census_tract_shapes<br>    .merge(population_df[[&#39;Cod_setor&#39;, &#39;V002&#39;]], left_on=&#39;CD_GEOCODI&#39;, right_on=&#39;Cod_setor&#39;, how=&#39;left&#39;) # Joining dataframe<br>    .merge(total_monthly_income_df[[&#39;Cod_setor&#39;, &#39;V003&#39;]], left_on=&#39;CD_GEOCODI&#39;, right_on=&#39;Cod_setor&#39;, how=&#39;left&#39;) # Joining dataframe<br>    .drop(columns=[&#39;Cod_setor_x&#39;, &#39;Cod_setor_y&#39;]) # Dropping duplicated columns<br>    .rename(columns={&#39;V002&#39;: &#39;pop_count&#39;, &#39;V003&#39;: &#39;total_monthly_income&#39;}) # Renaming columns<br>    )<br><br># Renaming columns to be all in lowercase<br>sp_census_tract.columns = map(str.lower, sp_census_tract.columns)<br><br># Convertin &quot;X&quot; values to 0<br>sp_census_tract[&#39;pop_count&#39;] = np.where(sp_census_tract[&#39;pop_count&#39;] == &quot;X&quot;, 0, sp_census_tract[&#39;pop_count&#39;])<br>sp_census_tract[&#39;total_monthly_income&#39;] = np.where(sp_census_tract[&#39;total_monthly_income&#39;] == &quot;X&quot;, 0, sp_census_tract[&#39;total_monthly_income&#39;])<br><br># Converting STR to FLOAT of pop_count and total_monthly_income columns<br>sp_census_tract[&#39;pop_count&#39;] = sp_census_tract[&#39;pop_count&#39;].astype(&#39;float64&#39;)<br>sp_census_tract[&#39;total_monthly_income&#39;] = sp_census_tract[&#39;total_monthly_income&#39;].astype(&#39;float64&#39;)<br><br>sp_census_tract.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGBB1m1CLPomB9sZs7cMNg.png" /><figcaption>Shape dataframe with pop_count and total_monthly_income columns</figcaption></figure><p>We added the <em>pop_count</em> and <em>total_montly_income </em>columns<em> </em>into the shape dataframe that contains the geometry column. That is all the manipulation needed.</p><p>Now we are set to aggregate information between the census tract dataframe and the Carrefour store dataframe to know how many people lives within 1 km of distance from each store and the total monthly income.</p><h3>Aggregating information of two GeoDataFrames</h3><p>Before we do the aggregation for all buffers, I will do the aggregation for a single buffer to make it easier to understand the manipulations made and the code.</p><p>First of all, let’s get a single buffer:</p><pre># Selecting a single buffer<br>single_buffer = gdf_carrefour[gdf_carrefour[&#39;store_name&#39;] == &#39;Market Paraíso&#39;]<br><br># Plottin the map to visualize<br>single_buffer.explore()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Ef6IE-3S8PrVt1uevva4Q.png" /><figcaption>Map with 1km radius buffer layer.</figcaption></figure><p>Now we will get all census tract that intersects the buffer:</p><blockquote>geometric objects intersect if they have any boundary or interior point in common. (definition from <a href="https://shapely.readthedocs.io/en/stable/manual.html#predicates-and-relationships:~:text=object.intersects(other)">shapely documentation</a>)</blockquote><pre># Filtering census tract that intersects the buffer<br>intersected_census_tract = sp_census_tract[sp_census_tract[&#39;geometry&#39;].intersects(single_buffer.loc[8, &#39;1km_buffer_geom&#39;])]<br><br># Plottin the map to visualize<br>intersected_census_tract.explore()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaG9021qsienyFN8O-LK7g.png" /><figcaption>Map with tracts layer that intersects the buffer.</figcaption></figure><p>Let’s visualize both layers together in the same map:</p><pre># Creating a folium tile base map<br>m = folium.Map(location=[-23.568865965761308, -46.629872859184125], zoom_start=12, tiles=&#39;OpenStreetMap&#39;, crs=&#39;EPSG3857&#39;, width=&#39;60%&#39;, height=&#39;60%&#39;)<br><br># Adding intesected census_tract layer to the map<br>intersected_census_tract.explore(m=m)<br><br># Adding buffer layer to the map<br>single_buffer.explore(m=m,style_kwds={&#39;fillOpacity&#39;: 0.0, &#39;color&#39;: &#39;#CE2020&#39;})<br><br># Showing the map<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftCFmeSXQrXl9OFUs1bymA.png" /><figcaption>Visualizing both layers</figcaption></figure><p>The image above shows that we have selected all census tract (blue polygons) that intersects the buffer (red polygon). Now we have to sum the column <strong><em>pop_count </em></strong>and <strong><em>total_monthly_income </em></strong>to extract informations that we need. However, before we sum these columns we should ponder what to do with tracts that have area outside the buffer. Should we consider only tracts that are 100% inside? Should we consider all of these tracts? Or should we consider just a portion of the information stored in the tracts that have area outside the buffer?</p><p>That are many ways that we can deal with these polygons with area outside the buffer.</p><ul><li>We could use the centroid of the polygon: if the centroid is inside the buffer we consider the totality of the information stored in that polygon.</li><li>Consider only polygons that are 100% inside the buffer</li><li>Consider a portion of the data stored in the polygon according to the proportion of the area inside the buffer</li></ul><p>Depending on the use case you might want to use different approaches. For example, if we are working with polygons that represents borough/districts of a city, we have to be carefull to not consider the same tract twice in different borough/districts, duplicating information, as well as we might not consider a polygon at all, causing misinformation, depending on the chosen approach.</p><p>In our case I chose to use the third approach mentioned above. To get started, first we need to calculate the proportion of the area that is inside the buffer for each tract polygon.</p><pre># Calculating the proportion of tract area inside the buffer<br>intersected_census_tract[&#39;prop_area&#39;] = intersected_census_tract[&#39;geometry&#39;].intersection(single_buffer.loc[8, &#39;1km_buffer_geom&#39;]).area / intersected_census_tract[&#39;geometry&#39;].area<br><br># Rounding number to be 1 (100%) <br>intersected_census_tract[&#39;prop_area&#39;] = np.where(intersected_census_tract[&#39;prop_area&#39;] &gt;= 0.998, 1 , intersected_census_tract[&#39;prop_area&#39;])<br><br>intersected_census_tract.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-mgLt-ZdqEL4IGWfObFxbw.png" /><figcaption>Dataframe with prop_area column</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p4vagVdidHpUc_DzUHzKNw.png" /></figure><p>To explain what the above code did, basically, it calculates the area that are inside the buffer (like the map to the right) and divide the result by the total area of that tract. After that, we create a new column to store the proportion of the area. Also, the code round the number to 1 when the value in <strong><em>prop_area </em></strong>column is grater than 0.998. We do that, because when we do the division, the area calculated is not exact, having some minor differences, so even if the tract is 100% inside, the value will be 0.9999 due to this minor difference.</p><p>After that, we can use the <strong><em>prop_area</em></strong> column to calculate the proportion of the information to be considered when summing <strong><em>pop_count </em></strong>and <strong><em>total_monthly_income </em></strong>columns.</p><pre># Calculating the proportion of the pop_count according to the prop_area<br>intersected_census_tract[&#39;prop_pop_count&#39;] = round(intersected_census_tract[&#39;pop_count&#39;] * intersected_census_tract[&#39;prop_area&#39;])<br><br># Calculating the proportion of the total_monthly_income according to the prop_area<br>intersected_census_tract[&#39;prop_total_monthly_income&#39;] = round(intersected_census_tract[&#39;total_monthly_income&#39;] * intersected_census_tract[&#39;prop_area&#39;])<br><br>intersected_census_tract.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XWFB8e2yJ2QPir_qkuEZ9Q.png" /></figure><p>Then, we can calculate the sum of the <strong><em>prop_pop_count </em></strong>and <strong><em>prop_total_monthly_income </em></strong>columns to know how many people live and the total monthly income that are within 1km of distance from the store.</p><pre># Calculating the sum of pop_count and total_monthly_income inside the buffer<br>single_buffer[&#39;1km_buffer_pop_count&#39;] = intersected_census_tract[&#39;prop_pop_count&#39;].sum()<br>single_buffer[&#39;1km_buffer_total_monthly_income&#39;] = intersected_census_tract[&#39;prop_total_monthly_income&#39;].sum()<br><br>single_buffer</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fO996xihC8EqcO8hxPKvQ.png" /></figure><p>Now that we have done all the processing for one buffer, I will show the code for all buffers.</p><pre># Iterating over each buffer<br>for index, value in gdf_carrefour.iterrows():<br><br>    # Selecting Tracts that intersect the buffer<br>    df_intersected = sp_census_tract[sp_census_tract[&#39;geometry&#39;].intersects(value[&#39;1km_buffer_geom&#39;])]<br><br>    # Calculating the proportion of the area inside the buffer<br>    df_intersected[&#39;prop_area&#39;] = df_intersected[&#39;geometry&#39;].intersection(value[&#39;1km_buffer_geom&#39;]).area / df_intersected[&#39;geometry&#39;].area<br><br>    # Rounding number to be 1 (100%) <br>    df_intersected[&#39;prop_area&#39;] = np.where(df_intersected[&#39;prop_area&#39;] &gt;= 0.998, 1, df_intersected[&#39;prop_area&#39;])<br><br>    # Calculating the proportion of the pop_count and total_monthly_income according to the prop_area<br>    df_intersected[[&#39;prop_pop_count&#39;, &#39;prop_total_monthly_income&#39;]] = df_intersected.loc[:, [&#39;pop_count&#39;, &#39;total_monthly_income&#39;]].multiply(df_intersected.loc[:,&#39;prop_area&#39;], axis=0)<br><br>    # Calculating total pop_count and total monthly income inside the buffer<br>    gdf_carrefour.loc[index, [&#39;1km_buffer_pop_count&#39;, &#39;1km_buffer_total_monthly_income&#39;]] = list(df_intersected[[&#39;prop_pop_count&#39;, &#39;prop_total_monthly_income&#39;]].sum())<br>    <br>gdf_carrefour.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DI4qbgd6GBskwUqhPv-OLw.png" /></figure><p>At last, we can calculate the monthly income per capita to know which stores have population with highest buying potential to prioritize marketing campaign for these stores.</p><pre># Calculating monthly income per capita<br>gdf_carrefour[&#39;monthly_income_per_capita&#39;] = gdf_carrefour[&#39;1km_buffer_total_monthly_income&#39;] / gdf_carrefour[&#39;1km_buffer_pop_count&#39;]<br><br># Sorting DataFrame to show 5 stores with highest monthly income per capita<br>gdf_carrefour.sort_values(by=&#39;monthly_income_per_capita&#39;, ascending=False).head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihA6o4AjgamKThLbKRTEwQ.png" /></figure><p>With that we could prioritize marketing campaign for these 5 stores to attract new customers and make customers to spend more on these stores.</p><pre># Creating a copy to use as store point layer<br>point_gdf_carrefour = gdf_carrefour.copy()<br><br># Setting the geometry to the &quot;geometry&quot; columns (geometry representing points of the location of stores)<br>point_gdf_carrefour = point_gdf_carrefour.set_geometry(&#39;geometry&#39;)<br><br># Creating a folium tile base map<br>m = folium.Map(location=[-23.568865965761308, -46.629872859184125], zoom_start=12, tiles=&#39;OpenStreetMap&#39;, crs=&#39;EPSG3857&#39;, width=&#39;70%&#39;, height=&#39;70%&#39;)<br><br># Adding buffer layer to the map<br>gdf_carrefour.sort_values(by=&#39;monthly_income_per_capita&#39;, ascending=False).head().explore(style_kwds={&#39;fillOpacity&#39;: 0.0}, m=m)<br><br># Adding Store location layer to the map<br>point_gdf_carrefour.loc[gdf_carrefour.sort_values(by=&#39;monthly_income_per_capita&#39;, ascending=False).head().index, :].explore(style_kwds={&#39;color&#39;: &#39;#000000&#39;, &#39;weight&#39;: 8}, m=m)<br><br># Showing the map<br>m</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w53teuPT7_nzWer8oWBBbA.png" /></figure><h3>Conclusion</h3><p>In the GIS (Geographic Information System) market, this kind of manipulation is used very often and there are a lot of other use cases that we can use it.</p><p>I wanted to show how it is done in Python, because, as a data scientist who have worked with GIS before, I believe that we can enhance our analysis and models with this kind of manipulations. For instance, we could use the aggregated informations for each buffer as new features to a machine learning model.</p><p>I hope this post helps you in any way and don’t forget that the notebook with the code and data used in this post is in my Github.</p><p><a href="https://github.com/AlvaroMatsuda/medium_posts/tree/main/spatial%20aggregation">medium_posts/spatial aggregation at main · AlvaroMatsuda/medium_posts</a></p><h4>About me</h4><p>I am a geographer currently working as a data scientist. For that reason, I am an advocate of spatial data science.</p><p>Follow me for more content. I will write a post every month about data science concepts and techniques, spatial data science and GIS (Geographic Information System).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dcee1df74e0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spatial Data Science: 3 main data structures for GeoSpatial data]]></title>
            <link>https://kazumatsuda.medium.com/spatial-data-science-3-main-data-structures-for-geospatial-data-adc5f9093610?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/adc5f9093610</guid>
            <category><![CDATA[spatial-analysis]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[geographic-information]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Fri, 06 Jan 2023 13:01:50 GMT</pubDate>
            <atom:updated>2023-03-21T02:30:50.549Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hSNRZw_DOlIJh_Xq" /><figcaption>Photo by <a href="https://unsplash.com/@kylejglenn?utm_source=medium&amp;utm_medium=referral">Kyle Glenn</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>It is said that wherever that is data, there is work for data scientist. And in the geospatial field that are lots of data being generated that can be analysed to extract insights from. As <a href="https://sergerey.org/">Sergio J. Rey</a>, <a href="https://darribas.org/">Dani Arribas-Bel</a> and <a href="http://www.ljwolf.org/">Levi J. Wolf</a> wrote in their free online book (<a href="https://geographicdata.science/book/intro.html">Geographic Data Science with Python</a>):</p><blockquote>“everything has a location in space-time, and this location can be used directly to make better predictions or inferences.”</blockquote><p>So in theory,<strong> </strong>every data that we store could potentially have a location attached to it, because everything that happens in our world takes place in a certain location. And adding this geospatial element to our data can enhace our analysis.</p><p>As we can see, geographic data can be everywhere. And to start working with geospatial data, first we need to know how is the data structure of it. So in this post I will make a summary of the Part I of the aforementioned book, about the section <a href="https://geographicdata.science/book/notebooks/01_geo_thinking.html"><strong><em>Geographic thinking for data scientists</em></strong></a><em> </em>where it discuss the three main data structures used for geospatial data analysis:</p><ol><li><strong>Geographic tables;</strong></li><li><strong>Surface;</strong></li><li><strong>Spatial graphs.</strong></li></ol><h3>Geographic Tables</h3><p>Basically, geographic table is a typical table of rows and columns where one of the columns stores geographic information. This column stores the geometry that describes how that sample (row) is going to be represented in a map along with latitude and longitude.</p><p>In cartography, it was set that every thing can be mapped using 3 geometries: point, line, polygon. The image below show how these 3 geometries are used to map the world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ECC4AboeJMMK2ekS6k2Xtw.png" /><figcaption>Image from google maps from the Savassi borough in Belo Horizonte city in Brazil.</figcaption></figure><ul><li><strong>Points</strong>: McDonald’s, Royal Golden Hotel Savassi, Supermernosso Funcionários, etc.</li><li><strong>Lines</strong>: Mainly the streets.</li><li><strong>Polygon</strong>: The suface/area that is inside the red line, delimiting the Savassi borough.</li></ul><blockquote>Each of these 3 geometries have a <strong>Multi </strong>variant that indicate a collection of multiple geometries of the same type.</blockquote><p>So, when we use geographic table, this additional column will describe if the sample is represented as a point, line or polygon with their respective latitude and longitude.</p><p>In the example below, we loaded the New York city borough dataset — from the <a href="https://geopandas.org/en/stable/">GeoPandas </a>library — that contains information of borough code, name, lenght, area and the geometry column.</p><pre>import geopandas as gpd<br><br>gdf = gpd.read_file(gpd.datasets.get_path(&#39;nybb&#39;))<br>gdf<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*U5LiHmLNpuYPSMIfpwoUSQ.png" /></figure><p>As we can see, the geometry column stores the geometry that represent the area of each borough (multipolygon) and their coordinates that delimits the surface/area. If we get the data type of each column we will see that the geometry column is a geometry type. This is a special feature of the GeoPandas, that it can interpret this type of information.</p><pre>gdf.dtypes</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/215/1*ZzgtBLpgDXSNlueJA5rFtw.png" /><figcaption>Data types of each column.</figcaption></figure><p>And if we use the plot() method we will see the shape of each borough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*p2VNXjGbY0TSYevVfZX9cQ.png" /></figure><p>Because the fact that a geographic table has a tabular structure, we can leverage the advantages that it brings to data manipulantion. As you might have thought, the geometry column is treated as one more feature. Therefore, we can apply every method of data manipulation that can be done with a tabular structure.</p><p>In fact, with a geographic table, we can go further as we can do manipulations considering the spatial element. Some of the most comum manipulation of spatial data are the aggregation of information that is contained in a polygon, counting points contained in a polygon, calculation of area and distance from 2 geometries, density of points. Those are just some examples of what we can do with a geographic table.</p><h3>Surface</h3><p>A surface data structure is compared to an image data structure. If you have already worked with image in data science, you already know the structure of band/layer and pixel. A surface data structure is just like that, however instead of a pixel, each row is a specific latitude and each column is a specific longitude and the value of each cell store information about that specific location of a certain measurement.</p><blockquote>For example, a surface for air pollution will be represented as an array where each row will be linked to the measured pollutant level across a specific latitude, and each column for a specific longitude. If we want to represent more that one phenomenon (e.g. air pollution and elevation), or the same phenomenon at different points in time, we will need different arrrays that are possibly connected.</blockquote><p>To manipulate this type of data, we can use the <a href="https://docs.xarray.dev/en/stable/"><strong>xarray</strong> </a>library. This library deals with N-Dimentional arrays, also known as cube or tensors. Xarray allow us to easily manipulate these type of data making math operations and aggregation across arrays/layers and much more.</p><p>Let’s look at an example from the temperature dataset that is available in the xarray tutorial class:</p><pre>import xarray<br><br>temperature = xarray.tutorial.open_dataset(&#39;air_temperature&#39;)<br>temperature</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*Cp7cUUD1WfO-g-xASSm-Rw.png" /><figcaption>The output of the above code showing the data structure of this dataset.</figcaption></figure><p>Looking at the output, we can identify some things like the dimension (25, 2920, 53), arrays consisting of latitude, longitude and a time dimension and the variable that is represented in the values is about the air. And we can add attributes to our data to describe and add information about the dataset.</p><p>In summary, we can interpret this dataset as having arrays consisting of “lat” as rows, “lon” as columns and “time” as the time reference of the values contained in a array/layer and the values being about the air temperature.</p><h3>Spatial Graphs</h3><p>Spatial graphs is a data structure that capture relationships between objects in space. Spatial graphs is derived from the graph theory that study relationships between objects. In fact, a spatial problem was what originated the graph theory and today it is applied in a variety of fields. We can define it, in other words, as geographic networks.</p><p>In the graph theory there are basically two main elements:</p><ol><li>Vertex or node;</li><li>Edges that connects nodes. Edges can store information about direction or not.</li></ol><p>Therefore, a spatial graph data structuctures stores information about how a given node is spatially connected/related to other nodes in a dataset. The <a href="https://networkx.org/">Networkx </a>library does exactly that. The internal data structure used in networkx is, as defined by them:</p><blockquote>The graph internal data structures are based on an adjacency list representation and implemented using Python <a href="https://networkx.org/documentation/networkx-2.8.8/reference/glossary.html#term-dictionary">dictionary</a> datastructures. The graph adjacency structure is implemented as a Python dictionary of dictionaries; the outer dictionary is keyed by nodes to values that are themselves dictionaries keyed by neighboring node to the edge attributes associated with that edge.</blockquote><p>An example of use of this type of data, is the study from IBGE (Instituto Brasileiro de Geografia e Estatística) about network of cities, that defines hierarchies among cities that are connected/related according to some parameters, like quantity and quality of services such as hospitals, universities, flow of population and more. And according to this study, many cities and regions make their planning based on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*Trnk30KggSw4a-F5.jpg" /><figcaption>Map of Brazil’s city network.</figcaption></figure><p>From the map above, each point are nodes and the lines (relationships between cities) are edges that connects nodes.</p><p>An example of the Networkx library is shown bellow:</p><pre>graph_sp = osmnx.graph_from_place(&#39;Parque Ibirapuera, Sao Paulo, Brazil&#39;)<br>osmnx.plot_graph(graph_sp)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*XSq_HwRnWUpeY_aV-zwAzQ.png" /><figcaption>Graph from Parque Ibirapuera, São Paulo, Brazil.</figcaption></figure><p>The first line of code extracts the dataset that represents the graph of Parque Ibirapuera in São Paulo City from the osmnx library. The <em>graph_sp </em>variable is a xarray object. Then, we use the plot method to visualize the graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*HC4Za_XMcZ-f4WXV4G1y1Q.png" /></figure><p>As we can see, the graph from Parque do Ibirapuera has 251 nodes and 729 edges and in this case nodes are intersections of streets and edges are the streets. The Networkx library offers many things like, manipulation, analyses, algorithms and more.</p><h4>Spatial Weights Matrix</h4><p>Another structure used for spatial graphs is Spatial Weights Matrix. As the name suggests, it is a matrix where each cell represents the relationship of each spatially referenced object in a dataset. This relationships is often called neighbors. Therefore, each cell indicates whether the object represented by the row is a neighbor of the object represented by the column.</p><p>There are two elements in spatial weights matrix that we need to define and adjust according to what we want to accomplish:</p><ol><li>Define how to consider a neighbor</li><li>How to encode the weight in case of neighbor objects.</li></ol><p>There are many ways or rules that we can define to determine if a pair of objects are neighbors or not. For example, we can determine neighbors by contiguity, in other words, if a pair of objects shares a boundary. Or we can use the distance, setting a fixed radius distance and every object within the radius are considered neighbors.</p><p>After we decided how to identify neighbors, we have to decide how we want to encode the relationship between observations. One way to encode is with a binary encode [0, 1], 0 for non neighbors and 1 for neighbors.</p><p>Another way, is setting 0 for non neighbors and a decimal between 0 and 1 for neighbors. And we can apply many rules to define the weight for each neighbor. For example, one of the most commom methods to assing a weight is by a decay function according to the distance, where close neighbors have large weights and further neighbors have smaller weights.</p><p>Let’s take a quick look at pysal library. To do that, first I create a geopandas dataframe with some hexagons:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*WnWufTYOHCF_WHBIosT2eQ.png" /></figure><p>Then, we can construct our spatial weight matrix from the geodataframe using pysal as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*M44XbF1m3fmkm6j-PON9-w.png" /></figure><p>To construct a spatial weight from a geopandas dataframe is as simple as that. Moreover, we can see how each hexagon is related with each other.</p><p>We could use others types os weights constructors, like Rook, voronoi, distance based, and many others that pysal offers. To see other types os weights constructor check <a href="https://pysal.org/libpysal/api.html">pysal documentantion</a>.</p><p>We can check that the weights object is of the type <em>weights.contiguity.Queen </em>from pysal. Knowing that, we can check other things like, neighbors matrix and mean_neighbors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*gzFZ-cS-o575tJ5SWRSApQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*c71MbaLqJn7WPDo5rsTeaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*DBWLUjB-eJ3k1wQgok0TSg.png" /></figure><p>There are many intricacies in spatial weights, and this post is just an introduction of these topics. If want to know more about the libraries shown, check their documentation.</p><h3>Conclusion</h3><p>Geospatial data structures are very similar to others data structures, but they have something additional: a spatial component. We saw, briefly, how are those data structures (geographic table, surface and spatial graphs) and what python libraries handle them.</p><p>Dealing with geospatial data can bring a bit of complexity, however it greatly expand and enhance our analyses.</p><h4>About me</h4><p>I am a geographer currently working as a data scientist. For that reason, I am an advocate of spatial data science.</p><p>Follow me for more content. I will write a post every month about data science concepts and techniques, spatial data science and GIS (Geographic Information System).</p><h3>References</h3><p><a href="https://geographicdata.science/book/intro.html">Part I — Building Blocks of the free online book Geographic Data Science with Python by Sergio J. Rey, Dani Arribas-Bel and Levi J. Wolf.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adc5f9093610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learning to Rank — Another use of Machine Learning]]></title>
            <link>https://kazumatsuda.medium.com/learning-to-rank-another-use-of-machine-learning-55fd8b124101?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/55fd8b124101</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[learning-to-rank]]></category>
            <category><![CDATA[ranknet]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Tue, 28 Sep 2021 23:18:00 GMT</pubDate>
            <atom:updated>2023-03-21T02:31:21.878Z</atom:updated>
            <content:encoded><![CDATA[<h3>Learning to Rank — Another use of Machine Learning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*njV-GMhockLH9nyy" /><figcaption>Photo by <a href="https://unsplash.com/@edgr?utm_source=medium&amp;utm_medium=referral">Edu Grande</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When we think of problems that machine learning can solve, the first thing that comes to our minds are classification, regression, NLP, clustering. We rarely see someone talking about Learning to Rank.</p><p>So in this post you are going to see:</p><ul><li>What is Learning to Rank;</li><li>How I applied Learning to Rank in one of my projects;</li></ul><h3>What is Learning to Rank?</h3><p>Searching about Learning to Rank I found this medium post by Nikhil Dandekar: <a href="https://bit.ly/3CDfmBl">https://bit.ly/3CDfmBl</a></p><p>In his post he difines it as:</p><blockquote>Learning to Rank (LTR) is a class of techiniques that apply supervised machine learning (ML) to solve ranking problems. The main difference between LTR and traditional supervised ML is this:</blockquote><blockquote>- Traditional ML solves a prediction problem (classification or regression) on a single instance at a time. The aim of traditional ML is to come up with a class (yes or no) or a single numerical score for that instantance;</blockquote><blockquote>- LTR solves a ranking problem on a list of items. The aim of LTR is to come up with optional ordering of those items. As such, LTR doesn’t care much about the exact score that each item gets, but cares more about the relative ordering among all the items.</blockquote><p>As we can see, in a LTR problem we are not interested in the exact classification of an item, but rather if an item should be ranked higher or lower compared to another item.</p><p>The LRT has its own algorithms such as RankNet, LambdaRank and LambdaMART that, in summary, the ranking is transformed into a pairwise classification or regression. That means you look at pairs of items at a time, come up with the optimal ordering for that pair of items, and then use for the final ranking of all items.</p><p>The most commom use of LTR are: information retrieval (e.g. google search engine) and recomendation systems. But in reality, it can be employed in any ranking/sorting problem.</p><p>If you want to know more about LTR, don’t forget to check Nikhil Dandekar’s post.</p><h3>How I applied Learning to Rank in one of my projects</h3><p>In one of my personal projects I used LTR to solve a problem with a bit difference of what was discribed above. Instead of using specifically LTR algorithms, I used classification models and used their probability to sort a list of leads that a company had to offer their product.</p><p>You can have access to my project here: <a href="https://bit.ly/2Y5Xro4">https://bit.ly/2XJ0cLA</a></p><h4>The context of the problem</h4><p>A company that offers health insurance was studying to also offer car insurance. For that, they did a research with their current customers asking them if they had interest in car insurance and their answers were registered together with other informations of the customer.</p><p>The company had 127 thousand leads registered in their database and they had capacity of making 20,000 calls offering car insurance and they wanted to maximize their convertion rate.</p><p>So the problem here is that they can’t call all of the leads, and they need to prioritize those that are more likely to have interest in car insurance to maximize the convertion rate through 20,000 calls.</p><h4>The solution</h4><p>To solve this problem I used traditional classification model to predict their probability score, and with it I sorted the leads accordingly to the probability.</p><p>I trained and tested the model with the data provided by the research the company did, and then used the trained model to score the list of 127 thousand leads.</p><p>One thing that is worth noting is that, to measure the performance of the model I used precision@k and recall@k where k denotes that the metrics are evaluated only on top <em>k</em> elements.</p><h4>Results</h4><p>With 20,000 calls, if the sales team radomly selected leads to call, they would reach around 20.42% of all interested leads, and with the list sorted by the model the sales team would reach around 58.52% of all interested leads. As we can see there is a big difference in performance, and the company would have a big increase in their convertion rate, thus their profit.</p><h3>Final Thoughts</h3><p>Learning to Rank is one of many solution that machine learning can solve and it have its own complexity. I started learning about it when I was searching for a better solution to this problem.</p><p>And one of the main lessons I learned with this project was that defining how the model will be used and what is the problem that it is trying to solve is a major step to the success of your solution. If we do that, we have a understanding to build the proper solution.</p><p>Just imagine that instead of a sorted list by the highest probability, I delivered the actual classification (don’t have interest/have interest in car insurance). Sure, it might still be better than a random selection, but is not the best solution.</p><h4>About me</h4><p>I am a geographer currently working as a data scientist. For that reason, I am an advocate of spatial data science.</p><p>Follow me for more content. I will write a post every month about data science concepts and techniques, spatial data science and GIS (Geographic Information System).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55fd8b124101" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first Data Science project and what I’ve learned with it.]]></title>
            <link>https://kazumatsuda.medium.com/my-first-data-science-project-and-what-ive-learned-with-it-31b82cbaa23c?source=rss-326bb903f729------2</link>
            <guid isPermaLink="false">https://medium.com/p/31b82cbaa23c</guid>
            <category><![CDATA[sales-prediction]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[insight-data-science]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Alvaro Matsuda]]></dc:creator>
            <pubDate>Thu, 03 Jun 2021 18:26:24 GMT</pubDate>
            <atom:updated>2023-03-21T02:31:53.778Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lGNRW2MQDyWeTIu5" /><figcaption>Photo by <a href="https://unsplash.com/@isaacmsmith?utm_source=medium&amp;utm_medium=referral">Isaac Smith</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hi everyone!</p><p>As my first data science project I’ve learned a lot doing it and I would like to share some things, as it may help others and is a way to register my progress.</p><p>This post do not have any technical knowledge and is not the intend of it. I’ll show the steps I took to develop the project and tell the Why’s of each step.</p><h3>The Project</h3><p><strong>The business context: </strong>Rossmann is a drugstore chain that operates in many countries in Europe. The CFO asked stores managers to predict their sales up to six weeks in advance because they are going to reform their store to match a new visual identity and with the prediction he can plan better how to allocate the budget for each store.</p><p><strong>Proposed solution:</strong> Build a regression model to predict the sales up to six weeks in advance, as it helps the CFO to plan better the allocation of the budget for each store. To facilitate the access to the sales prediction I deployed the model to be accessed through a Telegram Bot that returns the prediction given an Id store.</p><p>You can see the whole development of the project here:<br><a href="https://github.com/AlvaroMatsuda/Rossmann_Sales_Prediction">https://github.com/AlvaroMatsuda/Rossmann_Sales_Prediction</a></p><h3>The 10 steps taken to develop this project</h3><p>At this section I’ll go through each step explaining the importance and the why’s of each one of them.</p><h4><strong>Step 1. Data Description</strong></h4><p>This is the first step after collecting the data. The purpose of it is to have a quick look at the data. Here we calculate basics statistics of all variables such as count, mean, median, mode, minimum, maximum, quantiles, range, standard deviation and skew and kurtosis and check data types and missing values.</p><p>With all this basic statistics we already get some information of our data like if there are missing values, outliers, the distribution of the variables, the magnitude and the dimension of our dataset.</p><p>Now we have a better idea of the problem we are facing going forward. Sometime the data is too big or there are many missing values and we have to plan the develpment of the project accordingly.</p><h4><strong>Step 2. Feature Engineering</strong></h4><p>The objective of this step is to derive new variables of the data already available to try to describe better the phenomenon we are modeling.</p><p>To guide the feature engineering, I created hypothesis about what may affect the behavior of what we are modeling, in this case what may affect the sales of Rossmann’s stores. With all the hypothesis created, I could define what features/variables I was able to create/derive from the original dataset that could answer the hypothesis.</p><h4><strong>Step 3. Variable Filtration</strong></h4><p>This step is before Exploratory Data Analysis so that we can filter some of the data that could interfere on our analysis. Another reason for this step, if you work on a company, is to filter data and variables that could be a business limitation or does not make sense to analyse those data to the actual objective of the project.</p><p>For exemple, in my project I removed data of closed stores and with no sales, which represents days that the store was closed, thus there were no sales. I also removed the columns ‘customers’ as I could not predict the number of customers up to six weeks in advance. Actually this could turn into another project.</p><h4><strong>Step 4. Exploratory Data Analysis (EDA)</strong></h4><p>This step is one of the most important as it gives us business understanding, even if we are not very familiar of the company’s business model. I’ll highlight three main goals of EDA:</p><p>1- Better understanding of the business;</p><p>2- Discover which variables explains better what we are trying to predict, thus which ones are important to our model;</p><p>3- Validate hypothesis and generate insights.</p><p>That are three methods to explore our data:<strong> Univariate, Bivariate and Multivariate. </strong>We usually use visual graphics to help us analyse the data, as it is more direct.</p><p>On the univariate analysis we analyse each variables individualy one by one. To do so we usually use basic statistcs covered on the data description section and graphs such as histogram, scatterplot (for numerical variables) and boxplot and countplot (for categorical variables).</p><p>On the bivariate analysis we verify how an independant variable (variables that describes what we are trying to predict) impact on the behavior of the dependant variable (what we are trying to predict). In other words, we check if that are correlation between the independant and dependant variables. With that we can already tell which variables are important for our model as the most correlated are the ones that describes better the phenomemon. To do the bivariate analysis we use all sorts of graphics: scatterplot, barplot, lineplot, heatmap, regplot, and others.</p><p>The multivariate analysis we plot a heatmap with pearson correlation for numerical variables and in this project I calculated the cramer-V correlation for categorical variables, both gives us the correlation among all variables.</p><h4><strong>Step 5. Data Preparation</strong></h4><p>After we explored our data it’s time to prepare them to be used by the models. One of the reasons to prepare the data is that how can we compare 2 different variables with different scales like, the sales of a given store and the distance to the nearest competitor? How can we transform categorical variables into numerical variables so that algorithms can interpret, conserving the information that it has? For that, we basically have three main methods: <strong>Normalization, Rescaling and Tranformation.</strong></p><p>The Normalization method we basically transform the distribution of the variable into a normal distribution where the mean becomes 0 with standard deviation (STD) of 1. What it implies is that the mesurement becomes the std. For exemple imagine we have a variable that has mean of 100 with std of 20, after we normalize the variable the mean becomes 0 and std of 1. Now if an observation had a value of 40 before the normalization, after it will become -3, which means that the value 40 represents -3 standard deviation from the mean of 100.</p><p>The rescaling method we rescale the range of the data to go from [0,1] or [-1,1], depending on the method. Using the same values of the exemplo above the value 40 would become 0,2 with the Min-Max scaler. There are others rescaling methods like Robust Scaler where instead of using the minimum and maximum to rescale it uses the inter quantile range (IQR) and the mean rescaling, each one of them have their pros and cons.</p><p>Finally we have the transformation where we turn categorial variables into numerical. Here we have to be carefull because we need to transform categorical into numerical variables conserving their information. For example, imagine we have a <em>‘</em><strong><em>Temperature</em></strong><em>’ </em>variable with the following values:<strong>[cold, warm, hot, very hot]</strong>. This is an ordinal categorical variable, which means that it transmit an idea of sequence. Now imagine we have a <em>‘</em><strong><em>City</em></strong><em>’ </em>variable with the following values: <strong>[São Paulo, Rio de Janeiro, Campinas, Maceió]</strong>. This variable does not transmit an idea of sequence, are just names.</p><p>So for each case there are the best transformation method. I’m not going to discuss each method, I’ll just list some of them: One Hot Encoding, Label Encoding, Ordinal Encoding, Target Encoding, Frequency Enconding, Embedding Encoding.</p><h4><strong>Step 6. Feature Selection</strong></h4><p>Now it’s time to select the most important variables to be used by the models. Here we follow the Occam’s Razor principal that says that<strong><em> the most simple explanation of an event/phenomenom should prevail over more complex explanation</em>.</strong> Applying it to Data Science, we want to select variables that best explain what we are modeling.</p><p>Again we have three main methods to select the best variables: Filter method, Embedded and Wrapper methods. In this project I used the Wrapper method, so I’ll discuss only this method.</p><p>The Wrapper method uses machine learning algorithms to evaluate all possible combination of variables calculating its performance for each combination. First it takes a subset of variables and calculate the performance of the model, then it will add another variable and train the model and calculate its performance. If the performance with the added variable is better than it is considered important, and if the performance is worst than we can conclude that it is not important.</p><p>In this step we also split our data into training and test dataset. The <strong>train </strong>dataset is used to train and fit Machine Learning Models and we can evaluate the performance of how well the model learned. With the <strong>test</strong> dataset we can evaluate the performance of generalization of the model, giving data that it never saw before. It indicates how well our model is to new data.</p><h4><strong>Step 7. Machine Learning Modeling</strong></h4><p>Here is where the magic happens. It’s where we train our model and evaluate the performance. There are types of Machine Learning Algorithms: Supervised, unsupervised and reinforcement learning.</p><p>In Supervied models we know the value of what we are predicting and for new data, it compares to the trainning dataset. With this type of model we have Classification, Regression and Time Series models.</p><p>Unsupervied models classificates/predict the class without the need to indicate the classes/predictions. Here we have Clustering models.</p><p>In Reinforcement Learning the model learn on the fly, where it maximizes reward in a particular situation. It learns through past experiences in a cumulative way.</p><p>In this project we have a supervised problem where we want to predict the sales. I used the following models: Random Forest Regressor, Linear Regression and Lasso Linear Regression and XGBoost Regressor. I calculated an average model to be a benchmark. Evaluating the performance of all models, Random Forest Regressor had the best performance and XGBoost the worst. But I chose XGBoost to see how much Hyperparameter Fine Tunning could improve the model, which I’ll talk about next.</p><h4><strong>Step 8. Hyperparameter Fine Tunning</strong></h4><p>After modelling and calculating the performance of each trained model and chose one to be implemented, we can tweak the parameters of the model to maximize its performance.</p><p>In my project I used the Random Search where you pass a list of values for each parameter and randomly sets values of the parameters and run the model. We also need to set how many time we are going to run the model. After we run the model the set amount of time we defined, we set our parameters equal to the best result we got.</p><p>There are also the Grid Search where we need to pass a list of values for each paramenter and it runs the model with every possible combination of the parameters. Than we set our parameters with the best results. It’s important to note that this method can be very expensive time wise, as it combine every possible combination and train the model.</p><h4><strong>Step 9. Translating and Interpreting the Performance</strong></h4><p>Here is where we get the real value of Data Science as we translate the performance of the model to business $$.</p><p>But first we need to interpret the performance of our model as we need to explain it to those who are not familiar with data science language. In this project I calculated the performance through 3 parameters for regression model: <strong>MAE (Mean Absolute Error), MAPE (Mean Absolute Percentage Error) and RMSE (Root Mean Square Error).</strong></p><p>What those parameters tells us is how much we are wrong with the prediction. Another way to put is how far my prediction is from the real value. The MAE and MAPE are basically the same. MAE tells us the total error of our model, summing all errors, and MAPE is the percentage of MAE. RMSE is another way to tell the error of the model, but in this case bigger error weights more on the calculation, meaning if there are many predictions very far from the real value the error will be bigger than MAE. It is most used to evaluate the performance of the model while MAE and MAPE are better to communicate to non techinical people as it is easier to understand.</p><p>Calculating those errors I could create best and worst scenarios of sales based on the error. The MAE can be interpreted like Standard Deviation, so for the predicted value we sum and subtract MAE, giving the best and worst scenario. With those scenarios and giving the error for each store the CFO can decide which scenario to take into account to plan the allocation of the budget.</p><h4><strong>Step 10. Deploy of the Model</strong></h4><p>After all the steps we’ve taken it’s finally time to deploy the model to be accessed by anyone who needs to get the prediction. On this project I deployed it on a Telegram Bot where the CFO can get the prediction on his cellphone. All we need to do is pass an ID of the store we want to get the prediction and the Bol will return the predicion.</p><p>Here is a demonstration of Telegram Bot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*0rSQkbjJXtKp9wRXHh6QEA.gif" /></figure><h3>Final Thoghts</h3><p>It was a long way to finish this project, I got some problems during the development but in the end, I got through it. Data Science is a complex field and involves so many different knowledge that some times it gets overwhelming. But if I can get a piece of advice is: start your studies solving a real case. This makes us motivated as we get to see the results of our effort.</p><p>All the knowledge I acquered doing this project was only the essencial to solve the problem. I do not come from a math background and sometimes I didn’t get some of the calculation at first (and some I still don’t understand), but we have to have a cyclical way of study. Each time we pass through the same problem we get a little bit further.</p><h4>About me</h4><p>I am a geographer currently working as a data scientist. For that reason, I am an advocate of spatial data science.</p><p>Follow me for more content. I will write a post every month about data science concepts and techniques, spatial data science and GIS (Geographic Information System).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31b82cbaa23c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>