<?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 Sarah Ismael on Medium]]></title>
        <description><![CDATA[Stories by Sarah Ismael on Medium]]></description>
        <link>https://medium.com/@sa.ali.ismael?source=rss-dc239fdc08eb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jwLIhPZ2GbU7usuq_okzow.jpeg</url>
            <title>Stories by Sarah Ismael on Medium</title>
            <link>https://medium.com/@sa.ali.ismael?source=rss-dc239fdc08eb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:16:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sa.ali.ismael/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[Time Series Forecasting for COVID-19]]></title>
            <link>https://pub.towardsai.net/time-series-forecasting-for-covid-19-c638688d8835?source=rss-dc239fdc08eb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c638688d8835</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[time-series-forecasting]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[covid19]]></category>
            <dc:creator><![CDATA[Sarah Ismael]]></dc:creator>
            <pubDate>Sat, 02 May 2020 00:01:01 GMT</pubDate>
            <atom:updated>2020-05-02T00:01:01.015Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>A guideline to performing time series forecasting with Facebook’s Prophet using COVID-19 data from Johns Hopkins University Center</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8-b75WJOIqIAJuLHMjxiYw.png" /></figure><p>A time series is merely a series of data points ordered across time at a regular interval, where time usually is the independent variable, and the goal is to make a forecast (prediction) for the future. Time series is a common pattern with many applications in life — e.g., stock prices, weather, sales. Learning how to forecast time series data is an essential skill in the data science world.</p><p>The new coronavirus, otherwise known as COVID-19, is an ongoing pandemic that has been widely spreading across the world since December 2019. Using time-series forecasting to predict the future daily cases of COVID-19 will undoubtedly help understand how fast it is increasing and what might determine that increase. Also, it can help to acknowledge what an intervention like physical distancing or a lockdown might impact the increase over time.</p><p>Prophet is a library provided by Facebook’s data science engineering team, and it is a powerful yet simple tool for analyzing and predicting periodic data and is available for both Python and R.</p><p>This article aims to explain how to perform time series forecasting with Prophet using COVID-19 data from Johns Hopkins University Center.</p><h3>Tools</h3><p>Our environment setup for this article uses Python 3.7 with the following packages installed:</p><ul><li>NumPy</li><li>pandas</li><li>Matplotlib</li><li>fbprophet</li><li>scikit-learn</li></ul><h3>Loading the dataset</h3><p>The data used in this article is provided by the Johns Hopkins University Center. It is updated daily from official sources with newly reported cases for COVID-19 worldwide. The dataset is available at GitHub repository <a href="https://github.com/CSSEGISandData/COVID-19">https://github.com/CSSEGISandData/COVID-19</a>.</p><p>For this article, we shall access the raw CSV file directly from the repository via its URL. First, we load the data using Pandas’ read_csv() method, which loads the CSV data from the URL into a DataFrame. We then display the first few rows using head() to get a brief look at the data structure and composition.</p><p>The data is from the 22nd Jan 2020 up until the date we accessed it on. Each row represents a province (state) with columns representing the country, latitude, longitude, and confirmed cases count per day. Countries are in alphabetical order, and each date has a column storing the total confirmed cases numbers.</p><blockquote>import pandas as pd<br>%matplotlib inline</blockquote><blockquote>#loading the data<br>data_url = ‘<a href="https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv&#39;">https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv&#39;</a><br>df = pd.read_csv(data_url)<br>df.head()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*45W-N65tYhP14raY_fycFA.png" /></figure><h3>Data preparation</h3><p>The next step is to prepare and clean the data. Firstly, we filter the data using the Country/Region column as we are going to be doing our forecasting per country. loc[] gives access to a group of rows and columns by passing a boolean array containing the filtering condition, which in our case is df[‘Country/Region’] == ‘Germany.’ Note that you can change the country name in this line to forecast results for a different country. Next, we remove columns we do not need, such as Province/State, Lat, and Long.</p><blockquote>#filter using country name<br>df = df.loc[df[‘Country/Region’] == ‘Germany’] #change country name here</blockquote><blockquote>#remove unused columns<br>df.drop(‘Province/State’, axis=1, inplace=True)<br>df.drop(‘Lat’, axis=1, inplace=True)<br>df.drop(‘Long’, axis=1, inplace=True)<br>df.head()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ImLjHEecZABecOYUN3DfsQ.png" /></figure><p>Next, a group by the operation is used to combine the results using the Country/Region column, i.e., some countries can have multiple rows for multiple Province/States. The number of cases per day is summed using the sum function. We continue to remove all columns having zero values (no cases). Then, we reset the index to remove the unused country column.</p><blockquote>#group all rows of same country<br>df = df.groupby(‘Country/Region’).sum()</blockquote><blockquote>#remove zero values<br>df = df.loc[:, (df != 0).any(axis=0)]</blockquote><blockquote>#remove the unused country column<br>df.reset_index(inplace=True)<br>df.drop(‘Country/Region’, axis=1, inplace=True)<br>df.head()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0VY0y_UXwvIFfe3W2_N1ow.png" /></figure><p>We are going to need our data frame to have one row for each time series value. We use transpose() function to transpose index and columns to be in the desired format. Furthermore, we convert the data type of our date column to be Timestamp instead of a string.</p><blockquote>#transpose the matrix to create a row for each date entry<br>df = df.transpose()</blockquote><blockquote>#change to datetime<br>dformat = ‘%m/%d/%y’<br>df.index = pd.DatetimeIndex(pd.to_datetime(df.index, format=dformat))<br>df.head()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*j1rl3toxNMKpdcOpsSMJOA.png" /></figure><p>The Prophet model requires the data frame to have a particular format of columns, and we change the names of our columns to be ‘ds’ and ‘y’ to match the required format. And we reset our index using reset_index.</p><blockquote>#prepare for Prophet<br>df.reset_index(inplace=True)<br>df.rename(columns={‘index’:’ds’, 0:’y’},inplace=True)<br>df.head()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*54ikC4RUm5ei-HV5hRse1Q.png" /></figure><h3>Data visualization</h3><p>Now that our data is prepared in the required format, we plot the data using the plot function, and dates are displayed on the x-axis and number of cases on the y-axis. The purpose of this step is to understand the data more deeply. This helps us later in choosing the hyperparameters used for our model. The plot below shows that the number of cases is increasing dramatically over time.</p><blockquote>#plot number of cases accross time<br>ax = df.plot(x=’ds’, y=’y’,figsize=(12,6), title=’Covid-19 daily cases’)<br>ax.autoscale(axis=’both’,tight=True)<br>ax.set(xlabel=’Date’,ylabel=’Cases’);</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VeAPfJhEnLPEpuzdLmEnpg.png" /></figure><h3>Model training</h3><p>Next, we are going to set Prophet up to begin modeling our data. We import the required library. Furthermore, we split the data into training and test sets. Since our model is going to be retrained every time we want to generate a new prediction, we shall use 95% for training and 5% for testing to evaluate model results.</p><blockquote>from fbprophet import Prophet</blockquote><blockquote>#split data into training and test sets<br>train_to_index = round(len(df) * .95)<br>train_data = df.iloc[:train_to_index]<br>test_data = df.iloc[train_to_index:]</blockquote><blockquote>print(‘training data length’,len(train_data),’test data length’,len(test_data))</blockquote><p>We create an instance of the Prophet model. Since our data plot was showing an exponential trend, i.e., the general tendency of the data to increase during a period, we set the input arguments seasonality_mode=’multiplicative’ and growth =’linear.’ And since our data is on the daily frequency, we set daily_seasonality=True. The tuning parameter changepoint_prior_scale is set it to 0.5. Next, we train our model on the training set. Furthermore, parameter tuning can be adjusted based on the dataset and problem domain.</p><p>A data frame is generated with future dates for forecasting using ‘make_future_dataframe’ with the frequency set to ‘D’ as our data is daily. The length of these dates is set to the same length as the test set, as we are going to be comparing the results later on for model evaluation. The data frame is then passed to our model to predict the values for these dates.</p><blockquote>#create model and train on training set<br>model = Prophet(growth =’linear’, <br> seasonality_mode=’multiplicative’, <br> changepoint_prior_scale=0.5, <br> weekly_seasonality=False, <br> daily_seasonality=True)<br>model.fit(train_data)</blockquote><blockquote>#generate a dataframe with future dates, frequency is set to daily<br>future = model.make_future_dataframe(periods=len(test_data),freq=’D’)</blockquote><blockquote>#predict values for future dates<br>forecast = model.predict(future)</blockquote><h3>Plotting model results</h3><p>Now that our model is trained, we need to visualize the results. Prophet has a plotting functionality termed plot which draws the original data (black dots), the model (blue line), and the error of the forecast (shaded blue area).</p><blockquote>#plot model results<br>m.plot(forecast);</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*viMgGlw0J9X2q0Ael81NTQ.png" /></figure><h3>Model evaluation</h3><p>To help us understand the accuracy of our forecasts, we compare the predicted number of cases to the real number of cases for the time series. To do this, we need to build a combined data frame with ‘yhat’ from the forecasts and the original ‘y’ values from the data.</p><blockquote>#generate combined dataframe<br>metric_df = forecast.set_index(‘ds’)[[‘yhat’]].join(df.set_index(‘ds’).y).reset_index()<br>metric_df.tail()</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/1*sXIQRI6YrFPHiNeKvvwLlw.png" /></figure><p>Now that we have our forecasted values against real values, we use r2_score() from sci-kit-learn to generate our R-Squared. The coefficient of determination (denoted by R2) is interpreted as the proportion of the variance in the dependent variable that is predictable from the independent variable.</p><p>The best possible score is 1.0, so the value of 0.99 is very good for our model.</p><blockquote>from sklearn.metrics import r2_score</blockquote><blockquote>r2_score(metric_df.y, metric_df.yhat)</blockquote><p>Furthermore, we use mean_squared_error() from scikit-learn for evaluating our results. Mean squared error (MSE) is the summation of squares of all (predicted — actual values) divided by the number of data points. The MSE is a measure of the quality of an estimator. The smaller the MSE, the closer we are to finding the line of best fit. Our MSE value is 4455269, which is pretty large and means that there is still room for further improvement using hyperparameter tuning on the model or more data to get better results.</p><blockquote>from sklearn.metrics import mean_squared_error</blockquote><blockquote>mean_squared_error(metric_df.y, metric_df.yhat)</blockquote><h3>Forecasting future dates</h3><p>In the previous sections, we evaluated our model on a forecast of the test data dates that we already have. Now we need to build some future dates to forecast into. To forecast this future data, we generate a data frame with 10 future days, then we run it through Prophet’s model ‘predict’ function, and we display the results.</p><blockquote>#generate a dataframe with future dates, frequency is set to daily<br>future = m.make_future_dataframe(periods=10, freq = ‘D’)</blockquote><blockquote>#predict values for future dates<br>forecast = m.predict(future)</blockquote><blockquote>#print only required columns ds, yhat, yhat_lower, yhat_upper<br>forecast[[‘ds’, ‘yhat’, ‘yhat_lower’, ‘yhat_upper’]].tail(10)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*b8Qu_V5RrazkYxZCN1QDkw.png" /></figure><h3>Conclusion</h3><p>We have explained how to do time series forecasting with Prophet using data from Coronavirus (Covid19) Johns Hopkins University Center. We went through loading the data, preparing the data for the Prophet model, plotting the data, training the model, plotting model results, model evaluation, and forecasting future dates. We note that it is impossible to come up with a general approach for all forecasting problems, as each problem has its own distinctions and requires special steps. However, this article was meant to give a basic guideline and understanding about time series forecasting that can be further modified according to the problem domain.</p><h3>References and further reading</h3><p>[1] <a href="https://github.com/CSSEGISandData/COVID-19">https://github.com/CSSEGISandData/COVID-19</a><br>[2] <a href="https://facebook.github.io/prophet/docs/quick_start.html">https://facebook.github.io/prophet/docs/quick_start.html</a><br>[3] <a href="https://nextjournal.com/eric-brown/forecasting-with-prophet">https://nextjournal.com/eric-brown/forecasting-with-prophet</a><br>[4] <a href="https://nextjournal.com/eric-brown/forecasting-with-prophet-part-4">https://nextjournal.com/eric-brown/forecasting-with-prophet-part-4</a><br>[5] <a href="https://towardsdatascience.com/implementing-facebook-prophet-efficiently-c241305405a3">https://towardsdatascience.com/implementing-facebook-prophet-efficiently-c241305405a3</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c638688d8835" width="1" height="1" alt=""><hr><p><a href="https://pub.towardsai.net/time-series-forecasting-for-covid-19-c638688d8835">Time Series Forecasting for COVID-19</a> was originally published in <a href="https://pub.towardsai.net/">Towards AI</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>