<?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 Young Yoon on Medium]]></title>
        <description><![CDATA[Stories by Young Yoon on Medium]]></description>
        <link>https://medium.com/@y.s.yoon?source=rss-38a240a7297d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Icj8jBhLCBbKnu5x-5l94Q.jpeg</url>
            <title>Stories by Young Yoon on Medium</title>
            <link>https://medium.com/@y.s.yoon?source=rss-38a240a7297d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:35:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@y.s.yoon/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[Scalable Time-Series Forecasting in Spark — Prophet, CNN, LSTM, and SARIMA]]></title>
            <link>https://medium.com/@y.s.yoon/scalable-time-series-forecasting-in-spark-prophet-cnn-lstm-and-sarima-a5306153711e?source=rss-38a240a7297d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5306153711e</guid>
            <dc:creator><![CDATA[Young Yoon]]></dc:creator>
            <pubDate>Fri, 29 Apr 2022 04:26:24 GMT</pubDate>
            <atom:updated>2022-05-02T21:12:21.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scalable Time-Series Forecasting with Spark and Prophet</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qOMk-wR4u8xyCQCG7QFrDQ.gif" /></figure><h3>1. Introduction</h3><p>In this post, we will explore scalable time-series forecasting in PySpark. We will build time-series models using Facebook Prophet. We will then train 500 time-series Prophet models in parallel with PySpark in Google Colab. I am going to break down each step in detail, from installing packages to evaluating the models.</p><p>Let’s get started!</p><p>You can also find my code on my <a href="https://github.com/youngdataspace/Time-Series-Forecasting-in-Spark">GitHub</a>. If you have any comments or suggestions, email me at <a href="/service/mailto:y.s.yoon@berkeley.edu">y.s.yoon@berkeley.edu</a>.</p><h3>2. Create a Virtual Environment</h3><p>Prophet only runs in Python 3.8 or a lower version. For those of us who use a higher version like myself, we can create a virtual environment and use a lower version. I’ve listed the detailed steps to create a virtual environment with Python 3.7.</p><h3>2.1. Create and view virtual environments</h3><ul><li>in Windows: type “cmd” in “Type here to search” and right-click the “Command Prompt” to run it as administrator</li><li>in cmd: conda create -n py37prophet python=3.7</li><li>in cmd: conda info — envs</li></ul><p>FYI, we can remove the virtual environment with the following command but don’t run it now.</p><ul><li>in cmd: conda env remove -n py37prophet</li></ul><h3>2.2. Activate the virtual environment</h3><ul><li>in cmd: conda activate py37prophet</li></ul><p>FYI, we can deactivate the virtual environment with the following command but don’t run it now.</p><ul><li>in cmd: conda deactivate</li></ul><h3>2.3. Check the Python’s Version</h3><p>Make sure you have Python 3.7 installed.</p><ul><li>in py37prophet: python — version</li></ul><h3>2.4. Add the virtual environment to Jupyter Notebook’s list of Kernels</h3><ul><li>in py37prophet: pip install ipykernel</li><li>in py37prophet: python -m ipykernel install — user — name=py37prophet</li><li>in cmd or py37prophet: jupyter kernelspec list</li></ul><p>FYI, we can remove it with the following command but don’t run it now.</p><ul><li>in cmd or py37prophet: jupyter kernelspec uninstall py37prophet</li></ul><h3>2.5. Start Jupyter Notebook in the virtual environment</h3><ul><li>in windows: In File Explorer, go to the folder you want to use and type “cmd” in the address bar</li><li>in cmd: conda activate py37prophet</li><li>in py37prophet: jupyter notebook</li><li>in jupyter notebook: !python — version # To check the python version</li></ul><h3>3. Install Prophet and Other Useful Packages</h3><h3>3.1. Install Prophet</h3><p>Installing Facebook Prophet can be a headache. Make sure you have Python 3.8 or lower and follow the below instructions.</p><ul><li>in windows: type “cmd” in “Type here to search” and run it as administrator</li><li>in cmd: conda activate py37prophet</li><li>in py37prophet: pip install pystan</li><li>in py37prophet: conda install -c conda-forge prophet</li></ul><p><a href="https://stackoverflow.com/questions/53178281/installing-fbprophet-python-on-windows-10">This post</a> was very helpful for me.</p><h3>3.2. Prophet asks us to install/update the following (not an absolute must)</h3><ul><li>pip install plotly</li><li>pip install jupyter</li><li>pip install ipywidgets</li></ul><h3>4. Implementation of Demand Forecasting in Python</h3><h3>4.1. Data</h3><p>In this exercise, we are going to use the <a href="https://www.kaggle.com/competitions/demand-forecasting-kernels-only">retail store data</a> available on Kaggle. This data set has 5 years of store-item sales data for 50 different items at 10 different stores (i.e., 5 years of data for 500 item-stores).</p><h3>4.2. Preparation</h3><h4>4.2.1. Check the version of Python and make sure Prophet is working</h4><pre># Check the version of Python<br>!python --version</pre><pre># Make sure Prophet is working - import Prophet<br>from prophet import Prophet</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/208/1*8dSPo7a-2xrX53AdtvAW2Q.png" /></figure><h4>4.2.2. Import other necessary packages</h4><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><h4>4.2.3. Import the data set</h4><pre># Import the CSV file<br>df = pd.read_csv(&#39;train.csv&#39;)</pre><pre># View the first 5 entries<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*X5_5Zsv-l0bJrDrTqFaSpg.png" /></figure><p>The above shows that we have date, store and item identifiers, and sales amounts.</p><pre># Describe the data frame<br>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/509/1*JLFXW9L7YhTds69xV7bkcQ.png" /></figure><p>Several observations:</p><ul><li>The values in the store column range from 1–10 (i.e., we have 10 stores).</li><li>Similarly, the item values range from 1–50 (i.e., we have 50 items).</li><li>We have some missing sales values.</li></ul><pre># Number of missing values<br>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*114w8Nzmw9n8EZsSZeOFcA.png" /></figure><p>There are no missing values.</p><pre># Check for duplicates<br>df.groupby([&quot;item&quot;, &quot;store&quot;, &quot;date&quot;]).count().max()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/153/1*xiqwh5dosrl8FyIdLjWjzg.png" /></figure><p>None of the store-items have more than 1 observation.</p><h3>4.3. Exploratory Data Analysis (EDA) — Identify trends and seasonality</h3><h4>4.3.1. Identify trends — Sales in aggregate and by store</h4><pre># Convert the date column to datetime<br>df[&#39;date&#39;] = pd.to_datetime(df[&#39;date&#39;])</pre><pre># Extract year from date<br>df[&#39;year&#39;] = df[&#39;date&#39;].dt.year</pre><pre># Compute aggregate sales for each year<br>df_yearly = df.groupby([&#39;year&#39;], as_index=False).sum()</pre><pre># Plot aggregate sales<br>plt.figure(figsize=(10,4))<br>plt.bar(&#39;year&#39;, <br>        &#39;sales&#39;, <br>        data=df_yearly,<br>       color=&#39;blue&#39;)<br>plt.ylabel(&quot;Sales ($)&quot;, fontsize = 18)<br>plt.xticks(fontsize=15)<br>plt.yticks(fontsize=15)<br>plt.title(&#39;Annual Aggregate Sales&#39;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zLRCIe0X52-ka5t9v0ROng.png" /></figure><pre># Compute annual sales by store<br>df_yearly_store = pd.DataFrame(df.groupby([&#39;year&#39;, &#39;store&#39;]).sum()[&#39;sales&#39;]).unstack()</pre><pre># Plot it<br>plt.figure(figsize=(10,4))<br>plt.plot(df_yearly_store)<br>plt.ylabel(&quot;Sales ($)&quot;, fontsize = 18)<br>plt.xticks(fontsize=15)<br>plt.yticks(fontsize=15)<br>plt.title(&#39;Annual Sales by Store&#39;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NEm2Y8VVsY-TlUAcv28Lg.png" /></figure><pre># Compute annual sales by store<br>df_yearly_item = pd.DataFrame(df.groupby([&#39;year&#39;, &#39;item&#39;]).sum()[&#39;sales&#39;]).unstack()</pre><pre># Plot it<br>plt.figure(figsize=(10,4))<br>plt.plot(df_yearly_item)<br>plt.ylabel(&quot;Sales ($)&quot;, fontsize = 18)<br>plt.xticks(fontsize=15)<br>plt.yticks(fontsize=15)<br>plt.title(&#39;Annual Sales by Item&#39;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9_c46G3k_8vB1BxVC0nRQ.png" /></figure><p>Clearly, all store sales and items are trending upwards. We’ll incorporate this trend in our time-series models.</p><h4>4.3.2. Identify seasonality — Daily sales by store and by item<a href="http://localhost:8888/notebooks/Jupyter%20Notebook%20Projects/DemandForecasting/CNN_LSTM_Prophet_SARIMA_Models.ipynb#4.3.2.-Identify-seasonality---Daily-sales-by-store-and-by-item">¶</a></h4><pre># Aggregate sales by store and date<br>df_daily_store = pd.DataFrame(df.groupby([&#39;date&#39;,&#39;store&#39;]).sum()[&#39;sales&#39;]).unstack()</pre><pre># Plot daily sales by store<br>plt.figure(figsize=(10,5))<br>plt.plot(df_daily_store)<br>plt.title(&#39;Daily Sales by Store&#39;, fontsize = 20)<br>plt.ylabel(&quot;Sales ($)&quot;, fontsize = 18)<br>plt.xticks(fontsize=15)<br>plt.yticks(fontsize=15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L70U63-A14J1CZ_u54TCSw.png" /></figure><pre># Aggregate sales by store and date<br>df_daily_item = pd.DataFrame(df.groupby([&#39;date&#39;,&#39;item&#39;]).sum()[&#39;sales&#39;]).unstack()</pre><pre># Plot daily sales by store<br>plt.figure(figsize=(10,5))<br>plt.plot(df_daily_item)<br>plt.title(&#39;Daily Sales by Item&#39;, fontsize = 20)<br>plt.ylabel(&quot;Sales ($)&quot;, fontsize = 18)<br>plt.xticks(fontsize=15)<br>plt.yticks(fontsize=15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0kQKNi-T9lrpEck835csA.png" /></figure><p>Clearly, there is weekly seasonality. We will have to incorporate that into our models.</p><h3>4.4. Prophet — Forecast One Product</h3><p>Before we build 50 store x 10 item models in PySpark, let’s build a time-series Prophet model for store 1, item 1.</p><h4>4.4.1. Prepare and fit the model</h4><p>In our Prophet model, we are going to include a linear trend as well as weekly and annual seasonality.</p><pre># Store 1 item 1 data<br>s1i1 = df[(df.item==1)&amp;(df.store==1)]</pre><pre># Select columns<br>s1i1 = s1i1[[&quot;date&quot;, &quot;sales&quot;]]</pre><pre># Prophet wants us to name columns as shown below<br>s1i1.columns = [&quot;ds&quot;, &quot;y&quot;]</pre><pre># instantiate the model and set parameters<br>model = Prophet(<br>    interval_width=0.95,<br>    growth=&#39;linear&#39;,<br>    daily_seasonality=False,<br>    weekly_seasonality=True,<br>    yearly_seasonality=True,<br>    seasonality_mode=&#39;multiplicative&#39;<br>)</pre><pre># fit the model to historical data<br>model.fit(s1i1);</pre><h4>4.4.2. Evaluation — In-sample prediction</h4><p>To evaluate the model, we are going to predict the time series in the last 3 months of the sample and compare it with the actual value. We will first visually inspect by plotting the actual and predicted values. Then, we will evaluate using a metric called Symmetric Mean Absolute Percentage Error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R065UpGFAiCbmsBOGNWlmg.png" /></figure><p>Based on the plot, our in-sample prediction isn’t too bad but we cannot say it is doing fantastic. In a later post, we will try to see if CNN, LSTM, or Seasonal ARIMA models perform better.</p><p>Next, we will evaluate the model using popular evaluation metrics, MAPE and SMAPE. MAPE stands for Mean Absolute Percentage Error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*CfIFMJabSeMQpZgk" /></figure><p>Y refers to actual values and Y hat refers to predicted values. As the equation suggests, MAPE is the proportion of the MAPE is the average absolute forecast error as a percentage of actual values. Lower values indicate a better model.</p><p>One disadvantage of MAPE is that it puts a heavier penalty on negative errors. To overcome this, we can use SMAPE, which only ranges from 0 to 200%. The equation is shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/0*_5ZVCM_i1Skungx3" /></figure><p><a href="https://analyticsindiamag.com/a-guide-to-different-evaluation-metrics-for-time-series-forecasting-models/">This post</a> provides a good summary of popular evaluation metrics and <a href="https://towardsdatascience.com/choosing-the-correct-error-metric-mape-vs-smape-5328dec53fac">this post</a> nicely compares MAPE and SMAPE.</p><pre># SMAPE function<br>def smape_kun(y_true, y_pred):<br>    mape = np.mean(abs((y_true-y_pred)/y_true))*100<br>    smape = np.mean((np.abs(y_pred - y_true) * 200/ <br>                     (np.abs(y_pred) + np.abs(y_true))).fillna(0))<br>    print(&#39;MAPE: %.2f %% \nSMAPE: %.2f&#39;% (mape,smape), &quot;%&quot;)</pre><pre># Create a data frame of prediction and actual values<br>evaluation = pd.merge(<br>    # Prediction<br>    prediction[[&quot;ds&quot;, &quot;yhat&quot;]], <br>    # Actual<br>    s1i1[[&quot;ds&quot;, &quot;y&quot;]], <br>    # Inner join on date<br>    how=&#39;inner&#39;, on=&#39;ds&#39;)</pre><pre># MAPE and SMAPE<br>smape_kun(evaluation[&#39;y&#39;],evaluation[&#39;yhat&#39;])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*jXkGYPzySAYonYxIskpApA.png" /></figure><h4>4.4.3. Out-of-sample prediction</h4><p>What’s more interesting is actually predicting out-of-sample future values. Let’s forecast 3 additional months of store sales.</p><pre># Create a data frame that lists 90 dates starting from Jan 1 2018<br>future = model.make_future_dataframe(<br>    periods=90,<br>    freq=&#39;d&#39;,<br>    include_history=True)</pre><pre># Out of sample prediction<br>future = model.predict(future)</pre><pre># Plot<br>fig = model.plot(future, figsize=(10,5))<br>ax = fig.gca()<br>ax.set_title(&quot;Out-of-Sample Forecast&quot;, size=20)<br>ax.set_xlabel(&quot;Date&quot;, size=18)<br>ax.set_ylabel(&quot;Sales&quot;, size=18)<br>ax.tick_params(axis=&#39;x&#39;, rotation=45, labelsize=15)<br>ax.set_xlim(pd.to_datetime([&#39;2017-01-01&#39;, &#39;2018-03-31&#39;])) <br>plt.show();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8U00MD747UbxZHMUQQvGWA.png" /></figure><h3>4.8. Export the data set for forecasting multiple models in parallel with PySpark</h3><p>Rather than continuing the analysis locally, we will export the data set and upload it to Google Drive. This way, we can continue with the PySpark analysis in Google Colab. I recommend you do the same at least because setting up PySpark is much easier in Google Colab.</p><pre># Select necessary columns<br>df_export = df[[&#39;date&#39;, &#39;store&#39;, &#39;item&#39;, &#39;sales&#39;]]</pre><pre># Rename columns - Following Prophet requirements<br>df_export.columns = [&#39;ds&#39;, &#39;store&#39;, &#39;item&#39;, &#39;y&#39;]</pre><pre># Export to csv<br>df_export.to_csv(&#39;store_sales.csv&#39;, index=False)</pre><h3>5. Implementation of Scalable Demand Forecasting with PySpark in Google Colab</h3><p>Similar to setting up Prophet, PySpark installation can be very difficult at times. However, those tasks are extremely easy Google Colaboratory.</p><p>First, go to <a href="https://research.google.com/colaboratory">Google Colab</a> and click “File” -&gt; “New notebook” to create a new notebook.</p><h3>5.1. Preparation</h3><h4>5.1.1. Mount to Google Drive</h4><p>For easy access to files, connect the notebook to your Google Drive.</p><pre># Import library<br>from google.colab import drive</pre><pre># Connect to your google drive<br>drive.mount(&#39;/content/drive&#39;)</pre><h4>5.1.2. Install PySpark and Prophet</h4><p>Installing PySpark and Prophet only require one line of code for each.</p><pre># Install PySpark<br>!pip install pyspark</pre><pre># Install Prophet<br>!pip install Prophet</pre><h4>5.1.3. Load necessary packages</h4><pre># Import library<br>import pandas as pd<br>from pyspark.sql import SparkSession<br>from pyspark.sql.functions import pandas_udf, PandasUDFType<br>from pyspark.sql.types import *<br>from prophet import Prophet</pre><h4>5.1.4. Upload the CSV file to Google Drive</h4><ul><li>Click the folder icon in the left menu as shown in the image below.</li><li>Although you can save anywhere you wish, I like to save it in the Google Drive Colab Notebook folder. To do so, go to “content” -&gt; “dive” -&gt; “MyDrive” -&gt; Colab Notebooks -&gt; create “data” folder</li><li>Click the three dots next to “data”. You can upload the CSV file we saved by clicking “Upload”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/0*sBATQ3ZNegfGzODe" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/0*F1DWtMe4YrcA-aFB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/0*47-1rwiMqw6KcZjE" /></figure><h4>5.1.5. Import the CSV file and explore it</h4><p>Import the CSV file we just uploaded to Google Drive.</p><pre># Import the csv file and explore it<br>sales_pd = pd.read_csv(&#39;/content/drive/MyDrive/Colab Notebooks/data/store_sales.csv&#39;)</pre><pre># Convert ds to datetime<br>sales_pd[&#39;ds&#39;] = pd.to_datetime(sales_pd[&#39;ds&#39;])</pre><pre># Display info<br>sales_pd.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/549/1*tmJhu0YY7Xq9uXrVA9x12Q.png" /></figure><pre># Descriptive statistics<br>sales_pd.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*EOIFYixopXK3Q5WrKMfzyw.png" /></figure><h4>5.1.6. Increase the sample size by 10X</h4><p>Check the number of unique groups.</p><pre># Unique store-items<br>sales_pd[[&#39;item&#39;, &#39;store&#39;]].nunique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/111/1*1fzaDsN-8fY-DUEN4W4yug.png" /></figure><p>We have 50 items and 10 stores, which means that we have 500 unique groups. Let’s increase this data set by ten folds by concatenating it by itself until the number of groups reaches 5,000.</p><pre># Create a larger data frame<br>sales_pd_10k = pd.DataFrame()<br>for i in range(0,10):<br>   temp_pd = sales_pd.copy()<br>   ip1 = i + 1<br>   temp_pd[&#39;store&#39;] = temp_pd[&#39;store&#39;] + (10 * i)<br>   sales_pd_10k = pd.concat([sales_pd_10k, temp_pd])<br>   print(&#39;added data frame&#39;, ip1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/173/1*ZfCYEDIg4Z-Pq0kaVlre-g.png" /></figure><pre># Check the number of unique groups<br>sales_pd_10k[[&#39;item&#39;, &#39;store&#39;]].nunique()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/119/1*PERPngUX_eNSIskNyUB4MA.png" /></figure><p>We now have 100 stores x 50 items = 5,000 store-item groups.</p><h3>5.2. Prophet x PySpark</h3><h4>5.2.1. Create a Spark session</h4><p>Spark Sessions utilize Spark’s functions. They are created in the Driver program, which is inside the Master node.</p><p>Spark uses Master-Slave architecture. Salve nodes execute the tasks assigned by the Master node.</p><pre># Create a Spark Session - Run it on a standalone mode for practice<br># master(): Either yarn or mesos; local[] when running in standalone<br># appName(): Name of the application<br># getOrCreate: returns SparkSession; otherwise, create a new one<br>spark = SparkSession.builder\<br>.master(&quot;local&quot;)\<br>.appName(&quot;Colab&quot;)\<br>.config(&#39;spark.ui.port&#39;, &#39;4050&#39;)\<br>.getOrCreate()</pre><h4>5.2.2. Parallelization and structure schema</h4><p>Reading the CSV file with PySpark.</p><pre># Read the csv file<br>sales_df = spark.createDataFrame(sales_pd_10k)</pre><pre># Display the schema<br>sales_df.printSchema()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*3GU6zosyVhS3uGFB5XZ-kg.png" /></figure><p>We need to partition all the data based on store and item for parallel processing.</p><pre># Partition the data<br>sales_df.createOrReplaceTempView(&quot;item_sales&quot;)<br>sql = &quot;select * from item_sales&quot;<br>sales_part = (spark.sql(sql)\<br>   .repartition(spark.sparkContext.defaultParallelism, <br>   [&#39;store&#39;, &#39;item&#39;])).cache()<br>sales_part.explain()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/912/1*gfd3oIxYHNLbCbMeXtg7yg.png" /></figure><p>Next, we will structure the output of the data. See <a href="https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.sql.types.StructType.html">here</a> for different types of struct fields.</p><pre># Define a schema<br>schema = StructType([<br>                     StructField(&#39;store&#39;, IntegerType()),<br>                     StructField(&#39;item&#39;, IntegerType()),<br>                     StructField(&#39;ds&#39;, TimestampType()),<br>                     StructField(&#39;y&#39;, FloatType()),<br>                     StructField(&#39;yhat&#39;, DoubleType()),<br>                     StructField(&#39;yhat_upper&#39;, DoubleType()),<br>                     StructField(&#39;yhat_lower&#39;, DoubleType()),</pre><pre>])</pre><h4>5.2.3. Utilize Pandas UDF and PySpark to train multiple models in parallel</h4><p>The next step is to set parameters, fit the model, and predict sales just as we did for 1 forecast model. We are going to build a function and apply that function to all store-item groups. The only difference between this and our previous 1-model forecast is that we are going to utilize Pandas UDF and PySpark to parallelize the process.</p><pre># define the Pandas UDF<br>@pandas_udf(schema, PandasUDFType.GROUPED_MAP)<br>def apply_model(store_pd):</pre><pre>  # instantiate the model and set parameters<br>  model = Prophet(<br>      interval_width=0.95,<br>      growth=&#39;linear&#39;,<br>      daily_seasonality=False,<br>      weekly_seasonality=True,<br>      yearly_seasonality=True,<br>      seasonality_mode=&#39;multiplicative&#39;<br>  )</pre><pre>  # fit the model to historical data<br>  model.fit(store_pd)</pre><pre>  # Create a data frame that lists 90 dates starting from Jan 1 2018<br>  future = model.make_future_dataframe(<br>      periods=90,<br>      freq=&#39;d&#39;,<br>      include_history=True<br>   )</pre><pre>  # Out of sample prediction<br>  future = model.predict(future)</pre><pre>  # Create a data frame that contains store, item, y, and yhat<br>  f_pd = future[[&#39;ds&#39;, &#39;yhat&#39;, &#39;yhat_upper&#39;, &#39;yhat_lower&#39;]]<br>  st_pd = store_pd[[&#39;ds&#39;, &#39;store&#39;, &#39;item&#39;, &#39;y&#39;]]<br>  result_pd = f_pd.join(st_pd.set_index(&#39;ds&#39;), on=&#39;ds&#39;, how=&#39;left&#39;)</pre><pre>  # fill store and item<br>  result_pd[&#39;store&#39;] = store_pd[&#39;store&#39;].iloc[0]<br>  result_pd[&#39;item&#39;] = store_pd[&#39;item&#39;].iloc[0]</pre><pre>  return result_pd[[&#39;store&#39;, &#39;item&#39;, &#39;ds&#39;, &#39;y&#39;, &#39;yhat&#39;,<br>                    &#39;yhat_upper&#39;, &#39;yhat_lower&#39;]]</pre><pre># Apply the function to all store-items<br>results = sales_part.groupby([&#39;store&#39;, &#39;item&#39;]).apply(apply_model)</pre><pre># Print the results - calculate the time to run<br>import timeit<br>start = timeit.default_timer()<br>results.show()<br>stop = timeit.default_timer()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ANyJ_R6QUGHYmZy5pt86QQ.png" /></figure><pre># Print the time it took to forecast 5,000 models<br>print(&#39;Time: &#39;, stop - start)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*OfIVgYKhFdxKqz5P_MXBMQ.png" /></figure><p>It only took 64 seconds to train 5,000 models and forecast 3 months out!</p><h3>6. Conclusion</h3><p>In this long post, we went through several topics. We started with identifying trends and seasonality, moved on to building a Prophet model, and scaled the process to model 500 distinct models with PySpark. We didn’t get to cover CNN, LSTM, and Seasonal ARIMA but I am planning on adding them in a few days.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5306153711e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Artificial Neural Network (ANN) Classifier + Deployment on AWS Cloud Servers]]></title>
            <link>https://medium.com/@y.s.yoon/artificial-neural-network-ann-classifier-deployment-on-aws-cloud-servers-405254909161?source=rss-38a240a7297d------2</link>
            <guid isPermaLink="false">https://medium.com/p/405254909161</guid>
            <dc:creator><![CDATA[Young Yoon]]></dc:creator>
            <pubDate>Wed, 20 Apr 2022 20:19:50 GMT</pubDate>
            <atom:updated>2022-04-26T21:14:17.775Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DvucZBTQGKb8Ab2clfTovA.gif" /></figure><p>In this post, we will build a spam message classifier and deploy it. First, we will train and evaluate an Artificial Neural Network (ANN) model locally. Once we are satisfied with our model, we will deploy it on AWS using SageMaker.</p><p>You can also find my code on my <a href="https://github.com/youngdataspace/Build-and-Deploy-a-Spam-Detector-Model-on-AWS">GitHub</a>.</p><h3>Part 1 — Build a Spam Classifier Locally</h3><h3>Virtual Environment</h3><p>Once we build a deep learning model using TensorFlow, we will deploy it on AWS using SageMaker. However, the version of SageMaker’s TensorFlow is 1.15.5 at the time of this writing. This means that we have to use Python 3.7. For those of you who have Python 3.8 like me, it is important that we train the model using Python 3.7 in a virtual environment.</p><ol><li>Type the following in Anaconda Prompt<br>“conda create -n python37 python=3.7”</li><li>Activate the python37 virtual environment<br>“conda activate python37”<br>By the way, we can deactivate the virtual environment by typing “conda deactivate” but let&#39;s leave it active for now.</li><li>Install necessary packages in the environment. For TensorFlow, let’s match the version with SageMaker’s version. pip install tensorflow==1.15.5 pip install pandas pip install matplotlib</li><li>Make the environment available in Jupyter Notebook</li></ol><pre>pip install ipykernel<br>ipython kernel install --user --name=python37</pre><p>These will allow us to use the python37 kernel in Jupyter Notebook as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/0*gwQtY0mbAqezAXmu" /></figure><h3>Build a Classifier Using Jupyter Notebook (spam_classifier.ipynb)</h3><p>From the above image, click “python37” and create a new notebook using the virtual environment we just created.</p><p>Now we are ready to start working with data. Let’s start writing in the spam_classifier.ipynb notebook.</p><h3>1. Data</h3><p>We will train our model using UCI Machine Learning’s SMS spam collection dataset available <a href="https://www.kaggle.com/datasets/uciml/sms-spam-collection-dataset">here</a>.</p><h3>2. Preparation</h3><h4>2.1. Import libraries and lad the UCI’s spam dataset</h4><pre># Import library<br>import pandas as pd<br>import numpy as np<br>import matplotlib.pyplot as plt</pre><pre># Import the UCI&#39;s Spam dataset<br>df = pd.read_csv(&quot;./spam.csv&quot;, encoding=&#39;latin-1&#39;)</pre><h4>2.2. Explore the data</h4><p>Before we do anything, we are going to explore the data to think about the next steps.</p><pre># View the first 5 entries<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*9CID4TCLEp_TKLxIem4vBA.png" /></figure><pre># Describe the data<br>df.describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*fwihtzy9mkveCz8gip8IuA.png" /></figure><p>Based on the above basic exploration, it seems that (1) we can remove the last 3 columns and (2) remove the duplicates in v2.</p><h3>3. Clean the data</h3><h4>3.1. Remove unnecessary columns</h4><p>We are going to drop the last three columns and change the variable names to “label” and “message”.</p><pre># Drop the last 3 columns<br>df.drop(columns=[&#39;Unnamed: 2&#39;,&#39;Unnamed: 3&#39;,&#39;Unnamed: 4&#39;],<br>        inplace=True)</pre><pre># Change the column names<br>df.columns = [&#39;label&#39;, &#39;message&#39;]<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*hBRlb2QGiekPzGraJe9AsA.png" /></figure><h4>3.2. Check for missing values and duplicates</h4><pre># Check for missing values<br>df.isnull().sum()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*Fh6cVWmJrWZKpudqxwzb_g.png" /></figure><p>There are no missing values in the remaining two columns.</p><p>As mentioned above, we have some duplicates. Let’s remove them.</p><pre># Remove duplicates<br>df.drop_duplicates(keep=&#39;first&#39;, inplace = True)</pre><pre># Check duplicates<br>df.duplicated().sum()</pre><h3>4. Exploratory Data Analysis (EDA)</h3><p>Before we proceed with modeling, let’s perform an EDA and better understand the data.</p><pre># Create counts and define labels and colors<br>counts = [len(df[df[&#39;label&#39;]==&#39;ham&#39;]), <br>          len(df[df[&#39;label&#39;]==&#39;spam&#39;])]<br>labels = &#39;Ham&#39;, &#39;Spam&#39;<br>colors = [&quot;#DAA03DFF&quot;, &quot;#616247FF&quot;]</pre><pre># Make it look nice - remove tics and labels<br>fig1, ax1 = plt.subplots()<br>ax1.bar(labels, counts, color = colors)<br>plt.tick_params(<br>    left=False,<br>    bottom=False,    <br>    labelleft=False,<br>    labelbottom=False)<br>plt.box(False)<br>plt.title(&quot;Count Bar Chart&quot;, fontsize = 20)</pre><pre># Show values for each bar<br>for bars in ax1.containers:<br>    ax1.bar_label(bars)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/347/1*Jpu7UAQUaQ39ZFpIxNTYTA.png" /></figure><p>We have an imbalanced dataset with 4,516 normal messages and 653 spam messages.</p><pre># Pie Chart<br>fig2, ax2 = plt.subplots()</pre><pre>ax2.pie(counts,            # Plot counts<br>        labels=labels,     # Use the labels defined above<br>        colors=colors,     # Use the colors defined above<br>        explode=(0, 0.1),  # Only &quot;explode&quot; the 2nd slice<br>        autopct=&#39;%1.1f%%&#39;, # Show %<br>        shadow=True,       # Shadow<br>        startangle=90)     # Rotate<br>ax2.axis(&#39;equal&#39;)          # Ensures that the pie is a circle<br>plt.title(&quot;Count Pie Chart&quot;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/227/1*yB72O06h562IiZnGJ1hscQ.png" /></figure><p>The pie chart above shows the same inference: we have an imbalanced dataset.</p><h3>5. Data preprocessing</h3><p>Next, we are going to perform preprocessing on the message. Specifically, we are going to perform the following:</p><ul><li>Covert to lower cases</li><li>Remove punctuations and numbers: There are various ways to remove punctuations, but based on <a href="https://towardsdatascience.com/how-to-efficiently-remove-punctuations-from-a-string-899ad4a059fb">this article</a>, the translate method is the fastest method.</li><li>Tokenization: It refers to the process of splitting strings. It allows us to manipulate words or conduct analyses on them. We will tokenize texts into words.</li><li>Stop word: It refers to are words that do not have much meaning and thus removed for many nlp projects. Some examples include “the”, “a”, “so”, “what”. There are various libraries, but for this analysis, we will use the SciKit Learn’s list.</li><li>Lemmatization: Covert the word to its basic form (e.g, ran = &gt; run)</li></ul><h4>5.1. Preparation</h4><pre># Libraries<br>import string<br>import nltk<br>from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS<br>from nltk.tokenize import word_tokenize<br>from nltk.stem import PorterStemmer<br>from nltk.stem import WordNetLemmatizer<br>nltk.download(&#39;punkt&#39;)   # Required for tokenization<br>nltk.download(&#39;wordnet&#39;) # Required for lemmatization</pre><pre># Instantiate<br>stemmer = PorterStemmer()<br>lemmatizer = WordNetLemmatizer()</pre><pre># More stop words<br>stop_words = [&#39;å£&#39;] + list(ENGLISH_STOP_WORDS)</pre><pre># Exclusion list of punctuations and numbers<br>exclist = string.punctuation + string.digits</pre><pre># Print the exclusion list<br>print(exclist)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*siZ17O6WsZFNaMCeLmM_MA.png" /></figure><p>We will remove the above punctuations and numbers.</p><h4>5.2. Conduct preprocessing</h4><p>Let’s create a function that performs all the preprocessing steps listed above.</p><pre># Create a Function<br>def clean_texts(text):<br>    &quot;&quot;&quot; Function to perform preprocessing &quot;&quot;&quot;<br>    <br>    # Convert to lower cases<br>    text = text.lower()<br>    <br>    # Remove punctuations and numbers<br>    text = text.translate(str.maketrans(&quot;&quot;, &quot;&quot;, exclist))<br>    <br>    # Tokenization<br>    tokens = word_tokenize(text)<br>    <br>    # Remove stop words<br>    tokens = [token for token in tokens if token not in stop_words]<br>    <br>    # Stemming<br>    tokens = [stemmer.stem(token) for token in tokens]<br>    <br>    # Lemmatization<br>    tokens = [lemmatizer.lemmatize(token) for token in tokens]<br>    <br>    # Join tokens<br>    clean_text = &quot; &quot;.join(tokens)<br>    <br>    # Return the output<br>    return clean_text</pre><p>Apply the function to all the messages.</p><pre># Preprocessing<br>df[&#39;clean_message&#39;] = df[&#39;message&#39;].apply(clean_texts)<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/646/1*bD4iUotpudhttlo7tUxraA.png" /></figure><h3>6. Word clouds and word counts</h3><p>Since we cleaned the messages, let’s conduct a bit more EDA and examine the difference in word counts between spam vs. non-spam messages.</p><h4>6.1. Word Clouds — Spam</h4><pre># Import library<br>from wordcloud import WordCloud</pre><pre># Instantiate Word Cloud<br>wc = WordCloud(width=1500,<br>               height=1500,<br>               min_font_size=10,<br>               background_color=&#39;white&#39;)</pre><pre># Generate a word cloud for spam messages<br>plt.figure(figsize = (24, 6))<br>spam_wc = wc.generate(df[df[&#39;label&#39;] == &quot;spam&quot;][&#39;clean_message&#39;].str.cat(sep=&quot; &quot;))<br>plt.xticks([])<br>plt.yticks([])<br>plt.imshow(spam_wc);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*WrXq76v_mJGSDS2qubtpfA.png" /></figure><p>Some notable high-frequency words include free, text, offer, claim, and win. It makes sense that these words appear a lot in spam messages.</p><h4>6.2. Word Clouds — Non-Spam</h4><pre># Generate a word cloud for non-spam messages<br>plt.figure(figsize = (24, 6))<br>ham_wc = wc.generate(df[df[&#39;label&#39;] == &quot;ham&quot;][&#39;clean_message&#39;].str.cat(sep=&quot; &quot;))<br>plt.xticks([])<br>plt.yticks([])<br>plt.imshow(ham_wc);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*p5_f4AZTv-PIoXDdyGG1qw.png" /></figure><p>Normal messages have very different high-frequent words: u, ok, got, I’m, love, etc. Once again, this plot also makes sense.</p><h4>6.3. Word Count Plots — Spam</h4><p>The inferences from word count plots should be the same as the word clouds but it’s always good to see the count plots to make sure we didn’t miss anything. If we identify some words we think should be excluded, we can go back to the preprocessing step and add them to the list of stop words.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*tyVmXTmytyzgPs3h-NrZrw.png" /></figure><h4>6.4. Word Count Plots — Ham</h4><pre># Plot spam message count bar chart<br>count_plot(&quot;ham&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*23xiYOCzVB54j4jIL-BEIA.png" /></figure><p>Everything looks good! Let’s move on to the next step.</p><h3>7. Vectorization</h3><p>Machines cannot read texts. Thus we have to convert them to numbers. This process is called vectorization or word embeddings.</p><h4>7.1. Test and training set split</h4><p>First, let’s split the data into test and training sets to avoid data leakage during the vectorization step.</p><pre># Import library<br>from sklearn.preprocessing import LabelEncoder<br>from sklearn.model_selection import train_test_split</pre><pre># Encode the label<br>label_encoder = LabelEncoder()<br>df[&quot;label&quot;] = label_encoder.fit_transform(df[&quot;label&quot;])</pre><pre># Split the samples into train and test sets<br>X_train, X_test, y_train, y_test = \<br>train_test_split(df[&#39;message&#39;], df[&#39;label&#39;], <br>                 test_size = 0.2, random_state=1)</pre><pre># View the shapes of all dataframes<br>X_train.shape, X_test.shape, y_train.shape, y_test.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/308/1*eB9wt1WbFj6JL4TAIclFYQ.png" /></figure><h4>7.2. TF-IDF</h4><p>TF-IDF is one of the most popular ways to vectorize corpus. TF-IDF stands for “Term Frequency — Inverse Document Frequency”. Term Frequency measures the frequency of a word in a document. Inverse Document Frequency is the natural log of the inverse of document frequency, which is the number of documents where the word appears.</p><pre># Import library<br>from sklearn.feature_extraction.text import TfidfVectorizer</pre><pre># Instantiate<br>vectorizer = TfidfVectorizer()</pre><pre># Fit the training data (only the training data)<br>vectorizer.fit(X_train)</pre><pre># Vectorize <br>X_train_vec = vectorizer.transform(X_train).toarray()<br>X_test_vec = vectorizer.transform(X_test).toarray()</pre><pre># Display the the vectors<br>X_train_vec, X_test_vec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/349/1*Xu0k4QRY37Pm29IbCr7ong.png" /></figure><h3>8. Model building</h3><p>There are numerous classifiers we can use. For this exercise, we will start with Artificial Neural Network (ANN) and turn to other classifiers if the performance is not satisfying.</p><h4>8.1. Compile</h4><pre># Import library<br>import tensorflow as tf</pre><pre># Instantiate<br>ann_model = tf.keras.models.Sequential()</pre><pre># Add layers<br>ann_model.add(tf.keras.layers.Dense(units=6, activation=&#39;relu&#39;))<br>ann_model.add(tf.keras.layers.Dense(units=6, activation=&#39;relu&#39;))<br>ann_model.add(tf.keras.layers.Dense(units=1, activation=&#39;sigmoid&#39;))</pre><pre>ann_model.compile(optimizer=&#39;adam&#39;, <br>            loss = &#39;binary_crossentropy&#39;, <br>            metrics = [&#39;accuracy&#39;]) <br>#Compiling<br>ann_model.fit(X_train_vec, y_train.values, batch_size=32, epochs=10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*uXyNU64FPSn1C4YQp6KOlQ.png" /></figure><h4>8.2. Predict</h4><p>Now that we trained the model, let’s set the decision boundary at 0.5 and classify everything above 0.5 as spam messages.</p><pre>y_predict = (ann_model.predict(X_test_vec) &gt; 0.5)</pre><h3>9. Evaluation</h3><p>In this section, we will evaluate our model using various measures.</p><h4>9.1. Confusion Matrix</h4><pre># Import library<br>from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score</pre><pre># Create a function to tabulate Confusion Matrix<br>def cm_function(matrix_input, y_test_input, title):<br>    &#39;&#39;&#39; Function to plot Confusion Matrix &#39;&#39;&#39;<br>    <br>    # Gather values and labels that will be used in the matrix<br>    group_names = [&#39;True Negative&#39;,&#39;False Positive&#39;,<br>          &#39;False Negative&#39;,&#39;True Positive&#39;]<br>    group_counts = [&quot;{0:0.0f}&quot;.format(value) for value <br>          in matrix_input.flatten()]<br>    group_percentages = [&quot;({0:0.0%})&quot;.format(value) <br>          for value in matrix_input.flatten()/y_test_input.count()]<br>    <br>    # Create 4 texts that will be shown in each box of the matrix<br>    labels = [f&quot;{v1}\n{v2}\n{v3}&quot; for v1, v2, v3 in<br>              zip(group_names, group_counts, group_percentages)]<br>    labels = np.asarray(labels).reshape(2,2)<br>    <br>    # Plot the matrix and adjust the format<br>    sns.set(font_scale = 1.2)<br>    fig = sns.heatmap(matrix_input, fmt=&#39;&#39;, annot = labels)<br>    plt.title(title, fontsize=20)<br>    plt.xlabel(&quot;Prediction&quot;, fontsize = 15)<br>    plt.ylabel(&quot;True Class&quot;, fontsize = 15) <br>    plt.show()</pre><pre># Process and tabulate the Confusion Matrix<br>cm = confusion_matrix(y_test, y_predict)<br>cm_function(cm, y_test, <br>            &quot;Confusion Matrix&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/1*6zvuFks49MzFCAuTRjn5nA.png" /></figure><p>The confusion matrix above shows that our model did a great job!</p><h4>9.2. Accuracy, Precision, Recall, F1-Score</h4><p>To better evaluate the model, let’s report some popular evaluations metrics.</p><pre># Report accuracy, precision, and recall<br>print(classification_report(y_test, y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*PnKqQkbE3LIm40YYMVox-Q.png" /></figure><p>The ANN model has very good accuracy, precision, recall, and f1-score.</p><h4>9.3. Test some messages</h4><p>As the last evaluation step, let’s test out whether the following typical message is correctly classified as spam.</p><pre>ann_model.predict(vectorizer.transform([&quot;you won $99&quot;]).toarray())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/307/1*Jb-zfl_4YePhF0_vVbjGow.png" /></figure><p>The spam prediction is well above 0.5, so the detector will correctly predict this message as a spam message. Good!</p><p>Next, let’s try a normal message.</p><pre>ann_model.predict(vectorizer.transform([&quot;Hey, Young. Should we meet at 5?&quot;]).toarray())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*bDrUlsi4DmO1yNgmyZSwHQ.png" /></figure><p>The spam prediction is very low. The detector will correctly predict the above message as a normal message.</p><h4>10. Save the model for deployment</h4><p>The last step is to save the trained model in the json format and the weights in the hdf5 format.</p><pre>from keras.models import model_from_json</pre><pre># serialize model to json<br>json_model = ann_model.to_json()</pre><pre># Save the model architecture to JSON file<br>with open(&#39;ann_model.json&#39;, &#39;w&#39;) as json_file:<br>    json_file.write(json_model)</pre><pre>#saving the weights of the model <br>ann_model.save_weights(&#39;ann_model_weights.h5&#39;)</pre><p>Two files (ann_model.jason and ann_model_weights.h5) should have been created. Zip the two files in my computers and name it “ann_model.zip”.</p><p>We are now done with the first part. Save the notebook and proceed to the next step.</p><h3>Part 2 — Deploy the Trained Model on AWS Using SageMaker</h3><h3>Preparation</h3><h4>Account</h4><ul><li>Create an AWS account</li><li>Sign in</li></ul><h4>Create an S3 bucket and upload the model</h4><ul><li>Search S3 and go to Buckets</li><li>Click the “create bucket” button in orange.</li><li>Give it a name (e.g., spam-detector-s3) and select your region (I selected us-west-1)</li><li>Click the name of the bucket to go into the bucket</li><li>Upload “ann_model.zip” to the bucket</li></ul><h4>Create a Jupyter Notebook</h4><ul><li>Go to the SageMaker Dashboard by searching SageMaker.</li><li>On the left menu, expand “notebook” and click instances.</li><li>Click the “create notebook instance” button in orange.</li><li>Give a name to the instance (I am calling it “spam-detector”)</li><li>The only other thing we need to set is “IAM role”. Create one if you don’t already have one.</li><li>Leave all other settings as default and click the “create notebook instance” button in orange at the bottom.</li><li>Click “Open Jupyter” to open Jupyter Notebook in SageMaker</li><li>Create a new notebook by clicking “new” and selecting “conda_tensorflow_p36”</li></ul><p>The remainder of this post will be explaining the deployment process in the notebook that we just created.</p><h3>Implementation of the Deployment Using SageMaker (deploy_spam_detector.ipynb)</h3><h4>Check the TensorFlow version and save it</h4><p>SageMaker’s TensorFlow version is 1.15.5. This is the reason why we created a virtual environment to specifically use Python 3.7 + TensorFlow 1.15.5 to build the model.</p><pre># Import library<br>import tensorflow as tf</pre><pre># Print the version and save it<br>print(tf.__version__)<br>tf_framework_version = tf.__version__</pre><h4>Import libraries and retrieve the IAM</h4><p>Retrieve the AWS Identity and Access Management (IAM). Some of the codes are tweaks from the code in <a href="https://aws.amazon.com/blogs/machine-learning/deploy-trained-keras-or-tensorflow-models-using-amazon-sagemaker/">this post</a>.</p><pre># import libraries<br>from sagemaker import get_execution_role<br>from sagemaker import Session</pre><pre># Retrive the IAM<br>role = get_execution_role()<br>sess = Session()<br>bucket = sess.default_bucket()</pre><h4>Download the model</h4><p>The following code downloads the zip file we uploaded in the S3 bucket.</p><pre># Create a directory called keras_model<br>!mkdir keras_model</pre><pre># Download the zip file we uploaded<br>!aws s3 cp s3://spam-detector-s3/ann_model.zip ann_model.zip</pre><pre># Unzip the file in the keras_model folder<br>!unzip ann_model.zip -d keras_model</pre><h4>Load the model</h4><p>The next step is to load the model and weights. The following <a href="https://stackoverflow.com/questions/53183865/unknown-initializer-glorotuniform-when-loading-keras-model">Stack Overflow Q&amp;A</a> was very helpful.</p><pre># Import libraries<br>import keras<br>import os<br>import tensorflow as tf<br>import tensorflow.keras as keras<br>from keras.models import model_from_json<br>from keras.utils import CustomObjectScope<br>from keras.initializers import glorot_uniform</pre><pre># Load the model<br>with open(os.path.join(&#39;keras_model&#39;, &#39;ann_model.json&#39;), &#39;r&#39;) as fp:<br>    loaded_model_json = fp.read()<br>with CustomObjectScope({&#39;GlorotUniform&#39;: glorot_uniform()}):<br>        loaded_model = model_from_json(loaded_model_json)</pre><pre># Load the weights<br>loaded_model.load_weights(&#39;keras_model/ann_model_weights.h5&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/225/1*qYEAsYk4WOiL5B_DUIegOw.png" /><figcaption>The model and the weights</figcaption></figure><h4>Export the Keras model to the TensorFlow ProtoBuf format</h4><p>This will translate the Keras model to a format that SageMaker can read. The output will be saved in the ‘export/Servo/1&quot; folder as “saved_model.pb”.</p><pre>from tensorflow.python.saved_model import builder<br>from tensorflow.python.saved_model.signature_def_utils import predict_signature_def<br>from tensorflow.python.saved_model import tag_constants</pre><pre># Note: This directory structure will need to be followed <br>model_version = &#39;1&#39;<br>export_dir = &#39;export/Servo/&#39; + model_version<br># Build the Protocol Buffer SavedModel at &#39;export_dir&#39;<br>builder = builder.SavedModelBuilder(export_dir)</pre><pre># Create prediction signature<br>signature = predict_signature_def(<br>    inputs={&quot;inputs&quot;: loaded_model.input}, outputs={&quot;score&quot;: loaded_model.output})</pre><pre>session = tf.compat.v1.Session()<br>init_op = tf.compat.v1.global_variables_initializer()<br>session.run(init_op)</pre><pre># Save the meta graph and variables<br>builder.add_meta_graph_and_variables(<br>    sess=session, tags=[tag_constants.SERVING], <br>    signature_def_map={&quot;serving_default&quot;: signature})<br>builder.save()</pre><h4>Compress and upload files to S3</h4><p>We are going to compress the file in the tar.gz format and then upload the file to our S3 bucket. The following <a href="https://baraaalbourghli.medium.com/deploy-your-keras-or-tensorflow-machine-learning-model-to-aws-using-amazon-sagemaker-how-to-2d88a6e779cc">post</a> was very helpful.</p><pre># Import libraries<br>import tarfile<br>import sagemaker</pre><pre># Compress the file<br>with tarfile.open(&#39;model.tar.gz&#39;, mode=&#39;w:gz&#39;) as archive:<br>    archive.add(&#39;export&#39;, recursive=True)</pre><pre># Upload the file to the S3<br>sagemaker_session = sagemaker.Session()<br>inputs = sagemaker_session.upload_data(path=&#39;model.tar.gz&#39;, key_prefix=&#39;model&#39;)</pre><h4>Deploy the model</h4><p>Prepare for the deployment.</p><pre># Import library<br>from sagemaker.tensorflow.serving import Model</pre><pre># Instance Type<br>instance_type = &#39;ml.c5.xlarge&#39;</pre><pre># Model<br>sm_model = Model(model_data=inputs, <br>                 framework_version=tf_framework_version,<br>                 role=role)</pre><p>Implement the deployment.</p><pre>%%time<br>uncompiled_predictor = sm_model.deploy(initial_instance_count=1, instance_type=instance_type) <br>print(&#39;/Model is deployed&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*JFZnYfNj9MPDaTf4PQHcxg.png" /></figure><p>The model is now deployed!</p><p>Let’s check the endpoint to double-check. Go to SageMaker Dashboard -&gt; expand inference -&gt; Endpoints. If you see something like the following, then it means that your model has been successfully deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*_EettsHehqGBANBN" /></figure><h4>Delete the endpoint</h4><p>Don’t forget to delete the endpoint by running the following code. Otherwise, you may incur charges.</p><pre>sagemaker_session.delete_endpoint(uncompiled_predictor.endpoint)</pre><h3>Conclusion</h3><p>Hopefully, this post helped you understand how to train and evaluate an ANN model and deploy it on AWS using SageMaker. If you have any comments or suggestions, email me at <a href="/service/mailto:y.s.yoon@berkeley.edu">y.s.yoon@berkeley.edu</a>.</p><p>I am planning on updating this post to include (1) the demonstration of calling the API and (2) monitoring the model.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=405254909161" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NLP Illustration in Python — Extracting Keywords]]></title>
            <link>https://medium.com/@y.s.yoon/nlp-illustration-in-python-extracting-keywords-e9c4a6e0a267?source=rss-38a240a7297d------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9c4a6e0a267</guid>
            <dc:creator><![CDATA[Young Yoon]]></dc:creator>
            <pubDate>Sun, 17 Apr 2022 23:06:17 GMT</pubDate>
            <atom:updated>2022-08-01T21:37:01.223Z</atom:updated>
            <content:encoded><![CDATA[<h3>NLP Illustration in Python — Extracting Keywords</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tL7cirx4VR8coRg5XLwMVw.gif" /></figure><p>The importance of the ability to extract keywords is ever-growing as more and more text data become available. In this post, I illustrate how we can use implement various keyword extraction techniques in Python. Specifically, I will focus on Word Cloud, TF-IDF, KeyBERT, and YAKE. To demonstrate, I will use lease disclosure data that I use in my UC Berkeley Haas Dissertation, available <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3689446">here</a>.</p><p>You can also find my code on <a href="https://github.com/youngdataspace/NLP-Lease-Disclosure">GitHub</a>. If you have any comments or suggestions, email me at <a href="/service/mailto:y.s.yoon@berkeley.edu">y.s.yoon@berkeley.edu</a>.</p><h3>Problem Statement</h3><p>Starting in 2019, the Financial Accounting Standards Board mandated firms to provide a detailed lease disclosure. Since it is the first time we are observing detailed lease information, many stakeholders, practitioners, and academics are interested in learning about them.</p><h3>Implementation in Python</h3><p>Without further ado, let’s dive in!</p><h3>1. Data</h3><p>I gathered lease footnote disclosure from the top 100 US public companies that began adopting the new lease standard in 2019. For each company, I scraped all the texts within the lease footnote disclosure.</p><h3>2. Preparation</h3><h4>2.1. Import libraries and load the data</h4><pre># Import libraries<br>import pandas as pd<br>import matplotlib.pyplot as plt</pre><pre># Load the csv file that contains lease disclosures<br>df = pd.read_csv(&quot;lease disclosures.csv&quot;)</pre><h4>2.2. Explore the data</h4><pre># Display the first 5 rows<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q-foElShdg1QWek25DL26w.png" /></figure><pre># Display the information of the data<br>df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*YFWhREr6-a9ElKwo2f2ulg.png" /></figure><p>The last column contains the lease disclosures. Other columns display some basic information, including company names and ticker symbols, but we don’t need them. So, let’s remove all other columns in the next step.</p><h3>3. Clean the data</h3><h4>3.1. Remove unnecessary columns</h4><pre># Only leave the LeaseFootnote column<br>df = df[[&quot;LeaseFootnote&quot;]].dropna()<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*fSNHtXKuEzdoMUTG1g8egw.png" /></figure><h4>3.2. Inspect an example footnote</h4><p>Let’s expand one of the rows and visually inspect what’s disclosed.</p><pre># Examine the first footnote <br>df[&#39;LeaseFootnote&#39;][0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*NBD-XhLSEnWVoRJdCxFiLw.png" /></figure><p>It looks like there are many line breaks (“/n”). Let’s remove them.</p><pre># Replace \n with an empty space<br>df[&quot;LeaseFootnote&quot;] = df[&quot;LeaseFootnote&quot;].str.replace(&quot;\n&quot;, &quot; &quot;)</pre><pre># View the first footnote again<br>df[&#39;LeaseFootnote&#39;][0]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/686/1*8WrurK-kqaqqtKtYu_ZyTA.png" /></figure><p>Looks much better!</p><h4>3.3. Word count — Histogram and Kernel Density Plot</h4><p>How much information do firms disclose? We can use word count as a proxy for the quantity of disclosure. Using histogram and kernel density plots, we can examine the distribution of word counts.</p><pre># Import library<br>import seaborn as sns</pre><pre># Create a new column of word counts<br>df[&#39;word_count&#39;] = df[&#39;LeaseFootnote&#39;].str.split().str.len()</pre><pre># Histogram<br>fig = plt.figure(figsize=(15, 4))             # Size<br>plt.hist(df[&#39;word_count&#39;] )                   # Plot<br>plt.rcParams[&#39;font.size&#39;] = 20                # Font size<br>plt.ylabel(&quot;Frequency&quot;, fontsize = 20)        # Y label<br>plt.xlabel(&quot;Word Count&quot;, fontsize = 20)       # X label<br>plt.title(&quot;Histogram&quot;, fontsize = 30)         # Title<br>plt.show()</pre><pre># Kernel Density Plot<br>fig = plt.figure(figsize=(15, 4))             # Size<br>ax = sns.kdeplot(df[&#39;word_count&#39;],            # Plot<br>         color = &quot;Red&quot;, shade = True)<br>ax.set_ylabel(&quot;Density&quot;, fontsize = 20)       # Y label<br>ax.set_xlabel(&quot;Word Count&quot;, fontsize = 20)    # X label<br>plt.title(<br>    &quot;Word Count - Kernel Density Estimation&quot;, <br>    fontsize = 30)                            #title<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*hbI-1l8udpSI_DM2MoiE_Q.png" /></figure><pre># Descriptive stats<br>df[&#39;word_count&#39;].describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*gVufgXxLjRIexLCxgK8p6Q.png" /></figure><p>Word counts follow a normal distribution with a few outlier firms that report almost 2,000 words. The average firm reports around 621 words, and the interquartile range is from 415 to 725 words.</p><h3>4. Pre-processing</h3><p>A series of preprocessing steps will help us better analyze the data. I am going to implement the following steps:</p><ol><li>Convert all words to lower cases</li><li>Remove punctuations and numbers</li><li>Tokenize texts to words so that machines can work with them.</li><li>Remove stop words: There are many libraries of stop words we can import. However, because we want to make sure that we are not removing any important words, we are going to create my own list of stop words. To do so, I had to come back to this step repeatedly to add more stop words.</li><li>Lemmatization: It refers to replacing a word with its most basic form.</li></ol><h4>4.1. Preparation</h4><pre># Import Libraries<br>import string<br>import nltk<br>from nltk.tokenize import word_tokenize<br>from nltk.stem import WordNetLemmatizer<br>nltk.download(&#39;punkt&#39;)   # Required for tokenization<br>nltk.download(&#39;wordnet&#39;) # Required for lemmatization</pre><pre># Instantiate<br>lemmatizer = WordNetLemmatizer()</pre><pre># Create our own stop words<br>stop_words = (                                        \<br>    &quot;\n ’ the company and of for in to a or years l   \<br>    other were that ended we at with our included s   \<br>    firm follows under consolidated have these over   \<br>    include billion million december which an le from \<br>    certain le — million had show apple including     \<br>    as noncurrent current total three are on not is   \<br>    involving millions shows centers contains      &quot;  \<br>             ).split()</pre><pre># Exclusion list of punctuations and numbers<br>exclist = string.punctuation + string.digits</pre><pre># Print the exclusion list<br>print(exclist)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*fzrv2-8jbcknOdKpdRzHtg.png" /></figure><p>The above punctuations and numbers will be excluded.</p><h4>4.2. Implement pre-processing</h4><pre># Create a Function<br>def clean_texts(text):<br>    &quot;&quot;&quot; Function to perform preprocessing &quot;&quot;&quot;<br>    <br>    # Convert to lower cases<br>    text = text.lower()<br>    <br>    # Remove punctuations and numbers<br>    text = text.translate(str.maketrans(&quot;&quot;, &quot;&quot;, exclist))<br>    <br>    # Replace certain words<br>    text = text.replace(&quot;leased&quot;, &quot;lease&quot;)<br>    <br>    # Tokenization<br>    tokens = word_tokenize(text)<br>        <br>    # Lemmatization<br>    tokens = [lemmatizer.lemmatize(token) for token in tokens]<br>    <br>    # Remove stop words<br>    tokens = [token for token in tokens if token not in stop_words]<br>    <br>    # Join tokens<br>    clean_text = &quot; &quot;.join(tokens)<br>    <br>    # Return the output<br>    return clean_text</pre><pre># Apply the function to all disclosures<br>df[&#39;LeaseFootnote&#39;] = df[&#39;LeaseFootnote&#39;].apply(clean_texts)</pre><pre># View the first 5 rows<br>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*juhd-6zsri8NNISinZvbQQ.png" /></figure><h3>5. Extract keywords</h3><p>Now that we have clean disclosures, we can extract keywords.</p><h4>5.1. Word Clouds</h4><p>One way to extract keywords is to examine words that are used most frequently by generating word clouds.</p><pre># Import library<br>from wordcloud import WordCloud<br>from collections import Counter</pre><pre># Instantiate Word Cloud<br>wc = WordCloud(width=2400,<br>               height=1500,<br>               min_font_size=10,<br>               background_color=&#39;white&#39;)</pre><pre># Generate a word cloud<br>plt.figure(figsize = (24, 6))<br>lease_wc = wc.generate(df[&#39;LeaseFootnote&#39;].str.cat(sep=&quot; &quot;))<br>plt.xticks([])<br>plt.yticks([])<br>plt.imshow(lease_wc);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*Aol6VkmCACEKyeur9y1Gzg.png" /></figure><p>Several observations:</p><ol><li>Companies discuss operating leases more often than finance leases.</li><li>Similarly, they discuss lease liabilities more often than ROU assets (i.e., lease assets).</li><li>Some other subtopics include the following</li></ol><ul><li>“lease cost” and “lease expense”, which are synonyms</li><li>“future minimum”, “remaining lease”, “lease payments”, “present value”, “borrowing rate” (lease liabilities are determined by the taking the present value of remaining future minimum lease payments where borrowing rate is used for the present value computation)</li><li>“weighted average” and “lease term”</li></ul><p>From this word cloud, it is very clear what type of information is disclosed.</p><h4>5.2. Word Count Bar Plots</h4><p>The second way to extract keywords is to plot the most popular words. While the word cloud focused more on two-word groups, the bar chart examines the frequency of each word.</p><pre># Bar plot - Create a corpus of disclosures<br>corpus = []<br>for disclosures in df[&#39;LeaseFootnote&#39;].tolist():<br>    for word in disclosures.split():<br>        corpus.append(word)</pre><pre># Bar plot - Create a dataframe of the most common 30 words<br>common_words = pd.DataFrame(Counter(corpus).most_common(20))<br>common_words.columns = (&#39;Word&#39;, &#39;Count&#39;)</pre><pre># Plot a bar chart of the most common 20 words<br>sns.set(font_scale = 1.5)<br>sns.barplot(x= common_words[&#39;Word&#39;], y=common_words[&#39;Count&#39;])<br>plt.xticks(rotation=&#39;vertical&#39;)</pre><pre>plt.title(&quot;Key Word Count&quot;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*-VvD-beRxz01z8XolONBcw.png" /></figure><p>Similar to the word cloud, we can infer that companies discuss the following topics (in the order of frequency):</p><ul><li>operating lease</li><li>lease liabilities</li><li>lease assets</li><li>operating lease payments</li><li>remaining lease term</li><li>operating lease cost, operating lease expense</li><li>discount rate</li></ul><h4>5.3. TF-IDF</h4><p>TF-IDF is short for term frequency-inverse document frequency. It increases with the frequency of a word in a document and decreases with the number of documents that contain the word. Put differently, it adjusts for the fact that some words appear more frequently in general.</p><pre># Import library<br>from sklearn.feature_extraction.text import TfidfVectorizer</pre><pre># Instantiate<br>vectorizer = TfidfVectorizer()</pre><pre># Fit the data<br>tfidf = vectorizer.fit_transform(df[&#39;LeaseFootnote&#39;])</pre><pre># Create a dataframe of TFIDF<br>tfidf_df = pd.DataFrame(tfidf[0].T.todense(), <br>                      index=vectorizer.get_feature_names_out(), <br>                      columns=[&quot;TF-IDF&quot;])</pre><pre># Sort<br>tfidf_df = tfidf_df.sort_values(&#39;TF-IDF&#39;, ascending=False)</pre><pre># Bar Plot<br>tfidf_df[:20].plot.bar(title=&quot;Top 30 TF-IDF Words&quot;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*1OOIgO_RsyzxDdWd9_D9zw.png" /></figure><p>Notice that the ranks of words that appear in most of the disclosures (e.g., “operating”) went down a lot. But for some words like “leases”, we still have high TF-IDF values because they simply appear a lot. Some interesting keywords that showed up are “retail” and “facility”. We can infer that companies that have many retail spaces and facilities tend to disclose extensively about them. This makes sense because firms that rent real estate spend a significant amount on related expenses.</p><h4>5.4. KeyBERT</h4><p><a href="https://github.com/MaartenGr/KeyBERT">KeyBERT</a> is a keyword extraction technique that leverages BERT embeddings. It finds sub-phrases in a document that has the highest cosine similarity to the document itself. More specifically, it implements the following three steps.</p><ol><li>Extract document embeddings with BERT</li><li>Extract word embeddings for N-gram words or phrases.</li><li>Find the words/phrases that have the highest cosign similarity to the document</li></ol><pre># Import library<br>from keybert import KeyBERT</pre><pre># Instantiate<br>kw_model = KeyBERT()</pre><pre># Extract keywords<br>keywords = df[&#39;LeaseFootnote&#39;].apply(kw_model.extract_keywords)</pre><pre># Print the keywords in the first two disclosures<br>print(keywords[0])<br>print(keywords[1])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*-GLXAfsr-G1FXxBkTPVHsg.png" /></figure><p>The output is in a nested list format. For each corpus, the function outputs the top 5 keywords that have the highest cosine similarity to its original corpus.</p><p>One way to use this is to extract keywords from the above KeyBERT output (the first half of the code below) and create a bar chart of the most frequent words that appear in them (the last half of the code below).</p><pre># Extract keywords from the KeyBERT output<br>text = []<br>for list in keywords:<br>    for component in list:<br>        text.append(str(component[0]))</pre><pre># Bar plot - Create a dataframe of the most common 20 words<br>common_words = pd.DataFrame(Counter(text).most_common(20))<br>common_words.columns = (&#39;Word&#39;, &#39;Count&#39;)</pre><pre># Plot a bar chart of the most common 20 words<br>sns.barplot(x= common_words[&#39;Word&#39;], y=common_words[&#39;Count&#39;])<br>plt.xticks(rotation=&#39;vertical&#39;)<br>plt.title(&quot;KeyBERT Top 20 &quot;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*MpxQcP9WDhzoSccbA3fDlw.png" /></figure><p>We see that some new words appeared in the KeyBERT output. Below summarizes them and in what context they appear.</p><ul><li>Rental: we can consider this as synonyms for lease since many companies use them interchangeably.</li><li>Contractual: companies use this term as in “contractual lease term” so we can infer that companies disclose lease terms.</li><li>Accrued: operating lease liabilities are often disclosed in balance sheets as accrued liabilities. Thus, this shows that companies explain how operating lease amounts are disclosed.</li><li>Renewal and contract: Companies discuss renewal terms in their contract.</li></ul><p>As we can see from the above, KeyBERT catches many disclosures about contracts. This is a very important and different insight!</p><h4>5.5. YAKE!</h4><p><a href="https://repositorio.inesctec.pt/server/api/core/bitstreams/ef121a01-a0a6-4be8-945d-3324a58fc944/content">YAKE!</a> stands for Yet Another Keyword Extraction. According to the authors who first introduced this method, one of the advantages of this technique is speed as it takes an unsupervised approach.</p><pre># Import library<br>import yake</pre><pre># Instantiate (set n-word groupings hyperparameters to 2)<br>kw_extractor = yake.KeywordExtractor(n=2)</pre><pre># Extract keywords and scores from each disclosure<br>keywords = df[&#39;LeaseFootnote&#39;].apply(kw_extractor.extract_keywords)</pre><pre># Extract scores from the YAKE output<br>text = []<br>for list in keywords:<br>    for component in list:<br>        text.append(str(component[0]))<br>        <br># Bar plot - Create a dataframe of the most common 20 words<br>common_words = pd.DataFrame(Counter(text).most_common(20))<br>common_words.columns = (&#39;Word&#39;, &#39;Count&#39;)</pre><pre># Plot a bar chart of the most common 20 words<br>sns.barplot(x= common_words[&#39;Word&#39;], y=common_words[&#39;Count&#39;])<br>plt.xticks(rotation=&#39;vertical&#39;)<br>plt.title(&quot;Key Word Count&quot;, fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*HxuXlO6Opbr89iAT7cLOqw.png" /></figure><p>We see many overlaps of keywords, especially with ones from the Word Cloud. Thus, the inferences here are the same as before.</p><h3>6. Inferences</h3><p>To summarize, leasing disclosures contain</p><ul><li>operating lease amounts (more often than finance lease amounts)</li><li>lease liabilities (more often than lease assets)</li><li>annual lease expenses</li><li>various components that go into computing lease amounts</li><li>weighted average lease term</li><li>real estate leasees disclose heavily about retail space and facility leases</li><li>discussion about lease contracts</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9c4a6e0a267" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Predict a Firm’s Disclosure Choice Using Machine Learning Classifiers]]></title>
            <link>https://medium.com/@y.s.yoon/predict-a-firms-disclosure-choice-using-machine-learning-classifiers-b03f56e400d6?source=rss-38a240a7297d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b03f56e400d6</guid>
            <dc:creator><![CDATA[Young Yoon]]></dc:creator>
            <pubDate>Mon, 11 Apr 2022 22:26:25 GMT</pubDate>
            <atom:updated>2022-04-24T00:52:42.118Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*80PqMokCx0ID9ZFEeB_59A.gif" /></figure><h3>Outline and Introduction</h3><p>In this post, I explain how we can build and evaluate supervised machine learning classifiers in Python.</p><p>The outline of this post is summarized as follows:</p><ul><li>Build classification models using Logistic Regression, Naive Bayes, K-Nearest Neighbors, Support Vector Machine, Random Forest, and AdaBoost</li><li>Tune hyperparameters using the Grid Search method</li><li>Evaluate the models and select the best model using precision, recall, and AUC</li></ul><p>As a working example, I will explain how we can predict whether an IPO firm chooses to reduce its pre-IPO disclosures using its firm characteristics. I use these predictions in the first chapter of my UC Berkeley Haas dissertation (<a href="https://sites.google.com/view/young-yoon-brief-abstracts/home">link</a>). Nonetheless, it can be generalized and used to solve many other classification and prediction problems. By the way, a part of the first chapter is co-authored with my UC Berkeley PhD advisors and is published in the Critical Finance Review (a top 4 finance journal). Be sure to check the publication <a href="https://cfr.pub/forthcoming/papers/eventov2021jobs.pdf">here</a>.</p><p>If you have any comments or suggestions, email me at <a href="/service/mailto:y.s.yoon@berkeley.edu">y.s.yoon@berkeley.edu</a>. Enjoy reading the rest of the post!</p><h3>Background and Problem Statement</h3><p>In 2012, the JOBS Act allowed IPO firms to reduce their financial disclosures before going public. In the first chapter of my dissertation, I examine the economic consequences of this Act and find that firms that choose to disclose less (hereafter “reduced-disclosure firms”) become more overpriced. To explain the channel, I examine whether the reduction in disclosure requirement is the driver of overpricing or whether certain types of IPOs that are known to be overpriced went public after the JOBS Act.</p><p>The purpose of this post is to test the channel. To do so, we will examine whether firms’ choices to disclose less can be predicted using their firm characteristics. If we can indeed predict their choices, then we can rule out one of the two possibilities that the reduction in disclosure requirement caused IPOs to become more overpriced.</p><h3>Analysis</h3><p>Let’s dive right into the analysis.</p><h3>1. Data</h3><p>The data “EGC_Post.csv” contains IPOs from April 5, 2012 (i.e., after the JOBS Act) to 2015. The sample only includes Emerging Growth Companies (EGCs), IPOs with revenues below $1B, because they are the only ones that are allowed to reduce financial disclosures.</p><h3>1.1. Variable Definition</h3><ul><li><em>gvkey</em>: firm identifier</li><li><em>IPOYear</em>: year of the IPO</li><li><em>ReducedDisclosure</em>: target class; 1 if reduced financial disclosure; 0 otherwise</li><li><em>LogAge</em>: Natural logarithm of firm age</li><li><em>LogAsset</em>: Natural logarithm of the dollar amount of total assets</li><li><em>LogOnePlusRevt</em>: Natural logarithm of one plus revenues</li><li><em>LogProceeds</em>: Natural logarithm of total dollar gross proceeds</li><li><em>PercentSharesRetained</em>: Fraction of shares outstanding in the company that is retained by pre-IPO shareholders</li><li><em>OfferPriceRevision</em>: Percentage change in offer price from the midpoint of the preliminary offer price range</li><li><em>LogDaysInRegistration</em>: Natural logarithm of the number of days between the S-1 filing date and the IPO date</li><li><em>ReturnOnAssets</em>: Net income divided by total assets</li><li><em>RD</em>: R&amp;D expense divided by total assets</li><li><em>CapitalExpenditures</em>: Capital expenditure divided by total assets</li><li><em>NegativeROA</em>: An indicator variable that = 1 if the company reports negative net income</li><li><em>NegativeBVE</em>: An indicator variable that = 1 if the company reports negative book value of equity</li><li><em>PositiveRD</em>: An indicator variable that = 1 if the company reports positive R&amp;D expense</li><li><em>VentureBacked</em>: An indicator variable = 1 if the issuer has venture-capital backing</li><li><em>TechIndustry</em>: An indicator variable = 1 if the issuer is in the Internet Software &amp; Services industry (GICS Code 451010) or the Software industry (GICS Code 451030)</li><li><em>BiotechPharmaIndustry</em>: An indicator variable = 1 if the issuer is in the Biotechnology industry (GICS Code 352010) or the Pharmaceutical industry (GICS Code 352020)</li><li><em>Nasdaq</em>: An indicator variable = 1 if the issuer is listed on NASDAQ</li><li><em>NYSE</em>: An indicator variable = 1 if the issuer is listed on NYSE</li><li><em>Underwriters</em>: An indicator variable that = 1 if Loughran and Ritter’s (2004) IPO underwriter rank score is = 9</li><li><em>Big4</em>: An indicator variable = 1 if the issuer is audited by Deloitte, Ernest &amp; Young, KPMG, or PwC</li><li><em>NIPO</em>: Number of IPOs in registration in the 90 days prior to the IPO.</li><li><em>NasdaqPrior90Ret</em>: Average buy-and-hold return of all NASDAQ-traded stocks during the 90 days prior to the IPO</li></ul><h3>2. Implementation of Predicting Reduced-Disclosure Firms</h3><h3>2.1. Preparation</h3><h4>2.1.1. Import libraries</h4><pre>import numpy as np<br>import pandas as pd<br>import matplotlib.pyplot as plt<br>import seaborn as sns</pre><h4>2.1.2. Read the CSV File</h4><pre>disclosure_df = pd.read_csv(&quot;EGC_Post.csv&quot;)</pre><h3>2.2. Exploratory Data Analysis (EDA)</h3><h4>2.2.1. Explore the dataframe</h4><pre># View the first 5 entries<br>disclosure_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*RZgIM8zGCwCjO6afjWErqQ.png" /></figure><p>We have firm identifiers (gvkey), the outcome variable we want to predict (ReducedDisclosure), and many firm characteristics.</p><pre># View info<br>disclosure_df.info()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*-Lu-K4JTS1pODReoDH-tFg.png" /></figure><p>Two things are worth noting. All the variables have non-missing data since I already cleaned them. Also, all of them have numeric values.</p><h4>2.2.2. Visualize firm characteristics</h4><pre># Plot histograms<br>disclosure_df.hist(figsize = (20,20))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*BVU_9LIrTc2Avt76sFKrJA.png" /></figure><p>Based on the histogram above, we see that there are both continuous variables and indicator variables (i.e., 0/1 binary) and that there are no outliers.</p><h4>2.2.3. Correlation Matrix</h4><pre># Tabulate the Correlation Matrix<br>corr_matrix = disclosure_df.corr()<br>plt.figure(figsize = (15, 15))<br>plt.rcParams[&#39;font.size&#39;] = 12<br>sns.heatmap(corr_matrix, annot = True, fmt = &#39;.2f&#39;)<br>plt.title(&quot;Correlation Matrix of IPO Firm Characteristics&quot;,<br>          fontsize = 20)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*uyD2lbs9Yg7eIuTkURyKAA.png" /></figure><p>The variable of interest in <em>ReducedDisclosure</em>. We see that there are many variables that are correlated with this variable. For example, we see that <em>LogOnePlusRevt</em>, <em>ReturnOnAssets</em>, and <em>TechIndustry</em> are negatively correlated with <em>ReducedDisclosure</em>.</p><h4>2.2.4. Feature Importances</h4><p>Using a forest of trees, we can evaluate the importance of features based on a mean decrease in impurity. See <a href="https://scikit-learn.org/stable/auto_examples/ensemble/plot_forest_importances.html">here</a> for details.</p><pre># Import liabrary<br>from sklearn.ensemble import RandomForestClassifier</pre><pre># Prepare the features and label<br>X = disclosure_df.drop([&quot;gvkey&quot;, &quot;ReducedDisclosure&quot;], <br>                       axis = &quot;columns&quot;)<br>y = disclosure_df[&quot;ReducedDisclosure&quot;]</pre><pre># Fit the data using Random Forest<br>rf = RandomForestClassifier(random_state=0)<br>rf.fit(X, y)</pre><pre># Extract feature importances and their standard deviations<br>importances = rf.feature_importances_<br>std = np.std([tree.feature_importances_ <br>              for tree in rf.estimators_], axis=0)</pre><pre># Prepare the data before plotting<br>forest_importances = pd.Series(importances, index=X.columns,<br>            name = &quot;importances&quot;).sort_values(ascending=False)</pre><pre># Plot<br>fig, ax = plt.subplots()<br>plt.rcParams[&#39;font.size&#39;] = 14<br>forest_importances.plot.bar(yerr=std, ax=ax, figsize = (15,4))<br>ax.set_title(&quot;Feature importances using MDI&quot;, fontsize=20)<br>ax.set_ylabel(&quot;Mean decrease in impurity&quot;, fontsize=15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*UtGxuBcqhR92h8mKcaffdA.png" /></figure><p>Consistent with the correlation matrix, the above box plots based on the mean decrease in impurity show that <em>LogOnePlusRevt</em> and <em>ReturnOnAssets</em> are the two most important features.</p><p>If my prediction models do not perform well, I am going to select some features by dropping firm characteristics that are not important in the prediction process.</p><h4>2.2.5. Kernel Density Estimation</h4><p>To further visualize the importance of <em>LogOnePlusRevt</em> and <em>ReturnOnAssets</em>, I will conduct kernel density plots separately for reduced-disclosure firms and other firms.</p><pre># Create a function that performs Kernel Density Estimation<br>def kdeplots(var, dataframe):<br>    &quot;&quot;&quot; <br>    Plot KDE separately for ReducedDisclosure and others<br>    &quot;&quot;&quot;<br>    <br>    # Define the figure size<br>    fig = plt.figure(figsize=(15, 4))<br>    <br>    # Generate a scatter plot<br>    ax = sns.kdeplot(dataframe[var] <br>         [(dataframe[&quot;ReducedDisclosure&quot;] == 0)],<br>         color = &quot;Red&quot;, shade = True)<br>    ax = sns.kdeplot(dataframe[var]<br>         [(dataframe[&quot;ReducedDisclosure&quot;] == 1)],<br>         color = &quot;Blue&quot;, shade = True)<br>   <br>    # Layout<br>    ax.legend([&quot;Reduced-Disclosure Firms&quot;,<br>               &quot;non-Reduced-Disclosure Firms&quot;],<br>              loc = &quot;upper right&quot;)<br>    ax.set_ylabel(&quot;Density&quot;, fontsize = 15)<br>    ax.set_xlabel(var, fontsize = 15)<br>    ax.set_title(&quot;Distiribution of {}&quot;.format(var), fontsize=20)</pre><pre># Plot KDEs for LogOnePlusRevt<br>kdeplots(&quot;LogOnePlusRevt&quot;, disclosure_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*PBau1aTHqDMRQiScuWvarw.png" /></figure><pre># Plot KDEs for LogOnePlusRevt<br>kdeplots(&quot;LogAsset&quot;, disclosure_df)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*BxFFlHjKk3wJMVUYYmYzZA.png" /></figure><p>Both figures confirm that firms with more revenues and assets tend to disclose less.</p><h3>2.3. Prediction</h3><p>Now that we have a better understanding of the data and feature importance, we can build classifier models and predict a firm’s choice to disclose less.</p><h4>2.3.1. Preparation</h4><pre># Prepare features (X) and label (y)<br>X = disclosure_df.drop([&quot;gvkey&quot;, &quot;ReducedDisclosure&quot;],<br>                       axis = &quot;columns&quot;)<br>y = disclosure_df[&quot;ReducedDisclosure&quot;]</pre><pre># View the shapes of X and y<br>X.shape, y.shape</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*moWQqFQ1vDxqb_FugfZn1Q.png" /></figure><pre># Import library<br>from sklearn.model_selection import train_test_split</pre><pre># Split the samples into train and test sets<br>X_train, X_test, y_train, y_test = \<br>train_test_split(X, y, test_size = 0.2, random_state=1)</pre><pre># View the shapes of all dataframes<br>X_train.shape, X_test.shape, y_train.shape, y_test.shape<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*JZTx6lKx0bvom_F20Z2x5w.png" /></figure><p>We will start with Logistic Regression to build a model and predict firms’ choices. The Python code is fairly simple:</p><pre># Import library<br>from sklearn.linear_model import LogisticRegression</pre><pre># Instantiate and fit the model <br>model_lr = LogisticRegression(max_iter=10000)<br>model_lr.fit(X_train, y_train)</pre><pre># Predict the classification<br>y_predict = model_lr.predict(X_test)</pre><p>Now that we have predictions, let’s evaluate the model using a Confusion Matrix as well as Precision &amp; Recall scores. Since I am going to build Confusion Matrices repeatedly, I will write a function.</p><pre># Import library<br>from sklearn.metrics import classification_report, confusion_matrix, precision_score, recall_score</pre><pre># Create a function to tabulate Confusion Matrix<br>def cm_function(matrix_input, y_test_input, title):<br>    &#39;&#39;&#39; Function to plot Confusion Matrix &#39;&#39;&#39;<br>    <br>    # Gather values and labels that will be used in the matrix<br>    group_names = [&#39;True Negative&#39;,&#39;False Positive&#39;,<br>          &#39;False Negative&#39;,&#39;True Positive&#39;]<br>    group_counts = [&quot;{0:0.0f}&quot;.format(value) for value <br>          in matrix_input.flatten()]<br>    group_percentages = [&quot;({0:0.0%})&quot;.format(value) <br>          for value in matrix_input.flatten()/y_test_input.count()]<br>    <br>    # Create 4 texts that will be shown in each box of the matrix<br>    labels = [f&quot;{v1}\n{v2}\n{v3}&quot; for v1, v2, v3 in<br>              zip(group_names, group_counts, group_percentages)]<br>    labels = np.asarray(labels).reshape(2,2)<br>    <br>    # Plot the matrix and adjust the format<br>    sns.set(font_scale = 1.2)<br>    fig = sns.heatmap(matrix_input, fmt=&#39;&#39;, annot = labels)<br>    plt.title(title, fontsize=20)<br>    plt.xlabel(&quot;Prediction&quot;, fontsize = 15)<br>    plt.ylabel(&quot;True Class&quot;, fontsize = 15) <br>    plt.show()</pre><pre># Process and tabulate the Confusion Matrix<br>cm = confusion_matrix(y_test, y_predict)<br>cm_function(cm, y_test, <br>            &quot;Confusion Matrix for the Logistic Regression Model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*jxKOFGVoeOhFS2jWh1AcBw.png" /></figure><pre># Store precision and recall scores for later use<br>precision_score_lr = precision_score(y_test, y_predict)<br>recall_score_lr = recall_score(y_test, y_predict)</pre><pre># Report accuracy, precision, and recall<br>print(classification_report(y_test, y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*xlaXcACqgCzMy-1oQ7Dguw.png" /></figure><p>The Logistic Regression model has an accuracy of 0.83, a precision of 0.88, and a recall of 0.68, which are pretty good values!</p><h4>2.3.3. Naive Bayes Classifier</h4><p>Next, we will build another model and predict using Naive Bayes. We are going to use Gaussian Naive Bayes Classifier for continuous variables because as shown in the above histogram, we see that most continuous variables follow a normal distribution.</p><pre># Import library<br>from sklearn.naive_bayes import GaussianNB</pre><pre># Instantiate and fit the model <br>model_nb = GaussianNB()<br>model_nb.fit(X_train, y_train)</pre><pre># Predict the classification<br>y_predict = model_nb.predict(X_test)</pre><p>Evaluate the model using a Confusion Matrix as well as Precision &amp; Recall scores.</p><pre># Process and tabulate the Confusion Matrix<br>cm = confusion_matrix(y_test, y_predict)<br>cm_function(cm, y_test, <br>            &quot;Confusion Matrix for the Naive Bayes Classifier Model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*fTGjEMesZ2wzWDsUZYJN0A.png" /></figure><pre># Store precision and recall scores for later use<br>precision_score_nb = precision_score(y_test, y_predict)<br>recall_score_nb = recall_score(y_test, y_predict)</pre><pre># Report accuracy, precision, and recall<br>print(classification_report(y_test, y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*i-_uU-SAvUkFgYqc0uVTTw.png" /></figure><p>The Naive Bayes model also has an accuracy of 0.83, a precision of 0.86, and a recall of 0.74, which are, once again, pretty good values!</p><h4>2.3.4. K-Nearest Neighbors</h4><p>Because KNN uses Euclidean distances, we first have to standardize the features.</p><pre># Import library<br>from sklearn import preprocessing</pre><pre># Standardize X_train and X_test<br>X_train_std = preprocessing.StandardScaler().fit_transform(X_train)<br>X_test_std = preprocessing.StandardScaler().fit_transform(X_test)</pre><p>For K-Nearest Neighbors, we have to select K. We will select it based on a figure of error rates. Another popular method to choose K is using the Grid Search method. However, because I prefer to show figures whenever possible, I will go with the figure approach.</p><pre># Import library<br>from sklearn.neighbors import KNeighborsClassifier<br>    <br># For each K from 1 to 40, we will compute the error rate<br>error_rate = []<br>for i in range(1,41):<br> model_knn = KNeighborsClassifier(n_neighbors=i)<br> model_knn.fit(X_train_std,y_train)<br> pred_i = model_knn.predict(X_test_std)<br> error_rate.append(np.mean(pred_i != y_test))</pre><pre># Plot the error rate against K Values<br>plt.figure(figsize=(10,6))<br>plt.plot(range(1,41), error_rate, color=&#39;blue&#39;, linestyle=&#39;dashed&#39;, <br>         marker=&#39;o&#39;,markerfacecolor=&#39;red&#39;, markersize=10)<br>plt.title(&#39;Error Rate vs. K Value&#39;, fontsize = 20)<br>plt.xlabel(&#39;K&#39;, fontsize = 15)<br>plt.ylabel(&#39;Error Rate&#39;, fontsize = 15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*neYe-FQ-3kxf4JmTWnOvVg.png" /></figure><pre># Print the K with the minimum error rate<br>print(&quot;Minimum error:-&quot;,min(error_rate),<br>      &quot;at K =&quot;,error_rate.index(min(error_rate))+1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*CaiIu7bPzWENM4TRVdZbZw.png" /></figure><p>As shown in the figure above, most values &gt;= 16 have the minimum error rates. Thus, we will select K=16.</p><pre># Instantiate and fit the model <br>model_knn = KNeighborsClassifier(n_neighbors=16)<br>model_knn.fit(X_train_std,y_train)</pre><pre># Predict the classification<br>y_predict = model_knn.predict(X_test_std)</pre><p>Evaluate the model using a Confusion Matrix as well as Precision &amp; Recall scores.</p><pre># Process and tabulate the Confusion Matrix<br>cm = confusion_matrix(y_test, y_predict)<br>cm_function(cm, y_test, <br>            &quot;Confusion Matrix for the K-Nearest Neighbors Model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*42bG3rsMEMuW1lqZFWqAGQ.png" /></figure><pre># Store precision and recall scores for later use<br>precision_score_knn = precision_score(y_test, y_predict)<br>recall_score_knn = recall_score(y_test, y_predict)</pre><pre># Report accuracy, precision, and recall<br>print(classification_report(y_test, y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*WR7ogFu1Fy0lJRu7atmNMg.png" /></figure><p>The K-Nearest Neighbor model has accuracy, precision, and recall values that are similar to other models.</p><h4>2.3.5. Support Vector Machine — Grid Search Cross Validation</h4><p>Before using the Support Vector Machine, there are two important hyperparameters we need to consider: which gamma and C values to use. Check out <a href="https://towardsdatascience.com/hyperparameter-tuning-for-support-vector-machines-c-and-gamma-parameters-6a5097416167">this blog</a>, which summarizes them very well.</p><ol><li>C parameter: Penalty for each misclassified data point (default 1.0)</li><li>gamma: Hyperparameter used only for Gaussian RBF kernel; determines the range of each training eaxample reaches (default: 1 / (n_features * X.var()))</li></ol><pre># Import libraries<br>from sklearn.svm import SVC<br>from sklearn.model_selection import GridSearchCV<br> <br># Define the hyperparameters<br>param_grid = {&#39;C&#39;: [0.1, 1, 10, 100, 1000],<br>              &#39;gamma&#39;: [1, 0.1, 0.01, 0.001, 0.0001],<br>              &#39;kernel&#39;: [&#39;rbf&#39;]}</pre><pre># Instantiate GridSearchCV<br># use 5-fold cv and f1 score to choose the best model<br>gs_svm = GridSearchCV(SVC(probability=True), <br>                      param_grid = param_grid, cv=5, scoring=&#39;f1&#39;)</pre><pre># Fit the model<br>gs_svm.fit(X_train , y_train)</pre><pre># Predict the classification<br>y_predict = gs_svm.predict(X_test)</pre><pre># Print the best parameters<br>print(gs_svm.best_params_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*AHTA4A9Joo76ZgCT-kaCCA.png" /></figure><p>The model with the highest f1 score has the {‘C’: 100, ‘gamma’: 0.001, ‘kernel’: ‘rbf’} hyperparameters.</p><p>Next, we will evaluate the model using a Confusion Matrix as well as Precision &amp; Recall scores.</p><pre># Process and tabulate the Confusion Matrix<br>cm = confusion_matrix(y_test, y_predict)<br>cm_function(cm, y_test, &quot;Confusion Matrix for the SVM Model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/557/1*GM0NFMh_74gkYUyINC1wvQ.png" /></figure><pre># Store precision and recall scores for later use<br>precision_score_svm = precision_score(y_test, y_predict)<br>recall_score_svm = recall_score(y_test, y_predict)</pre><pre># Report accuracy, precision, and recall<br>print(classification_report(y_test, y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*-9gcp0qQzSYRu20Uul6MzA.png" /></figure><p>The best SVM model has accuracy, precision, and recall values that are similar to other models.</p><h4>2.3.6. Random Forest — Grid Search Cross Validation</h4><p>There are many important hyperparameters we need to consider before using the Random Forest algorithm.</p><p>Important ones are summarized below (we have to consider the bias-variance tradeoff for each):</p><ol><li>N_estimators: The number of decision trees used in the forest (default = 100); having too few trees may lead to overfitting since it becomes closers to a single decision tree</li><li>Max_depth: The maximum depth of the tree (default = none, meaning that trees are branched until all leaves are pure); by going too deep, we face a risk of overfitting</li><li>Min_samples_split: The minimum number of samples required to branch further (default 2); we can lower the risk of overfitting by increasing the minimum sample requirement</li></ol><pre># Import libraries<br>from sklearn.ensemble import RandomForestClassifier</pre><pre># Define the hyperparameters<br>param_grid = {<br>    &#39;n_estimators&#39;: [100, 150, 200],<br>    &#39;max_depth&#39;: [None, 1, 5, 10, 15],<br>    &#39;min_samples_split&#39;: [2, 5, 10]<br>}</pre><pre># Instantiate GridSearchCV<br>gs_rf = GridSearchCV(RandomForestClassifier(), <br>                     param_grid = param_grid, cv=5, scoring=&#39;f1&#39;)</pre><pre># Fit the model<br>gs_rf.fit(X_train , y_train)</pre><pre># Predict the classification<br>y_predict = gs_rf.predict(X_test)</pre><pre># Print the best parameters<br>print(gs_rf.best_params_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*ed74t2pdUhRKBEXQ9Imbpg.png" /></figure><p>The model with the highest f1 score has the {‘max_depth’: None, ‘min_samples_split’: 5, ‘n_estimators’: 150} hyperparameters.</p><p>Next, we will evaluate the model using a Confusion Matrix as well as Precision &amp; Recall scores.</p><pre># Process and tabulate the Confusion Matrix<br>cm = confusion_matrix(y_test, y_predict)<br>cm_function(cm, y_test, <br>            &quot;Confusion Matrix for the Random Forest Model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*t20MMbu2C4_R9V0RcaTZ2w.png" /></figure><pre># Store precision and recall scores for later use<br>precision_score_rf = precision_score(y_test, y_predict)<br>recall_score_rf = recall_score(y_test, y_predict)</pre><pre># Report accuracy, precision, and recall<br>print(classification_report(y_test, y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/626/1*94u4ablo0j40UCukS1qhNg.png" /></figure><p>The best Random Forest model has accuracy, precision, and recall values that are similar to other models.</p><h4>2.3.7. Ada Boost — Grid Search Cross Validation</h4><p>Ada Boost also has several hyperparameters to consider.</p><p>Important ones are summarized below (we have to consider the bias-variance tradeoff for each):</p><ol><li>N_estimators: The number of decision trees used in the ensemble (default = 50)</li><li>Learning_rate: The rate at which each model contributes to the prediction (default 1.0, i.e., full contribution)</li></ol><pre># Import libraries<br>from sklearn.ensemble import AdaBoostClassifier</pre><pre># Define the hyperparameters<br>param_grid = {<br>    &#39;n_estimators&#39;: [50, 100, 200],<br>    &#39;learning_rate&#39;: [0.8, 1, 1.2]<br>}</pre><pre># Instantiate GridSearchCV <br>gs_ab = GridSearchCV(AdaBoostClassifier(), <br>                     param_grid = param_grid, cv=5, scoring=&#39;f1&#39;)</pre><pre># Fit the model<br>gs_ab.fit(X_train , y_train)</pre><pre># Predict the classification<br>y_predict = gs_ab.predict(X_test)</pre><pre># Print the best parameters<br>print(gs_ab.best_params_)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*aFbmRcL3GEK9QAGJ7tmJEw.png" /></figure><p>The model with the highest f1 score has the {‘learning_rate’: 0.8, ‘n_estimators’: 50} hyperparameters.</p><p>Next, we will evaluate the model using a Confusion Matrix as well as Precision &amp; Recall scores.</p><pre># Process and tabulate the Confusion Matrix<br>cm = confusion_matrix(y_test, y_predict)<br>cm_function(cm, y_test, &quot;Confusion Matrix for the AdaBoost Model&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*vIcXKfvCzV8p_pptEhnnjg.png" /></figure><pre># Store precision and recall scores for later use<br>precision_score_ab = precision_score(y_test, y_predict)<br>recall_score_ab = recall_score(y_test, y_predict)</pre><pre># Report accuracy, precision, and recall<br>print(classification_report(y_test, y_predict))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/624/1*Lx4LdxGzRLcbze2VyngGeA.png" /></figure><p>The best AdaBoost model also has accuracy, precision, and recall values that are similar to other models.</p><h3>2.4. Compare the Models’ AUC</h3><h4>2.4.1. Preparation</h4><p>In this section, I am going to plot Receiver Operating Characteristic (ROC) curves for each model and compute the Area Under the ROC Curve (AUC).</p><p>I am going to start by extracting true and false positive rates and computing AUC Scores.</p><pre># Import library<br>from sklearn.metrics import roc_curve, roc_auc_score</pre><pre># Extract true and false positive rates for each model<br>fpr1, tpr1, thresh1 = roc_curve(<br>    y_test, model_nb.predict_proba(X_test)[:,1], pos_label=1)<br>fpr2, tpr2, thresh2 = roc_curve(<br>    y_test, gs_ab.predict_proba(X_test)[:,1], pos_label=1)<br>fpr3, tpr3, thresh3 = roc_curve(<br>    y_test, gs_rf.predict_proba(X_test)[:,1], pos_label=1)<br>fpr4, tpr4, thresh4 = roc_curve(<br>    y_test, model_lr.predict_proba(X_test)[:,1], pos_label=1)<br>fpr5, tpr5, thresh5 = roc_curve(<br>    y_test, gs_svm.predict_proba(X_test)[:,1], pos_label=1)<br>fpr6, tpr6, thresh6 = roc_curve(<br>    y_test, model_knn.predict_proba(X_test)[:,1], pos_label=1)</pre><pre># Compute AUC scores for each model<br>auc_score_nb = roc_auc_score(y_test, <br>                             model_nb.predict_proba(X_test)[:,1])<br>auc_score_ab = roc_auc_score(y_test, <br>                             gs_ab.predict_proba(X_test)[:,1])<br>auc_score_rf = roc_auc_score(y_test, <br>                             gs_rf.predict_proba(X_test)[:,1])<br>auc_score_lr = roc_auc_score(y_test, <br>                             model_lr.predict_proba(X_test)[:,1])<br>auc_score_svm = roc_auc_score(y_test, <br>                              gs_svm.predict_proba(X_test)[:,1])<br>auc_score_knn = roc_auc_score(y_test, <br>                              model_knn.predict_proba(X_test)[:,1])</pre><h4>2.4.2. Plot ROC curves and display AUC scores</h4><pre>plt.figure(figsize=(10,7))<br>plt.title(&#39;Receiver Operating Characteristic (ROC) Curves&#39;, <br>    fontsize = 20)<br>plt.plot(fpr1, tpr1, linestyle = &quot;--&quot;, color = &quot;black&quot;, label = \<br>    &quot;Naive Bayes (AUC %0.2f, Precision %0.2f, Recall %0.2f)&quot;<br>    % (auc_score_nb, precision_score_nb, recall_score_nb))<br>plt.plot(fpr2, tpr2, linestyle = &quot;--&quot;, color = &quot;blue&quot;, label = \<br>    &quot;AdaBoost (AUC %0.2f, Precision %0.2f, Recall %0.2f)&quot; <br>    % (auc_score_ab, precision_score_ab, recall_score_ab))<br>plt.plot(fpr3, tpr3, linestyle = &quot;--&quot;, color = &quot;red&quot;, label = \<br>    &quot;Random Forest (AUC %0.2f, Precision %0.2f, Recall %0.2f)&quot; <br>    % (auc_score_rf, precision_score_rf, recall_score_rf))<br>plt.plot(fpr4, tpr4, linestyle = &quot;--&quot;, color = &quot;green&quot;, label = \<br>    &quot;Logistic Regression (AUC %0.2f, Precision %0.2f, Recall %0.2f)&quot; <br>    % (auc_score_lr, precision_score_lr, recall_score_lr))<br>plt.plot(fpr5, tpr5, linestyle = &quot;--&quot;, color = &quot;orange&quot;, label = \<br>    &quot;SVM (AUC %0.2f, Precision %0.2f, Recall %0.2f)&quot; <br>    % (auc_score_svm, precision_score_svm, recall_score_svm))<br>plt.plot(fpr6, tpr6, linestyle = &quot;--&quot;, color = &quot;gray&quot;, label = \<br>    &quot;K-Nearest Neighbor (AUC %0.2f, Precision %0.2f, Recall %0.2f)&quot; <br>    % (auc_score_knn, precision_score_knn, recall_score_knn))<br>plt.legend(loc = &#39;lower right&#39;)<br>plt.plot([0, 1], [0, 1],linestyle=&#39;--&#39;)<br>plt.ylabel(&#39;True Positive Rate&#39;, fontsize = 15) <br>plt.xlabel(&#39;False Positive Rate&#39;, fontsize = 15)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*8LdRWi1k9KGDDOPYl883dA.png" /></figure><p>The above figure shows that the Naive Bayes model has the highest AUC and one of the highest precision and recall scores. But more importantly, we can see that most models perform really well in modeling firms’ disclosure choices.</p><p>In conclusion, this analysis lends support to the argument that it is not the reduced-disclosure choice per see leading to more prevalent overpricing but rather the characteristics of IPO firms that choose to scale back their financial disclosures.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b03f56e400d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Isolation Forest Anomaly Detection — Identify Outliers]]></title>
            <link>https://medium.com/@y.s.yoon/isolation-forest-anomaly-detection-identify-outliers-101123a9ff63?source=rss-38a240a7297d------2</link>
            <guid isPermaLink="false">https://medium.com/p/101123a9ff63</guid>
            <dc:creator><![CDATA[Young Yoon]]></dc:creator>
            <pubDate>Tue, 08 Mar 2022 06:51:22 GMT</pubDate>
            <atom:updated>2022-05-03T03:49:23.510Z</atom:updated>
            <content:encoded><![CDATA[<h3>Isolation Forest Anomaly Detection — Identify Outliers</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5UGQoBaapqYa-SxGscx7Ow.gif" /></figure><h3>Outline</h3><p>In this blog, I explain and implement Isolation Forest. My goal is to explain using plain English so that non-technical readers can understand the algorithm.</p><p>This post includes the following topics:</p><ul><li>Why and how to look for outliers.</li><li>How Isolation Forest works.</li><li>The benefits and drawbacks of Isolation Forest.</li><li>The implementation of Isolation Forest in Python.</li></ul><p>You can find my code on <a href="https://github.com/youngdataspace/treat-outliers">GitHub</a>. If you have any comments or suggestions, email me at <a href="/service/mailto:y.s.yoon@berkeley.edu">y.s.yoon@berkeley.edu</a>.</p><p>Let’s get started!</p><h3>Introduction</h3><p>I detect outliers using the Isolation Forest method. I use US public firm data, which are also used in my UC Berkeley Haas PhD Dissertation (<a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3689446">Yoon 2022</a>). Although I detect anomalies (outliers) to treat them before I conduct data analyses, the anomaly detection technique can be applied to many business settings, such as detecting fraudulent credit card spending.</p><p>Figure 1 shows US public firms’ features (characteristics) in 2-dimensions. The goal of this notebook is to detect outliers, as shown in red in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*0mZBMfGtJNzDlY8o.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*sfezDADotOCqwkfM.png" /></figure><h3>Why and how to look for outliers</h3><p>Many machine learning algorithms and regression models are susceptible to outliers. An outlier is a data point that significantly deviates from other points. Unless they are properly taken care of, the inferences obtained from statistical models conducted may not be useful.</p><p>There are many popular methods to detect outliers, namely, the Z-Score and Interquartile Range methods. These methods are effective when the underlying data follows a normal distribution (a distribution where most data points are closer to the mean and become less frequent as the distance to the mean increases). However, if the data is not normally distributed, then these methods may incorrectly classify normal observations as outliers. On the other hand, the Isolation Forest method is non-parametric, which simply means that we don’t have to make assumptions about how the underlying data is distributed.</p><p>Furthermore, the Z-Score and Interquartile Range methods identify at the variable level. If you have reason to believe that multiple variables interact with each other and create outliers, these methods will not be able to detect those outliers. For example, an SAT score of 1350/1600 (90th percentile) does not seem to be an outlier by itself. However, if we introduce another dimension, age, and find that a 12-year-old got 1350/1600, then this observation is likely an outlier for a sub-sample of 12-year-olds. Unlike single-variable outlier detection methods, Isolation Forest detects outliers in multi-dimensional space.</p><h3>Isolation Forest</h3><p>Isolation Forest is a tree ensemble method of detecting anomalies first proposed by <a href="https://ieeexplore.ieee.org/abstract/document/4781136?casa_token=A5ZM3TQZHhsAAAAA:DPITalJ8ZZ-5KnuBufXLZkFg6fsICEyyi0vfXmuGejd8gFtAldJ2ZFuS0JUoBAS8GPoF0JG5Kg">Liu, Ting, and Zhou (2008)</a>. Unlike other methods that first try to understand the normal points and classify abnormal points as anomalies, Isolation Forest explicitly isolates anomalies.</p><p>Anomalies have two characteristics. They are distanced from normal points and there are only a few of them. The Isolation Forest algorithm exploits these two characteristics.</p><h4>Plain English</h4><p>Isolation Forest randomly cuts a given sample until a point is isolated. The intuition is that outliers are relatively easy to isolate. Take a look at the following GIF.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eNc-PZX1mFdqhF0V" /></figure><p>It took 4 times to randomly cut the sample and isolate the red point, which is clearly an outlier.</p><p>Now, take a look at the next GIF, which attempts to cut the sample until the yellow point (normal point) is isolated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgjBE1oHI9KNHoAj-imsGA.gif" /></figure><p>This time, the algorithm took a lot more cuts.</p><p>As you can infer from the above, a data point is likely an outlier if it can be isolated only with a few random sample cuts.</p><h4>Step by Step</h4><p>Here are the steps involving the Random Forest algorithm.</p><p>First, the algorithm creates an isolation tree by going through the following steps:<br>[1] Randomly select a sub-sample (Sci-kit learn’s default: 100 instances/data points)<br>[2] Select a point to isolate.<br>[3] Randomly select a feature (i.e., variable) from the set of features X.<br>[4] Randomly select a threshold between the minimum and the maximum value of the feature x.<br>[5] If the data point is less (greater) than the threshold, then it flows through the left branch of the tree (right). In other words, define the new minimum (maximum) of the range to the threshold for the next iteration.<br>[6] Repeat steps 3 through 5 until the point is isolated or until a pre-defined max number of iterations is reached.<br>[7] Record the number of times the steps 3 through 5 were repeated.</p><p>Prediction process: Isolation Forest is created by computing the following score based on a collection of trees (like 100 trees).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/0*C7xKcDdbUgv2Q3AV.JPG" /></figure><p>where E[h(x)] is the average number of successful iterations for firm x and c(n) is the average iterations for unsuccessful iterations.</p><h3>Benefits and drawbacks of using Isolation Forest</h3><h4>Benefits</h4><p>As I noted above, Isolation Forest does not assume normal distribution and is able to detect outliers at a multi-dimensional level. More importantly, Isolation Forest is computationally efficient: the algorithm has a linear time complexity with a low constant and a low memory requirement. Therefore, it scales well to large data sets.</p><p>According to <a href="https://ieeexplore.ieee.org/abstract/document/4781136?casa_token=A5ZM3TQZHhsAAAAA:DPITalJ8ZZ-5KnuBufXLZkFg6fsICEyyi0vfXmuGejd8gFtAldJ2ZFuS0JUoBAS8GPoF0JG5Kg">Liu, Ting, and Zhou (2008)</a>, Isolation Forest performs better than Random Forest, especially in large data sets.</p><h4>Drawbacks</h4><p>As I will discuss more in the implementation step, the Isolation Forest algorithm requires us to pick the percentage of anomalies in the dataset. Thus, we need to have at least some idea of the proportion of anomalies in our data.</p><p>Second, axis-parallel splits create some artificial normal regions. I won’t go into details, but this issue is addressed by the follow-up study <a href="https://ieeexplore.ieee.org/document/8888179">Hariri, Kind, and Brunner (2021)</a>. And here are more resources: <a href="https://github.com/sahandha/eif">GitHub</a> and <a href="https://medium.datadriveninvestor.com/lets-find-some-outliers-with-isolation-forest-4ed22175a8d3">blog</a>. I will post a blog on this topic when I get a chance.</p><h3>Implementation of Isolation Forest to Detect Outliers in Python (Scikit-learn)</h3><h3>1. Preparation</h3><h4>1.1. Input data</h4><p>The data “sample_detect_outliers.csv” contains US public firms’ features that are related to leases (my dissertation is on leases).</p><h4>1.2. Output data</h4><p>The following lines of code will output an indicator variable that equals 1 if the firm (e.g., observation) is an outlier and 0 otherwise. For more details on the steps after I identify outliers, please see my dissertation, <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3689446">Yoon (2022)</a>.</p><h4>1.3. Feature (i.e., variable) definition</h4><ul><li><em>lag_lease</em>: prior year’s lease activity</li><li><em>lag_market_value</em>: prior year’s market capitalization of the stock</li><li><em>lag_dividend</em>: an indicator value that equals 1 if the company paid any dividends in the prior, and 0 otherwise</li><li><em>lag_loss</em>: an indicator value that equals 1 if the company reported negative profits in the prior year</li><li><em>lag_cash</em>: prior year’s cash balance</li><li><em>lag_tax_rate</em>: effective tax rate in the prior year</li><li><em>lag_big4_auditor</em>: an indicator value that equals 1 if the company hired a Big 4 auditor in the prior year</li></ul><h4>1.4. Import libraries and the data set</h4><pre><em># Import libraries</em><br><strong>import</strong> numpy <strong>as</strong> np<br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> seaborn <strong>as</strong> sns<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>import</strong> plotly.express <strong>as</strong> px<br><strong>from</strong> sklearn.ensemble <strong>import</strong> IsolationForest<br><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler<br><strong>from</strong> sklearn.decomposition <strong>import</strong> PCA</pre><pre><em># Import the data set</em><br>sample_with_outliers <strong>=</strong> pd<strong>.</strong>read_csv(&#39;sample_detect_outliers.csv&#39;)</pre><h3>2. Conduct an Exploratory Data Analysis (EDA)</h3><h4>2.1. Show the first 5 entries in the data</h4><pre><em># First 5 entries</em><br>sample_with_outliers<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*xIj6aly0j-I4WHhQm8WdSA.png" /></figure><h4>2.2. The # of entries and the # of features</h4><p>There are 6,279 entries and 9 variables = 1 identifier + 1 label (i.e., outcome variable) + 7 firm features. The second variable, <em>lease</em>, is the label.</p><pre><em># (Number of entries, Number of features)</em><br>print(sample_with_outliers<strong>.</strong>shape)</pre><pre>(6279, 9)</pre><h4>2.3. Empirical distributions and histograms</h4><p>There are many interesting observations that are worth noting. First, there are no missing values as indicated by counts that all equal 6,279. I discuss other interesting observations in the next section.</p><pre><em># Show empirical distributions</em><br>sample_with_outliers<strong>.</strong>describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*Pkk1PLYMe6LVnmtxQNnSgQ.png" /></figure><pre># Show histograms - all variables except for the identifier<br>sample_z_score = sample_with_outliers.drop(columns=&#39;identifier&#39;)<br>sample_z_score.hist(bins = 20, figsize =(20, 10))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-RjseogVxFWwY90foix8Q.png" /></figure><h4>2.4. Drop variables without outliers</h4><p>The above two panels show that <em>lag_loss</em> and <em>lag_big4_auditor</em> are indicator variables and thus do not have outliers.</p><p>In addition, the histogram suggests that <em>lag_tax_rate</em> also does not have outliers. During the sample period (2016–2019), the corporate tax rate was reduced from 35% to 21%. Two big spikes in the histogram around 35% and 21% and all other values smaller than 35% make economic sense.</p><p>Therefore, I drop these three variables that do not have outliers.</p><pre># Drop identifier, lag_loss, lag_big4_auditor, and lag_tax_rate <br>var = [&#39;identifier&#39;, &#39;lag_loss&#39;, &#39;lag_big4_auditor&#39;, &#39;lag_tax_rate&#39;]<br>sample_z_score = sample_with_outliers.drop(columns=var)</pre><h3>3. Z-Score — Detect and Remove Outliers</h3><p>Before implementing Isolation Forest, I will first attempt to detect outliers using the Z-score method.</p><p>As indicated in a previous section, the Z-Score method is effective in addressing outliers for data points that follow a normal distribution.</p><p>The z-score indicates the distance of a data point from the mean as the number of standard deviations. The formula is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/101/0*3qVhnXlavfBWQN5e" /></figure><p>I am going to assume that observations with a Z-score below -2.5 or above 2.5 (i.e., 2.5 standard deviations away from the mean; 1% of the sample) are outliers.</p><h4>3.1. lag_market_value — Identify and remove outliers</h4><p>The histogram above shows that <em>lag_market_value</em> follows a normal distribution. To detect outliers, I first write a function to print the upper limits and lower limits of the Z-Score.</p><pre># Create a function to report the limits of the Z-Score<br>def print_z_score_limits (df, column_name):<br>    &quot;&quot;&quot; Print the upper and lower limits of the Z-score &quot;&quot;&quot;<br>    <br>    # Compute the limits<br>    upper_limit = df[column_name].mean() + 3 * df[column_name].std()<br>    lower_limit = df[column_name].mean() - 3 * df[column_name].std()<br>    <br>    # Round and return the limits<br>    upper_limit = round(upper_limit, 2)<br>    lower_limit = round(lower_limit, 2)<br>    print_this = &quot;Variable Name: &quot; + column_name + &quot; | Upper limit: &quot; + str(upper_limit) + &quot; | Lower limit: &quot; + str(lower_limit)<br>    return(print_this)</pre><pre><em># Print the upper and lower limits</em><br>print_z_score_limits(sample_z_score, &quot;lag_market_value&quot;)</pre><pre>&#39;Variable Name: lag_market_value | Upper limit: 12.82 | Lower limit: 2.43&#39;</pre><p>It turns out that all of the values (N=6,279) are within the boundary values of 2.43 and 12.82. Thus, none of the observations are trimmed.</p><pre><em># Filter outliers</em><br>sample_z = sample_z[(sample_z[&#39;lag_market_value&#39;] &gt;= 2.43) | (sample_z[&#39;lag_market_value&#39;] &lt;= 12.82)]<br>print(sample_z.shape)</pre><pre>(6279, 5)</pre><p>I’ll drop lag_market_value since an outlier treatment is not necessary for this feature.</p><pre><em># Drop lag_market_value</em><br>sample_z = sample_z.drop(columns=[&#39;lag_market_value&#39;])</pre><h4>3.2. Log transformation of other variables</h4><p>Going back to the histograms above, we can see that lease, lag_lease, lag_dividend, and lag_cash are all significantly right-skewed. In this case, the Z-Score method or many other popular outlier detection methods such as the Interquartile Range (IQR) method won’t do any good. To address this issue, I conduct log transformations on these variables to see if I can describe them with normal distribution.</p><p>The histogram also shows that the four variables have many zeros (or very small values), which make economic sense. Therefore, I will only look for outliers on the right-hand side of the distribution.</p><p>First, I will replace zeros with NaNs. This is okay because zeros will not be considered outliers.</p><pre># Replace zeros with NaNs<br>sample_z[&#39;lag_dividend&#39;] = sample_z[&#39;lag_dividend&#39;].replace([0],np.NaN)<br>sample_z[&#39;lease&#39;] = sample_z[&#39;lease&#39;].replace([0],np.NaN)</pre><p>Next, I perform the log transformations and plot histograms</p><pre># Create a function to conduct log transformation<br>def log_transformation_function (df, column_name):<br>    &quot;&quot;&quot; Conduct a log transformation of a variable &quot;&quot;&quot;<br>    # Replace the values with log-transformed values<br>    df[[column_name]] = df[[column_name]].apply(np.log)</pre><pre># Conduct log transformation on all the variables<br>for column in sample_z:<br>    log_transformation_function(sample_z, column)   <br>    <br># Plot histograms<br>sample_z.hist(bins = 20, figsize =(20, 10))<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YjjyTrna5nPVHdmIZ8PxDQ.png" /></figure><h4>3.3. Other variables — Identify and remove outliers</h4><p>The distributions now look much more like normal distributions. Once again, I will use the Z-Score to identify outliers.</p><p>First, I report the Z-Score upper limits for each variable.</p><pre># Print the upper and lower limits<br>for column in sample_z:<br>    print(print_z_score_limits(sample_z, column))</pre><pre>Variable Name: lease | Upper limit: 3.55 | Lower limit: -3.64<br>Variable Name: lag_lease | Upper limit: 3.42 | Lower limit: -3.66<br>Variable Name: lag_dividend | Upper limit: -0.8 | Lower limit: -6.86<br>Variable Name: lag_cash | Upper limit: 1.97 | Lower limit: -6.76</pre><p>Next, I report the maximum values of each variable.</p><pre># Print the maximum values<br>print(&quot;MAXIMUM VALUES&quot;)<br>print(round(sample_z.max(),2))</pre><pre>MAXIMUM VALUES<br>lease           3.54<br>lag_lease       2.76<br>lag_dividend   -1.59<br>lag_cash       -0.04<br>dtype: float64</pre><p>All of the maximum values are smaller than the upper limits. Thus, none of the variables seems to have outliers.</p><h3>4. Isolation Forest — Multi-dimensional Outlier Detection</h3><p>Although the data points do not seem to have outliers at the variable level, there could be outliers at a multi-dimensional level. Therefore, I employ Isolation Forest to detect outliers.</p><h4>4.1. Setup</h4><p>I begin by dropping the identifier from the original sample.</p><pre>sample_isf <strong>=</strong> sample_with_outliers<strong>.</strong>drop(columns<strong>=</strong>&#39;identifier&#39;)</pre><h4>4.2. Conduct Principal Component Analysis (PCA)</h4><p>I conduct PCA to reduce the firm feature dimensions from 7 to 2. Note that this step is not necessary because Isolation Forest works fine with multi-dimensions. Regardless, I reduce dimensions to visualize the outlier points in my data.</p><pre># Standardize features<br>sample_scaled = StandardScaler().fit_transform(sample_isf)</pre><pre># Define dimensions = 2<br>pca = PCA(n_components=2)</pre><pre># Conduct the PCA<br>principal_comp = pca.fit_transform(sample_scaled)</pre><pre># Convert to dataframe<br>pca_df = pd.DataFrame(data = principal_comp, columns = [&#39;principal_component_1&#39;, &#39;principal_component_2&#39;])<br>pca_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*mOaKAfHMnTK01I3FdHWHxw.png" /></figure><h4>4.3. Train the model and make predictions</h4><p>As indicated before, we need to pre-define outlier frequency. After experimenting with data, I decide to use 4%.</p><pre><em># Train the model</em><br>isf <strong>=</strong> IsolationForest(contamination<strong>=</strong>0.04)<br>isf<strong>.</strong>fit(pca_df)</pre><pre><em># Predictions</em><br>predictions <strong>=</strong> isf<strong>.</strong>predict(pca_df)</pre><h4>4.3. Extract predictions and isolation scores</h4><pre><em># Extract scores</em><br>pca_df[&quot;iso_forest_scores&quot;] <strong>=</strong> isf<strong>.</strong>decision_function(pca_df)</pre><pre><em># Extract predictions</em><br>pca_df[&quot;iso_forest_outliers&quot;] <strong>=</strong> predictions</pre><pre><em># Describe the dataframe</em><br>pca_df<strong>.</strong>describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*xPRbq9lWFdbLZ5mY4Jpn6g.png" /></figure><p>Let’s replace “-1” with “Yes” and “1” with “No”</p><pre><em># Replace &quot;-1&quot; with &quot;Yes&quot; and &quot;1&quot; with &quot;No&quot;</em><br>pca_df[&#39;iso_forest_outliers&#39;] <strong>=</strong> pca_df[&#39;iso_forest_outliers&#39;]<strong>.</strong>replace([<strong>-</strong>1, 1], [&quot;Yes&quot;, &quot;No&quot;])</pre><pre><em># Print the first 5 firms</em><br>pca_df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*81tMTAzS_YgHo-i-JLarAw.png" /></figure><h4>4.4. Plots</h4><p>Plot the firms in the 2-dimensional space in the following order.<br>[1] All firms<br>[2] Normal Firms vs. Outlier Firms<br>[3] Isolation Forest Scores</p><pre># Create a function to plot firms on the 2-dimensional space<br>def plot_firms (dataframe, title, color = None):<br>    &quot;&quot;&quot; Plot firms on the 2-dimensional space &quot;&quot;&quot;<br>    <br>    # Generate a scatter plot<br>    fig = px.scatter(pca_df, x=&quot;principal_component_1&quot;, y=&quot;principal_component_2&quot;, title=title, color=color)<br>    <br>    # Layout<br>    fig.update_layout(<br>        font_family=&#39;Arial Black&#39;,<br>        title=dict(font=dict(size=20, color=&#39;red&#39;)),<br>        yaxis=dict(tickfont=dict(size=13, color=&#39;black&#39;),<br>                   titlefont=dict(size=15, color=&#39;black&#39;)),<br>        xaxis=dict(tickfont=dict(size=13, color=&#39;black&#39;),<br>                   titlefont=dict(size=15, color=&#39;black&#39;)),<br>        legend=dict(font=dict(size=10, color=&#39;black&#39;)),<br>        plot_bgcolor=&#39;white&#39;<br>    )<br>      <br>    return(fig)</pre><pre><em># Need to import renderers to view the plots on GitHub</em><br><strong>import</strong> plotly.io <strong>as</strong> pio</pre><pre># Plot [1] All firms<br>plot_firms(pca_df, &quot;Figure 1: All Firms&quot;).show(&quot;png&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*QYkKJjQv7r2SioyI" /></figure><pre><em># [2] Normal Firms vs. Outlier Firms</em><br>plot_firms(dataframe<strong>=</strong>pca_df, title<strong>=</strong>&quot;Figure 2: Normal Firms vs. Outlier Firms&quot;, color<strong>=</strong>&#39;iso_forest_outliers&#39;)<strong>.</strong>show(&quot;png&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*wnt1_8o66DCWY0He" /></figure><pre><em># [3] Isolation Forest Scores</em><br>plot_firms(dataframe<strong>=</strong>pca_df, title<strong>=</strong>&quot;Figure 3: Isolation Forest Scores&quot;, color<strong>=</strong>&#39;iso_forest_scores&#39;)<strong>.</strong>show(&quot;png&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*jOmLFs5gUrdw-Kmf" /></figure><h4>4.6. Observations</h4><p>A few observations are in order.</p><p>According to Figure 2, most of the outer points are identified as outliers. These outliers correctly meet the outlier characteristics that they are “distant and few.”</p><h3>5. Export and conclude</h3><pre><em># Add identifiers and cluster assignments (labels) to the sample<br></em>pca_df <strong>=</strong> pd.concat([sample_with_outliers[&#39;identifier&#39;], pca_df], axis<strong>=</strong>1)</pre><pre><em># Print the first 5 firms<br></em>pca_df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/676/1*xHFVKzRc9mqz_HGKQgvTTQ.png" /></figure><pre># Export the sample as a csv file<br>pca_df.to_csv(&#39;outliers_detected.csv&#39;)</pre><h3>References</h3><p>[1] <a href="https://ieeexplore.ieee.org/abstract/document/4781136?casa_token=A5ZM3TQZHhsAAAAA:DPITalJ8ZZ-5KnuBufXLZkFg6fsICEyyi0vfXmuGejd8gFtAldJ2ZFuS0JUoBAS8GPoF0JG5Kg">Liu, Ting, and Zhou (2008) Isolation Forest</a><br>[2] <a href="https://quantdare.com/isolation-forest-algorithm/">Fuertes (2018) Isolation forest: the art of cutting off from the world</a><br>[3] <a href="https://towardsdatascience.com/outlier-detection-with-isolation-forest-3d190448d45e">Lewinson (2018) Outlier Detection with Isolation Forest</a><br>[4] <a href="https://www.analyticsvidhya.com/blog/2021/07/anomaly-detection-using-isolation-forest-a-complete-guide/">Akshara (2021) Anomaly detection using Isolation Forest — A Complete Guide</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=101123a9ff63" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[K-Means Clustering Fixed Effects: Form Clusters Through Unsupervised Machine Learning]]></title>
            <link>https://medium.com/@y.s.yoon/k-means-clustering-fixed-effects-form-clusters-through-unsupervised-machine-learning-a8d355a09da0?source=rss-38a240a7297d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8d355a09da0</guid>
            <dc:creator><![CDATA[Young Yoon]]></dc:creator>
            <pubDate>Wed, 16 Feb 2022 18:35:23 GMT</pubDate>
            <atom:updated>2022-05-02T22:16:20.514Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0O8MjJdJ8gG4VJbj.gif" /></figure><h3>Outline</h3><ul><li>Understand and implement the K-means clustering algorithm and group firms.</li><li>Conduct Principal Component Analysis (PCA) to perform dimensionality reduction and visualize the groupings.</li><li>Understand the benefits of using machine learning to group firms when defining fixed effects for regression models.</li></ul><p>You can find the code on my <a href="https://github.com/youngdataspace/K-Means-Clustering-Fixed-Effects">GitHub</a>. If you have any comments or suggestions, email me at <a href="/service/mailto:y.s.yoon@berkeley.edu">y.s.yoon@berkeley.edu</a>.</p><h3>Introduction</h3><p>In this blog, I explain how I group US public firms by implementing the K-means unsupervised learning.</p><p>I form groups to construct fixed effects and use them in my UC Berkeley Haas PhD Dissertation (<a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3689446">Yoon 2022</a>). However, this code can be generalized and used in many other settings, such as customer/market segmentation and recommendation systems.</p><h3>Goal: Group firms as shown in Figure 2</h3><p>Figure 1 presents companies’ seven features shown in a 2-dimensional space after conducting dimensionality reduction. My goal is to group companies that share similar features, as shown in Figure 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*u4lPRrwDjjw8G2uC.JPG" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*j1M-yS6HJFxsLTXk.JPG" /></figure><h3>Why is the machine learning approach beneficial?</h3><p>In my dissertation, I study whether the new lease rule causes firms to reduce their leasing activity (e.g., discontinue a truck lease). To establish this causality between the new lease rule and firms’ leasing activity, I need to eliminate other factors that can also affect lease use. For example, imagine that a group of automobile companies experienced a supply shock that resulted in a reduction in leasing activity. Because such shock is unrelated to the new lease rule, I need to nullify its effects on leasing activity in order to study the effects of the new lease rule.</p><p>The fixed effects method is one of the popular ways to control for group-specific shocks. Going back to the previous example, because the group of automobile companies belongs to the automobile industry, conducting industry fixed effects analysis would eliminate the automobile industry-specific shocks. In my dissertation, however, industry grouping may not be adequate because leasing decisions depend on various firm features and not just an industry membership. If the relationships between firm features and leasing decisions are perfectly linear, then adding firm features as control variables in regression models should be sufficient. However, since that is unlikely the case, adding fixed effects of groups generated using firm features provides an incremental benefit.</p><p>One way to form groups is to transform all firm features to high/low values and group firms with similar values. For example, I can create two groups based on high/low values of firm size or four groups based on high/low values of firm size and past leasing activity. However, the challenge is that I have a lot more than two firm features, and I don’t know an adequate number of groups. To overcome these challenges, I let the computer conduct unsupervised learning on my data and help me decide how to form groups.</p><h3>K-means clustering</h3><p>The K-means clustering algorithm is one of the most popular unsupervised machine learning algorithms to form groups. A cluster refers to a group of similar things close to each other. The main goal of the algorithm is to find clusters that minimize the distances between points within clusters. I use Python’s Scikit-learn library to implement the algorithm, but here is what’s going on behind the scenes.</p><h4>K-means clustering implementation steps (apply Lloyd’s algorithm)</h4><ul><li>Step 1: Choose the number of clusters (k) using the elbow method.</li><li>Step 2: Randomly place k centroids in the data space.</li><li>Step 3: Calculate the Euclidean distance between data points and centroids.</li><li>Step 4: Assign each data point to the nearest centroids. Clusters are formed at this step.</li><li>Step 5: Recalculate the centroid of the clusters (i.e., average the data — where the name K-‘means’ comes from).</li><li>Step 6: Repeat steps 4 and 5.</li></ul><p>Stop the loop when one or more of the following is true:</p><ul><li>(1) Centroids of new clusters no longer change.</li><li>(2) The same data points are assigned to the same centroids.</li><li>(3) A pre-specified maximum number of iterations are reached.</li></ul><h3>1. Data</h3><h4>1.1. Input Data</h4><p>The data “characteristics.csv” contains US public firms’ characteristics that are related to leases. They are averaged across the 3-year period from 2016 to 2018.</p><h4>1.2. Output data</h4><p>The code will output a list of companies along with a cluster assignment.</p><h4>1.3. Feature (i.e., variable) definition. For details, see <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3689446">Yoon (2022)</a>.</h4><ul><li><em>lag_lease</em>: prior year’s lease activity</li><li><em>lag_market_value</em>: prior year’s market capitalization of the stock</li><li><em>lag_dividend</em>: an indicator value that equals 1 if the company paid any dividends in the prior, and 0 otherwise</li><li><em>lag_loss</em>: an indicator value that equals 1 if the company reported negative profits in the prior year</li><li><em>lag_cash</em>: prior year’s cash balance</li><li><em>lag_tax_rate</em>: effective tax rate in the prior year</li><li><em>lag_big4_auditor</em>: an indicator value that equals 1 if the company hired a Big 4 auditor in the prior year</li></ul><h3>2. Implementing K-means clustering in Python (Scikit-learn)</h3><h3>2.1. Preparation</h3><p>First things first. I import libraries and the sample in the below code.</p><pre><em># Import libraries</em><br><strong>import</strong> pandas <strong>as</strong> pd<br><strong>import</strong> seaborn <strong>as</strong> sns<br><strong>import</strong> matplotlib.pyplot <strong>as</strong> plt<br><strong>from</strong> sklearn.preprocessing <strong>import</strong> StandardScaler<br><strong>from</strong> sklearn.cluster <strong>import</strong> KMeans, MiniBatchKMeans<br><strong>from</strong> sklearn.decomposition <strong>import</strong> PCA</pre><pre><em># Import the csv file</em><br>characteristics <strong>=</strong> pd<strong>.</strong>read_csv(&#39;characteristics.csv&#39;)</pre><h3>2.2. Conduct an Exploratory Data Analysis (EDA)</h3><h4>2.2.1. Show the first 5 entries in the data</h4><pre><em># First 5 entries</em><br>characteristics<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*Zt8E7ZItwu4Ci43v8f_8cA.png" /></figure><h4>2.2.2. The # of variables and entries</h4><p>There are a total of 8 variables = 1 identifier + 7 firm features and a total of 1640 entries, which are all unique firm entries.</p><pre><em># (Number of entries, Number of features)</em><br>print(characteristics<strong>.</strong>shape)</pre><pre><em># The number of unique firms</em><br>print(characteristics[&#39;identifier&#39;]<strong>.</strong>nunique())</pre><pre>(1640, 8)</pre><h4>2.2.3. Remove identifiers</h4><p>Because I don’t need the identifier column for this analysis, I will create a new data frame without it.</p><pre><em># Create a sample to conduct the analysis</em><br>sample <strong>=</strong> characteristics<strong>.</strong>drop(columns<strong>=</strong>[&#39;identifier&#39;])</pre><h4>2.2.4. Descriptive stats (empirical distributions, histograms, and correlation plots)</h4><pre><em># Show empirical distributions</em><br>sample<strong>.</strong>describe()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*keY2KT9nd8lhA08vVqlHVw.png" /></figure><pre><em># Show histograms</em><br>sample<strong>.</strong>hist(bins <strong>=</strong> 20, figsize <strong>=</strong>(20, 10))<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*G4KT_R7bf64Sg6R87tSyWA.png" /></figure><pre><em># Plot correlation heatmap</em><br>correlations <strong>=</strong> sample<strong>.</strong>corr()                  <em># Compute correlations</em><br>f, ax <strong>=</strong> plt<strong>.</strong>subplots(figsize<strong>=</strong>(10,10))         <em># Figure size</em><br>sns<strong>.</strong>heatmap(correlations, annot<strong>=True</strong>)         <em># Create a heatmap</em><br>sns<strong>.</strong>set(font_scale<strong>=</strong>2)                         <em># Font size</em><br>plt<strong>.</strong>title(&#39;Heatmap of Firm Characteristics&#39;, fontsize <strong>=</strong> 35)<br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*WK88P5x8Xe8qFBE0XKN9zg.png" /></figure><p>A few observations:</p><ul><li>There are no missing values (all counts equal 1640).</li><li>Features do not have outliers. This is important because one of the disadvantages of K-means clustering is that centroids can be significantly affected by outliers instead of being ignored.</li><li><em>lag_lease</em>, <em>lag_dividend</em>, <em>lag_cash</em> are right-skewed, which make economic sense.</li><li><em>lag_market_value</em> follows a normal distribution.</li><li>The <em>lag_tax_rate</em> values are clustered around 35%.</li></ul><p>In summary, this is clean data with values that make economic sense.</p><p>For simplicity, I do not provide a detailed explanation of the data. See <a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3689446">Yoon (2022)</a> for more details.</p><h3>2.3. K-Means Clustering</h3><h4>2.3.1. Feature engineering — Standardizing the features</h4><p>Because I want to minimize within-cluster euclidean distances, it is important to standardize features first.</p><pre><em># Standardize features</em><br>sample_scaled <strong>=</strong> StandardScaler()<strong>.</strong>fit_transform(sample)</pre><h4>2.3.2. The Elbow method</h4><p>One disadvantage of K-means clustering is that we have to choose k manually. But we can choose k intellectually by using the Elbow method, one of the most popular and effective methods.</p><p>In the Elbow method, we are going to gradually increase k from 1 and plot inertia across k. Inertia refers to the within-cluster sum of squared distances from centroids. As shown in the figure below, the line resembles an arm. Starting at around k=4, we can see that the line flattens out. In other words, k=4 seems to be the “elbow point”. In my dissertation, I use k=4, 6, and 8 to ensure that my results are not sensitive to the choice of k.</p><h4>2.3.3. K-Means++</h4><p>The second disadvantage of K-means clustering is that it depends on the initial values of centroids. If you run the following code a couple of times, you will notices that the lines change slightly because the algorithm can end up at a local optimum.</p><p>To overcome this challenge, we can use K-Means++. Unlike K-means, which randomly selects all of k centroids’ initial points, K-Means++ randomly selects the first centroid point and selects the next centroid as the data point that has the maximum distance from the nearest centroid. This algorithm repeats until k centroids have been selected. The main idea is to select centroids that are far away from one another so that centroids are more likely to be located in different clusters.</p><pre><em># Initialize inertia</em><br>inertia <strong>=</strong> []</pre><pre><em># Calculate inertia for k=[1:10]</em><br><strong>for</strong> i <strong>in</strong> range(1,11):                <em># i ranges from 1 to 10</em><br>    kmeans <strong>=</strong> KMeans(n_clusters <strong>=</strong> i,  <em># Assign i number of clusters</em><br>                    init<strong>=</strong>&#39;k-means++&#39;,<em># Use K-Means++ initialization</em><br>                    max_iter<strong>=</strong>1000)   <em># Set maximum # of iterations</em><br>    kmeans<strong>.</strong>fit(sample_scaled)        <em># Fitting the k means algorithm</em><br>    inertia<strong>.</strong>append(kmeans<strong>.</strong>inertia_)  <em># Record inertia</em><br>    <br><em># Plot the inertia across k</em><br>plt<strong>.</strong>plot(inertia, &#39;bx-&#39;)<br>plt<strong>.</strong>xticks(list(range(0,10)),list(range(1,11)))   <em># Change the x ticks from 0:8 to 0:9</em><br>plt<strong>.</strong>xlabel(&#39;Values of K&#39;) <br>plt<strong>.</strong>ylabel(&#39;Inertia&#39;)        <br>plt<strong>.</strong>title(&#39;Elbow Curve&#39;)    <br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*qsfOrp9OGZUjISNGl4xOzw.png" /></figure><h4>2.3.4. Implement K-means clustering</h4><p>Now that we have chosen to use K=4 clusters, we can implement K-means clustering and group firms.</p><pre><em># Select k=4</em><br>kmeans <strong>=</strong> KMeans(n_clusters <strong>=</strong> 4,       <em># Assign i number of clusters</em><br>                    init<strong>=</strong>&#39;k-means++&#39;, <em># Use K-Means++ </em><br>                    max_iter<strong>=</strong>1000)    <em># Set the max # of iterations</em></pre><pre><em># fitting the k means algorithm</em><br>kmeans<strong>.</strong>fit(sample_scaled)</pre><pre><em># Get cluster assignemnts</em><br>labels <strong>=</strong> kmeans<strong>.</strong>labels_</pre><h3>2.4. Principal Component Analysis (PCA) — Visualize Clusters</h3><p>Before I export the cluster assignments and use them to conduct fixed effects analysis, I visualize clusters by conducting a principal component analysis.</p><h4>2.4.1. Conduct PCA</h4><p>It is very difficult to visualize seven features. To better visualize the 7-dimensional data, I will first reduce it to 2-dimensional data in the following code.</p><pre><em># Add identifiers and cluster assignments (labels) to the sample</em><br>sample <strong>=</strong> pd<strong>.</strong>concat([characteristics[&#39;identifier&#39;], sample, pd<strong>.</strong>DataFrame({&#39;cluster&#39;:labels})], axis<strong>=</strong>1)</pre><pre><em># Set the number of components</em><br>pca <strong>=</strong> PCA(n_components<strong>=</strong>2)                 </pre><pre><em># Conduct dimentionality reduction</em><br>principal_comp <strong>=</strong> pca<strong>.</strong>fit_transform(sample_scaled)</pre><pre><em># Create a dataframe and add a column of labels </em><br>pca_df <strong>=</strong> pd<strong>.</strong>DataFrame(data <strong>=</strong> principal_comp, <br>                      columns <strong>=</strong> [&#39;principal_component1&#39;, <br>                                 &#39;principal_component2&#39;])<br>pca_df <strong>=</strong> pd<strong>.</strong>concat([pca_df, pd<strong>.</strong>DataFrame({&#39;Cluster&#39;:labels})], <br>                    axis <strong>=</strong> 1)      </pre><pre><em># Show the first 5 firms</em><br>pca_df<strong>.</strong>head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*JLGa7paMK08UBua6RARKnA.png" /></figure><h4>2.4.2. Plot the two principal components</h4><p>The following code plots the two principal components. Note that each component does not have a particular meaning.</p><pre>does <em># Create a scatter plot of two components</em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>(7,7))                             <em># figure size</em><br>ax <strong>=</strong> sns<strong>.</strong>scatterplot(<br>    x<strong>=</strong>&quot;principal_component1&quot;, y<strong>=</strong>&quot;principal_component2&quot;,                    <br>    data <strong>=</strong> pca_df)                                    <em># plot</em><br>plt<strong>.</strong>xlabel(&quot;Principal Component 1&quot;, size<strong>=</strong>20)          <em># x label</em><br>plt<strong>.</strong>ylabel(&quot;Principal Component 2&quot;, size<strong>=</strong>20)          <em># y label</em><br>plt<strong>.</strong>xticks(fontsize<strong>=</strong>17)                               <em># x tick</em><br>plt<strong>.</strong>yticks(fontsize<strong>=</strong>17)                               <em># y tick</em><br>plt<strong>.</strong>title(&quot;Figure 1. PCA - Before Grouping Clusters&quot;, size<strong>=</strong>25) <br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/0*u4lPRrwDjjw8G2uC.JPG" /></figure><h4>2.4.3. Show clusters</h4><p>Using the cluster assignments, we can group the points in clusters. Let’s visualize them.</p><pre><em># Create a scatter plot of two components and group them into clusters</em><br>plt<strong>.</strong>figure(figsize<strong>=</strong>(7,7))                         <em># figure size</em><br>ax <strong>=</strong> sns<strong>.</strong>scatterplot(<br>    x<strong>=</strong>&quot;principal_component1&quot;, y<strong>=</strong>&quot;principal_component2&quot;,                    <br>    hue <strong>=</strong> &quot;Cluster&quot;, <br>    data <strong>=</strong> pca_df, <br>    palette <strong>=</strong> [&#39;#99B898&#39;, &#39;#E84A5F&#39;, &#39;#2A363B&#39;, &#39;#FECEA8&#39;])   <br>plt<strong>.</strong>legend(loc<strong>=</strong>&#39;upper right&#39;)                      <br>plt<strong>.</strong>setp(ax<strong>.</strong>get_legend()<strong>.</strong>get_texts(), fontsize<strong>=</strong>&#39;17&#39;)<br>plt<strong>.</strong>setp(ax<strong>.</strong>get_legend()<strong>.</strong>get_title(), fontsize<strong>=</strong>&#39;17&#39;)<br>plt<strong>.</strong>xlabel(&quot;Principal Component 1&quot;, size<strong>=</strong>20)                    <br>plt<strong>.</strong>ylabel(&quot;Principal Component 2&quot;, size<strong>=</strong>20)                    <br>plt<strong>.</strong>xticks(fontsize<strong>=</strong>17)                                         <br>plt<strong>.</strong>yticks(fontsize<strong>=</strong>17)                                         <br>plt<strong>.</strong>title(&quot;Figure 2. PCA - After Grouping Clusters&quot;, size<strong>=</strong>25)   <br>plt<strong>.</strong>show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/0*j1M-yS6HJFxsLTXk.JPG" /></figure><h3>2.5. Export to csv</h3><p>We are almost done. I am going to use the cluster assignments to form fixed effects. To do so, I export the sample and conduct regression analysis. The results can be found in my dissertation (<a href="https://papers.ssrn.com/sol3/papers.cfm?abstract_id=3689446">Yoon 2022</a>).</p><pre><em># Export the sample as a csv file</em><br>sample<strong>.</strong>to_csv(&#39;characteristics_with_clusters.csv&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8d355a09da0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>