<?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 Daniel Carter on Medium]]></title>
        <description><![CDATA[Stories by Daniel Carter on Medium]]></description>
        <link>https://medium.com/@daniel-carter?source=rss-3f0c5d200547------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mWVN89dkRIcqyqy_5oTU6Q.png</url>
            <title>Stories by Daniel Carter on Medium</title>
            <link>https://medium.com/@daniel-carter?source=rss-3f0c5d200547------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 15:53:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@daniel-carter/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[Predicting Stock Movements With ChatGPT]]></title>
            <link>https://daniel-carter.medium.com/predicting-stock-movements-with-chatgpt-611f58970fa2?source=rss-3f0c5d200547------2</link>
            <guid isPermaLink="false">https://medium.com/p/611f58970fa2</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[gpt]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Daniel Carter]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 19:51:23 GMT</pubDate>
            <atom:updated>2023-04-28T19:51:23.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_CzO87fp1KPUhHjMHkr1Mg.jpeg" /></figure><p>Large Language Models, such as GPT, are undeniably impressive in their ability to generate eloquent and engaging writing based on a sequence of words given to it by users. Their proficiency in this task has even led some to wonder whether these models possess a certain degree of sentience.</p><p>As I thought about the capabilities of these models, it occurred to me that GPT’s sequence-predicting abilities could potentially be applied to forecasting stock prices. The ups and downs of the stock market across time can also be considered a sequence, so I embarked on an exploration to see if ChatGPT could predict future stock movements.</p><p>To replicate my work, you will need a fundamental understanding of Python and access to the OpenAI API. I highly recommend using Google Colab for simple reproducibility, but other environments will suffice.</p><p>Begin by installing the OpenAI API package, followed by importing the necessary modules and configuring the settings accordingly.</p><pre>!pip install openai</pre><pre># imports<br>import pandas as pd<br>import openai<br>import yfinance as yf<br>from tqdm import tqdm<br>from sklearn import metrics<br><br># pandas dataframe settings<br>pd.set_option(&quot;max_colwidth&quot;, 100)<br>pd.set_option(&quot;display.max_rows&quot;, None)<br>pd.set_option(&quot;display.max_columns&quot;, None)<br><br># insert your OpenAI API key below<br>openai.api_key = &#39;&#39;</pre><p>Let’s grab some stock market data from the Yahoo Finance API. Initially, I used more data, but to avoid overloading the GPT model, I reduced it. Also, to minimize day-to-day market noise, I decided to use weekly data.</p><pre># get stock data from yahoo finance api<br>stk= yf.download(&quot;AAPL&quot;, start=&quot;2021-04-21&quot;, end=&quot;2023-04-21&quot;)<br><br># only get adjusted close column<br>stk = stk[[&#39;Adj Close&#39;]].copy()<br><br># turn daily data into weekly data<br>stk = stk.resample(&#39;W&#39;).mean()<br>stk[&#39;Adj Close&#39;] = stk[&#39;Adj Close&#39;].round(2)</pre><p>Run the following code to get a glimpse of the data:</p><pre>stk.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/155/1*bQFpNjGInDX61hg9h4h7qQ.png" /></figure><p>Let’s transform this ordinary stock market data into data that can be used to make and evaluate predictions.</p><pre># price sequence length<br>num_weeks = 24<br><br># dictionary for data storage<br>data_dict = {<br>    &#39;start_date&#39;: [],<br>    &#39;end_date&#39;: [],<br>    &#39;pred_date&#39;: [],<br>    &#39;price_seq&#39;: [],<br>    &#39;last_week_price&#39;: [],<br>    &#39;next_week_price&#39;: [],<br>    &#39;y_true&#39;: [],<br>}<br><br># step through stock data with num_weeks window<br>for i in list(range(len(stk) - num_weeks)):<br><br>  # cut stock data with 25 week window<br>  # 1 extra week so we know if next week was higher or lower than last week in sequence<br>  stk_cut = stk[i:i+num_weeks+1]<br><br>  # get data necessary for prediction and evaluation<br>  start_date = stk_cut.index.tolist()[0]<br>  end_date = stk_cut.index.tolist()[-2]<br>  pred_date = stk_cut.index.tolist()[-1]<br><br>  price_seq = stk_cut[&#39;Adj Close&#39;].tolist()[:-1]<br>  last_week_price = stk_cut[&#39;Adj Close&#39;].tolist()[-2]<br>  next_week_price = stk_cut[&#39;Adj Close&#39;].tolist()[-1]<br><br>  # label 1 if next week&#39;s price was higher, else label 0<br>  y_true = 1 if next_week_price &gt; last_week_price else 0<br>  <br>  # store data<br>  data_dict[&#39;start_date&#39;].append(start_date)<br>  data_dict[&#39;end_date&#39;].append(end_date)<br>  data_dict[&#39;pred_date&#39;].append(pred_date)<br>  data_dict[&#39;price_seq&#39;].append(price_seq)<br>  data_dict[&#39;last_week_price&#39;].append(last_week_price)<br>  data_dict[&#39;next_week_price&#39;].append(next_week_price)<br>  data_dict[&#39;y_true&#39;].append(y_true)<br><br># make pandas dataframe with data<br>df = pd.DataFrame(data_dict)</pre><p>Now, let’s take a closer look at what we’ve just created. Among the useful data we’ve stored, the most important are the price_seqand y_truecolumns. The former represents a sequence of 24 weeks of stock prices, which we will feed into GPT to predict whether the next price will be higher or lower than the last price in the sequence. The latter tells us what actually happened, with 1 indicating that next week’s price was higher and 0 indicating it was lower.</p><pre>df.head()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*-NNg2DTifkXX5nZ9C-wF8g.png" /></figure><p>By running the following code, we can see that the distribution between higher and lower is almost even:</p><pre>df[&#39;y_true&#39;].value_counts(normalize=True)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/100/1*_X5qTnhP1w_vSYzA6qPDzg.png" /></figure><p>If you have used ChatGPT in the past, you know that it does not like to make financial predictions. It’s unfortunate, but I get it. OpenAI does not want to be responsible for a r/wallstreetbets Ape who YOLO’s his life savings into a bad investment because a chat bot told him to. So, in the prompt, I don’t mention stocks or finance at all. GPT also gets a little shy when it comes to making uncertain predictions, but I urge it to take a guess, even if it’s feeling clueless. Finding a good prompt took some tinkering, and I’m sure there are better prompts out there waiting to be discovered.</p><p>Six months ago, I never would have thought that I’d be writing paragraphs of natural language in my code to coax a chat bot into doing my bidding, but here we are!</p><p>By running the code below, we can harness the power of GPT to make predictions on stock price movements by analyzing sequences of historical data.</p><pre># function to get prediction out of reply string<br>def get_pred_from_reply(reply):<br>  if &#39;higher&#39; in reply.lower():<br>    return 1<br>  elif &#39;lower&#39; in reply.lower():<br>    return 0<br>  else:<br>    return -1<br><br># prompt for GPT -- convinces GPT to make guess even if it can&#39;t find a pattern<br>prompt_template = &quot;&quot;&quot;<br>Guess if the next number in the following sequence is lower or higher than the last number in the sequence.<br>Even if there is no recognizable pattern you should still make a guess.<br>There is no penalty for being wrong, but you should attempt to be right.\n<br>&quot;&quot;&quot;<br><br># set max message history<br># GPT can only handle so many tokens (characters), so we limit the number of messages stored<br>max_history_length = 15<br><br>message_history = [] # message history storage<br>preds = []  # prediction storage<br><br># loop through all prices sequences<br>for ps in tqdm(df[&#39;price_seq&#39;]):<br><br>  # turn price sequence list into a string<br>  price_seq_str = &quot;, &quot;.join(str(x) for x in ps)<br><br>  # add price sequence string to end of prompt template to create prompt<br>  prompt = prompt_template + price_seq_str<br><br>  # add prompt to message history<br>  message_history.append({&#39;role&#39;: &#39;user&#39;, &#39;content&#39;: prompt})<br><br>  # keep only the most recent max_history_length messages in the list<br>  message_history = message_history[-max_history_length:]<br><br>  # get GPT to make a guess with message history for context<br>  completion = openai.ChatCompletion.create(<br>    model=&quot;gpt-3.5-turbo&quot;,<br>    messages=message_history<br>  )<br><br>  # retrieve GPT&#39;s reply<br>  reply = completion.choices[0].message.content<br><br>  # add GPT&#39;s reply to message history<br>  message_history.append({&#39;role&#39;: &#39;assistant&#39;, &#39;content&#39;: reply})<br><br>  # store GPT&#39;s prediction<br>  preds.append(get_pred_from_reply(reply))<br><br># add prediction column to dataframe<br>df[&#39;y_pred&#39;] = preds</pre><p>Get ready for the exciting part. Unbelievably, GPT predicts the next move in stock prices with 67% accuracy. Given the challenges associated with making stock market predictions, this is an impressive result.</p><pre># evaulate performance<br>accuracy = metrics.accuracy_score(df[&#39;y_true&#39;], df[&#39;y_pred&#39;])<br><br>print(f&quot;Accuracy: {round(accuracy * 100)}%&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/104/1*sQCmc91G4QmND3mmnIeKmw.png" /></figure><p>I tested it on another stock in a different timeframe to make sure I wasn’t just getting lucky.</p><pre>stk= yf.download(&quot;PG&quot;, start=&quot;2015-03-31&quot;, end=&quot;2017-03-31&quot;)</pre><p>After running the same code with Proctor &amp; Gamble stock data, the accuracy was 63%. Although not as high as the Apple example, this is still an impressive result.</p><p>While more runtime and money will be required to fully explore this concept, it holds immense promise for integration into more sophisticated trading systems. Of course, it’s not a magic wand that guarantees instant riches. But it’s a tool with the potential to help us make informed trading and investment decisions. What’s most exciting about this concept is that it showcases the versatility of GPT and its potential to transform the way we approach finance.</p><p><em>Note: The information provided in this article is for educational and informational purposes only. It should not be construed as financial or investment advice. Before making any trading or investment decisions, it is important to conduct your own research, carefully consider your objectives, financial situation, and risk tolerance, and consult with a licensed financial advisor if necessary. Any trades or investments made based on the information in this article are done at your own risk and you are solely responsible for the outcomes of such decisions.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=611f58970fa2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Counting in the Age of Crowds]]></title>
            <link>https://daniel-carter.medium.com/counting-in-the-era-of-crowds-with-artificial-intelligence-9d3888ca6ea5?source=rss-3f0c5d200547------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d3888ca6ea5</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[neural-networks]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Daniel Carter]]></dc:creator>
            <pubDate>Tue, 02 Mar 2021 10:56:59 GMT</pubDate>
            <atom:updated>2023-04-28T19:54:15.920Z</atom:updated>
            <content:encoded><![CDATA[<h4>Learn how to count large crowds in milliseconds with Artificial Intelligence</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*R3dQke1lZ2lhtZGfEDS8yw.gif" /></figure><h3>Introduction</h3><p>The impact of crowds on history is undeniable. Throughout time, the world has seen the rise of religions, the fall of empires, and the birth of nations, all marked by the rising activity of crowds. Today, we are witnessing a resurgence of crowds, driven by a variety of socioeconomic and political factors. While it’s impossible to predict the future, it’s clear that we are in the midst of an era of heightened crowd activity. Only time will reveal what lies ahead.</p><p>Recent advancements in Artificial Intelligence and Computer Vision have given us new ways to view ourselves, in all of our glory and imperfection. In this article I’ll go over how I used AI to quickly and accurately view one of the most important features of a crowd: its size. This technology, along with other tech, may someday give us a clearer picture of how crowd activity influences the world.</p><p>If you just want to see cool crowd counting pictures of recent events, scroll down to the Counting Recent Events section. If you want to know how this is actually done, stay tuned.</p><h3>Quick Overview</h3><p>The goal of this project was to quickly and accurately count crowds in images and videos. To accomplish this goal, I trained an encoder-decoder neural network that takes a crowd image as an input and returns a density map of the crowd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*ucreuwD2cnWExTG1BqeDPw.png" /><figcaption>Figure 1: Crowd image and its corresponding density map</figcaption></figure><p>The density map gives us a useful visualization of head location, head size and overall crowd density. The <a href="https://en.wikipedia.org/wiki/Integral">integral</a> of the density map is the crowd count, but more on this in a minute.</p><p>Now that you know the basic concept, let’s get into the details.</p><h3>Making Sense of the Data</h3><p>Before training the model, it is essential that we preprocess the data in a way that gives the model the best chance at making the correct prediction.</p><p>For training data, I used the popular ShanghaiTech crowd dataset. You can download the data <a href="https://pan.baidu.com/s/1nuAYslz">here</a>. This dataset is separated into parts A and B. The A dataset contains larger crowd sizes and the B dataset contains smaller crowd sizes.</p><p>The ShanghaiTech dataset gives us everything we need to get started — over a thousand images and their ground truth annotations (i.e. the coordinates of every human head in the image).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*Dw5M8nUK1ok2Nsmw5Lo6qg.png" /><figcaption>Figure 2: ShanghaiTech image with ground truth points</figcaption></figure><p>Each ground truth point in the image can be represented by a <a href="https://en.wikipedia.org/wiki/Dirac_delta_function">Dirac delta function</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/172/1*48HmZIkMzobfAhWHwJbMtQ.png" /></figure><p>Thus an image with N heads labeled can be represented by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*kcCzGArCqj6r-6x7Wbw5vA.png" /></figure><h4>Gaussian Kernels</h4><p>The building blocks for this project are Gaussian Kernels. These kernels are based on the famous Gaussian function, which describes a normal distribution in statistics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*7ObHI0fML5YAJhHb-V9mBA.png" /><figcaption>Figure 3: Gaussian Function</figcaption></figure><p>Interestingly, if you take a vector of outputs from the Gaussian function and multiply it by the <a href="https://en.wikipedia.org/wiki/Transpose">transpose</a> of the same output vector, you get a Gaussian Kernel matrix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*1kucJhWjES_zRngBjlCeig.png" /><figcaption>Figure 4: Gaussian Kernel</figcaption></figure><p>The Gaussian Kernel is most often used to smooth or <a href="https://ai.stanford.edu/~syyeung/cvweb/tutorial1.html">blur images through convolution</a>. However, for a crowd counting project, Gaussian Kernels are useful for two reasons: 1) they are circular like the shape of a human head and 2) the sum of a Gaussian Kernel matrix is one.</p><p>Let’s talk about the second point in a bit more detail. The academic literature refers to the crowd count as the integral of the density map. In calculus, integrals are most commonly thought of as the area/volume under a curve/surface, but it’s weird to think in those terms when we are looking at a flat image.</p><p>It makes a lot more sense when we give each pixel in the Gaussian Kernel a height. Now we can clearly see the Gaussian Kernel shape. The volume under this surface equals one — a great way to count exactly one head in an image.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Etesseract314%2F5.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Etesseract314%2F5%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb7e0f521c2984716e080b7a24b9859/href">https://medium.com/media/bcb7e0f521c2984716e080b7a24b9859/href</a></iframe><p>The Gaussian Kernel can be represented by the function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/131/1*jaCShdlKnBqeto7H_rExNQ.png" /></figure><h4>Geometry-Adaptive Kernels</h4><p>To give our model a better chance of predicting accurate crowd sizes, we need a way to correct for the perspective distortion that occurs from representing a 3D scene with a 2D image. In other words, depending on perspective, some heads will be small and some will be large, and we need a way to convey that information to the model.</p><p>The idea of geometry-adaptive kernels was first introduced in the 2016 paper <a href="http://people.eecs.berkeley.edu/~yima/psfile/Single-Image-Crowd-Counting.pdf">Single-Image Crowd Counting via Multi-Column Convolutional Neural Network</a>. The idea behind geometry-adaptive kernels is simple: heads appearing smaller in an image tend to be closer to nearest neighbors and heads appearing larger tend to be further from nearest neighbors.</p><p>Let’s revisit the image we saw above, except this time we’ll focus on only a few heads. Each ground truth point has red arrows drawn to its three nearest neighbors. The yellow circle represents the size of the Gaussian Kernel. You’ll notice that when the average distance to the nearest neighbors shrinks, so does the radius of the Gaussian Kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rtTps87JdTznd0vhyqoNmw.png" /><figcaption>Figure 6: Size of the Gaussian Kernel depends on average distance to nearest neighbors</figcaption></figure><p>Obviously this method is not perfect as there could be a small head in the background far from other heads. But it still adds some interesting context.</p><p>If we denote <em>k </em>nearest neighbors as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*ypMlDshrLvHWaLC1jSMMdA.png" /></figure><p>Then the average distance is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/279/1*6US58fcCaHV5S5WjuBlRYA.png" /></figure><p>The average distance is then multiplied by a constant (β) to arrive at the radius of the Gaussian Kernel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/159/1*-kpxO55A-ikfHnNYyuQcqA.png" /></figure><p>The number of nearest neighbors and β can be tinkered with. For my preprocessing, I used 3 nearest neighbors and 0.5 for β.</p><h4>Density Maps</h4><p>Now that we’ve learned about Gaussian Kernels and how to dynamically adjust their size, let’s take a look at how we can use them to build density maps. Density maps are what we want the neural network to reproduce. Density maps not only give us the crowd count but a useful visualization.</p><p>To build a density map, we first start with a 2D array (matrix) of zeros with the height and width of the original image. For each ground truth coordinate, we calculate the appropriate radius of the Gaussian Kernel based on its nearest neighbors and then add that kernel to the array centered on the ground truth point.</p><p>When heads in the image overlap, so do the Gaussian Kernels. This means that places in the image that have a high density of heads will have higher pixel values. And, as you can see from the density map below, higher pixel values are represented by the dark red spots. Giving the model the context of these varying densities will help it count heads that are slightly obscured.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjetYUYmnazP2AfgUYRDyw.png" /><figcaption>Figure 7: Image and ground truth density map</figcaption></figure><p>We can get the entire crowd count by taking the integral of the density map. Again, if we want to visualize why the integral works, we can give each pixel value in the density map a height. The crowd count is equal to the volume under the surface.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fplotly.com%2F%7Etesseract314%2F9.embed%3Fautosize%3Dtrue&amp;display_name=Plotly&amp;url=https%3A%2F%2Fchart-studio.plotly.com%2F%7Etesseract314%2F9%2F&amp;image=https%3A%2F%2Fchart-studio.plotly.com%2Fstatic%2Fwebapp%2Fimages%2Fplotly-logo.8d56a320dbb8.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=plotly" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/636ba4782d5635a2f2a413a2a8e53838/href">https://medium.com/media/636ba4782d5635a2f2a413a2a8e53838/href</a></iframe><p>Bringing together everything that we have defined so far, the density map can be represented by:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*S6b6MQTkmr4_UJTEqVCPbQ.png" /></figure><p>Every ground truth point (represented by the Dirac delta function) is <a href="https://en.wikipedia.org/wiki/Convolution">convolved</a> with a geometry-adaptive Gaussian Kernel. The academic literature refers to this as a convolution and, although it technically is, it can be confusing when reading a paper on Convolutional Neural Networks. Remember, this convolution is simply adding the geometry-adaptive Gaussian Kernel into a 2D array at the ground truth point. We’ll get into the other kind of convolutions in a minute.</p><h4>Input Image Normalization</h4><p>Before we get to the modeling, let’s quickly go over one more step in preprocessing. The density map is what we want the model to replicate, but we first have to input an image.</p><p>The pixel values of a color image typically range from 0 to 255. However, when dealing with neural networks, it’s better to use smaller numbers because of the <a href="https://deepai.org/machine-learning-glossary-and-terms/exploding-gradient-problem">exploding gradient problem</a>. To get smaller numbers, we divide every pixel value in the image by 255. This gives us a pixel value range from 0 to 1.</p><p>Next we must consider the separate parts of a color image. A color image is actually three channels (matrices) of pixels, one channel for each primary color in the visible light spectrum — red, green and blue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/306/1*f6QZHwRgcDHLLaucEqFxlg.png" /><figcaption>Figure 9: RGB channels of color image</figcaption></figure><p>To finish normalization, we subtract a mean from each pixel to center the data around 0, then we divide each pixel by a standard deviation to ‘standardize’ the spread of the data . The mean and standard deviation depends on what channel we are dealing with. It is common practice to use the RGB means and standard deviations of a very large dataset called ImageNet. If this concept is still a bit confusing, read this post <a href="https://stats.stackexchange.com/questions/211436/why-normalize-images-by-subtracting-datasets-image-mean-instead-of-the-current">here </a>that talks about the idea in more detail.</p><h3>Building a Model to Predict Crowd Counts</h3><p>In this section I will be going over the specifics of the neural network I used for this project. I will describe the model at a high level for people who are already familiar with Artificial Intelligence, but also delve into some of the basics for newcomers.</p><p>The model I used for this project came from the 2018 paper <a href="https://openaccess.thecvf.com/content_ECCV_2018/papers/Xinkun_Cao_Scale_Aggregation_Network_ECCV_2018_paper.pdf">Scale Aggregation Network for Accurate and Efficient Crowd Counting</a>. The SANet is an encoder-decoder Neural Network. During the model’s training, the encoder takes in an image of a crowd and learns the features of the image. After the encoder learns the image features, that information is passed to the decoder and the decoder attempts to reproduce the ground truth density map.</p><h4>Architecture</h4><p>The encoder (top half of Figure 10) is based on the <a href="https://www.cs.colostate.edu/~dwhite54/InceptionNetworkOverview.pdf">Inception Network</a>, which is a popular Convolutional Neural Network architecture. The encoder takes the color image as input. As you can see, the convolutional layers are broken down into four parts. The first number on one of the convolutional layer parts is the kernel size and the second number is the depth of the channels. For example, “Conv3_16” means the kernel size is 3x3 and there are 16 channels/feature maps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*95GHSvIjWTcXqnnCSAH7uw.png" /><figcaption>Figure 10: SANet Architecture (<a href="https://openaccess.thecvf.com/content_ECCV_2018/papers/Xinkun_Cao_Scale_Aggregation_Network_ECCV_2018_paper.pdf">source</a>)</figcaption></figure><p>The Inception architecture was designed to cut down on computational cost, but in this case it has another benefit. In crowd images, humans appear in multiple sizes and positions. With four different kernel sizes, the model can get a multi-scale perspective of the input image because, essentially, there are multiple sized windows scanning for features in the image.</p><p>The convolutions use “same” <a href="https://d2l.ai/chapter_convolutional-neural-networks/padding-and-strides.html">padding</a> so the dimension of the output is not reduced during the operation. The data from every convolution is passed through an activation function. The channels for each of the four convolutional parts are combined with a concatenation layer, then the information contained in the feature maps is summarized in a max pooling layer.</p><p>The decoder (bottom half of Figure 10) is what produces the density map and is a bit simpler in structure. There are five standard convolutional layers (not Inception-like) and three transposed convolutional layers. Each convolutional layer, both standard and transposed, is followed by an activation function.</p><p>If things are still fuzzy, don’t worry. I will try to clear things up by going into greater detail below.</p><h4>Convolutional Layers</h4><p>Above I spoke a lot about convolutions, but what does that mean in this context? Convolutional layers are where the model learns the details (features) of an image.</p><p>At a low level, the concept behind convolutional layers is quite simple. Take a minute to study the movements of the GIF in Figure 11.</p><p>Think of the large blue matrix on the left as an image. The numbers inside the image are the pixel values. The shaded window moving across the image is a 3x3 kernel. The numbers inside the kernel are called weights. The green matrix on the right is the output, or feature map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/0*OC8lwRsDkGJBejPw.gif" /><figcaption>Figure 11: Convolution operation in a convolutional layer (<a href="https://arxiv.org/abs/1603.07285">source</a>)</figcaption></figure><p>The math to produce the output is easy — it’s element-wise multiplication and then addition. Consider the top-left position of the kernel on the image. If we multiply element-wise and then add everything together, we get:</p><p>(3x0) + (3x1) + (2x2) + (0x2) + (0x2) + (1x0) + (3x0) + (1x1) + (2x2) =</p><p>0 + 3 + 4 + 0 + 0 + 0 + 0 + 1 + 4 =</p><p><strong>12</strong></p><p>This number corresponds to the top-left pixel on the feature map.</p><p>So, why are we doing this again?</p><p>By adjusting the weights in the kernel we can uncover information in an image that will help the model make accurate predictions. Let’s look at a simple but real example to try to make more sense of this concept.</p><p>Consider this kernel and its weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*dpsJ9p-hMGmGFUBw9V8vFA.png" /><figcaption>Figure 12: Sobel Kernel for vertical edge detection</figcaption></figure><p>Instead of sliding this kernel across the blue matrix we saw above, we’ll slide it over this image:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*8pqq-AKbdqkLmB_xOLT6og.png" /><figcaption>Figure 13: Example input image for simple convolution</figcaption></figure><p>And here is the output (feature map):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*UOIZqN0IYj_rEMZ_OdLTZQ.png" /><figcaption>Figure 14: Feature map showing vertical edges from input image</figcaption></figure><p>We can see that the convolution of the kernel and the image gives us an output that highlights the edges of objects in the image — in this case people. Also notice how the edges are more pronounced in the vertical direction.</p><p>Let’s change the weights in the kernel and do the convolution again. This time we’ll use the following weights:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/238/1*3GvfBeV_7ROaezrWu1Gf8g.png" /><figcaption>Figure 15: Sobel Kernel for horizontal edge detection</figcaption></figure><p>And here is the output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*aHk6YHR8EF1lF1hew4NcLQ.png" /><figcaption>Figure 16: Feature map showing horizontal edges from input image</figcaption></figure><p>Again, edges are being highlighted, but this time the edges are more pronounced in the horizontal direction.</p><p>By changing the weights inside the kernel, we can retrieve useful information from the image. This is what helps the neural network determine what’s in the image —for this project, how many heads are in an image and where those heads are located.</p><p>It’s important to keep in mind that the above is a very simple example of what happens in a convolutional layer. When a Convolutional Neural Network is training, what it’s actually doing is changing the kernel weights to improve model accuracy, and the weight combinations get very complex. The kernels could be detecting edges, shapes or patterns. It’s hard to say. In fact, understanding what happens inside of neural networks (interpretability) is still a major area of research.</p><p>Another thing to consider is that a convolution can have multiple kernels, which produces multiple outputs. These outputs/feature maps are the channels referred to in the Architecture section above. This is why we see depth to the output of the convolutional layer in Figure 17. These are feature maps stacked together. We’ll talk about why there are four section to the output in a minute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/284/1*QaUsu-2gxmk5OJG2s4QAOA.png" /><figcaption>Figure 17: Output from a convolutional layer showing channel depth</figcaption></figure><p>The entirety of the convolutional layer is a bit more complex than what is shown in Figure 10. If we zoom into a convolutional layer and rotate it 90 degrees, we see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/859/1*AA9KlrRN6xkZaojDlh4S_g.png" /><figcaption>Figure 18: Detailed view of a convolutional layer in SANet</figcaption></figure><p>When data comes from the previous layer, it is first passed through four separate 1x1 convolutions. It may seem strange to have 1x1 kernels, but this is a great feature of the Inception-like architecture. I won’t go into great detail here, but the 1x1 convolutions are used to <a href="https://stats.stackexchange.com/questions/194142/what-does-1x1-convolution-mean-in-a-neural-network">reduce the depth of channels</a> which significantly reduces computational cost.</p><p>The outputs from the 1x1 convolutions are then passed through activation functions. After that, the data is passed to 3x3, 5x5 and 7x7 convolutions. These different kernel sizes are used to get information from an image on multiple scales. Again, people can appear in many different sizes in an image, so these different size kernels help identify people on multiple scales.</p><p>Finally the data is passed through more activation functions. Before the data reaches the next convolutional layer, it goes through a concatenation layer and a max pooling layer.</p><h4>Activation Function, Concatenation &amp; Max Pooling</h4><p>So we’ve gone over convolutions in detail, but some of the concepts within the convolutional layer may still be a bit fuzzy.</p><p>Activation functions determine the strength of the connections in a neural network. If the activation function outputs a relatively large number, the connection to the subsequent part of the network is strong. If the activation function outputs a relatively small number, the connection to the subsequent part of the network is weak.</p><p>This concept is easier to visualize in <a href="https://missinglink.ai/guides/convolutional-neural-networks/fully-connected-layers-convolutional-neural-networks-complete-guide/">fully connected layers</a> but the idea is the same. Take a look at the fully connected layer in Figure 19. Data is being passed from one set of neurons to the next. Some connections are strong (bold) and some are weak. The strength of the connection depends on the output of the activation function, which is calculated before the data is sent to the next layer of neurons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*jPqA4vHmLlU_mx_25brVhA.png" /><figcaption>Figure 19: Fully-connected layer showing weak and strong connections</figcaption></figure><p>You can take this concept and apply it to the convolutional layer in Figure 18. But instead of only thinking in terms of neurons, think in terms of pixels as well. This wiring, along with the kernel weights, is what determines the model’s accuracy. The activation function used throughout the model is <a href="https://en.wikipedia.org/wiki/Rectifier_(neural_networks)">ReLU</a>.</p><p>After the convolutions and activation functions, we get to a concatenation layer. This layer takes all the feature maps/channels produced by the four multi-scale convolutions and combines them into one. This is why Figure 17 was broken into four sections.</p><p>Finally we arrive at the max pooling layer. In the max pooling layer, we slide a kernel along the input like we did for the convolutions. But instead of doing element-wise multiplication, we simply take the maximum value within the window. This does two things 1) it helps us only focus on the most prominent features within an image and 2) it reduces dimensionality of the data and thus reduces computational cost. We can see that over the span of the encoder, the height and width dimensions shrink due to max pooling.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*9xxEgHGu993MLJQOIjEZRQ.png" /><figcaption>Figure 20: Height and width of data shrinks due to max pooling layers</figcaption></figure><h4>Transposed Convolutions</h4><p>We have now covered all the major concepts of the encoder part of the neural network. The decoder is simpler, but there is one more important concept we must consider: transposed convolutions.</p><p>Think about what happened to the shape of the data throughout the encoder. We reduced the width and height dimensions while learning the features of the image. However our goal isn’t merely to learn what’s in the image — it’s to produce a density map of the crowd. This is where transposed convolutions come into play.</p><p>Instead of reducing dimensionality, transposed convolutions increase dimensionality. This operation allows us to take the low resolution feature maps from the encoder and produce a high resolution density map.</p><p>To better understand this concept, let’s take a look at a simple example. In Figure 21 we can see an input and a kernel on the left. To start, take the blue (upper left) weight in the kernel and multiply it by every value in the input. That gives us all zeros in the upper left of the output. If we do the multiplication with the red (upper right) weight, we get a copy of the input in the upper right of the output because the red weight is one. If we do the same with the other weights and then do element-wise addition, we get the final output on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1013/1*l0tiGo9-q1awbRQrwr2IQw.png" /><figcaption>Figure 21: Simple transposed convolution example</figcaption></figure><p>The transposed convolutional layers are why we see the height and width of the data expand throughout the decoder. Also notice the channel depth is decreasing throughout the decoder as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*6NazwPqdG_KHUJ1K5I7o6A.png" /><figcaption>Figure 22: Height and width increasing throughout decoder due to transposed convolutions</figcaption></figure><p>There are regular convolutional layers in the decoder, although these layers are not as complex as the convolutional layers in the encoder. The decoder convolutional layers are not multi-scale. There is no concatenation or max pooling either, but each layer, including the transposed convolutions, is followed by a ReLU activation function.</p><p>The kernel weights in the decoder are not used to find image features like they are in the encoder, but rather to manipulate the pixel values in a way that most accurately produces the density map.</p><h4>Loss Function</h4><p>Once a density map is produced by the neural network, how do we know if it’s a good representation of the crowd image? We need a <a href="https://en.wikipedia.org/wiki/Loss_function">loss function</a> to compare the human-created density maps and the neural-network-created density maps.</p><p>As I stated above, the sum of the pixels is the crowd count. So we could just take the sum of the ground truth density map and the sum of the predicted density map and compare the two, right? Think about the model spitting out a condensed blob of pixels onto a density map that just so happens to equal the actual crowd count. It wouldn’t actually represent the location of the heads or the density of the crowd but the count would technically be accurate.</p><p>To get a better idea of the problem we need to overcome consider Figure 23. Each image has the same number of black and white pixels, but the images themselves are radically different. Instead of evaluating the image globally (e.g. summation of pixels), we need to evaluate local patterns.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*rABtAbAFr0X8vEN4a639nA.png" /><figcaption>Figure 23: Each image has the same global statistics but are much different locally (<a href="https://jwnorman.com/">source</a>)</figcaption></figure><p>This section is going to get a bit “mathy” but I’ll do my best to describe what’s going on in plain English.</p><p>The loss function for this model is actually a combination of two loss functions. The first function of the two is Euclidean Loss, which is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*dzA3JdSCxnhxcjDOvkPVpg.png" /></figure><p>Euclidean Loss is essentially pixel-wise <a href="https://en.wikipedia.org/wiki/Mean_squared_error">mean squared error</a>. First we take a pixel value from the ground truth density map (x) and subtract the corresponding pixel value from the predicted density map (y). Then we square the difference to make the error positive and to make large errors result in very large losses. Finally we add all the pixel errors together and divide by the total number of pixels (N) in the density map.</p><p>The Euclidean Loss is good for evaluating error on a pixel level, but it would be nice to compare larger local areas too. That’s where the Structural Similarity Index (SSIM) comes into play.</p><p>The idea of SSIM was first published in the 2004 paper <a href="https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf">Image Quality Assessment: From Error Visibility to Structural Similarity</a>. It was first developed to measure the difference between an original image and an image that had been distorted from processing, compression, storage, etc. The SSIM is a value between 0 and 1 — zero meaning the two images are not similar at all and 1 meaning the two images are perfectly similar.</p><p>For the implementation of SSIM, we’ll use our old friends convolutions and Gaussian Kernels. Scanning a window (kernel) across an input — in this case the ground truth and predicted density maps — will allow us to calculate local statistics for each window position.</p><p>We can see another convolution example in the Figure 24 GIF. The blue matrix would be the density map (input), the shaded window moving across the density map would be the Gaussian Kernel, and the green matrix is the output. You’ll also notice a border around the input. This is referred to as padding and it ensures the output is the same dimension as the input. The padding was present in the convolutional layers as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/0*XmAoQbHNOqVE_z9q.gif" /><figcaption>Figure 24: Convolution with padding (<a href="https://arxiv.org/pdf/1603.07285.pdf">source</a>)</figcaption></figure><p>For every possible kernel location on both density maps, the local mean, the local variance and the local covariance is calculated. The formulas used to calculate these statistics may look unusual if you are reading them in the academic literature but I’ll go over the formulas in plain English.</p><p>Here is the formula for calculating the local mean:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/478/1*jZmf5eC88EWQtxtUlH4-VQ.png" /></figure><p>Weird, huh? That’s not the mean formula we typically see. What this is actually doing is using the Gaussian Kernel weights (W) to convolve the predicted density map (F) at every possible kernel position (P). Again, the output is a matrix with the same dimensions as the density map. The above is the mean formula for the predicted density map but the same operation is done with the ground truth density map.</p><p>The local variance formula found in the academic literature is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*YchtfFfjSWpkCbCjIcoozA.png" /></figure><p>However, across almost every statistical tool (Python, Matlab, etc.), this more computationally efficient version is used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/1*OQbGkkE6pKwmCvbHkKZw1A.png" /></figure><p>If you’re wondering how this is formula is derived, I recommend looking at the explanation <a href="https://www.khanacademy.org/math/statistics-probability/summarizing-quantitative-data/variance-standard-deviation-population/v/statistics-alternate-variance-formulas">here</a>. So to get local variance, we take the convolution of the Gaussian Kernel weights and the squared density map, then subtract the squared mean of the density map. The above variance formula is for the predicted density map but the same operation is done with the ground truth density map.</p><p>Next we calculate the local covariance. The way it is presented in the academic literature is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/1*BpetlwiYiDbh2Fc8bnkzNA.png" /></figure><p>But this version is used for the statistical tools:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/927/1*g1r0Cd47ds61Az5g51Kjxg.png" /></figure><p>To get local covariance, we first take the convolution of the Gaussian Kernel and the product of the predicted and ground truth density maps, then subtract the product of the predicted and ground truth density map means.</p><p>Next we calculate the SSIM value for each pixel by plugging the above statistics into this formula:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*muSczKmnudd6ra31TYexZA.png" /></figure><p>Although I won’t go into detail here, this formula is a combination of luminance, contrast and structure. The C1 and C2 variables are very small constants to prevent division by zero.</p><p>Once SSIM is calculated for each pixel, each pixel value is added together and the sum is divided by the total number of pixels (N). To get the loss, we simply subtract the final SSIM value from one. This loss is called Local Consistency Loss and it is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*qWGRfDOFQW4ZmPDJF_JWCg.png" /></figure><p>Now that we have Euclidean Loss and Local Consistency Loss, we combine the two to arrive at the final loss function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*V2euWVI68In4eGiJ9Fh2og.png" /></figure><p>The α is a weight to balance both losses. It was set to 0.001 for this project.</p><p>Now that I’ve beaten you over the head with the math, let’s relax and talk about what we’re actually doing with this loss function.</p><p>The loss function tells the model how well it’s performing during training. The model will use the ground truth and predicted density maps to calculate loss, adjust the kernel weights, then calculate loss again to see if performance improved from the kernel weights being adjusted. This happens many many times during training and is how the model eventually learns to count crowds.</p><p>We can think of this process like a blind person walking along a landscape. The person takes a step in one direction and uses what they know about their last position to determine if their current position is higher or lower in elevation. The person continues to take steps until they believe they‘ve found the lowest point on the landscape. Below is an image of the actual loss landscape of ResNet-56 (a popular neural network). The lowest point is where the model’s weights produce the most accurate results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*N_o_aMuIBRAo5kO1ZotEgg.png" /><figcaption>Figure 25: Loss Landscape of ResNet-56 (s<a href="https://arxiv.org/abs/1712.09913">ource</a>)</figcaption></figure><h3>Evaluating the Model</h3><p>The model was trained in a Google Colab Pro notebook and used their NVIDIA Tesla P100 GPU and “High-RAM” virtual machine. The runtimes are longer in Colab Pro but the training would time out over night. In total, the training took about three days. After that long wait I can now predict crowd counts in milliseconds.</p><p>The average error (i.e. difference between actual and predicted crowd count) was 86.4 for Part A of the test data (larger crowds). The average error for Part B of the test data (smaller crowds) was 16.9. These numbers are good but slightly behind some of the newer models. My goal over the next few months will be to use the newer techniques as well as train on a lot more data to improve accuracy.</p><p>Let’s look at some real examples from the test data to see this model’s strengths and shortcomings.</p><p>We’ll start with the old black and white input image below. For such a large crowd size the model did well. It was able to detect the location of the crowd in the foreground and background. The model could also detect the denser areas of the crowd but had a little trouble with the smaller heads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yT0lsBhVHZEUTaVY1EMhNQ.png" /></figure><p>The model performs similarly with the image below. The model sees density but has a bit of trouble with the granularity of the crowd in the background and undercounts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SrqoaLRBX5I11erbZqi53w.png" /></figure><p>Remember how the Gaussian Kernel radius for the ground truth density maps is based on how close a head was to its nearest neighbors? As I mentioned before, this method is not perfect. Sometimes if there is a small head not close to any other heads, the Gaussian Kernel radius blows up to an unrealistic size. The radius becomes so large that the Gaussian Kernels become too faint to be seen on the ground truth density map. We can see from the example below that the model corrected for these discrepancies during training. The markings in the foreground of the predicted density map are much closer to the actual head sizes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NW2Nd2sT-Mm9SbGfGlxwg.png" /></figure><p>Below we can see an example of the model’s biggest flaw. It finds the crowd but also misidentifies some inanimate objects as people, and thus overcounts. You will also notice the model incorrectly seeing heads in the background of the GIF at the very top of the article. There is an analogy for this effect in psychology called <a href="https://en.wikipedia.org/wiki/Pareidolia#:~:text=Pareidolia%20(%2Fp%C9%9Bra%C9%AA%CB%88,Moon%20or%20the%20Moon%20rabbit.">pareidolia</a>, which is when people mistakenly see faces in inanimate objects. I believe this flaw may be overcome with <a href="https://www.cs.toronto.edu/~tingwuwang/semantic_segmentation.pdf">semantic segmentation</a> to block out background objects, although that may overcomplicate the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmvmtu76E83H8WdoOJ81SQ.png" /></figure><p>The model performs best when there is good lighting, few background objects and a high camera angle. Both examples below demonstrate the excellent accuracy under these conditions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*68omMDzGdkvyRLd6EQLuAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wzf3dkuvNH9QDC3VNWAaKQ.png" /></figure><h3>Counting Recent Events</h3><p>Over the past few years we have witnessed an incredible rise in crowd activity. There are many socioeconomic and political topics we could discuss to figure out why this is the case, but let’s save that discussion for another time. Instead, let’s use this new and exciting technology to visualize these phenomena.</p><p>In recent years mass shootings have sparked a national debate on gun regulation and public safety. To make their voices heard, gun control advocates took to the streets in early 2018 during the nation-wide March for Our Lives demonstration. Below we can see a crowd of almost 2,700 people gathered in Tampa Bay, Florida. Larger crowds gathered in DC, but I chose this image because it has a good angle and captures a large portion of the entire crowd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3CFYNI1-TSynr-Xkm6YWoA.png" /><figcaption>Original Photo Credit: Luis Santana | Tampa Bay Times</figcaption></figure><p>Large crowds have also made their way to political rallies in recent years. Below you can see about 2,000 people gathered for a Trump rally. This rally took place in Tampa a few months after the March for Our Lives rally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FiJGWz7JxTQpcWLWuG81VQ.png" /><figcaption>Original Photo Credit: James Borchuck | Tampa Bay Times</figcaption></figure><p>Crowd activity has not only increased in the United States but all over the world. Below is an image of 3,700 people gathered in Hong Kong in 2019 to protest a law that would allow extradition to mainland China. This is my favorite image because of the granularity the model is able to capture in such a massive crowd. The model even sees the people on the walkway over the street.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XnISaO9rhuzey2obanwYGw.png" /><figcaption>Original Photo Credit: South China Morning Post</figcaption></figure><p>In late May of 2020, a disturbing video surfaced of a police officer killing an unarmed man named George Floyd. This video caused a nation-wide uproar over police brutality and racial injustice. Millions of people across the country took to the streets in support of Floyd and the Black Lives Matter movement. One of the most active cities during these protests was Portland. Below is a picture of about 1,600 gathered in Portland to support racial justice on June 2nd, 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSBHiJJ0nTGMei7S0LJg1Q.png" /><figcaption>Original Photo Credit: Chad DeHart | KGW</figcaption></figure><p>Below is a top-down image of a crowd in Merrick, NY that gathered to support George Floyd and BLM on June 4th, 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M2Xp3AL5IlW_fHhc0Bd8ow.png" /><figcaption>Original Photo Credit: Al Bello | Getty Images</figcaption></figure><p>Below is a crowd of a little over 400 people gathered in Atlanta to support George Floyd and BLM on June 6th, 2020. This crowd is smaller but, remember, these crowds were all throughout the United States.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I9AWPIwiMn6Nwig2epdF_A.png" /><figcaption>Original Photo Credit: Elijah Nouvelage | Getty Images</figcaption></figure><p>Below is a crowd of almost 800 people gathered in Washington DC to support racial justice on June 6th, 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*apOJOtfWD34Wa_hSFEj2qg.png" /><figcaption>Original Photo Credit: Chip Somodevilla | Getty Images</figcaption></figure><p>Below is a crowd of almost 1,300 people gathered in Hollywood to support racial justice on June 7th, 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q77CBX9M2wPVQ7R_YNRp7g.png" /><figcaption>Original Photo Credit: David McNew | Getty Images</figcaption></figure><p>Below is a crowd of 1,200 people gathered in Seattle to support racial justice on July 7th, 2020.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nJVNeUc4Gkx4ebz68Eo_GA.png" /><figcaption>Original Photo Credit: Ruth Fremson | The New York Times</figcaption></figure><p>On June 15th of 2020, Chinese and Indian troops clashed over a border dispute in Galwan Valley, which left four people dead. A recent video released by the Chinese government shows a large group of Indian troops approaching the Chinese troops, so I decided to count them. The model saw 72 troops and the actual count is 64. I find this level of accuracy impressive because the model was never trained on images of people in military gear. Moreover, the colors of the military gear are meant to blend in to the background, but the model is still able to spot even the smallest heads in the image. The model does mistakenly see some heads in the rocks, hence the overcounting, but I’m still blown away by the model’s performance. This example shows the potential of this technology in Defense and National Security.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWNAoF0nQOF341iSBM34Zw.png" /><figcaption>Original Photo Credit: Chinese Government</figcaption></figure><p>The most recent large crowd event in the United States was one of the most explosive political events in the country’s history. Tens of thousands of people gathered in Washington DC on January 6th, 2021 to protest Donald Trump’s election loss. Below is a portion of the crowd, about 2,500 people, that gathered to hear Trump speak. The model is picking up some background noise but, because it’s such a dense crowd, it may still be undercounting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4WnzWsAzMdbx6wpaFJU-Q.png" /><figcaption>Original Photo Credit: Getty Images</figcaption></figure><p>After Trump’s speech, things got ugly. Below is an image of over 500 people storming the Capitol building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EH46Y7DU6xQ45HIVYfY8Qw.png" /><figcaption>Original Photo Credit: Michael Nigro | Pacific Press</figcaption></figure><h3>Next Steps</h3><p>You may have noticed that there is a natural limit when counting crowds in images. It’s difficult to capture an event’s total crowd size in a single image. And, if we zoom out to capture the entire crowd, the crowd becomes too dense for our model to count accurately.</p><p>There are two ways to overcome this problem. First, the model can and will be trained on denser crowds to improve accuracy on very large crowds. Second, the technology’s ideal platform is a drone. With a drone, I could quickly maneuver to the best vantage point and scan over a crowd that can’t fit in only one frame. This would allow me to count events in their entirety (e.g. the total number of people who attended the January 6th rally/riot).</p><p>These are the obvious next steps, but there are many other ideas I have in mind. The ultimate goal is to view humans in ways we’ve never been viewed before so that we get a better idea of where we’re going. And if we get a better idea of where we’re going, maybe we can alter the path.</p><h3>Conclusion</h3><p>Thanks for reading!</p><h3>References</h3><ul><li>Yingying Zhang, Desen Zhou, Siqin Chen, Shenghua Gao, Yi Ma, <a href="http://people.eecs.berkeley.edu/~yima/psfile/Single-Image-Crowd-Counting.pdf"><strong>Single-Image Crowd Counting via Multi-Column Convolutional Neural Network</strong></a></li><li>Xinkun Cao, Zhipeng Wang, Yanyun Zhao , Fei Su, <a href="https://openaccess.thecvf.com/content_ECCV_2018/papers/Xinkun_Cao_Scale_Aggregation_Network_ECCV_2018_paper.pdf"><strong>Scale Aggregation Network for Accurate and Efficient Crowd Counting</strong></a></li><li>Zhou Wang, Alan Conrad Bovik, Hamid Rahim Sheikh, Eero P. Simoncelli, <a href="https://www.cns.nyu.edu/pub/eero/wang03-reprint.pdf"><strong>Image Quality Assessment: From Error Visibility to Structural Similarity</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d3888ca6ea5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speed Up Your API Requests With Thread Pools]]></title>
            <link>https://daniel-carter.medium.com/speed-up-your-api-requests-with-thread-pools-588ab8e66f19?source=rss-3f0c5d200547------2</link>
            <guid isPermaLink="false">https://medium.com/p/588ab8e66f19</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pool]]></category>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[threadpoolexecutor]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Daniel Carter]]></dc:creator>
            <pubDate>Tue, 04 Feb 2020 07:44:55 GMT</pubDate>
            <atom:updated>2020-02-04T07:44:55.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*L2svT8CPjprvDBG-" /></figure><p>APIs have become an integral part of Data Science and the development of web applications. However retrieving large quantities of data from APIs can be incredibly time-consuming. If you are trying to put your Data Science projects into production, these long wait times are unacceptable. In this article, I’ll go over Thread Pools and how to use them to speed up your API requests.</p><h4>Overview &amp; Setup</h4><p>I’m an investor so I often need to retrieve financial data from APIs to analyze the market. I’ll be going over a simple example of how to pull data from the Yahoo Finance API and calculate the Free Cash Flow of several mining companies — first normally, then with Thread Pools.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*7VKQnNtxuDC14w067Qg1vQ.png" /></figure><p>If you would like to follow along in a Jupyter notebook, you can start by downloading <a href="https://github.com/JECSand/yahoofinancials">yahoofinancials</a>, a Python package that makes interacting with the Yahoo Finance API easy.</p><pre>!pip install yahoofinancials</pre><p>Depending on your environment, you may have to install <a href="https://pandas.pydata.org/">pandas</a> as well. We’ll be using the concurrent package too (which we’ll talk about later), but that package comes with Python.</p><h3>Normal API Requests</h3><p>If we were to visualize what we’d normally do to retrieve data from an API, it might look something like the image below. We have multiple tasks (red circles) in the Task Queue on the left. Think of these as functions waiting to make API requests. Then, once the API request is made and the data is retrieved, the green circle moves to the Completed Tasks section on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1009/1*n-Ds3l81lYbtxoPpGXY2tA.png" /></figure><p>This one-by-one method of retrieving data from APIs is what can become time-consuming.</p><p>To make this concept more concrete, let’s use a bit of Python code to build a function that makes requests from the Yahoo Finance API. Let’s start by importing the packages we need for this example.</p><pre>from yahoofinancials import YahooFinancials<br>import pandas as pd<br>import concurrent.futures</pre><p>Now let’s build a function that retrieves Total Cash from Operating Expenses and Capital Expenditures, then subtracts capex from total cash to get Free Cash Flow.</p><pre>def calculate_fcf(ticker):</pre><pre>    # make yahoofinancials instance<br>    yahoo_financials = YahooFinancials(ticker)</pre><pre>    # get date for the last quarter reported<br>    last_quarter_reported =     next(iter(yahoo_financials.get_financial_stmts(‘quarterly’, ‘cash’[‘cashflowStatementHistoryQuarterly’][ticker][0]))</pre><pre>    # get total cash from operating activities<br>    tcfoa = yahoo_financials.get_financial_stmts(‘quarterly’, ‘cash’)[‘cashflowStatementHistoryQuarterly’][ticker][0][last_quarter_reported][‘totalCashFromOperatingActivities’]</pre><pre>    # get capital expenditures<br>    capex = yahoo_financials.get_financial_stmts(‘quarterly’,  ‘cash’)[‘cashflowStatementHistoryQuarterly’][ticker][0][last_quarter_reported][‘capitalExpenditures’]</pre><pre>    # get free cash flow<br>    fcf = tcfoa — abs(capex)</pre><pre>    # return date of last quarter reported and free cash flow<br>    return last_quarter_reported, fcf</pre><p>(Note: Sorry about the weird formatting. If you copy-paste into Jupyter it should come out okay.)</p><p>Now let’s loop over each stock ticker and use the function above to calculate Free Cash Flow for each mining company.</p><pre>%%time</pre><pre>tickers = [‘NEM’, ‘FCX’, ‘BBL’, ‘GLNCY’, ‘VALE’, ‘RTNTF’, ‘SCCO’, ‘AU’, ‘NGLOY’, ‘HL’] #ticker list</pre><pre>quarter_dates = [] # list to store quarter dates<br>fcfs = [] # list to store free cash flows<br>for ticker in tickers: # loop through tickers list<br>    calc_fcf = calculate_fcf(ticker) # use function for API request<br>    quarter_date = calc_fcf[0] # get date element from function<br>    fcf = calc_fcf[1] # get fcf element from function</pre><pre>    # append results to lists<br>    quarter_dates.append(quarter_date)<br>    fcfs.append(fcf)</pre><p>Think of each potential ticker-function combination in the loop as a red circle in the Tasks Queue above. Once the API request for each ticker is made, it takes time to retrieve the data (think of the red circle changing to green in the image above). Then, when the data is fully retrieved and stored in the lists (i.e. memory), the green circle moves to the Completed Tasks section in the image above.</p><p>If you’re following along in Jupyter, you’ll notice the “%%time” at the top of the code cell. This measures how long it took to run the code. It took 1 minute and 12 seconds to complete all tasks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*7i-c5G0LZT4meM7_tii_8g.png" /></figure><h3>API Requests with Thread Pools</h3><p>Let’s now use a Thread Pool to drastically improve this time. A Thread Pool will allow us to use multiple ‘workers’ to make concurrent API requests. If we have less workers than tasks in the Task Queue, a task will be sent to the Thread Pool as soon as an open space is available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*CHMkUjRPr09NOLsG7OOyxw.png" /></figure><p>We’ll use ThreadPoolExecutor() from the <a href="https://docs.python.org/3/library/concurrent.futures.html">concurrent</a> package to rework our Python code.</p><pre>%%time</pre><pre>with concurrent.futures.ThreadPoolExecutor() as executor: </pre><pre>    tickers = [‘NEM’, ‘FCX’, ‘BBL’, ‘GLNCY’, ‘VALE’, ‘RTNTF’, ‘SCCO’, ‘AU’, ‘NGLOY’, ‘HL’] # ticker list</pre><pre>    results = executor.map(calculate_fcf, tickers) # map takes the  function and iterables</pre><pre>    quarter_dates = [] # list to store quarter dates<br>    fcfs = [] # list to store free cash flows<br>    for result in results: # loop through results<br>        quarter_dates.append(result[0]) # append date element<br>        fcfs.append(result[1]) # append fcf element</pre><p>Instead of going straight to the for loop like in the first example, we obtain the results with ThreadPoolExecutor’s map function, where we pass the calculate_fcf function and the iterables (list of stock tickers). Then we loop through the results to get the data.</p><p>Let’s see how long this took.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*IHYifOS9pSmYC4BzDogWzw.png" /></figure><p>We went from over 1 minute to 9 seconds. The Thread Pool makes a huge difference!</p><p>With quick use of pandas, our data is ready to be analyzed.</p><pre>df = pd.DataFrame({‘Ticker’: tickers,’Last quarter reported’: quarter_dates, ‘Free Cash Flow’: fcfs})</pre><pre>df = df.sort_values(by=[‘Free Cash Flow’], ascending=False)</pre><pre>df[‘Free Cash Flow’] = df[‘Free Cash Flow’] / 1000000000</pre><pre>df = df.rename(columns={‘Free Cash Flow’: ‘Free Cash Flow (billions $)’})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*dDol0eOERJhMS1z0Hmzgzg.png" /></figure><h3>Summary</h3><p>Thread Pools can be used for much more than API requests. It is a common tool used to speed up software. This is simply a very practical use of Thread Pools for myself. And I thought it could be a practical or helpful guide for others.</p><p>Thread Pools are used for much more than API requests, but they are not good for everything. If you are doing something computationally expensive, you may need multiprocessing instead.</p><p>Also, it may be tempting to max out workers when using Thread Pools, but there are diminishing returns. Here’s an <a href="https://www.brentozar.com/archive/2017/02/max-worker-threads-dont-touch/">article</a> from a Microsoft Engineer on why not to use too many workers.</p><p>Thanks for reading and feel free to leave comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=588ab8e66f19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Is ‘Buy and Hold’ a Good Investment Strategy?]]></title>
            <link>https://daniel-carter.medium.com/is-buy-and-hold-a-good-investment-strategy-fe2d43266bb5?source=rss-3f0c5d200547------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe2d43266bb5</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[strategy]]></category>
            <dc:creator><![CDATA[Daniel Carter]]></dc:creator>
            <pubDate>Fri, 08 Feb 2019 03:03:02 GMT</pubDate>
            <atom:updated>2019-12-15T01:51:10.030Z</atom:updated>
            <content:encoded><![CDATA[<h4>Inflation-adjusted stock prices might make you think twice.</h4><p>Many legendary investors have stressed the importance of the Buy and Hold strategy. <a href="http://www.northstarfinancial.com/files/6314/6523/9571/2016_DALBAR_Advisor_Edition.pdf">Studies</a> have proven these investment legends correct by showing that investors typically hurt their profitability most when trying to time market oscillations. But the Buy and Hold strategy is not without its own risks.</p><p>To understand the potential pitfalls of the Buy and Hold strategy, we must visualize the data like few do.</p><h3>How to Visualize Long-Term Stock Market Trends</h3><p>Almost every investment website that provides stock charts will give you a visualization similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/654/1*43s7gojyzV_uCgF5ilWMAA.png" /></figure><p>Well, it’s settled. Buy and Hold and you will be fine. The only trouble was in the early and mid 2000&#39;s.</p><p>Hold on. There are three major issues with this chart. First, the chart only goes back to 1950. Such a short timeline will never reveal important long-term price trends. Second, the y-axis is scaled linearly. We want a logarithmic scale so we can better visualize percent changes. We also want the chart to be in real prices (i.e. prices adjusted for inflation) instead of nominal prices.</p><p>Let’s step through how to make these changes to the basic chart above.</p><p><strong>Step 1: Get More Data</strong></p><p>Most investment websites (e.g. Yahoo Finance, Google Finance, StockCharts, etc.) don’t provide the longest available time frames. Fortunately, I was able to track down a <a href="https://github.com/datasets/s-and-p-500">dataset</a> that goes all the way back to 1871. Let’s look at the chart with the extended timeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*sVpyFhS7-BuqZw4SW2WKmw.png" /></figure><p><strong>Step 2: Convert Y-Axis to Logarithmic Scale</strong></p><p>The chart above makes it look like the stock market did nothing for over 100 years before it took flight in the 1980’s. To see the wild fluctuations (i.e. percent changes) before the 1980’s, we need a logarithmic-scaled y-axis. If you’re dealing with the standard investment sites, Excel or Matplotlib, you have the option to use a logarithmic scale. Always use the logarithmic scale when looking at stock prices over the long-term.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*Z3otJ1kQARwEmNp5vVQL9A.png" /></figure><p><strong>Step 3: Use Inflation-Adjusted (Real) Stock Prices</strong></p><p>In the dataset I linked to above, the inflation-adjusted prices are conveniently located in the ‘Real Price’ column. Every data point in this column is priced in January 2000 dollars. Now, not only can we see the percent changes in detail, we can see how inflation has affected the price over time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*9eoDslI05EcVovcTm2YdpQ.png" /></figure><h3>Uncovering the Stock Market’s Cycles</h3><p>The natural world is filled with interesting cycles. The Earth’s <a href="http://www.indiana.edu/~geol105/images/gaia_chapter_4/milankovitch.htm">orbit</a>, the rise and fall of <a href="https://www.zerohedge.com/sites/default/files/images/user5/imageroot/images/History%20of%20money.jpg">empires</a>, and <a href="http://geoscience.wisc.edu/~chuck/Classes/Mtn_and_Plates/eq_cycle.html">earthquakes</a> are a few examples of things that behave cyclically. Seeing as how the stock market is a reflection of human nature, we‘d expect to find cycles there as well. And with our modified chart, we do.</p><p>With inflation-adjusted prices, we can see that the stock market has long uptrends and long downtrends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*8K1pWYnRQoqTuxyH0Ta97A.png" /></figure><p>Since 1871, there have been four major downtrends and four major uptrends. The most significant downtrend in terms of magnitude was the stock market crash that kicked off the Great Depression. It was a decline of over 80%. The longest downtrend was the 14-year downtrend from 1906 to 1920. The average duration of the downtrends was almost 10 years, and the average decline was about 68%.</p><p>Now let’s get to the good news. The uptrends far outweigh the downtrends. After all, the stock market is significantly above where it was in 1871. The largest uptrend — in terms of magnitude and duration — was the period between June 1932 and December 1968. This uptrend lasted 36.5 years and returned a colossal 755% price increase. The average duration of the uptrends was almost 23 years, and the average price increase was about 542%.</p><p>So, that settles it. Just buy stocks and hold onto stocks because the overall trend is in your favor. Actually, wait a minute.</p><h3>‘Buy and Hold’ at the Wrong Time Could Be Disastrous</h3><p>Everyone gets a finite amount of time to invest. If that time is for retirement investing, we get about 40 years. Furthermore, each one of us is seemingly born at random, so we are forced to invest during random 40-year time periods. I can’t go back in time and choose to Buy and Hold from 1932 to 1972. That would have been nice. I also can’t skip ahead to any ‘boom’ period in the future. I must play the cards I’m dealt.</p><p>So, what if you are dealt a really bad hand of cards? It has happened to investors before and it will happen again. If you happen to be a person unlucky enough to start your investment journey at a cyclical peak, it may take you years, if not decades, to break even. Below you can see how many years it took to break even for people who bought and held at a market peak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*AiCHdhIDXBe6GCs2V0PYKQ.png" /></figure><p>From market peaks, the average time it took to break even (i.e. match the previous market high) was 22 years. On average, you make no money for over half your investment lifespan if you Buy and Hold at market peaks.</p><p>To think of these scenarios in more terrifying terms, imagine investing at the peak of 1906. You would have hit the breakeven point in 1928, one year before the Great Depression hit. After that selloff, it would have taken decades more to break even.</p><p>Imagine investing at the peak of 1929. You would have hit the breakeven point in 1958, almost 30 years later. Then, when you were about to retire around 1968–69, the market tanks again. Starting to invest at the wrong time can present one disaster after another.</p><p>But these worst-case scenarios don’t really discredit Buy and Hold because few are unlucky enough to start investing at peaks. What would happen if we randomized the investment starting points?</p><h4>Randomized Investment Periods</h4><p>Instead of looking at worst-case scenarios, let’s look at a bunch of random scenarios. I pulled 200 random dates out of the dataset and then discarded the later dates that couldn’t be used to calculate a 40-year return. I ended up with a sample size of 151.</p><p>I ran this experiment several times and got similar results each time. There was definitely a distinction between good times to start investing and bad times to start investing. Here are some of the results:</p><p><strong>Top 20 Best Returns:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*kyGjULtWNWxGBEqkVbbN_g.png" /></figure><p>The top 20 returns are impressive. People who started their investment journey in the late 1970’s, early 1930’s, or early 1920’s enjoyed the best 40-year returns. People who started investing in the early 1980’s will most likely end up with great returns as well. But we don’t have the data yet to prove it. Since 1871, there were many great times to start investing.</p><p><strong>Top 20 Worst Returns:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*A11YMNmwgSP18C39WW-YtQ.png" /></figure><p>It would have been a miserable time to start investing during the late 1800’s or early 1900’s. If you ended up with a nice chunk of retirement money, it wasn’t because of stock market investing. Although the worst starting times for investing were clustered around these time periods, many other time periods yielded subpar returns as well.</p><p>Perhaps the most interesting part of this experiment was not the extremes but the average. The average 40-year return from this sample was 150.5%. That may sound great at first, but that’s only a 3.8% annual return. This just goes to show how bad inflation is for long-term profitability. There might be better ways to earn 3.8% per year than dealing with a volatile stock market.</p><p>So, what does this tell us about the Buy and Hold strategy?</p><h3>Conclusion</h3><p>Despite the dangers, I still believe Buy and Hold is a superior strategy than most. Certainly it is the best strategy for the average investor. Investing during periods of very low inflation coupled with stock market manias can be catastrophic for long-term profitability. But investing during high-inflation stock market panics can lead to remarkable profits in the long-term.</p><p>It’s important to keep in mind that the analysis above is simplified. Most people wouldn’t Buy and Hold at one time period and never add or subtract to that position later on. If one were to keep making payments into their portfolio during a downtrend, for example, they would break even much sooner on the way up. We must also consider taxes and fees that will eat away at profits, and proper diversification and reinvestment of dividends that will add to profits.</p><p>Investing is complicated, and the market can be very unforgiving. I hope this post will make you more aware of potential risks.</p><p>To send you off with a bit of encouragement, I’ll leave you with a quote from the Oracle of Omaha:</p><blockquote>“And if they insist on trying to time their participation in equities, they should try to be fearful when others are greedy and greedy only when others are fearful” — Warren Buffett</blockquote><p><em>Note: This post is not investment advice. Before you make changes to your investment portfolio, you should do your own research and/or talk with a financial advisor.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe2d43266bb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>