<?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 Chris Price on Medium]]></title>
        <description><![CDATA[Stories by Chris Price on Medium]]></description>
        <link>https://medium.com/@chrisprice-82740?source=rss-5e70db60a641------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*hkFLbPuHzwtjR-04</url>
            <title>Stories by Chris Price on Medium</title>
            <link>https://medium.com/@chrisprice-82740?source=rss-5e70db60a641------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:44:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chrisprice-82740/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[Estimating Causal Effects on Financial Time-Series with Causal Impact BSTS]]></title>
            <link>https://medium.com/data-science/estimating-causal-effects-on-financial-time-series-with-causal-impact-bsts-85d3c403f4a0?source=rss-5e70db60a641------2</link>
            <guid isPermaLink="false">https://medium.com/p/85d3c403f4a0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[bayesian-statistics]]></category>
            <category><![CDATA[time-series-analysis]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[bayesian-machine-learning]]></category>
            <dc:creator><![CDATA[Chris Price]]></dc:creator>
            <pubDate>Mon, 04 Jan 2021 12:29:18 GMT</pubDate>
            <atom:updated>2021-05-24T07:54:12.723Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief introduction to Google’s Causal Impact library in Python &amp; its utility in estimating causal effects on financial time-series.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*D0ytO-qzX5ToZgouIv11XA.png" /><figcaption>Image by Author</figcaption></figure><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><h3>Introduction</h3><p>The ability to quantify and explicate the impact of a known event on a dependent variable is a data science skill whose utility applies to innumerable disciplines. The impact of such analysis, however, and its ability to influence a business decision (notwithstanding the veracity of the analysis itself!) is only as a good as the Data Scientist/Analyst/Quant’s ability to rationalise the underlying choice of model and its decision, as well as the requisite domain expertise and understanding of the dependent variable.</p><p>Google’s <a href="https://medium.com/r?url=https%3A%2F%2Fgithub.com%2Fgoogle%2FCausalImpact">Causal Impact library</a> (implemented in both R and Python) can help us accomplish such a task in a very short space of time while providing methods that enable the user to fully explain the underlying modelling process and the model’s decision.</p><p>In this article, we are going to briefly explore how we can implement a Causal Impact model to estimate the effect of the <a href="https://en.wikipedia.org/wiki/Brumadinho_dam_disaster">Vale dam collapse</a> on the spot price of Iron Ore. <a href="https://github.com/cmp1/bsts-causal_impact/blob/main/Spot_IO_Causal_Impact_Vale_Dam_Accident_20210104.ipynb">You can find all of the code found in this article here</a>.</p><h4>What is Causal Impact?</h4><p>Google’s Causal Impact library provides a very straightforward implementation of a Structural Time-Series model that estimates the effect of a ‘designed’ intervention on a target time-series. This effect is measured by analysing the differences between the <em>expected</em> and the <em>observed </em>behaviour — specifically, the model generates a <strong>forecast counterfactual </strong>i.e.<strong> </strong>the <em>expected</em> observations of how the dependent variable <em>might</em> have evolved after the event <em>had the event not occurred.</em></p><h4>How does it work?</h4><p>Originally developed as an R package, Causal Impact works by fitting a Bayesian Structural Time Series (BSTS) model to a set of target and control time series observations, and subsequently performs posterior inference on the counterfactual.</p><p>For reference, structural time-series models are state-space models for time-series data, and can be defined in terms of the following pair of equations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*onhDADGKB8A7ZdjBAn5W2Q.png" /><figcaption>Structural Time-Series Model Definition. Image by Author</figcaption></figure><p>In the above expressions:</p><ul><li>Eq 1. is the observation equation. This links the observed data y_t to a latent d-dimensional state vector, α_t.</li><li>Equation 2. is the state equation; it governs the evolution of the state vector α_t through time. In other words, the alpha variable refers to the “state” of the time-series, and y_t is a linear combination of the states, plus a linear regression with some explanatory covariates, X, plus some epsilon, ϵ, of noise that is normally distributed about a mean of 0.</li><li><em>Epsilon_t </em>and <em>eta_t</em> are independent of all other unknowns.</li></ul><p>At this stage, it is worth noting one of the key differences between BSTS models and traditional statistical/deep learning variants:</p><p>Traditional time series forecasting architectures such as Linear Regression models, which estimate their coefficients via Maximum Likelihood Estimation, or, on the more powerful end of the scale, an LSTM which learns a function that maps a sequence of past observations as input to an output observation. BSTS models, on the other hand, employ a probabilistic approach to modelling a time series problem, namely, they return a posterior predictive distribution over which we can sample to provide not only a forecast <strong>but also a means of quantifying model uncertainty.</strong></p><h4>Why is this useful?</h4><p>Bayesian Structural-Time Series models are particularly powerful models in that they can generalise to a very large class of time series models such as ARIMA, SARIMAX, Holt-Winters to name but a few. You can observe, in the above expression, how we can achieve this by varying the matrices X, Z, T, G and R in order to model distinct behaviours and structure in the observed time-series, as well as adding linear covariates, BetaX, that might also be predictive of the dependent variable.</p><p><strong>Example - Second-Order AutoRegressive Process:</strong></p><p>Consider an example where we want to model a time series’s temporal structure (autocorrelation). We can model the time series as a second-order autoregressive process AR(2), by adjusting the expressions above!:</p><p><strong>Definition of an AR(2) process:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*nV168ImDTq1sYRnShA8Njw.png" /><figcaption>2nd Order AutoRegressive Process Definition. Image by Author</figcaption></figure><p><strong>In state-space form:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXgWMfJHF-ZArqJZJ3lbEg.png" /><figcaption>AR(2) process in state-space form. Image by Author</figcaption></figure><p>In light of this flexibility to choose any time series model you want to fit your data, one can quickly see how powerful these models can be.</p><p><strong>But this sounds like a lot of work?</strong></p><p>Well, yes, but <strong>fear not. </strong>The wonderful thing about Causal Impact, should you require an expedient initial analysis, is that you <strong>don’t have to</strong> explicitly define <em>any </em>of the model’s structural components.</p><p>If this is indeed the case, and you do not specify a model as in input, a local level model is built by default and is one that estimates the salient structural components of your time series for you. With the local level model, the target time-series, y, is defined as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*xiIKzseyO-0IpcdYECMbMQ.png" /><figcaption>Local Level Model. Image by Author</figcaption></figure><p>Here, a given point in time is modelled as a random-walk component, mu_t (also known as the local level component). <strong>Trend and seasonal components</strong>, gamma_t, are modelled as unobserved components. The trend is modelled as a fixed intercept and the seasonal components using trigonometric functions with fixed periodicities and harmonics. For a more detailed mathematical explanation, one can refer to the Causal Impact documentation <a href="http://google.github.io/CausalImpact/CausalImpact.html"><strong>here</strong></a>, and the<strong> S</strong><a href="https://www.statsmodels.org/devel/examples/notebooks/generated/statespace_seasonal.html"><strong>tatsmodels state-space seasonal documentation</strong></a>, whose logic is followed by that of the Python variant of Causal Impact.</p><p>In summary, our implementation (in Python) therefore is reduced to a one-line expression!:</p><pre>ci_model = CausalImpact(target, pre_period, post_period)</pre><p>For those interested in how to build a Bayesian Structural Time-Series in detail using TensorFlow you can see <strong>how in this article:</strong></p><p><a href="https://towardsdatascience.com/structural-time-series-forecasting-with-tensorflow-probability-iron-ore-mine-production-897d2334c72b"><strong>https://towardsdatascience.com/structural-time-series-forecasting-with-tensorflow-probability-iron-ore-mine-production-897d2334c72b</strong></a></p><p>Otherwise, let’s take a look at Causal Impact in action.</p><h3>The Problem</h3><p>We are going to explore how we can implement Causal Impact in estimating the effect of the Vale dam collapse on the spot price of Iron Ore. Whilst this event does not constitute a ‘designed’ intervention, utility still exists in the financial world in providing estimates of price moves in response to future events of a similar nature. Moreover, this is intended to serve as a demonstration of the utility of Google’s Causal Impact package in estimating the impact of an event on a response time-series. As a reminder, the link to the Python colab notebook can be found <a href="https://github.com/cmp1/bsts-causal_impact/blob/main/Spot_IO_Causal_Impact_Vale_Dam_Accident_20210104.ipynb"><strong>here</strong></a>.</p><p><strong>Vale Dam Incident</strong></p><p>In this instance, we are estimating the impact of the Vale dam incident that occurred at Vale’s (the worlds largest producer of Iron ore) Córrego do Feijão mine on the 25th January 2019, on the spot price of Iron ore.</p><p><strong>Caveat:</strong> Whilst modelling the outcome of any financial time-series is generally a highly-complicated, non-linear problem requiring far greater consideration and technical application than we are demonstrating, the intention of this demonstration is to illustrate the utility and expediency at which CI can perform such an analysis, and its interpretability — a pre-requisite quality in any business environment.</p><h4>Spot Iron Ore Price Data</h4><p>We begin by acquiring our spot iron ore price data, then plotting the close price of the spot iron ore time-series. We also create a 21 and 252 day rolling average to give us a directional steer on the current price movements:</p><pre>import matplotlib.pyplot as plt<br>import numpy as np<br>import pandas as pd</pre><pre>from causalimpact import CausalImpact<br>from statsmodels.tsa.seasonal import seasonal_decompose</pre><pre># Get spot prices<br>df = pd.read_excel(<br>    &#39;/Users/CMP/OneDrive/PriceCurves/IO_Spot_2015010120200501.xlsx&#39;,<br>    index_col=&#39;date&#39;<br>)<br># Plot close price, 21d and 252 roll avg.<br>df[&#39;close&#39;].plot(lw=2., figsize=(14,6), label=&#39;Close Price&#39;,c=&#39;royalblue&#39;)<br>df[&#39;close&#39;].rolling(21).mean().plot(lw=1.5, label=&#39;Roll_21d&#39;,c=&#39;orange&#39;)<br>df[&#39;close&#39;].rolling(252).mean().plot(lw=1.5, label=&#39;Roll_252d&#39;, c=&#39;salmon&#39;)<br>plt.title(&#39;Spot Iron Ore Historical ($/MT), 2015-2020&#39;)<br>plt.ylabel(&#39;Close Price, $/MT&#39;)<br>plt.grid(); plt.legend()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*UZ9y23_IC4Tg-wEJOBu3MA.png" /><figcaption>Iron Ore Spot Price and 21d/252d Rolling Average, 2015–2020. Image by Author</figcaption></figure><h4><strong>Vale Dam Event</strong></h4><p>So far so good. Prior to defining our pre-event and post-event periods, we can get a better idea of the magnitude of the event itself visually by marking the date of the event and plotting it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*BOHY9Sg_7iHRU4Yb9JHMZg.png" /><figcaption>Annotated Spot Iron Ore Close Price. Image by Author</figcaption></figure><p>In the above chart, you can observe two events:</p><ol><li>The<strong> first </strong>data point indicates the date of the Vale dam collapse.</li><li>The <strong>second </strong>data-point/event was a warning from Vale regarding the stability of one of its tailings dams.</li></ol><h4><strong>Before we start — Model Assumptions:</strong></h4><p>As with all forecast problems, it is imperative that we fully consider the assumptions made by any model before applying it to our problem.</p><ol><li><strong>Control Set</strong>: In the case of Causal Impact, the model assumes that a set control time series exists that was <strong><em>not </em></strong>itself<em> </em>affected by the event<em>.</em> In the context of our problem, this assumption is not strictly relevant.</li><li><strong>External Covariates: </strong>An additional assumption that<strong> is</strong> relevant,<strong> </strong>however, is that the model assumes that the relationship between external covariates and the target time series, as established during the pre-period, remains stable throughout the post-period. In the context of our problem, it is highly likely that features may be predictive of the price of iron ore <strong>would likely also be affected by the event.</strong></li><li><strong>Model Priors: </strong>The prior distributions for the unobserved states differ depending on whether you have chosen to implement Causal Impact in R, or Python. The R variant of Causal Impact sets the prior for the unobserved state based on the first observation of the target series, and the variance of the dataset. Statsmodels, on the other hand, uses a diffuse (uniform) prior. This shouldn’t result in any major differences between the two but it is worth bearing in mind (see observations, criticisms &amp; further analysis for the key differences between the R and Python packages).</li></ol><h3>Default Model</h3><p>With the basic information above, let’s fit the basic model to our spot price data, and examine the output. Implementation simple and straightforward:</p><pre># Define training data - period prior to the event<br>pre_period = [&#39;2016-01-04&#39;, &#39;2019-01-24&#39;] </pre><pre># Define post-event period - i.e. time AFTER the event occurred.<br>post_period = [&#39;2019-01-25&#39;, &#39;2019-08-01&#39;] </pre><pre># Instantiate CI model.<br>ci = CausalImpact(df[&#39;close&#39;], pre_period, post_period)</pre><p><em>Note: Causal Impact can (handily) accept date strings when specifying the bounds of our pre and post-event periods.</em></p><p>Fitting the Causal Impact model to our data returns an object whose methods when invoked, allow us to check model results, fitted parameters, etc. For now, we shall plot the results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GVCxYzHo1y-OgjNUbXpjmA.png" /><figcaption>Causal Impact results, including forecast counterfactual, pointwise and cumulative effects. Image by Author.</figcaption></figure><p>As you can observe in the above chart, by calling the.plot()method on our CI object we can access the results of the fitting process. By default, the plot method renders three separate charts:</p><ol><li>The <strong>observed</strong> ‘post-event’ time series and fitted model’s forecast counterfactual</li><li>The <strong><em>pointwise</em></strong> causal effect, as estimated by the model. This is the difference between the observed outcome and the predicted outcome.</li><li>The <strong>cumulative</strong> effect.</li></ol><p>Additionally, by invoking the CI object’s .summary()method, we yield a convenient summary report:</p><pre>print(ci.summary())</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*dRI17BXXB5ArKnos1nMCIQ.png" /><figcaption>Causal Impact Model: Summary Report. Image by Author.</figcaption></figure><h4>Evaluation of Results</h4><p>Examination of the above output reveals the results of the fitted model:</p><ul><li><strong>The Average</strong> column refers to the average price (over the time period) during the post-intervention period.</li><li>The <strong>Cumulative </strong>column is the sum of the individual daily observations — not so useful in our case, however very useful if the dependant variable is a metric whose cumulative sum is part of your experiment; additional sales, clicks, etc.</li></ul><p>A cursory glance at the forecast counterfactual and the point-wise effect suggests that an event of this magnitude has had a significant effect on the spot price. Indeed, the model asserts, with confidence, that the Vale dam incident had an absolute causal effect of $21, varying from $18.04 to $23.98. It is also important to note the p-value here (&lt; .05) to understand whether the observed behaviour is statistically significant or simply occurred by chance.</p><h4><strong>Fitted Model Diagnostics</strong></h4><p>It is immediately apparent, however, that our default model’s forecast counterfactual doesn’t look terribly convincing. For the most part, it would appear directionally accurate, however, it has clearly failed to capture the salient price movements, and the forecast appears to lag behind the observed spot price.</p><p>We can check the fitted model’s parameters and diagnostics to assess whether the model conforms to its underlying statistical assumptions:</p><pre>ci.trained_model.summary()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*cCkm_6xGaDZiY1XTgvnIVQ.png" /><figcaption>Fig. 1: Fitted model results and parameters. Image by Author.</figcaption></figure><pre># Plot residuals diagnostics <br>_ = ci.trained_model.plot_diagnostics(figsize=(14,6))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E5Snz8XwmfH37PLeDeTeUg.png" /><figcaption>Fig.2: Fitted model’s residuals. Image by Author.</figcaption></figure><p>Examination of Figure.1 above shows the parameters of the fitted model. A full explanation of the individual results is beyond the scope of this article, however the salient points, namely the model components; sigma2.irregular and sigma2.level and their coefficients show how weakly predictive they are of our target, the spot price of iron ore.</p><p>Indeed, if we consider figure 2 and the plot of the residuals we can examine the magnitude of the model errors, ‘Standardized residual for c’. We can also observe that the errors follow a distinctly non-normal distribution, and exhibit strong autocorrelation. Nevertheless, we have effectively established a <strong>baseline model</strong> to estimate the effect of the event on our target variable.</p><h3>Customised Model</h3><p>We have just implemented our first Causal Impact model and estimated the causal effect of the Vale dam incident on our spot iron ore data. So far, we’ve let the package decide how to construct a time-series model for our spot price data, and found, as a result of the fitted model’s diagnostics, that we cannot be confident of the inferred effect.</p><p>As mentioned above, a useful quality of structural time-series models is their modularity, affording us the flexibility to model individual behavioural dynamics of our time series such as seasonality, for example. The Causal Impact module offers several options that enable us to accomplish this, which we will exploit in an attempt to improve our inferred counterfactual.</p><h4>Seasonal Model &amp; Model with Exogenous Features (Covariates)</h4><p>In an attempt to improve our model and the forecast counterfactual, we will employ our domain expertise and adjust our model to include a known seasonal component frequently manifest in spot iron ore price action, and incorporate two features that exhibit a known linear correlation with the spot price of iron ore: spot steel scrap and Chinese domestic steel reinforcing bar (rebar):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/727/1*Fzowgg-H9CdSOp7a9yr1Ig.png" /><figcaption>Spot Iron Ore price curve with the addition of our two new features (covariates); rebar and steel scrap. Image by Author.</figcaption></figure><h4><strong>Adding Seasonal Components</strong></h4><p>We will begin by trialling the addition of a <strong>known</strong> seasonal component to our model. For many bulk commodities,<a href="https://www.businessinsider.com.au/iron-ore-price-seasonality-2018-1"> <strong>prices tend to rise</strong></a><strong> in the Chinese summer and winter</strong> ahead of peak periods of construction in the spring and autumn. The same behaviour can typically be observed with that of iron ore. For reference, a seasonal component can be described as a pattern that repeats itself with periodicity i.e. the signal is periodic.</p><p>By decomposing our time series into its constituent structural components, we observe the degree to which the aforementioned seasonality affects the spot price:</p><pre>s_dc = seasonal_decompose(df[&#39;close&#39;], model=&#39;additive&#39;, period=252).plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*xYe6k49EapjvPKzwx7vbug.png" /><figcaption>Spot Iron Ore time-series, decomposed. Image by Author.</figcaption></figure><p><em>Note: Statsmodels seasonal_decompose performs a naive decomposition of our time series — more sophisticated approaches would, and should typically be employed, particularly as our time-series is a financial one. For the purposes of this article and demonstrating how to add these as components to our model, however, this shall suffice.</em></p><p>Isolating a few examples corroborates our prior belief/domain expertise: we can see that the seasonal component’s frequency and amplitude correspond with the Chinese summer and winter:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*CNwG9xCW833j-cOeJ1if4Q.png" /><figcaption>Isolated seasonal component observations, 2015 &amp; 2016. Image by Author.</figcaption></figure><p>It would appear that the signal has a rough periodicity of 146 days, and a harmonic of 1, although these are crude interpretations. We can observe that the amplitude of the winter peak in both examples is of lesser magnitude than that of the summer, therefore the signal itself is not strictly symmetric. For now, we will proceed on our assumptions for the purposes of demonstration.</p><p>Incorporating seasonal components in Causal Impact is very straightforward: the Causal Impact class accepts a list of dictionaries containing the periodicity of each seasonal signal, and, if known, the <a href="https://en.wikipedia.org/wiki/Harmonic">harmonics</a>:</p><pre># Example - Adding seasonal components to a CI model</pre><pre>ci = CausalImpact(<br>    df[&#39;close&#39;], <br>    pre_period, <br>    post_period,<br>    nseasons=[{&#39;period&#39;: 146, &#39;harmonics&#39;: 1}]<br>)</pre><h4>Adding Exogenous Covariates</h4><p>We can now add the external covariates to our model, spot steel scrap price and Chinese domestic reinforcing bar.</p><p>Again, adding external covariates to our Causal Impact model is simple. These can be passed as a Pandas data frame along with our target variable. As per the <a href="https://github.com/dafiti/causalimpact/blob/master/causalimpact/main.py">source code</a>, Causal Impact expects the target/label column to be in the first index (0). All subsequent columns are registered as external covariates:</p><pre>df_1 = pd.concat([df, steel_scrap_df, rebar_df], join=&#39;inner&#39;, axis=1)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*Jjdlu3cVpWuFtp0wMBwlBA.png" /><figcaption>Our price curves DataFrame. Image by Author.</figcaption></figure><p>We then pass this data frame to our Causal Impact model, along with the same pre and post-period event definitions and our seasonal component. Note that we will not specify the harmonics of our seasonal component*:</p><pre># Fit new seasonal + beta coef variant<br>ci_1 = CausalImpact(df_1, pre_period, post_period, nseasons=[{&#39;period&#39;: 146}])</pre><pre># Plot result<br>ci_1.plot(figsize=(12, 6))</pre><p><em>*model defaults to calculating this as math.floor(periodicity / 2))</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*x5IATA4NiKTJGaULH8RvjQ.png" /><figcaption>Forecast counterfactual: seasonal + external covariate CI model variant. Image by Author.</figcaption></figure><p>Upon inspecting the counterfactual of our new model, we can observe a far more credible result. It would still appear as though we need to account for the temporal (autocorrelative) structure in the time series and can include this in a subsequent model, but the result would appear credible for a first pass. Upon checking the fitted model’s parameters, we can see that our seasonal component and it’s definition needs re-evaluating, whereas our external covariates explain a lot of what is observed in our response variable:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCMR3h6EQ1rGet14_cKQ-A.png" /><figcaption>Seasonal + external covariate model — fitted parameters. Image by Author.</figcaption></figure><p>Finally, we can have our model estimate the impact as a result of the Vale dam incident on our target with the useful method,.summary(&#39;report&#39;) that returns a detailed explanation of the observed effects:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/762/1*j9lZOuez6YgdG3o-M2oArg.png" /><figcaption>Seasonal + external covariate model — report. Image by Author</figcaption></figure><p>Here, we can see that the model concludes, with significance, that the incident resulted in a +33% increase in the spot price of iron ore — and logically, therefore, had the incident not occurred, then the spot price would have traded 33% lower during this period.</p><h3>Conclusion</h3><p>In this article, we have learned how Google’s Causal Impact package can be used to estimate the causal effect of an intervention on an observed time-series. Specifically, we implemented a CI model to estimate the effect of the Vale dam incident on the spot price of Iron Ore.</p><p>Furthermore, we have learned:</p><ul><li>What Bayesian Structural Time-Series Models are, their capabilities and to a degree, their limitations (see below).</li><li>What Google’s Causal Impact library is, and what it does.</li><li>How to implement a basic/default Causal Impact model.</li><li>How to implement a more sophisticated variant, by defining and adding known seasonal components and linearly correlated exogenous variables as linear covariates.</li><li>How to evaluate our fitted model’s results.</li></ul><h3>Observations, Criticisms &amp; Further Analysis</h3><ul><li><strong>Parameter Estimation:</strong> Depending on whether you implement Causal Impact in R or Python, you may find your models return disparate results. This is as a result of the different estimation methods employed by the respective libraries: The Python variant employs a Statsmodels Unobserved Components implementation to model the target time-series and whose parameters are estimated using maximum likelihood. The R variant employs the BSTS library whose parameters are estimated with Bayesian MCMC.</li><li><strong>Seasonality: </strong>See limitations mentioned above under ‘Adding seasonal component’</li><li><strong>Models Architectural Ability</strong>: It is a good idea to examine how well the target variable can be predicted <em>before the intervention, </em>by running CausalImpact() on a <strong>contrived intervention</strong>. This acts as a sanity check as to the model’s ability to capture the relevant structure in the data following this imaginary intervention. Logically, we would expect <strong>not</strong> to find a significant effect, i.e., counterfactual estimates and actual data should agree reasonably close.</li><li><strong>Model Assumptions: </strong>see ‘model assumptions’ above. Further note that we did not model for autocorrelation, inherent in nearly all financial time-series.</li><li><strong>Custom models: </strong>Please note that did not cover how to define custom models in this article, which would be verbose, and out of scope. However, a parameter of the Causal Impact class, model , enables us to pass any <a href="https://www.statsmodels.org/stable/generated/statsmodels.tsa.statespace.structural.UnobservedComponents.html#r0058a7c6fc36-1">Statsmodels state-space model</a> as an argument, illustrating the power and flexibility of the CI library.</li></ul><p>Many thanks for taking the time to read this article and as always, I welcome all constructive criticisms and comments.</p><h3>References</h3><ol><li>CausalImpact 1.2.1, Brodersen et al., Annals of Applied Statistics (2015), <a href="http://google.github.io/CausalImpact/">http://google.github.io/CausalImpact/</a>”</li></ol><p><a href="https://www.ft.com/content/8452e078-7880-11e9-bbad-7c18c0ea0201">2. https://www.ft.com/content/8452e078-7880-11e9-bbad-7c18c0ea0201</a></p><p>3. <a href="https://www.businessinsider.com.au/iron-ore-price-seasonality-2018-1">https://www.businessinsider.com.au/iron-ore-price-seasonality-2018-1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85d3c403f4a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/estimating-causal-effects-on-financial-time-series-with-causal-impact-bsts-85d3c403f4a0">Estimating Causal Effects on Financial Time-Series with Causal Impact BSTS</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neural Structured Learning & Adversarial Regularization]]></title>
            <link>https://medium.com/data-science/neural-structured-learning-adversarial-regularization-378523dace08?source=rss-5e70db60a641------2</link>
            <guid isPermaLink="false">https://medium.com/p/378523dace08</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[convolutional-network]]></category>
            <dc:creator><![CDATA[Chris Price]]></dc:creator>
            <pubDate>Mon, 07 Sep 2020 09:10:06 GMT</pubDate>
            <atom:updated>2021-07-27T09:45:25.081Z</atom:updated>
            <content:encoded><![CDATA[<h4>Improving Classification Model Robustness with Adversarial Regularization in TensorFlow</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*PGTvYzYzF8ilO6oCxbtzYg.png" /><figcaption>Image Authors Own</figcaption></figure><h3>Introduction</h3><p>As many of us are no doubt aware, the invariable progress made in the field of Computer Vision has lead to some incredible achievements across multiple disciplines from <a href="https://inews.co.uk/news/deepmind-google-ai-predict-eye-conditions-threatening-sight-429071">healthcare</a> and self-driving cars, to climate study and gaming, to name but a few.</p><p>From state-of-the-art Liquid Nitrogen cooled hardware in the form of <a href="https://cloud.google.com/tpu/docs/tpus">Tensor Processing Units (TPU)</a> to increasingly sophisticated, multi-million parameter Deep-Convolutional Networks such as <a href="https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/43022.pdf">GoogLeNet</a>, <a href="https://en.wikipedia.org/wiki/AlexNet">AlexNet</a> the capability of such technology continues to break previously unassailable barriers.</p><h4>Adversarial Vulnerability</h4><p>Despite these incredible achievements, it has been proven that even the most skilful models are not infallible. Multiple research efforts have demonstrated how sensitive these models are to even imperceivably small changes in the<strong> input data structure</strong>. Initially in the findings of the joint research paper by Google and New York University: <a href="http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/42503.pdf">‘Intriguing properties of neural networks, 2014’</a> the subject of model vulnerability to adversarial examples is now recognised as a subject of such importance that <a href="https://ai.googleblog.com/2018/09/introducing-unrestricted-adversarial.html">competitions </a>now exist to tackle it.</p><p>The existence of these errors raises a variety of questions about out-of-sample generalization, and how the use of such examples might be used to abuse deployed systems.</p><h3>Neural Structured Learning</h3><p>In some applications, these errors might not arise intentionally, moreover, they can arise as a result of human error or simply as a result of input instability. In the mining industry, computer vision has innumerable, highly useful applications, from streaming processing plant conveyor belt imagery in order to predict ore purity for example, to detecting commodity stockpile levels and illegal shipping/mining using satellite imagery.</p><p>Quite often we find that such image data is corrupted during collection, as a result of camera misalignment, vibrations or simply very unique out-of-sample examples that can lead to misclassification.</p><p><strong>In order to overcome examples such as these and generally improve our models against corrupt or perturbed data, we can employ a form of </strong><a href="https://github.com/tensorflow/neural-structured-learning"><strong>Neural Structured Learning</strong></a><strong> called </strong><a href="https://www.tensorflow.org/neural_structured_learning/api_docs/python/nsl/keras/AdversarialRegularization"><strong>Adversarial Regularization</strong></a><strong>.</strong></p><p>Neural Structured Learning (NSL)<strong> </strong>is a relatively new, open-source framework developed by the good folks at TensorFlow for training deep neural networks with structured signals (as opposed to the conventional single sample). NSL implements <a href="https://ai.google/research/pubs/pub46568.pdf">Neural Graph Learning</a>, in which a neural network is trained using <a href="https://en.wikipedia.org/wiki/Graph_database">graphs</a> (see image below) which carry information about both a target (node) and neighbouring information in other nodes connected via node edges.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/1*AuC-ZlRwuV3-obQj0Pk1uA.png" /><figcaption><a href="https://blog.tensorflow.org/2019/09/introducing-neural-structured-learning.html">Image from TensorFlow Blog: Introducing Neural Structured Learning in TensorFlow, 2019</a></figcaption></figure><p>In doing so, this allows the trained model to simultaneously exploit both labelled and unlabelled data through:</p><ol><li>Training the model on labelled data (standard procedure in any supervised learning problem);</li><li>Biasing the network to learn similar hidden representations for neighbouring nodes on a graph (with respect to the input data labels)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pawtkw3G3u1jrHHFogi1fw.png" /><figcaption><a href="https://blog.tensorflow.org/2019/09/introducing-neural-structured-learning.html">Image from TensorFlow Blog: Neural Structured Learning, Adversarial Examples, 2019</a>.</figcaption></figure><p>Consistent with point two, we can observe in the above expression both the minimisation of the empirical loss i.e. the supervised loss, and the <strong>neighbour loss. </strong>In the above example, this is computed as the dot product of the computed weight vector within a target hidden layer, and the distance measure (i.e. L1, L2 distance) between the input, <em>X, </em>and the same input with some degree of noise added to it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/195/1*HlqDz6YppaRHoYFYBJp1mg.png" /></figure><p>Adversarial examples are typically created by computing the gradient of the output with respect to the input, x_i, and then maximizing the loss. For example, where you have a model that classifies Chihuahuas and muffins, and you wish to create adversarial examples, you would input a 128 x 128 pixel Chihuahua image into your network, compute the gradient of the loss w.r.t. the input (a 128 x 128 tensor), then add the negative gradient (perturbation) to your image until the network classifies the image as a muffin. By training on these generated images again with the correct label, the network becomes <strong>more robust to noise/perturbation.</strong></p><h3>Why use NSL?</h3><ul><li><strong>Higher accuracy</strong>: the structured signal(s) among samples can provide information that is not always available in feature inputs.</li><li><strong>Greater Robustness</strong>: models trained with adversarial examples are <a href="https://arxiv.org/abs/1807.06732">demonstrably more robust </a>against adversarial perturbations designed for misleading a model’s prediction or classification.</li><li><strong>Less labelled data required</strong>: NSL enables neural networks to harness both labelled and unlabelled data, forcing the network to learn similar hidden representations for “neighbouring samples” that may or may not have labels.</li></ul><h3>Adversarial Regularisation</h3><p>What can we do if do not have such explicit structures as inputs?</p><p>What is <em>particularly </em>useful about TensorFlows Neural Structured Learning library is the provision of methods that enable users to dynamically construct <em>induced </em>adversarial examples as implicit structures from raw input data, through adversarial perturbation. This generalisation of NSL is known as <strong>Adversarial Regularisation, </strong>where adversarial examples are constructed to intentionally confuse the model during training, resulting in models that are robust against small input perturbations.</p><h3>Adversarial Regularisation In Practice</h3><p>In the following example, we are going to compare the performance of a baseline image classification model (specifically, a Convolutional Neural Network), against a variant that utilises adversarial regularisation. Unfortunately, we cannot demonstrate the use of AR on any of the aforementioned mining data, as this is proprietary.</p><p>We will instead perform this analysis for two models trained on a renowned image classification dataset — <a href="https://www.tensorflow.org/datasets/catalog/beans">Beans</a>. We will compare the results of the baseline model, versus one trained on adversarial examples in order to fully comprehend the effect that adversarial regularisation has on the ability and performance of each model.</p><p>The Colab notebook containing the code used in this article can be found <a href="https://github.com/cmp1/computer_vision_neural_structured_learning/tree/master">here</a>. An excellent tutorial, where the inspiration for this article and where some of the code originated from, can be found on the <a href="https://www.tensorflow.org/neural_structured_learning/tutorials/adversarial_keras_cnn_mnist#conclusion">TensorFlow NSL page</a>.</p><p>Before we get started, we must first install TensorFlow’s Neural Structured Learning package:</p><pre>!pip install neural_structured_learning</pre><h4>Imports</h4><pre>import matplotlib.image as mpimg<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import keras_preprocessing<br>import neural_structured_learning as nsl<br>import tensorflow as tf<br>import tensorflow_datasets.public_api as tfds</pre><pre>from tensorflow.keras import models<br>from keras_preprocessing import image<br>from keras_preprocessing.image import ImageDataGenerator</pre><h4>Load &amp; Inspect Image Data</h4><p>TensorFlow hosts a number of renowned datasets within its <a href="https://www.tensorflow.org/datasets">TensorFlow Datasets</a> collection.</p><p>We can load the Beans dataset that we want to train our model on using the tfds.load() method, which performs two operations:</p><ol><li>Downloads the dataset and save it as <a href="https://www.tensorflow.org/tutorials/load_data/tfrecord">tfrecord</a> files.</li><li>Loads the tfrecord files and returns an instance of <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset">tf.data.Dataset</a></li></ol><pre># load dataset<br>dataset = &#39;beans&#39; #@param</pre><pre>dataset = tfds.load(dataset, shuffle_files=True)<br>train, test = dataset[&#39;train&#39;], dataset[&#39;test&#39;]</pre><pre>IMAGE_INPUT_NAME = &#39;image&#39;<br>LABEL_INPUT_NAME = &#39;label&#39;</pre><p>Prior to performing any image scaling or image augmentation/perturbation, we can inspect a sample of the images within the dataset to gain an understanding of the various structures and compositions that a Convolutional layer might pick up as a feature(s), and to understand the differences between the various classes within the dataset:</p><pre># Get random batch<br>raw_images = train.take(10)</pre><pre># Tensor to np format<br>raw_images = [item[&#39;image&#39;] for item in<br>raw_images.as_numpy_iterator()]</pre><pre># Plot batch<br>fig = plt.gcf()<br>fig.set_size_inches(10, 10)<br>for i, img in enumerate(raw_images):<br>  sp = plt.subplot(2, 5, i+1)<br>  sp.axis(&#39;Off&#39;)<br>  plt.imshow(img)</pre><pre>plt.show()</pre><p>By default, the <a href="https://www.tensorflow.org/api_docs/python/tf/data/Dataset">tf.data.Dataset</a> object contains a dict of <a href="https://www.tensorflow.org/api_docs/python/tf/Tensor">tf.Tensor</a>s. We can iterate over the batch of images (the tf.data.Dataset key values) by calling .as_numpy_iterator() on our raw_images within our list comprehension. This method returns a generator which converts the batch elements of the dataset from a tf.Tensorto np.array format. We can then plot the resulting batch of images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*_pZxLQXIxzFSJykZvyTcHg.png" /><figcaption>Image Generated by Author: Sample batch of 10 training images within the ‘Beans’dataset depicting 3 no. distinct classes: ‘Healthy’, ‘Bean Rust’ &amp; ‘Angular Leaf Spot’</figcaption></figure><h4>Preprocessing</h4><p>We perform a simple scaling operation on our image data to map the inputs to a float tensor between 0 and 1 (the Beans dataset is a collection of 500 x 500 x 3 images). Helpfully, TDFS datasets store <a href="https://www.tensorflow.org/datasets/catalog/beans">feature attributes </a>as Dictionaries:</p><pre>FeaturesDict({<br>    &#39;image&#39;: Image(shape=(500, 500, 3), dtype=tf.uint8),<br>    &#39;label&#39;: ClassLabel(shape=(), dtype=tf.int64, num_classes=3),<br>})</pre><p>As a result, we can access the individual images and their labels and perform these preprocessing ops <strong>in-place</strong> with the .map() attribute of our train and test tf.Dataset instances:</p><pre>def normalize(features):<br>  &quot;&quot;&quot;Scale images to within 0-1 bound based on max image size.&quot;&quot;&quot;<br>  features[IMAGE_INPUT_NAME] = tf.cast(<br>    features[IMAGE_INPUT_NAME], <br>    dtype=tf.float32) / 500.0)<br>  return features</pre><pre>def examples_to_tuples(features):<br>  return features[IMAGE_INPUT_NAME], features[LABEL_INPUT_NAME]</pre><pre>def examples_to_dict(image, label):<br>  return {IMAGE_INPUT_NAME: image, LABEL_INPUT_NAME: label}</pre><pre># Define train set, preprocess. (Note: inputs shuffled on load)<br>train_dataset = train.map(normalize)<br>                     .batch(28)<br>                     .map(examples_to_tuples)</pre><pre>test_dataset = test.map(normalize)<br>                   .batch(28)<br>                   .map(examples_to_tuples)</pre><p>The function examples_to_dict will be explained shortly.</p><h4>Baseline Model</h4><p>We then build a simple, baseline convolution neural network model, and fit it to our image data:</p><pre>def conv_nn_model(img_input_shape: tuple) -&gt; tf.keras.Model():<br>  &quot;&quot;&quot;Simple Conv2D Neural Network.<br>    Args:<br>      img_input_shape: An (mxnxo) tuple defining the input image   <br>      shape.<br>    Returns:<br>      model: An instance of tf.keras.Model.<br>  &quot;&quot;&quot;<br>  model = tf.keras.models.Sequential([<br>      tf.keras.layers.Conv2D(16, (3,3), activation=&#39;relu&#39;,   <br>          input_shape=input_shape),<br>      tf.keras.layers.MaxPooling2D(2, 2),<br>      tf.keras.layers.Conv2D(32, (3,3), activation=&#39;relu&#39;),<br>      tf.keras.layers.MaxPooling2D(2,2),<br>      tf.keras.layers.Conv2D(32, (3,3), activation=&#39;relu&#39;),<br>      tf.keras.layers.MaxPooling2D(2,2),<br>      tf.keras.layers.Flatten(),<br>      tf.keras.layers.Dense(64, activation=&#39;relu&#39;),<br>      # Note to adjust output layer for number of classes<br>      tf.keras.layers.Dense(3, activation=&#39;softmax&#39;)])<br>  return model</pre><pre># Beans dataset img dims (pixel x pixel x bytes)<br>input_shape = (500, 500, 3)</pre><pre># Establish baseline<br>baseline_model = conv_nn_model(input_shape)<br>baseline_model.summary()</pre><pre>baseline_model.compile(<br>    optimizer=&#39;adam&#39;,<br>    loss=&#39;sparse_categorical_crossentropy&#39;,<br>    metrics=[&#39;acc&#39;])</pre><pre>baseline_history = baseline_model.fit(<br>    train_dataset,<br>    epochs=5)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_pYuIJdAax8Xj1fOwl6Qgg.png" /><figcaption>Our baseline Conv2D model architecture</figcaption></figure><pre>results = baseline_model.evaluate(test_dataset)<br>print(f&#39;Baseline Accuracy: {results[1]}&#39;)</pre><pre>3/3 [==============================] - 0s 72ms/step - loss: 0.1047 - acc: 0.8934 <br>Baseline Accuracy: 0.8934375</pre><p>We can see that our baseline model has performed well on the test dataset, achieving 89% accuracy.</p><h4>Adversarial Regularization Model</h4><p>We will now examine how this model performs against a test set that includes adversarially perturbed examples, and pitch it against a model trained on a dataset that includes said examples. We proceed by first creating another convolutional NN model, only this time we will incorporate adversarial training into its training objective.</p><p>Next, using TensorFlow’s NSL framework, we define a config object with NSL’s helper function, <a href="https://www.tensorflow.org/neural_structured_learning/api_docs/python/nsl/configs/make_adv_reg_config">nsl.configs.make_adv_reg_config</a> :</p><pre>#@title ADV Regularization Config</pre><pre># Create new CNN model instance<br>base_adv_model = conv_nn_model(input_shape)</pre><pre># Create AR config object <br>adv_reg_config = nsl.configs.make_adv_reg_config(<br>    multiplier=0.2,<br>    adv_step_size=0.2,<br>    adv_grad_norm=&#39;infinity&#39;)</pre><pre># Model wrapper <br>adv_reg_model = nsl.keras.AdversarialRegularization(<br>    base_adv_model,<br>    label_keys=[LABEL_INPUT_NAME],<br>    adv_config=adv_config)</pre><p>We can note that this function requires us to set a number of Hyperparameters. Some of these do not require explicit values, others require our input:</p><ul><li><strong>multiplier</strong>: The weight of the adversarial loss relative to the labelled loss during training, w.r.t our AR model’s objective function. We apply 0.2 as the regularization weight.</li><li><strong>adv_step_size</strong>: The degree/magnitude of adversarial perturbation to be applied during training.</li><li><strong>adv_grad_norm</strong>: The Tensor norm (L1 or L2) to normalize the gradient i.e A measure of the magnitude of the adversarial perturbation. Defaults to L2.</li></ul><p>We can then wrap our newly created model using the nsl.keras.AdversarialRegularization function, which will add the adversarial regularization we configured earlier with our adv_reg_configobject to the training objective (the loss function to be minimised) of our base model.</p><p><strong>An important point to note at this stage</strong> is that our model <em>expects its input to be a dictionary mapping of feature names to feature values</em>. One can see that when we instantiate our adversarial model, we must pass in label_keys as a parameter. The enables our model to distinguish between <strong>input data</strong> and <strong>target data</strong>. Here, we can use our examples_to_dict function and map it to our training and test datasets:</p><pre>train_set_for_adv_model = train_dataset.map(convert_to_dictionaries)<br>test_set_for_adv_model = test_dataset.map(convert_to_dictionaries)</pre><p>we then compile, fit and evaluate our adversarially regularised model as normal:</p><pre>4/4 [==============================] - 0s 76ms/step - loss: 0.1015 - sparse_categorical_crossentropy: 0.1858 - sparse_categorical_accuracy: 0.8656 - scaled_adversarial_loss: 0.1057  accuracy: 0.911625</pre><p>Similarly, our adversarially regularised model generalises well to our test dataset, achieving similar accuracy (0.91%) to that of our baseline_model.</p><h4>Evaluation Against Adverarially Perturbed Data</h4><p>Now for the interesting part.</p><p>In much the same way that one would evaluate a trained model’s ability on a test set, we shall perform the same operation on our two models. In this instance, however, we will compare our two models; the baseline CNN, and the variant that has been trained on adversarially-perturbed input data against a test dataset containing <em>adversarially perturbed examples</em>.</p><p>In order to generate the aforementioned examples, we must first create a reference model, whose configuration (losses, metrics and calibrated/learned weights) will be used to generate perturbed examples. To do so, we once again wrap our performance baseline model with the nsl.keras.AdversarialRegularization function and compile it. <strong>Note that we do not fit this model to our dataset — we want to retain the same learned weights as our base model</strong>):</p><pre># Wrap baseline model<br>reference_model = nsl.keras.AdversarialRegularization(<br>    baseline_model,<br>    label_keys=[LABEL_INPUT_NAME],<br>    adv_config=adv_reg_config)</pre><pre>reference_model.compile(<br>    optimizer=&#39;adam&#39;,<br>    loss=&#39;sparse_categorical_crossentropy&#39;,<br>    metrics=[&#39;acc&#39;]</pre><pre>models_to_eval = {<br>    &#39;base&#39;: baseline_model,<br>    &#39;adv-regularized&#39;: adv_reg_model.base_model}</pre><pre>metrics = {<br>    name: tf.keras.metrics.SparseCategoricalAccuracy()<br>    for name in models_to_eval.keys()}</pre><p>If at this point you are like me and like to understand the logic behind these things, you can find the <strong>source code</strong> containing the adversarial regularization class <a href="https://github.com/tensorflow/neural-structured-learning/blob/v1.3.1/neural_structured_learning/keras/adversarial_regularization.py#L695-L747">here</a>.</p><p>We then store our two models; the baseline and the adversarially regularized variant in a dictionary, and subsequently loop over each batch of our test dataset (evaluation in batches is a requirement of the AdversarialRegularization model).</p><p>With the .perturb_on_batch() method of our newly wrapped reference_model, we can generate adversarially perturbed batches consistent with our adv_reg_config object, and evaluate the performance of our two models on them:</p><pre>labels, y_preds = [], []</pre><pre># Generate perturbed batches, <br>for batch in test_set_for_adv_model:<br>  perturbed_batch = reference_model.perturb_on_batch(batch)<br>  perturbed_batch[IMAGE_INPUT_NAME] = tf.clip_by_value(<br>      perturbed_batch[IMAGE_INPUT_NAME], 0.0, 1.0)<br>  # drop label from batch<br>  y = perturbed_batch.pop(LABEL_INPUT_NAME)<br>  y_preds.append({})<br>  for name, model in models_to_eval.items():<br>    y_pred = model(perturbed_batch)<br>    metrics[name](y, y_pred)<br>    predictions[-1][name] = tf.argmax(y_pred, axis=-1).numpy()</pre><pre>for name, metric in metrics.items():<br>  print(f&#39;{name} model accuracy: {metric.result().numpy()}&#39;)</pre><pre>&gt;&gt; base model accuracy: 0.2201466 adv-regularized model accuracy: 0.8203125</pre><h4>Results</h4><p>The effectiveness of adversarial learning on improving model robustness is immediately apparent by the<strong> <em>dramatic </em></strong>reduction in our baseline model’s performance on adversarially perturbed data, vs that of the adv_reg_model.</p><p>Performance on our baseline model has dropped <strong>69% </strong>vs our adversarially regularised model, which realised only a 14% drop in performance.</p><p>With Kera’s Layers API, we can examine the effect of adversarially perturbed data on our baseline model by visualising the convolutional layers to understand what features are extracted both prior and after perturbation:</p><h4>Before perturbation</h4><pre># Random img &amp; conv layer idxs<br>IDX_IMAGE_1=2<br>IDX_IMAGE_2=5<br>IDX_IMAGE_3=10<br>CONVOLUTION_NUMBER = 10</pre><pre># Get baseline_model layers <br>layer_outputs = [layer.output for layer in baseline_model.layers]<br>activation_model = tf.keras.models.Model(<br>    inputs =baseline_model.input, <br>    outputs = layer_outputs)</pre><pre># Plot img at specified conv<br>f, axarr = plt.subplots(3,2, figsize=(8, 8))<br>for x in range(0, 2):<br>  f1 = activation_model.predict(test_images[IDX_IMAGE_1].reshape(<br>      1, 500, 500, 3))[x]<br>  axarr[0,x].imshow(f1[0, : , :, CONVOLUTION_NUMBER],cmap=&#39;inferno&#39;)<br>  axarr[0,x].grid(False)<br>  f2 = activation_model.predict(test_images[IDX_IMAGE_2].reshape(<br>      1,500, 500, 3))[x]<br>  axarr[1,x].imshow(f2[0, : , :, CONVOLUTION_NUMBER],cmap=&#39;inferno&#39;)<br>  axarr[1,x].grid(False)<br>  f3 = activation_model.predict(test_images[IDX_IMAGE_3].reshape(<br>      1, 500, 500, 3))[x]<br>  axarr[2,x].imshow(f3[0, : , :, CONVOLUTION_NUMBER],cmap=&#39;inferno&#39;)<br>  axarr[2,x].grid(False)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*PGTvYzYzF8ilO6oCxbtzYg.png" /><figcaption>Image Generated By Author: Intermediate image representations for a given convolutional layer</figcaption></figure><p>We can observe in the image above, that our baseline model appears to have identified the relevant distinguishing features that define each class: angular leaf rust, healthy and bean spot, made visible by the distinct colour gradients.</p><h4>After perturbation</h4><p>Now we can examine what features the baseline model identifies in the perturbed data:</p><pre># Pertubed test data<br>perturbed_images = []<br>for batch in test_set_for_adv_model:<br>  perturbed_batch = reference_model.perturb_on_batch(batch)<br>  perturbed_batch[IMAGE_INPUT_NAME] = tf.clip_by_value(<br>  perturbed_batch[IMAGE_INPUT_NAME], 0.0, 1.0)<br>  perturbed_images.append(perturbed_batch)</pre><pre># Get images<br>pt_img = [item[&#39;image&#39;] for item in perturbed_images]</pre><pre>IDX_IMAGE_1=0<br>IDX_IMAGE_2=1<br>IDX_IMAGE_3=2<br>CONVOLUTION_NUMBER = 11</pre><pre>base_mod_layer_out = [layer.output for layer in baseline_model.layers]</pre><pre>base_mod_activ = tf.keras.models.Model(<br>  inputs = baseline_model.input,<br>  outputs = base_mod_layer_out)</pre><pre>f1 = base_mod_activ.predict(pt_img[IDX_IMAGE_1].numpy())[x]<br>f2 = base_mod_activ.predict(pt_img[IDX_IMAGE_2].numpy())[x]<br>f3 = base_mod_activ.predict(pt_img[IDX_IMAGE_3].numpy())[x]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/887/1*t0jMQ5T4qFsEHC6iXPsP9w.png" /><figcaption>Image Generated by Author: Intermediate image representations; adversarially perturbed data.</figcaption></figure><p>As we can observe in the above representations, the network’s has struggled to represent the raw pixels in each image, and are considerably more abstract as a result of the perturbation. In the image to the far right, it would appear that network managed to successfully retain the features representative of the ‘angular leaf rust’ class, but the basic structure of the leaf is mostly lost. Of course, this is just a single convolutional layer within our untuned network but still serves as a credible demonstration of how a previously skilful model can be unseated as a result of adversarial input data.</p><h3>Conclusion</h3><p>In this article we examined how we can significantly increase a convolutional neural network model’s robustness and generalisation performance on adversarially perturbed data, using adversarial regularisation. Additionally, we explored:</p><ul><li>How to add adversarial regularisation to a Keras model.</li><li>How to compare an adversarially regularised model against a baseline performance model.</li><li>How to examine the effect of adversarially perturbed data on a conventionally trained model by visualising intermediate layers.</li></ul><p>Please do comment if you find errors or have any constructive criticism/builds.</p><p>Thank you for reading.</p><h3>References</h3><ul><li><a href="http://static.googleusercontent.com/media/research.google.com/en//pubs/archive/42503.pdf">Google Inc, NYU, 2014, Intriguing properties of neural networks</a></li><li><a href="https://blog.tensorflow.org/2019/09/introducing-neural-structured-learning.html">TensorFlow Blog, 2019, Neural Structured Learning</a></li><li><a href="https://arxiv.org/abs/1807.06732">Gilmer et al, 2018, Motivating the Rules of the Game for Adversarial Example Research.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=378523dace08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/neural-structured-learning-adversarial-regularization-378523dace08">Neural Structured Learning &amp; Adversarial Regularization</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spot vs Sentiment: NLP & Sentiment Scoring in the Spot Copper Market]]></title>
            <link>https://medium.com/data-science/spot-vs-sentiment-nlp-sentiment-scoring-in-the-spot-copper-market-492456b031b0?source=rss-5e70db60a641------2</link>
            <guid isPermaLink="false">https://medium.com/p/492456b031b0</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[trading-strategy]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Chris Price]]></dc:creator>
            <pubDate>Mon, 17 Aug 2020 20:01:28 GMT</pubDate>
            <atom:updated>2021-09-10T08:41:25.231Z</atom:updated>
            <content:encoded><![CDATA[<h3>Trading Sentiment: NLP &amp; Sentiment Scoring the Spot Copper Market</h3><h4>The search for Alpha amongst financial publication tweets with NLTK, Gensim &amp; VADER</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*YkGWZo6LTQslvB4Gz0FfHQ.png" /><figcaption>Daily Compound Sentiment Score vs Copper Spot Price, $/Oz.</figcaption></figure><p><strong><em>Note from Towards Data Science’s editors:</em></strong><em> While we allow independent authors to publish articles in accordance with our </em><a href="https://towardsdatascience.com/questions-96667b06af5"><em>rules and guidelines</em></a><em>, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our </em><a href="https://towardsdatascience.com/readers-terms-b5d780a700a4"><em>Reader Terms</em></a><em> for details.</em></p><h3>Introduction</h3><p>After Iron and Aluminium, Copper is one of the most consumed metals in the <a href="https://moneyweek.com/516039/the-cycles-in-the-metals-market-when-will-zinc-and-copper-shine">World</a>. An extremely versatile metal, Copper’s electrical and thermal conductivity, antimicrobial, and corrosion-resistant properties lend the metal to widespread application in most sectors of the economy. From power infrastructure, homes, and factories to electronics and medical equipment, the global economic dependency on Copper is so profound that it is sometimes referred to as ‘<a href="https://www.investopedia.com/terms/d/doctor-copper.asp">Dr. Copper</a>’, and is often cited as such by market and commodity analysts because of the metal’s ability to assess global economic health and activity.</p><p>From a trading perspective, Copper pricing is determined by the supply and demand dynamics on the metal exchanges, particularly the <a href="https://www.lme.com/en-GB/Metals/Non-ferrous/Copper#tabIndex=0">London Metal Exchange (LME)</a> and the<a href="https://www.cmegroup.com/trading/metals/base/copper-futures-and-options.html"> Chicago Mercantile Exchange (CME) COMEX</a>. The price Copper trades at, however, is affected by innumerable factors, many of which are very difficult to measure concurrently :</p><ul><li>Global economic growth (GDP)</li><li>Emerging market economies</li><li>China’s economy (<a href="https://asia.nikkei.com/Business/Markets/Commodities/Dr.-Copper-misdiagnoses-the-global-economy">China accounts for half of the global Copper demand</a>)</li><li>Political and environmental instability in Copper ore producing countries</li><li>The U.S. housing market</li><li>Trade sanctions &amp; tariffs</li><li>Many, many others.</li></ul><p>As well as the aforementioned fundamental factors, Copper’s price can also be artificially influenced by hedge funds, investment institutions, <a href="https://agmetalminer.com/2014/06/11/what-chinas-shadow-financing-market-aluminum-copper-collateral-means-for-metals-markets/">bonded metal</a>, and even domestic trading. From a systematic trading point of view, this makes for a very challenging situation when we want to develop a predictive model.</p><p>Short-term opportunities can exist however, in relation to events that are announced in the form of <strong>news</strong>. The spot and forward price of Copper has been <a href="https://www.kitco.com/news/2020-07-15/METALS-Copper-slips-on-profit-taking-triggered-by-U-S-China-tensions.html">buffeted throughout the US-China trade war</a> and like all markets, responds almost instantly to major news announcements.</p><p>Caught early enough, NLP-based systematic trading models can capitalize on these short-term price movements through parsing the announcements as a vector of tokens, evaluating the underlying sentiment, and subsequently taking a position prior to the anticipated (if applicable) price move, or, during the movement in the hope of capitalizing on a potential correction.</p><h3>Problem</h3><p>In this article, we are going to scrape historical (and current) tweets from a variety of financial news publications Twitter feeds. We will then analyse this data in order to understand the underlying sentiment behind each tweet, develop a sentiment score, and examine the correlation between this score and Copper’s spot price over the last five years.</p><p>We will cover:</p><ol><li><strong>How to obtain historic tweets</strong> with <a href="https://pypi.org/project/GetOldTweets3/">GetOldTweets3</a>.</li><li><strong>Basic Exploratory Data Analysis</strong> (EDA) techniques with our Twitter data.</li><li><strong>Text data preprocessing techniques</strong> (Stopwords, tokenization, n-grams, Stemming &amp; lemmatization etc).</li><li><a href="https://en.wikipedia.org/wiki/Latent_Dirichlet_allocation"><strong>Latent Dirichlet Allocation</strong></a> to model &amp; explore the distribution of topics and content their content within our Twitter data using <a href="https://pypi.org/project/gensim/">GenSim</a> &amp; <a href="https://pypi.org/project/pyLDAvis/">NLTK PyLDAvis.</a></li><li><strong>Sentiment scoring</strong> with <a href="https://www.nltk.org/_modules/nltk/sentiment/vader.html">NLTK Valence Aware Dictionary and <strong>sEntiment</strong> Reasoner (VADER).</a></li></ol><p>We will not go as far as developing and testing a fully-fledged trading strategy off the back of this work, the semantics of which is beyond the scope of this article. Moreover, this article is intended to demonstrate the various techniques a Data Scientist can employ to extract signals from text data in the search for profitable signals.</p><h3>Spot Copper NLP Strategy Model</h3><p>Let’s kick off by acquiring our data.</p><h4>Spot Price Data</h4><p>We will start by acquiring our spot Copper price data. The reason behind our choice to use Copper’s spot price, rather than a Copper <a href="https://www.lme.com/en-GB/Trading/Contract-types/Futures#tabIndex=0">forward contract</a> (an agreement to buy or sell a fixed amount of metal for delivery on an agreed fixed future date at a price agreed today) is that the spot price is the most reactive to market events — it is an offer to complete a commodity transaction <strong>immediately</strong>. Normally, we would use a Bloomberg terminal to acquire this data, however, we can get historical spot Copper data for free from <a href="https://markets.businessinsider.com/commodities/copper-price">Business Insider</a>:</p><pre># Imports<br>import glob<br>import GetOldTweets3 as got<br>import gensim as gs<br>import os<br>import keras<br>import matplotlib.pyplot as plt<br>import numpy as np<br>import nltk<br>import pandas as pd<br>import pyLDAvis.gensim<br>import re<br>import seaborn as sns</pre><pre>from keras.preprocessing.text import Tokenizer<br>from nltk.stem import *<br>from nltk.util import ngrams<br>from nltk.corpus import stopwords<br>from nltk.tokenize import TweetTokenizer<br>from nltk.sentiment.vader import SentimentIntensityAnalyzer<br>from sklearn.feature_extraction.text import CountVectorizer<br>from tensorflow.keras.preprocessing.sequence import pad_sequences</pre><pre># Get Cu Spot<br>prices_df = pd.read_csv(<br>    &#39;/content/Copper_120115_073120&#39;,<br>    parse_dates=True,<br>    index_col=&#39;Date&#39;<br>)<br># To lower case<br>cu_df.columns = cu_df.columns.str.lower()</pre><pre>#Plt close price<br>cu_df[&#39;close&#39;].plot(figsize=(16,4))<br>plt.ylabel(&#39;Spot, $/Oz&#39;)<br>plt.title(&#39;Cu Spot Close Price, $/Oz&#39;)<br>plt.legend()<br>plt.grid()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*hNdODLUUSKGd8kcMli62sQ.png" /><figcaption>Spot Copper, Close Price, 2015–01–01 to 2020–07–01, $/Mt</figcaption></figure><p>Whilst our price data looks fine, it is important to note that we are considering <strong>daily price </strong>data. Consequently, we are limiting ourselves to a timeframe that could see us losing information — any market reaction to a news event is likely to take place within minutes, likely <em>seconds</em> of its announcement. Ideally, we would be using 1–5-minute bars, but for the purposes of this article, this will do ok.</p><h4>Tweet Data</h4><p>We will extract our historical tweet data using a library called <a href="https://pypi.org/project/GetOldTweets3/"><strong>GetOldTweets3</strong></a><strong> (GOT). </strong>Unlike the official <a href="https://developer.twitter.com/en/docs">Twitter API</a>, GOT3 enables users to access an extensive history of twitter data. Given a list of Twitter handles belonging to financial news outlets and a few relevant keywords, we can define the search parameters over which we want to get data for (<strong>note:</strong> I have posted a screenshot, rather than a code snippet, of the requisite logic to perform this action below for formatting reasons):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*j1OMA8ZNQ7mkKAc4BhUndw.png" /><figcaption>Get historical twitter data for specified handles w.r.t search parameters</figcaption></figure><p>The method .setQuerySearch() accepts a single search query, so we are unable to extract tweets for multiple search criteria. We can easily solve this limitation using a loop. For example, one could simply assign variable names to each execution of a unique query, i.e. ‘spot copper’, ‘copper prices’ etc, but for the purposes of this article we can settle for a single query:</p><pre># Define handles<br>commodity_sources = [&#39;reuters&#39;,&#39;wsj&#39;,&#39;financialtimes&#39;, &#39;bloomberg&#39;]</pre><pre># Query <br>search_terms = &#39;spot copper&#39;</pre><pre># Get twitter data<br>tweets_df = get_tweets(<br>  commodity_sources,<br>  search_term = search_terms,<br>  top_only = False,<br>  start_date = &#39;2015-01-01&#39;,<br>  end_date = &#39;2020-01-01&#39;<br>).sort_values(&#39;date&#39;, ascending=False).set_index(&#39;date&#39;)</pre><pre>tweets_df.head(10)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT7qPNPSiJmP3HTjSRxhgw.png" /><figcaption>Historical Twitter Data</figcaption></figure><p>So far so good.</p><p>We now need to process this text data in order to make it interpretable for our topic and sentiment models.</p><h4>Preprocessing &amp; Exploratory Data Analysis</h4><p>Preprocessing of text data for Natural Language applications requires careful consideration. Composing a numerical vector from text data can be challenging from a loss point of view, with valuable information and subject context easily lost when performing seemingly basic tasks such as removing stopwords, as we shall see next.</p><p>Firstly, let&#39;s remove redundant information in the form of tags and URLs, i.e.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zlb-OdXMABqi6fcPcyOPAw.png" /><figcaption>Tweets from media outlets typically contain handle tags, hashtags, and links to articles, all of which need removing.</figcaption></figure><p>We define a couple of one-line <a href="https://docs.python.org/3/tutorial/controlflow.html"><strong>Lambda</strong></a> functions that use <a href="https://docs.python.org/2/library/re.html">Regex</a> to remove the letters and characters matching the expressions we want to remove:</p><pre>#@title Strip chars &amp; urls<br>remove_handles = lambda x: re.sub(‘@[^\s]+’,’’, x)<br>remove_urls = lambda x: re.sub(‘http[^\s]+’,’’, x)<br>remove_hashtags = lambda x: re.sub(&#39;#[^\s]*&#39;,&#39;&#39;,x)</pre><pre>tweets_df[‘text’] = tweets_df[‘text’].apply(remove_handles)<br>tweets_df[‘text’] = tweets_df[‘text’].apply(remove_urls)<br>tweets_df[‘text’] = tweets_df[‘text’].apply(remove_hashtags)</pre><p>Next, we perform some fundamental analysis of our twitter data by examining tweet composition, such as individual tweet lengths (words per tweet), number of characters, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*thlhCgMcYu8OkGIHHOUjqQ.png" /><figcaption>Basic Text EDA — Word &amp; Character Frequency Distributions</figcaption></figure><h4>Stop Words</h4><p>It is immediately apparent that the mean length of each tweet is relatively short (10.3 words, to be precise). This information suggests that at the expense of computational complexity and memory overhead, filtering stopwords might <strong>not</strong> be a good idea if we consider the potential information loss.</p><p>Initially, this experiment was trialled with having all stop words removed from Tweets, using NLTK’s very handy standard list of Stop Words:</p><pre># Standard tweet sw<br>stop_words_nltk = set(stopwords.words(&#39;english&#39;))</pre><pre># custom stop words<br>stop_words = get_top_ngram(tweets_df[&#39;text&#39;], 1)<br>stop_words_split = [<br>    w[0] for w in stop_words<br>    if w[0] not in [<br>        &#39;price&#39;, &#39;prices&#39;,<br>        &#39;china&#39;, &#39;copper&#39;,<br>        &#39;spot&#39;, &#39;other_stop_words_etc&#39;<br>    ] # Keep SW with hypothesised importance<br>]</pre><pre>stop_words_all = list(stop_words_nltk) + stop_words_split</pre><p>However, this action lead to a lot of miscategorised tweets (from a sentiment score point-of-view) which supports the notion of loss of information, and therefore best avoided.</p><p>At this point, It is well worth highlighting NLTK’s <em>excellent </em>library when it comes to dealing with Twitter data. It offers a comprehensive suite of tools and functions to help parse social media outputs, including emoticon interpretation!. One can find a really helpful guide to getting started with and using NLTK on Twitter data <a href="http://www.nltk.org/howto/twitter.html"><strong>here</strong></a>.</p><h4>N-grams</h4><p>The next step is to consider word order. When we vectorize a sequence of tokens into a bag-of-words (BOW — more on this in the next paragraph), we lose both context and meaning inherent in the order those words within a tweet. We can attempt to understand the importance of word order within our tweets DataFrame by examining the most frequent <a href="https://en.wikipedia.org/wiki/N-gram">n-grams</a>.</p><p>As observed in our initial analysis above, the average length of a given tweet is only 10 words. In light of this information, the <strong>order of words</strong> within a tweet and, specifically, ensuring we retain the context and meaning inherent within this ordering, is <strong>critical</strong> to generating an accurate sentiment score. We can extend the concept of a token to include multiword tokens i.e. <strong>n-grams </strong>in order to retain the meaning within the ordering of words.</p><p>NLTK has a very handy (and very efficient) n-gram tokenizer: from nltk.util import ngram. The n-gram function returns a generator that yields the top “n” n-grams as tuples. We, however, are interested in exploring what these n-grams actually are so will in the first instance, so will make use of Scikit-learn’s <a href="https://scikit-learn.org/stable/modules/generated/sklearn.feature_extraction.text.CountVectorizer.html#sklearn.feature_extraction.text.CountVectorizer.fit_transform">CountVectorizer</a> to parse our tweet data:</p><pre>def get_ngrams(doc, n=None):<br>  &quot;&quot;&quot;<br>  Get matrix of individual token counts for a given text document.<br>    Args:<br>      corpus: String, the text document to be vectorized into its  constituent tokens.<br>    n: Int, the number of contiguous words (n-grams) to return.      <br>    Returns:<br>      word_counts: A list of word:word frequency tuples.<br>  &quot;&quot;&quot;<br>  # Instantiate CountVectorizer class<br>  vectorizer = CountVectorizer(ngram_range=<br>  (n,n)).fit(doc)<br>  bag_of_words = vectorizer.transform(doc)<br>  sum_of_words = bag_of_words.sum(axis=0)<br>  # Get word frequencies<br>  word_counts = [(word, sum_of_words[0, index])<br>      for word, index in vectorizer.vocabulary_.items()<br>  ]<br>  word_counts = sorted(word_counts, key=lambda x:x[1], reverse=True)<br>  return word_counts</pre><pre># Get n-grams<br>top_bigrams = get_ngrams(tweets_df[&#39;text&#39;], 2)[:20]<br>top_trigrams = get_ngrams(tweets_df[&#39;text&#39;], 3)[:20]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cf2PLMvUk-ccCJrJcwpc7Q.png" /><figcaption>Contiguous Word Frequencies (n-grams).</figcaption></figure><p>Upon examination of our n-gram plots, we can see that apart from a few exceptions, an NLP-based predictive model would learn significantly more from our n-gram features. For example, the model will be able to correctly interpret ‘copper price’ as a<strong> reference </strong>to the physical price of copper, or ‘china trade’ to China’s trade, rather than interpreting the individual word’s meaning.</p><h4>Tokenization &amp; Lemmatization.</h4><p>Our next step is to tokenize our tweets for use in our LDA topic model. We will develop a function that will perform the necessary segmentation of our tweets (the Tokenizer’s job) and Lemmatization.</p><p>We will use NLTK’s <a href="https://www.nltk.org/api/nltk.tokenize.html"><strong>TweetTokenizer</strong></a> to perform the tokenization of our tweets, which has been developed specifically to parse tweets and understand their semantics relative to this social media platform.</p><p>Given the relatively brief nature of each tweet, dimensionality reduction is not so much of a pressing issue for our model. With this in mind, it is reasonable not to perform any Stemming operations on our data in an attempt to eliminate the small meaning differences in the plural vs possessive forms of words.</p><p>We shall instead implement a Lemmatizer, <a href="https://www.nltk.org/_modules/nltk/stem/wordnet.html"><strong>WordNetLemmatizer</strong></a>, to normalise the words within our tweet data. <a href="https://en.wikipedia.org/wiki/Lemmatisation">Lemmatisation </a>is arguably more accurate than stemming for our application as it takes into account a word’s <strong>meaning</strong>. WordNetLemmatizer can also help improve the accuracy of our topic model as it utilises part of speech (POS) tagging. The POS tag for a word indicates its role in the grammar of a sentence, such as drawing the distinction between a noun POS and an adjective POS, like “Copper” and “Copper’s price”.</p><p><em>Note: You must configure the POS tags manually within WordNetLemmatizer. Without a POS tag, it assumes everything you feed it is a noun.</em></p><pre>def preprocess_tweet(df: pd.DataFrame, stop_words: None):<br>  &quot;&quot;&quot;<br>  Tokenize and Lemmatize raw tweets in a given DataFrame.<br>    Args:<br>      df: A Pandas DataFrame of raw tweets indexed by index of type       DateTime.<br>      stop_words: Optional. A list of Strings containing stop words         to be removed.<br>    Returns:<br>      processed_tweets: A list of preprocessed tokens of type          String.<br>  &quot;&quot;&quot;<br>  processed_tweets = []<br>  tokenizer = TweetTokenizer()<br>  lemmatizer = WordNetLemmatizer()<br>  for text in df[&#39;text&#39;]:<br>    words = [w for w in tokenizer.tokenize(text) if (w not in    stop_words)]<br>    words = [lemmatizer.lemmatize(w) for w in words if len(w) &gt; 2]    </pre><pre>    processed_tweets.append(words)<br>    return processed_tweets</pre><pre># Tokenize &amp; normalise tweets<br>tweets_preprocessed = preprocess_tweet(tweets_df, stop_words_all)</pre><p>For the purposes of demonstrating the utility of the above function, we have also passed a list of <strong>stop words </strong>into the function.</p><h4>Vectorisation &amp; Continuous Bag-Of-Words</h4><p>We now need to convert our tokenised tweets to vectors, using a document representation method known as a B<strong>ag Of Words (BOW). </strong>In order to perform this mapping, we will use <a href="https://radimrehurek.com/gensim/corpora/dictionary.html">Gensim’s Dictionary class</a>:</p><pre>tweets_dict = gs.corpora.Dictionary(tweets_preprocessed)</pre><p>By passing the list of processed tweets as an argument, Gensim’s Dictionary creates a unique integer id mapping for each unique, normalised word (similar to a <a href="https://en.wikipedia.org/wiki/Hash_table">Hash Map</a>). We can view the word: id mapping by calling .token2id()on our tweets_dict. We then count the number of occurrences of each distinct word, convert the word to its integer word id, and return the result as a sparse vector:</p><pre>cbow_tweets = [tweets_dict.doc2bow(doc) for doc in tweets_preprocessed]</pre><h4>LDA Topic Modelling</h4><p>Now for the fun part.</p><p>A precursor to developing our NLP-based trading strategy is to understand whether the data we have extracted contains topics/signals that are relevant to the price of Copper, and, more importantly, whether it contains information that we could potentially trade on.</p><p>This requires us to examine and evaluate the various topics and the words that are representative of these topics within our data. Garbage in, garbage out.</p><p>In order to explore the various topics (and the subjects of said topics) within our tweet corpus, we will use Gensim’s <a href="https://radimrehurek.com/gensim/models/ldamodel.html#gensim.models.ldamodel.LdaModel">Latent Dirichlet Allocation </a>model. LDA is a generative probabilistic model applicable to collections of discrete data such as text. LDA functions as a hierarchical Bayesian model in which each item in a collection is modelled as a finite mixture over an underlying set of topics. Each topic is, in turn, modelled as an infinite mixture over an underlying set of topic probabilities (<a href="https://ai.stanford.edu/~ang/papers/jair03-lda.pdf">Blei, Ng et al 2003</a>).</p><p>We pass our newly vectorized tweets, cbow_tweetsand the dictionary mapping each word to an id, tweets_dictto Gensim’s LDA Model Class:</p><pre># Instantiate model <br>model = gs.models.LdaMulticore(<br>  cbow_tweets,<br>  num_topics = 4,<br>  id2word = tweets_dict,<br>  passes = 10,<br>  workers = 2)</pre><pre># Display topics <br>model.show_topics()</pre><p>You can see that we are required to provide an estimate of the number of topics within our dataset, via the num_topics hyperparameter. There are, as far as I am aware, two methods of determining the optimal number of topics:</p><ol><li>Build multiple LDA models and compute their <strong>coherence score </strong>with a<strong> </strong><a href="https://radimrehurek.com/gensim/models/coherencemodel.html"><strong>Coherence Model</strong></a><strong>.</strong></li><li>Domain expertise and intuition.</li></ol><p>From a trading point of view, this is where domain knowledge and market expertise can help. We would expect the topics within our Twitter data, bearing in mind they are the product of financial news publications, to focus primarily on the following subjects:</p><ul><li><strong>Copper price (naturally)</strong></li><li><strong>The U.S. / China trade war</strong></li><li><strong>The U.S. President Donald Trump</strong></li><li><strong>Major Copper miners</strong></li><li><strong>Macroeconomic announcements</strong></li><li><strong>Local producing country civil/political unrest</strong></li></ul><p>Aside from this, one should use their own judgment when determining this hyperparameter.</p><p>It is worth mentioning that a whole<strong> host </strong>of other hyperparameters exists. This flexibility makes Gensim’s LDA model extremely powerful. For example, as a Bayesian model, if we had ‘A-priori’ belief on a topic/word probability, our LDA model allows us to encode these priors for the Dirichlet distribution through the init_dir_prior method, or similarly through the eta hyperparameter.</p><p>Getting back to our model, you will note that we have used the multicore variant of Gensim’s LdaModelwhich allows for a faster implementation (ops are parallelized for multicore machines):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EME77pNqcubvxvYc5iIYIQ.png" /><figcaption>LDA Model show_topics() output: Note the topics numbered 0–4 containing the words and their associated weight i.e. how much they contribute to the topic.</figcaption></figure><p>A cursory inspection of the topics within our model would suggest that we have both relevant data and that our LDA model has done a reasonable job of modelling said topics.</p><p>In order to understand the distribution of topics and their keywords, we will use pyLDAvis which launches an interactive widget making it ideal for use in Jupyter/Colab notebooks:</p><pre>pyLDAvis.enable_notebook()<br>topic_vis = pyLDAvis.gensim.prepare(model, cbow_tweets, tweets_dict)<br>topic_vis</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AOFyZlF_ldA4Kf8hd9kn5w.png" /><figcaption>LDA Model — Twitter News Data, Topic Distribution.</figcaption></figure><h4>LDA Model Results</h4><p>Upon inspection of the resulting topic plot, we can see that our LDA model has done a reasonable job of capturing the salient topics and their constituent words within our Twitter data.</p><p><strong>What makes for a robust topic model?</strong></p><p>A good topic model typically exhibits large, distinct topics (circles) with no overlap. The areas of said circles are proportional to the proportions of the topics across the ‘N’ total tokens in the corpus (namely, our Twitter data). The centres of each topic circle are set in two dimensions: PC1 and PC2, and the distance between them set by the output of a dimensionality reduction model (Multidimensional Scaling, to be precise) that is run on the inter-topic distance matrix. A full explanation of the mathematical detail behind the pyLDAvis topic visual can be found <a href="https://cran.r-project.org/web/packages/LDAvis/vignettes/details.pdf">here</a>.</p><p><strong>Interpreting our results</strong></p><p>While remembering <strong>not </strong>to lose sight of the problem that we are trying to solve, specifically, understand whether there are any <strong>useful signals</strong> in our tweet data that might affect the Copper’s spot price, we must make a qualitative assessment.</p><p>Examining the individual topics in detail, we can see a promising set of results, specifically top words appearing within the individual topics, that adhere largely to our expected topic criteria above:</p><p><strong>Topic Number:</strong></p><ol><li><strong>Copper Mining &amp; Copper Exporting Countries</strong></li></ol><p>Top words include major Copper miners (BHP Billiton, Antofagasta, Anglo American &amp; Rio Tinto), along with mentions of major Copper exporting countries i.e. Peru, Chile, Mongolia, etc.</p><p>2. <strong>China Trade &amp; Manufacturing Activity</strong></p><p>Top words include ‘Copper’, ‘Copper price’, ‘China’, ‘Freeport’ and ‘Shanghai’.</p><p>3. <strong>U.S. / China Trade War</strong></p><p>Top words include ‘Copper’, ‘Price’, ‘China’, ‘Trump’, ‘Dollar’, and the ‘Fed’, but also some unusual terms like ‘Chile’ and ‘Video’.</p><p>On the strength of the results above, we make the decision to proceed with our NLP trading strategy, on the strength that our twitter data exhibits enough information relevant to the spot price of Copper. More importantly, we can be confident of the <em>relevancy</em> of our Twitter data with respect to the price of Copper — the topics that our LDA Model uncovered adhered to our view of the <strong><em>expected topics</em></strong><em> </em>that should be present within the data.</p><h4>Validate LDA Model</h4><p>As Data Scientists, we know that we must validate the integrity and robustness of any model. Our LDA Model is no different. We can do so by checking the Coherence (mentioned above) of our model. In layman terms, Coherence measures the relative distance between words within a topic. The mathematical detail on the mathematics behind precisely <em>how</em> this score is calculated can be found in this <a href="http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf"><strong>paper</strong></a><strong>. </strong>I have omitted to repeat the various expressions for brevity’s sake.</p><p>Generally speaking, a score between .55 and .70 is indicative of a skillful topic model:</p><pre># Compute Coherence Score<br>coherence_model = gs.models.CoherenceModel(<br>    model=model,<br>    texts=tweets_preprocessed,<br>    dictionary=tweets_dict,<br>    coherence=&#39;c_v&#39;)</pre><pre>coherence_score = coherence_model.get_coherence()<br>print(f&#39;Coherence Score: {coherence_score}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*xi-TdsuiLqnhY3t2KHskGQ.png" /><figcaption>Calculating the Coherence Score of our LDA model, based on the confirmation measure, ‘c_v’, (as opposed to UMass).</figcaption></figure><p>At a Coherence Score of .0639, we can be reasonably confident that our LDA Model has been trained on the correct number of topics, and retains an adequate degree of semantic similarity between high scoring words in each.</p><p>Our choice of score measure, observable in the signature of the above Coherence Model logic, is motivated by the results in the paper by <a href="http://svn.aksw.org/papers/2015/WSDM_Topic_Evaluation/public.pdf">Roder, Both &amp; Hindeburg</a>. You can see that we have chosen to score our model against the coherence = &#39;c_v measure, as opposed to <em>‘u_mass’, ‘c_v’, ‘c_uci’. </em>etc. The ‘c_v’ score measure was found to return superior results to that of the other measures, particularly in cases of small word sets, qualifying our choice.</p><h4>Sentiment Score: VADER</h4><p>Having been satisfied that our twitter data contains relevant enough information to potentially be predictive of short-term Copper price movements, we move onto the <a href="https://en.wikipedia.org/wiki/Sentiment_analysis"><strong>sentiment analysis</strong></a><strong> </strong>part<strong> </strong>of our problem.</p><p>We will use NLTK’s Valence Aware Dictionary and sEntiment Reasoner (VADER) to analyse our tweets, and, based on the sum of the underlying intensity of each word within each tweet, generate a sentiment score between -1 and 1.</p><p>Irrespective of whether we employ single-tokens, ngrams, stems, or lemmas in our NLP model, fundamentally, each token in our tweet data contains some information. Possibly the most important part of this information is the word’s <em>sentiment.</em></p><p>VADER is a popular heuristic, rule-based (composed by humans) sentiment analysis model by <a href="https://www.nltk.org/_modules/nltk/sentiment/vader.html">Hutto and Gilbert</a>. It is particularly accurate (and was designed specifically for this application) for use on social media text. It seems rational, therefore, to use it for our project.</p><p>VADER’s implementation is very straightforward:</p><pre># Instantiate SIA class<br>analyser = SentimentIntensityAnalyzer()</pre><pre>sentiment_score = []</pre><pre>for tweet in tweets_df[‘text’]:<br>  sentiment_score.append(analyser.polarity_scores(tweet))</pre><p>The SentimentIntensityAnalyzer contains a dictionary of tokens and their individual scores. We then generate a sentiment score for each tweet in our tweets DataFrame and access the result, a dictionary object, of the four separate score components generated by the VADER model:</p><ul><li>The negative proportion of the text</li><li>The positive proportion of the text</li><li>The neutral proportion of the text &amp;</li><li>The combined intensity of sentiment polarity in the above, the ‘Compound’ score</li></ul><pre>#@title Extract Sentiment Score Elements</pre><pre>sentiment_prop_negative = []<br>sentiment_prop_positive = []<br>sentiment_prop_neutral = []<br>sentiment_score_compound = []</pre><pre>for item in sentiment_score:<br>  sentiment_prop_negative.append(item[&#39;neg&#39;])<br>  sentiment_prop_positive.append(item[&#39;neu&#39;])<br>  sentiment_prop_neutral.append(item[&#39;pos&#39;])<br>  sentiment_score_compound.append(item[&#39;compound&#39;])</pre><pre># Append to tweets DataFrame<br>tweets_df[&#39;sentiment_prop_negative&#39;] = sentiment_prop_negative<br>tweets_df[&#39;sentiment_prop_positive&#39;] = sentiment_prop_positive<br>tweets_df[&#39;sentiment_prop_neutral&#39;] = sentiment_prop_neutral<br>tweets_df[&#39;sentiment_score_compound&#39;] = sentiment_score_compound</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*nmYW4wj4Fo4QC9UxTJUvmA.png" /><figcaption>Tweet Data Sentiment Scores: Negative, Positive, and Compound, Daily.</figcaption></figure><p>After plotting the rolling scores for the various components, negative, positive, and compound scores (we leave neutral out), we can make a few observations:</p><ul><li>Clearly, the sentiment score is very noisy/volatile — our Twitter data may simply contain redundant information, with a few causing large spikes in scores. This is, however, the nature of signal finding — we only need that one piece of salient information.</li><li>Our Twitter data appears to be predominantly positive: the mean negative score is .09, whilst the mean positive score is .83.</li></ul><h4>Sentiment Score VS Copper Spot Price</h4><p>Now we must evaluate whether our hard work has paid off: <strong>Is our sentiment score predictive of Copper’s spot price!</strong></p><p>On first glance, there does not appear to be any association between the spot price and our compound score:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*tkU2Y6ECuiMKy12XJBpPvA.png" /><figcaption>Compound Sentiment Score vs Spot Copper ($/Mt), Daily.</figcaption></figure><p>However, when we apply a classic smoothing technique and calculate the rolling average of our sentiment score, we see a different picture emerge:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*S7xktMdPWX2zHPcpXECz0A.png" /><figcaption>Rolling 21d Mean Compound Sentiment Score vs Spot Copper ($/mt), Daily.</figcaption></figure><p>This now looks a <strong>lot</strong> more promising. With the exception of the time period between January and August 2017, we can readily observe a near-symmetric, inverse relationship between our 21-day rolling mean compound score and the spot price of Copper.</p><h3>Conclusion</h3><p>At this juncture, we pause to consider the options available to us on how we want our model to process and classify the underlying sentiment within a piece of text data, and, critically, how the model will act on this classification in terms of its trading decisions.</p><p>Consistent with the <a href="https://en.wikipedia.org/wiki/Occam%27s_razor">Occam’s Razor</a> principle, we implemented an out-of-the-box solution to analyse the underlying sentiment within our twitter data. As well as exploring some renowned EDA and preprocessing techniques as a prerequisite, we used <a href="https://www.nltk.org/_modules/nltk/sentiment/vader.html">NLTK’s Valence Aware Dictionary and <strong>sEntiment</strong> Reasoner (VADER)</a>, to generate an associated sentiment score for each tweet, and examined the correlation of said score against simple corresponding Copper spot price movements.</p><p>Interestingly a correlation was observed between our rolling compound sentiment score and the price of Copper. This does not, of course, imply causation. Moreover, it may simply be the news data trails that of the price of Copper, and our tweet data is simply reporting on its movements. Nonetheless, there is scope for further work.</p><h3>Observations, Criticisms &amp; Further Analysis</h3><p>In reality, the design of a systematic trading strategy necessitates a great deal more mathematical and analytical rigour, as well as a good dose of domain expertise. One would typically invest a great deal of time designing a suitable label that best encompasses the signal and the magnitude of the price movement (if at all!) found within said signal, notwithstanding a thorough investigation of the signal itself.</p><p>Scope for very interesting further work and analysis exists in abundance with respect to our problem:</p><ol><li><strong>Neural Network Embeddings: </strong>As an example, in order to intimately understand how an NLP model, with an associated label (or labels), makes a trading decision we would look to train a Neural Network with an <a href="https://www.tensorflow.org/api_docs/python/tf/keras/layers/Embedding">Embedding Layer</a>. We could then examine the trained embedding layer to understand how the model treats the various tokens within the layer against those with a similar encoding, and the label(s). We could then visualise how the model groups words with respect to their effect on the class we wish to predict i.e. 0 for negative price movement, 1 for positive price movement. TensorFlow’s Embedding Projector, for example, is an invaluable tool for visualising such embeddings:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XTLxZ5KPnsVD4wUPmUCnBw.png" /></figure><p><strong>2. Multinomial Naive Bayes</strong></p><p>We used VADER to parse and interpret the underlying sentiment of our Twitter data, which it did a reasonable job of doing. The drawback of using VADER, however, is that <strong>it doesn’t consider all the words in a document, only about 7,500 in fact. </strong>Given the complexity of commodity trading and its associated terminology, we might be missing crucial information.</p><p>As an alternative, we could employ a Naive Bayes classifier to find sets of keywords that are predictive of our target, be it the price of Copper itself or a sentiment score.</p><p><strong>3</strong>. <strong>Intra-day Data</strong></p><p>Intra-day data in nearly all cases is a must when designing an NLP trading strategy model, for the reasons mentioned in the introduction. Time and trade execution is very much of the essence when attempting to capitalise on news/event-based price movements.</p><p>Thank you for taking the time to read my article, I hope you found it interesting.</p><p>Please do feel free to reach out — I very much welcome comments &amp; constructive critiques.</p><h3>References</h3><ol><li><a href="https://www.nltk.org/_modules/nltk/sentiment/vader.html">Hutto, C.J. &amp; Gilbert, E.E. (2014). VADER: A Parsimonious Rule-based Model for Sentiment Analysis of Social Media Text. Eighth International Conference on Weblogs and Social Media (ICWSM-14). Ann Arbor, MI, June 2014.</a></li><li>Lane, Howard, Hapke (2019): Natural Language Processing in Action.</li><li><a href="https://moneyweek.com/516039/the-cycles-in-the-metals-market-when-will-zinc-and-copper-shine">Moneyweek (2019): The Cycles In the Metals Market: When Will Zinc &amp; Copper Shine</a>.</li><li><a href="https://asia.nikkei.com/Business/Markets/Commodities/Dr.-Copper-misdiagnoses-the-global-economy">Nikkei, Asian Review (2020): ‘Dr. Copper’ misdiagnoses the global economy</a>.</li><li><a href="https://www.kitco.com/news/2020-07-15/METALS-Copper-slips-on-profit-taking-triggered-by-U-S-China-tensions.html">Kitco 2020: Copper slips on profit-taking triggered by U.S.-China tensions.</a></li><li><a href="https://agmetalminer.com/2014/06/11/what-chinas-shadow-financing-market-aluminum-copper-collateral-means-for-metals-markets/">Metal Miner, (2020): What China’s Shadow Metal Financing Means for Markets</a>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=492456b031b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/spot-vs-sentiment-nlp-sentiment-scoring-in-the-spot-copper-market-492456b031b0">Spot vs Sentiment: NLP &amp; Sentiment Scoring in the Spot Copper Market</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structural Time-Series Forecasting with TensorFlow Probability: Iron Ore Mine Production]]></title>
            <link>https://medium.com/data-science/structural-time-series-forecasting-with-tensorflow-probability-iron-ore-mine-production-897d2334c72b?source=rss-5e70db60a641------2</link>
            <guid isPermaLink="false">https://medium.com/p/897d2334c72b</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[tensorflow-probability]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Chris Price]]></dc:creator>
            <pubDate>Sat, 18 Jul 2020 14:04:48 GMT</pubDate>
            <atom:updated>2020-07-21T11:25:11.065Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bayesian Structural Time Series Forecasting with TensorFlow Probability Structural Time Series</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JO-Mf55PiRod_fCZLoeHcg.jpeg" /><figcaption>Image: <a href="https://unsplash.com/photos/-subrrYxv8A">https://unsplash.com/photos/-subrrYxv8A</a></figcaption></figure><h3>Introduction</h3><p><a href="https://www.spglobal.com/platts/en/our-methodology/price-assessments/metals/iodex-iron-ore-metals-price-assessment"><strong>Iron ore</strong></a><strong> </strong>is one of the <a href="https://www.ig.com/en/trading-opportunities/top-10-most-traded-commodities-180905">most heavily traded commodities</a> in the world. As the primary input for the production of steel, it provides the foundation upon which the world’s largest metal market trades, and commands one of the largest shares of the global dry bulk trade.</p><p>Iron ore production, unsurprisingly, starts at the mine. As a trader either physical or financial, an understanding of the fundamental supply-demand nature of the iron ore market is essential. Iron ore grade (quality) variance has a notable impact on not only the spot and forward contracts pricing, but also on mill penalty charges for impurities. Imbalances in the fundamental supply/demand relationship can cause <a href="https://www.ft.com/content/8452e078-7880-11e9-bbad-7c18c0ea0201">dramatic rises</a> in the price of iron ore. <strong>Forecasting iron ore output </strong>from the largest iron ore exporting countries in order to predict global iron ore supply can be very helpful when speculating on spot, futures and contaminant penalty price movements.</p><h3>Problem</h3><p>In this article, we are going to develop a forecast model using <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts">TensorFlow Probability’s Structural Time-Series</a> (STS) framework, to forecast the aggregate output of major iron ore mines in Brazil.</p><p>Brazil is the second largest exporter of iron ore globally. Major changes in supply from Brazil can have an affect on the price of iron ore, as noted above. Furthermore, Brazilian iron ore is typically very high-grade and low in impurities. As a result, the relative supply of ore from Brazil can have an affect on the penalty pricing of impurities charged by steel mills. If global supply is dominated by high-contaminant iron ore as a result of a shortage in supply from Brazilian mines, the price penalty of contaminants can <a href="https://www.argusmedia.com/en/news/1893132-iron-ore-alumina-penalties-soar-on-supply-crunch">rise dramatically</a>. Forecasting the output from Brazil therefore can lend itself to understanding the above dynamics.</p><p>The code used in this article follows similar logic to that outlined in the <a href="https://blog.tensorflow.org/2019/03/structural-time-series-modeling-in.html">Structural Time Series modeling</a> in TensorFlow Probability tutorial (Copyright 2019 The TensorFlow Authors).</p><h3>Why TensorFlow Probability STS?</h3><p>When approaching a time series forecast problem, investing time into understanding the complexity of the variable you wish to forecast is paramount. Stationarity, seasonality, distributions and exogenous feature relationships are but a handful of the many considerations to bear in mind before designing any model’s architecture.</p><p>Structural time series models (sometimes referred to as Bayesian Structural Time Series) are expressed as a sum of components such as trend, seasonal patterns, cycles and residuals:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*VmB8YMy_rFdO8YomnqC0tA.png" /></figure><p>These individual components are themselves time series defined by a structural assumption. The ability to configure each component in the time series makes TFP’s STS library particularly relevant in the context of our time series forecasting problem, as it enables us to encode domain-specific knowledge, such as trader and mine operator expertise, and known events into our model.</p><h4>How this helps with our problem</h4><p>Mines production outputs typically exhibit systematic behaviour that can be modelled as a structural time series. In the context of our problem, we know that many mines close down for a two-week period in December for scheduled maintenance. This repeatable pattern can be added as a seasonal component to a structural time series model. We also know that Iron ore and other open cast mines exhibit distinct seasonal patterns that correlate strongly with precipitation which, during periods of heavy rainfall, lead to reduced outputs as drainage pumps become overwhelmed.</p><p>What is particularly useful about structural time series models in the context of our problem is that they employ a probabilistic approach to modelling a time series problem, namely, they return a posterior predictive distribution over which we can sample to provide not only a forecast, but also a means of quantifying model uncertainty.</p><p>Another exciting and highly useful feature of STS models is that the resulting model can be <strong>decomposed</strong> as a collection of it separate components. These components can then be plotted, giving us a valuable insight into their respective affects on the dependent variable (Y-hat), and a deeper understanding of the global time series problem:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ndS-PGSMl8GtwsJQWxT9g.png" /><figcaption>Example time series decomposition taken from <a href="https://blog.tensorflow.org/2019/03/structural-time-series-modeling-in.html">https://blog.tensorflow.org/2019/03/structural-time-series-modeling-in.html</a></figcaption></figure><h3>Prerequisites</h3><p>Before we start, it is worth noting that TensorFlow probability has a specific set of dependencies. Moreover TensorFlow is <em>not</em> included as a dependency of the TensorFlow Probability library and will need to be installed separately:</p><p><a href="https://github.com/tensorflow/probability/releases">Releases · tensorflow/probability</a></p><pre>pip install --upgrade tensorflow-probability</pre><p>Alternatively, you can use <a href="https://colab.research.google.com/notebooks/intro.ipynb">Google’s Colaboratory</a> (Colab), who kindly provide hosted runtimes in Colab completely free of charge (CPU, GPU and <em>even </em>TPU!) subject to memory limits.</p><h3>Structural Time Series Model</h3><p>Let’s get started.</p><h4>Data</h4><p>We start by examining our mine loadings (output) data whose observations are the total weekly output of each mine in millions of metric tonnes, aggregated over all major Brazilian iron ore producers:</p><pre># Imports<br>import matplotlib.pyplot as plt<br>import pandas as pd<br>import numpy as np<br>import seaborn as sns<br>import tensorflow_probability as tfp<br>import tensorflow as tf</pre><pre>from statsmodels.tsa.seasonal import seasonal_decompose</pre><pre>df = pd.read_excel(<br>    &#39;/content/bloomberg_weekly_io_output_brazil.xlsx&#39;,<br>    header = 1, <br>    index_col = 0,<br>    parse_dates = True)</pre><pre># Loadings<br>df.plot(figsize=(16, 8))<br>plt.title(‘Weekly Iron Ore Output, Metric Tonnes’)<br>plt.ylabel(‘Loadings, Mt’)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/944/1*isJzufAfnn1WovBKn4Y2kg.png" /><figcaption>Mine Loadings in Millions of Tonnes, Weekly</figcaption></figure><p>If we examine the observed output time series carefully, we can vaguely see some of the structural components mentioned earlier in the article that we can attempt to encode in an STS model:</p><ul><li>A clear seasonal pattern. Judging by the amplitude and frequency of each cycle, it is reasonable to suggest that this is additive seasonality (defined below).</li><li>With the exception of late 2018/early 2019, a linear trend.</li><li>Around the Christmas period, a distinct drop in output when mines typically close for scheduled maintenance.</li><li>A degree of noise, possibly correlated with weather, strikes, equipment failures etc.</li></ul><h4>Time Series Decomposition</h4><p>We can verify some of the aforementioned components in the time series by attempting to decompose the time series into its constituent parts. We will use <a href="https://www.statsmodels.org/stable/tsa.html">statsmodels</a> time series analysis library to perform the decomposition and choose an ‘additive’ model as the seasonal component on the basis of the observed behaviour in our time series plot. For reference, additive seasonality is estimated as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*5dS1Kn5DPwPSi9-Xg2zYtg.png" /></figure><p>Passing the ‘iron_ore_brazil’ Pandas Series to the seasonal_decompose method we imported from statsmodels yields the following plot:</p><pre>tsa = seasonal_decompose(<br>    df[‘iron_ore_brazil’],model=’additive’<br>).plot()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*OzaSzkFRHuKNY_sAPsLroQ.png" /><figcaption>Iron Ore Output Tonnes — Seasonal Decomposition</figcaption></figure><p>Upon inspection, we can immediately identify the (mostly) linear trend and the seasonal component. If we look closely at the frequency and amplitude, you can see when the mine output diminishes each year during the winter period.</p><p>It is immediately apparent upon inspection of the residuals, that there are other relationships within this time series that <strong>cannot </strong>be explained by the seasonal and trend elements alone. The <strong>variance </strong>in the residuals, however, remains fairly constant and within a defined bound. <strong>This is useful information to bear in mind when defining our structural components.</strong></p><p><strong>“Aha!”</strong> I hear you cry at this point. “Why decompose the time series if that is the <em>point </em>of the STS model?”. Well, for two reasons:</p><ol><li>It helps as a starting point in identifying and understanding the various fundamental components in a time series: trend, seasonality, cycles and unexplained variance which in turn, can inform us <em>how </em>we can configure the input parameters to the STS model priors.</li><li>TFP’s STS models are trained on data through <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/build_factored_surrogate_posterior">Variational Inference </a>(VI) or <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/fit_with_hmc">Hamiltonian Monte Carlo (HMC)</a> methods:</li></ol><pre># Fit model to observed data with HMC<br>tfp.sts.fit_with_hmc(<br>    model, observed_time_series, num_results=100, num_warmup_steps=50,<br>    num_leapfrog_steps=15, initial_state=None, initial_step_size=None,<br>    chain_batch_shape=(), num_variational_steps=150, variational_optimizer=None,<br>    variational_sample_size=5, seed=None, name=None<br>)</pre><pre># Or, fit model to data with VI<br>tfp.sts.build_factored_surrogate_posterior(<br>    model, batch_shape=(), seed=None, name=None<br>)</pre><p>Both of these methods are, generally-speaking, quite computationally intensive (particularly in the case of HMC) on high-dimensional problems and are quite sensitive to tuning. Having an informed choice of input parameters when configuring STS components can help save time, resources and increase posterior distribution accuracy.</p><p>Explaining the mathematics behind HMC and VI is beyond the scope of this article, but you can find out more on HMC <a href="https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo">here</a> and VI <a href="https://en.wikipedia.org/wiki/Variational_Bayesian_methods">here</a>.</p><h4>Define Our Structural Components</h4><p>We can now define the various components to our STS model and configure them based on what we <em>know </em>about the data generating process. Let’s start with the seasonal component:</p><h4><strong>Seasonal:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*IdEepvfO8bgLQ_6iM187Ig.png" /><figcaption>Iron Ore Output (Tonnes): Seasonal Component</figcaption></figure><p>We define the seasonal inputs to our structural time series model as follows:</p><pre># Create train dataset<br>_train = df[‘iron_ore_brazil’][df.index &lt; ‘2018–01–01’]<br>_dates = train.index</pre><pre># Test data<br>test = df[‘iron_ore_brazil’][df.index &gt;= ‘2018–01–01’]</pre><pre># TensorFlow requires an an (N, 1) float tensor<br>train = _train.to_numpy().reshape(-1, 1))</pre><pre># Seasonal effect 1: weekly cycle as identified in decomp.<br>weekly_cycle = tfp.sts.Seasonal(<br>    num_seasons=52, # 52 weeks in year<br>    observed_time_series=train,<br>    allow_drift=True,<br>    name=’weekly_effect’)</pre><pre># Seasonal effect 2: month of year to capture winter drop in output.<br>monthly_affect = tfp.sts.Seasonal(<br>    num_seasons=12, # 12 months in year<br>    num_steps_per_season=4, # assumed 4 weeks in every month<br>    observed_time_series=train,<br>    name=’month_of_year_effect’)</pre><p>A valuable feature offered by the tfp.sts.Seasonal model is the ability to add <em>‘drift’ </em>to the seasonal affect. This parameter allows the effect of each season to evolve or ‘drift’ from one occurrence to the next following a Gaussian random walk(specifically, samples drawn from a normal distribution defined by a mean and variance plus some drift term). If we were confident of the mean and variance of the prior distribution of the seasonal component, we could configure it ourselves within the model:</p><pre>monthly_effect = tfp.sts.Seasonal(<br>    num_seasons=12, # 12 months in year<br>    num_steps_per_season=4, # assumed 4 weeks in month<br>    observed_time_series=train,<br>    drift_scale_prior=tfd.Normal(loc=1., scale=0.1), # define priors<br>    initial_effect_prior=tfd.Normal(loc=0., scale=5.),<br>    name=’month_of_year_effect’)</pre><p>For now, by setting the parameter ‘allow_drift=True’ we can let the model handle this for us.</p><h4><strong>Trend Component</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*A6fuWE012UIqkOfVGZdlbw.png" /><figcaption>Iron Ore Output (Tonnes) Trend Component</figcaption></figure><p>A visual inspection of our iron ore mine outputs shows (with the exception of late 2018/early 2019) a consistent linear trend. We can model this behaviour with a <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/LocalLinearTrend"><strong>LocalLinearTrend</strong></a><strong> </strong>model.</p><p>The local linear trend model represents a time series trend as a combination of some magnitude (level) and slope. Each of these elements evolve through time via a Gaussian random-walk:</p><pre>level[t] = level[t-1] + slope[t-1] + Normal(0., level_scale)<br>slope[t] = slope[t-1] + Normal(0., slope_scale) </pre><p>Implementation of the local linear trend component in our problem is quite straightforward:</p><pre># Add trend<br>trend = tfp.sts.LocalLinearTrend(<br>    observed_time_series=train,<br>    name=&#39;trend&#39;)</pre><p><strong>An important consideration </strong>to bear in mind when choosing how to model the trend component is the choice of model, which is dependent upon the nature of the problem. In the case of our time series problem, the observed trend is relatively stable over time and evolves gradually i.e. it does not display any strong nonlinear behaviour. Our choice of model to represent this trend, therefore, is a reasonable one, <strong>however</strong> this model can produce forecasts with very high uncertainty over longer forecast periods.</p><p><strong>What is the alternative?</strong></p><p>It is well known that most time series have inherent <a href="https://bookdown.org/rdpeng/timeseriesbook/the-structure-of-temporal-data.html">temporal structure</a> where succeeding observations are dependent on the previous <em>n </em>observations in time i.e. <a href="https://en.wikipedia.org/wiki/Autocorrelation">autocorrelation</a>. A wise choice therefore, might be to model the trend using TFP STS’s <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/LocalLinearTrend"><strong>SemiLocalLinearTrend </strong></a>model. In a semi-local linear trend model, the slopecomponent evolves according to a<strong> </strong>first-order autoregressive<strong> </strong>process. The AR process can therefore account for the <a href="https://en.wikipedia.org/wiki/Autocorrelation">autocorrelative</a> (of order <em>n</em>) effect in the time series, and typically lead to forecasts with greater certainty over a longer period of time.</p><h4><strong>Residuals:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*S31i1AHfj2PL10X3vN_zPg.png" /><figcaption>Iron Ore Output (Tonnes) Residual Component</figcaption></figure><p>As previously mentioned during our inspection of the seasonal decomposition plot, the residuals in our time series look relatively consistent suggesting that they are potentially <strong><em>stationary,</em></strong> i.e. they maintain a constant variance over time, do not exhibit bias or heteroskedasticity etc. We can therefore represent the residual behaviour in an sts.<a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/Autoregressive"><strong>AutoRegressive</strong></a> model:</p><pre># Residuals<br>residuals = tfp.sts.Autoregressive(<br>    order=1,<br>    observed_time_series=train,<br>    coefficients_prior=None,<br>    level_scale_prior=None,<br>    initial_state_prior=None,<br>    name=&#39;residuals_autoregressive&#39;)</pre><p>As with the other components, for a fully Bayesian approach one should specify the priors coefficients_prior, level_scale_prior and initial_state_prior. As we have not specified priors, a TensorFlow Distributions (tfd) MultivariateNormalDiag instance is used as a default prior for the coefficients, and a heuristic prior constructed for the level and initial states based on the input time series.</p><h4>Define Model</h4><p>We can now define our structural time series model using the <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/Sum"><strong>tfp.sts.Sum</strong></a> class. This class enables us to define the compositional specification of our structural time series model from the components we have defined above:</p><pre>model = tfp.sts.Sum(<br>    components=[<br>        trend,<br>        weekly_cycle,<br>        monthly_effect,<br>        residuals],<br>    observed_time_series=train) </pre><h4>Fit Model</h4><p>We will now fit our model to the observed time series, namely our iron ore output. Unlike traditional time series forecasting architectures such as Linear Regression models, which estimate their coefficients via Maximum Likelihood Estimation, or, on the more powerful end of the scale, an LSTM which learns a function that maps a sequence of past observations as input to an output observation, an STS model learns a <strong><em>distribution</em></strong><em>, </em>namely, the posterior.</p><p>We are going to fit the model to the data and build a posterior predictive distribution using Variational Inference. Simply put, VI fits a set of approximate posterior distributions for the model parameters we have defined (for each component) and optimises these by minimising a variational loss function known as negative Evidence Lower Bound (ELBO):</p><pre># VI posterior <br>variational_posteriors = tfp.sts.build_factored_surrogate_posterior(<br>    model=loadings_model)</pre><pre># Build and optimize the variational loss function (ELBO).<br>@tf.function()<br>def train_sts_model():<br>  elbo_loss_curve = tfp.vi.fit_surrogate_posterior(<br>      target_log_prob_fn=loadings_model.joint_log_prob(<br>      observed_time_series=training_data),<br>  surrogate_posterior=variational_posteriors,<br>  ptimizer=tf.optimizers.Adam(learning_rate=.1),<br>  num_steps=200)<br>  return elbo_loss_curve</pre><pre># Plot KL divergence<br>elbo = train_sts_model()()<br>plt.plot(elbo_loss_curve)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*MQfvXr8ZXDxC0ItEvMyHlA.png" /><figcaption>Plot of Evidence Lower Bound Optimisation (ELBO minimises Kullbeck-Leibler Divergence)</figcaption></figure><p>The astute among us might have noticed the decorator, <a href="https://www.tensorflow.org/api_docs/python/tf/function">@tf.function()</a>. This accepts a function, in this instance our STS model, as an argument and compiles it into a callable TensorFlow graph. An interesting introduction on how TensorFlow works and handles operations through the use of graphs can be found <a href="https://www.tensorflow.org/guide/intro_to_graphs">here</a>.</p><h4><strong>Forecast</strong></h4><p>Now for the fun part. After checking the loss function converges, we can perform a forecast. We draw traces (samples) from the variational posterior and construct a forecast by passing these as an argument to <a href="https://www.tensorflow.org/api_docs/python/tf/function">tfp.sts.forecast(</a>). Given our model, the observed time series and our sampled parameters,<strong> forecast()</strong> returns the predictive distribution over the future observations for the desired number of forecast steps:</p><pre># Draw traces from posterior<br>traces__ = variational_posteriors.sample(50)</pre><pre># No timesteps to forecast<br>n_forecast_steps = len(test)</pre><pre># Build forecast distribution over future timesteps<br>forecast_distribution = tfp.sts.forecast(<br>    loadings_model,<br>    observed_time_series=train,<br>    parameter_samples=traces__<br>    num_steps_forecast=n_forecast_steps)</pre><pre># Draw fcast samples<br>num_samples=50</pre><pre># Assign vars corresponding to variational posterior<br>fcst_mu, fcast_scale, fcast_samples=(<br>    forecast_distribution.mean().numpy()[..., 0],<br>    forecast_distribution.stddev().numpy()[..., 0],<br>    forecast_distribution.sample(num_samples).numpy()[..., 0])</pre><p>We can then visualise our forecast:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRPbhbbBoP73JQ3xVize7w.png" /><figcaption>Iron Ore Output (Tonnes) Forecast vs Observed</figcaption></figure><h4>Validate Model Performance</h4><p>Upon first glance, we can observe that the model (with the exception of the 2019 force majeure) has performed quite reasonably in forecasting our mine outputs. We can validate the accuracy of our forecast against the observed data points by calculating the Mean Absolute Error. From a business perspective, however, given the scale of the label i.e. in millions of tonnes it makes more sense to calculate and present the Mean Average Percentage Error (MAPE), as this is more interpretable and meaningful to non-data science individuals:</p><pre># Remember to check for div by zero errors first<br>print(np.mean(np.abs((test- fcast_mu) / test)) * 100)</pre><pre>&gt;&gt;&gt; 13.92</pre><p>At 13.92% MAPE It is clear that our iron ore output model has done a reasonable job of modelling the data generating distribution, particularly when we have not fully tuned the parameters of the model.</p><h4>Validate Structural Component Contributions</h4><p>We can further understand our model’s fit and verify the contribution of our individual structural components by decomposing it into their respective time series (again). We use<a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/decompose_by_component">tfp.sts.decompose_by_component</a> to perform this operation which returns acollections.OrderedDict of the individual components posterior distributions, mapped back to its respective observation model:</p><pre># Dist. over individual component outputs from posterior (train)<br>component_dists = tfp.sts.decompose_by_component(<br>    loadings_model,<br>    observed_time_series=train,<br>    parameter_samples=traces__)</pre><pre># Same for fcast.<br>forecast_component_dists = tfp.sts.decompose_forecast_by_component(<br>    loadings_model,<br>    forecast_dist=loadings_model_distribution,<br>    parameter_samples=traces__)</pre><p>After a bit of manipulation, we can plot the output of the decomposed time series to yield the following chart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*GeoCkf3vFs0HJASu_ql49Q.png" /><figcaption>Iron Ore Structural Time Series Decomposition by Component, Training &amp; Forecast Distributions</figcaption></figure><h3><strong>Observations, Criticisms &amp; Further Analysis</strong></h3><p>Examination of our decomposed model raises some points for further analysis:</p><ol><li>The mean and std deviation of our forecast posterior distributions provide us with marginal uncertainty at each time step. With this in mind, we can observe that our model is confident of our <strong>trend</strong> component’s contribution to the time series, exhibiting a stable profile up until 2018 where model uncertainty compounds. To counter this, we could improve the accuracy of our trend component by modelling it as a <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/SemiLocalLinearTrend"><strong>SemiLocalLinearTrend</strong></a> model, which allows the slope component to evolve as an AutoRegressive process.</li><li>Our model is confident of the <strong>weekly </strong>and <strong>monthly </strong>seasonal component contributions, exhibiting a consistent output at each time step, suggesting our configuration is correct. Whilst consistent, the uncertainty for our <strong>monthly </strong>component is significantly higher. We could potentially improve these components with the addition of informed priors i.e. initial_state_prior etc.</li><li>Interestingly, our <strong>AutoRegressive </strong>component contributes very little. Our model is also reasonably confident about this, suggesting that the residuals are not explained by an AR process. We could explore adding <strong>external features </strong>such as local weather/precipitation patterns and iron ore spot prices as linear covariates using <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/LinearRegression"><strong>sts.LinearRegression</strong></a><strong>.</strong></li><li>We might achieve a more accurate posterior by fitting the model to the data utilising a Markov chain Monte Carlo (MCMC) method i.e. <a href="https://www.tensorflow.org/probability/api_docs/python/tfp/sts/fit_with_hmc">tfp.sts.fit_with_hmc()</a> as opposed to using VI.</li></ol><h3>Conclusion</h3><p>In this article, we have seen how we can develop a Bayesian Structural Time Series model using TensorFlow Probability’s Structural Time Series library. Additionally, we explored:</p><ul><li>How define and configure structural time series model components.</li><li>How train an STS model to build a posterior predictive probability distribution.</li><li>How to sample the posterior distribution in order to preform a time series forecast.</li><li>How to decompose a structural time series models to examine the individual contributions of it’s respective components.</li><li>A brief look into some alternative ways of improving our STS model with some of the other awesome models offered by TensorFlow Probability STS.</li></ul><p>Thank you for reading!</p><h3>References</h3><ul><li>TensorFlow Blog, Structural Time Series Modelling in TensorFlow (2019): <a href="https://blog.tensorflow.org/2019/03/structural-time-series-modeling-in.html">https://blog.tensorflow.org/2019/03/structural-time-series-modeling-in.html</a></li><li>SPGlobal Platts, IODEX Iron Ore Metal Price Assessment (2020): <a href="https://www.spglobal.com/platts/en/our-methodology/price-assessments/metals/iodex-iron-ore-metals-price-assessment">https://www.spglobal.com/platts/en/our-methodology/price-assessments/metals/iodex-iron-ore-metals-price-assessment</a></li><li>IG.com, Top 10 Most Traded Commodities (2018), <a href="https://www.ig.com/en/trading-opportunities/top-10-most-traded-commodities-180905">https://www.ig.com/en/trading-opportunities/top-10-most-traded-commodities-180905</a></li><li>Financial Times, Iron ore at five-year high above $100 a tonne after Vale warning(2019): <a href="https://www.ft.com/content/8452e078-7880-11e9-bbad-7c18c0ea0201">https://www.ft.com/content/8452e078-7880-11e9-bbad-7c18c0ea0201</a></li><li>Argus Media, Iron ore alumina penalties soar on supply crunch(2019): <a href="https://www.argusmedia.com/en/news/1893132-iron-ore-alumina-penalties-soar-on-supply-crunch">https://www.argusmedia.com/en/news/1893132-iron-ore-alumina-penalties-soar-on-supply-crunch</a></li><li><em>Roger D. Peng, </em>A very short course on time series analysis:(2020): <a href="https://bookdown.org/rdpeng/timeseriesbook/the-structure-of-temporal-data.html">https://bookdown.org/rdpeng/timeseriesbook/the-structure-of-temporal-data.html</a></li><li>Wikipedia, Autocorrelation: <a href="https://en.wikipedia.org/wiki/Autocorrelation">https://en.wikipedia.org/wiki/Autocorrelation</a></li><li>Wikipedia, Hamiltonian Monte Carlo: <a href="https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo">https://en.wikipedia.org/wiki/Hamiltonian_Monte_Carlo</a></li><li>Wikipedia, Variational Bayesian Methods: <a href="https://en.wikipedia.org/wiki/Variational_Bayesian_methods">https://en.wikipedia.org/wiki/Variational_Bayesian_methods</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=897d2334c72b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/structural-time-series-forecasting-with-tensorflow-probability-iron-ore-mine-production-897d2334c72b">Structural Time-Series Forecasting with TensorFlow Probability: Iron Ore Mine Production</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>