<?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 Andrea Amparore on Medium]]></title>
        <description><![CDATA[Stories by Andrea Amparore on Medium]]></description>
        <link>https://medium.com/@andrea.amparore?source=rss-d7f3886e4d68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*tVAmVxaB0Q7oMwFQ-_lDdQ.jpeg</url>
            <title>Stories by Andrea Amparore on Medium</title>
            <link>https://medium.com/@andrea.amparore?source=rss-d7f3886e4d68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:15:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrea.amparore/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 real COVID-19 death toll]]></title>
            <link>https://medium.com/data-science/estimating-real-covid-19-death-toll-ef01a5eb9814?source=rss-d7f3886e4d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef01a5eb9814</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Andrea Amparore]]></dc:creator>
            <pubDate>Wed, 06 May 2020 12:43:31 GMT</pubDate>
            <atom:updated>2020-05-10T12:32:29.155Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why the virus may have killed more people than the official data says</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C5hLf_fFpXflfJOsp25BKA.jpeg" /></figure><p>There is no doubt about it: official figures are just wrong. Whether positive cases, official deaths, people recovered, most of the data available about COVID-19 is misleading. It’s commonly acknowledged that it’s just a matter of how far off the numbers really are.</p><p>In particular, official numbers of COVID-19 deaths generally come from hospitals. People who die at home may not be counted since they are never tested for the coronavirus. As a consequence, <strong>death toll</strong> <strong>may have been</strong> <strong>underestimated</strong>. However, this discrepancy is normally hard to quantify, since government data is often the only source of information available.</p><p>I focus my research on the situation in Italy, given the large availability of primary and secondary data on COVID-19 epidemic for this country. Tracking the evolution of any epidemic and quantifying its progression is an extremely challenging operation, therefore it is likely that other countries have faced the same problems leading to huge underestimations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h8DygQ_6O2yF_DjOgWBp2A.png" /></figure><p>Just two days ago, on May 4th, the Italian National Statistical Service (ISTAT) <a href="https://www.istat.it/it/files//2020/03/Dataset-decessi-comunali-giornalieri-e-tracciato-record.zip?fbclid=IwAR2F8BWx0IhNkegwRmKK3g-IuvMTP9pvM6vuOy5lso-8vAWMWjZmUIMGdoQ">has published a large dataset</a> reporting <a href="https://translate.google.it/translate?sl=it&amp;tl=en&amp;u=https%3A%2F%2Fwww.istat.it%2Fit%2Farchivio%2F240401">every single death occurred in the country</a>, from any cause and not necessarily related to COVID-19. Deaths are reported by day, municipality, gender and age group, containing data for 6,866 municipalities (out of 7,904 - 87% coverage). The dataset focuses on the period from January 1st to March 31st, and it is associated with the historical data for the last 5 years.</p><p><strong>The main goal of this paper is to compare the average mortality of a normal period with the number of deaths registered during the COVID-19 epidemic</strong>. The excess of deaths with respect to the years without the epidemic can be explained with the COVID-19 direct and indirect effects.</p><p>We will leverage the full potential of <em>Python</em> data science libraries to analyze the data, identify anomalies on death rates, compare them with official COVID-19 death tolls, and finally map the results.</p><h4>Main findings</h4><ol><li>The number of people affected by COVID-19 in Italy (and most likely everywhere in the world) is <strong>much higher than the official government figures.</strong></li><li>Data shows an anomalous increase on overall deaths in March 2020 compared to the last 5 years: <strong>+ 49.4% </strong>on a national level.</li><li>During the same period, some Regions (Italy’s first administrative level) experienced a dramatic increase in deaths: <strong>+ 186 % in <em>Lombardia</em></strong>, <strong>+ 70 % in <em>Emilia-Romagna</em></strong> and <strong>+ 65 % in <em>Trentino Alto Adige</em></strong>, to name a few.</li><li>At local level the epidemic has been extremely severe for some specific Provinces (second administrative level): for example, in March deaths have increase by <strong>567.6 % in <em>Bergamo</em></strong>, <strong>391.8 % in <em>Cremona</em></strong> and <strong>370.6 % in <em>Lodi</em> </strong>provinces.</li><li><strong>Official figures explain only 50.2 % of anomalies in deaths occurred in March 2020</strong>. The remaining numbers are most probably due to ‘hidden’ COVID-19 cases, or to indirect effects of the epidemic (saturated hospitals, lower health service, difficulty or reluctance to timely enter in hospitals…)</li><li>Data provided by ISTAT accounts only for 87% of the municipalities. Even though it is a statistically representative sample, we can assume that the reality has been even more dramatic. In fact, the percentage provided in point n. 5 is a <strong>conservative estimate</strong>, and it <strong>represents the lower bound on total deaths</strong>.</li><li>Some provinces of the country have been severely hit by the virus, while others have been relatively untouched for the whole duration of the crisis. <strong>This is probably due to timely and efficient lockdown measures</strong> enforced by regional and national authorities.</li></ol><h4>Importing and cleaning the data</h4><p>This work has been developed with <em>Python-3.7.1</em> on <em>macOS</em>, and it primarily makes use of open source data science libraries such as Pandas, Geopandas, andMatplotlib.</p><p><a href="https://github.com/Andrampa/covid_analysis/blob/master/Calculating_real_COVID_death_toll.ipynb"><strong>You can find the Python code for the whole article here</strong></a><strong>.</strong></p><p>Let’s start importing the necessary libraries.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4265fc81d3712daf5e4fef589db2645c/href">https://medium.com/media/4265fc81d3712daf5e4fef589db2645c/href</a></iframe><p>Now, we import the large sheet published by ISTAT, reporting deaths recorded by Municipality, age, gender and date (approximately 1 million records). We translate field names to English and remove the Municipalities when the data for March 2020 is missing (about 13% of the rows). Then, we keep only the data for February and March.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0da8fc9b9f1e13a23a2101134ddc50ee/href">https://medium.com/media/0da8fc9b9f1e13a23a2101134ddc50ee/href</a></iframe><p>The next step consists in calculating the number of deaths registered in every Municipality in a year without the epidemic. This variable, that we name <em>baseline_deaths,</em> is created by calculating the average of the deaths registered between 2015 and 2019. The difference between <em>baseline_deaths </em>and the deaths for March 2020 is called <em>excess_deaths</em>, and it consists in the anomalies that can be attributed to the COVID-19 epidemic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d787e7faf2057d659dafb44cb499e2f/href">https://medium.com/media/0d787e7faf2057d659dafb44cb499e2f/href</a></iframe><p><strong>National level analysis</strong></p><p>We can now visualize the evolution of these three key variables in time: <em>baseline_deaths </em>(the average number of deaths in the last 5 years)<em>, deaths_2020 </em>and<em> excess_deaths. </em>The following code produces a chart showing the trends on a national level<em>.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/75ac2b273e5e80c36a17afeed46d6602/href">https://medium.com/media/75ac2b273e5e80c36a17afeed46d6602/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVHPMr5QQFqRgKTCZmI4Qw.png" /></figure><p>The chart clearly shows us that <strong>in March 2020 something unusual and dramatic happened</strong>, and during some days between 21st and 28th March the number of daily deaths almost doubled in Italy. Now it would be interesting to visualize the percentage increase of deaths in 2020 compared to the average.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a6075e3044e9ef2b40dee95c41a17a7/href">https://medium.com/media/5a6075e3044e9ef2b40dee95c41a17a7/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1lLqYh-yLV4KaYQJ4Gn8jA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*piGy82Abx7Sava-6jdvbKQ.png" /></figure><p>The peak is even more visible in this chart. In fact, the winter of 2019–20 was exceptionally mild and there were fewer deaths due to the flu epidemic than the average of the previous years. Then, around March 4th, COVID-19 epidemic started killing the first people in the country. Considering the whole month of March, <strong>in Italy mortality has increased by 49.36 %</strong>.</p><p><strong>Reality VS official data</strong></p><p>We now have all we need to compare the anomalous amount of death registered in March 2020 with the official COVID-19 death toll <a href="https://github.com/pcm-dpc/COVID-19">published by the Italian Civil Protection</a>.</p><p>The code below downloads the official death toll of the Civil Protection <a href="https://github.com/pcm-dpc/COVID-19">GitHub account</a> and compares it with the excess deaths registered in 2020.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8e888525ec0758fecb74f8ed816a4ac/href">https://medium.com/media/c8e888525ec0758fecb74f8ed816a4ac/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9tC4qOtsgE3bW49O9_0HPw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*ZA8HjFq4LbRo5kRpFC5WDQ.png" /></figure><p>The peak registered in March is not fully explained by the official COVID-19 death toll provided by the Italian Civil Protection. In March 2020 <em>ISTAT</em> reported 24,668 additional deaths compared to an average non-epidemic year. For the same period, the Civil Protection reported only 12,399 official COVID-19 deaths, which is only the 50.26 % of the excess of deaths. <strong>The remaining numbers are most probably due to ‘hidden’ COVID-19 cases </strong>(people who died at home without being tested for the virus), <strong>or to indirect effects of the epidemic </strong>(saturated hospitals, lower health service, difficulty or reluctance to timely enter in hospitals…). Moreover, we know that ISTAT reports the figures only for 87% of the municipalities. Therefore, <strong>the reality is likely even worse than our conservative estimate suggests</strong>.</p><p><strong>Regional level analysis</strong></p><p>We know that the virus didn’t hit the whole country with the same intensity. The epidemic has brought northern Italy to its knees, while southern Regions have been left relatively untouched by the crisis. The dataset published by ISTAT provides information associated with very high spatial resolution, and it is possible to inspect the deaths anomalies also on a Regional and Provincial level.</p><p>First, let’s focus on the 6 most affected Regions, comparing their <em>baseline_deaths</em> with deaths registered in 2020.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c08a11c6285f1684326e22f9fc438a8b/href">https://medium.com/media/c08a11c6285f1684326e22f9fc438a8b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pM1sP2-QiWwQrrJU2IeslQ.png" /></figure><p>Again, we notice a regular trend of deaths in 2020, until the beginning of March. But the Region of <em>Lombardia</em> is considerably more affected than the others. Let’s now visualize the trend of <em>excess_deaths</em> and the percentage increase compared to the five years average.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/098ca3d70170758f4eb55a988765fcd8/href">https://medium.com/media/098ca3d70170758f4eb55a988765fcd8/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bngxx3u2CtT0bN5iRCye6g.png" /></figure><p>The chart above shows that around 23rd March 2020 <em>Piemonte</em>, <em>Liguria</em>, <em>Marche</em> and <em>Emilia-Romagna</em> have doubled the average daily deaths of the last 5 years. But again, the most severe situation occurred in <em>Lombardia</em>, that between 18th and 28th March has registered 3 times the number of the average daily deaths.</p><p><strong>Mapping regional excess of deaths</strong></p><p>It is now possible to create a map of the deaths increase registered in the entire month of March 2020, by Region. Boundaries of Italian Regions can be downloaded as a <em>shapefile</em> from the Italian National Institute of Statistics’ <a href="https://www4.istat.it/it/archivio/209722">website</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e517146a436bc258d03505ac52406f79/href">https://medium.com/media/e517146a436bc258d03505ac52406f79/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7f3m6z5rjPLvvwjq1XCsng.png" /></figure><p>The map clearly shows the different situations in the opposite sides of the Country: while northern Italy is suffering from an extreme increase of deaths, it is interesting to notice that in some southern Regions mortality has declined compared to the average of the last five years. This is probably due to the effects of the severe lockdown measures (less road and work accidents, reduced seasonal flu epidemic…) and the exceptionally mild winter, but this hypothesis should be further validated with dedicated analysis.</p><p><strong>Provincial level analysis</strong></p><p>ISTAT dataset allows us to go even deeper with our analysis, and compare <em>baseline_deaths</em> with <em>death_2020</em> on a provincial basis. In the following charts we will focus on the six most affected Provinces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfa0ae73b952f6f7ba6b1029cdd0ae25/href">https://medium.com/media/bfa0ae73b952f6f7ba6b1029cdd0ae25/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kgXPzvIC2BrmfkT2zgKj5g.png" /></figure><p>Among the 6 most affected Provinces, 4 are in <em>Lombardia</em> and 2 in <em>Emilia-Romagna </em>Regions. In particular, the chart shows an extreme peak for <em>Bergamo</em> Province: in March it has reported even more deaths than <em>Milano</em>, which is about 3 times bigger in terms of total population. Let’s now inspect the provincial <em>excess_deaths</em> and the percentage of death increase, by Province.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78fc051e9e560e7690ebe06e6cc9d935/href">https://medium.com/media/78fc051e9e560e7690ebe06e6cc9d935/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4xxJ2VhWugJNo8fqoLlUQ.png" /></figure><p>The magnitude of the disaster happened in <em>Bergamo</em> Province is now even clearer. In some days of the month (between 16th and 26th) this Province experienced <strong>10 times the average deaths of a non-epidemic year</strong>. Also other Provinces (<em>Piacenza</em>, <em>Brescia</em>, <em>Cremona</em>) have been heavily affected, with some peaks reaching 600% of the normal death rate.</p><p><strong>Mapping provincial excess of deaths</strong></p><p>The last step of this analysis consist in the creation of the provincial map of the death increase for the month of March 2020. Boundaries of Italian Provinces are available as <em>shapefile</em> on the ISTAT <a href="https://www.istat.it/it/archivio/222527">website</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d272f9a2952233cb17d750ca5b4ca3a/href">https://medium.com/media/5d272f9a2952233cb17d750ca5b4ca3a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0wAAbl0ZZNM-RzwC8RUfMA.png" /></figure><p>The outputs of the analysis for the most affected Provinces are summarized in the table below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7535d74ba8900306a57966ee3bc10196/href">https://medium.com/media/7535d74ba8900306a57966ee3bc10196/href</a></iframe><p>The information contained by the table above can be seen as the most accurate analysis on the epidemic effects in Italy in term of overall mortality.</p><h4>Conclusions</h4><ul><li>In this article I provided evidence that the death toll figures being reported daily by Italian officials is <strong>much lower than the reality</strong>.</li><li>On a national scale, the real death toll may have been <strong>underestimated by up to 12.000,</strong> or about 2 times of the official total.</li><li>The above estimates account for deaths caused by COVID-19 both directly and indirectly: some of the increase is probably linked to <strong>people who died of other illnesses not appropriately treated by the health system</strong> , or because they couldn’t find a hospital bed due to the crisis.</li><li><strong>In some southern Regions and Provinces, mortality has declined considerably compared to the average</strong>. This is is partly explained by the decline in road fatalities and work accidents due to Italy’s lockdown, and by an exceptionally mild winter season.</li></ul><p><strong>Acknowledgements</strong></p><p>Some analysis performed in this article have been inspired by the work published by Prof. <a href="https://medium.com/u/200e3fbf123d">Federico Ricci-Tersenghi</a>, who <a href="https://medium.com/@riccife/an-estimate-of-direct-and-indirect-deaths-related-to-the-covid-19-epidemic-in-italy-97a13c078df9">managed to quantify</a> the ratio between direct and indirect effects of COVID-19 on the excess deaths. I also thank Greg O’ Callaghan, Rohini Swaminathan and Virginia Eterno for reviewing the draft of this article and for suggesting edits and improvements.</p><p>All the code I developed for the analyses and maps displayed in this article are available <a href="https://github.com/Andrampa/covid_analysis/blob/master/Calculating_real_COVID_death_toll.ipynb">on my GitHub repository</a>.</p><h4>Thank you for reading ! If you enjoyed this article, don’t hesitate to comment or share it.</h4><p><em>I am learning everyday, if you notice any mistakes please feel free to correct me and write your suggestions in the comment section.</em></p><p><strong>Note from the author: I am not an epidemiologist, the analysis shown in this article are only based on pure maths applied to publicly available data.</strong></p><p><strong><em>Note from the editors:</em></strong><em> </em><a href="http://towardsdatascience.com/"><em>Towards Data Science</em></a><em> is a Medium publication primarily based on the study of data science and machine learning. We are not health professionals or epidemiologists, and the opinions of this article should not be interpreted as professional advice. To learn more about the coronavirus pandemic, you can click </em><a href="https://www.who.int/emergencies/diseases/novel-coronavirus-2019/situation-reports"><em>here</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef01a5eb9814" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/estimating-real-covid-19-death-toll-ef01a5eb9814">Estimating real COVID-19 death toll</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[Modeling regional COVID-19 epidemic with Python]]></title>
            <link>https://medium.com/data-science/modeling-and-mapping-regional-covid-19-trends-with-python-89f4415300f7?source=rss-d7f3886e4d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/89f4415300f7</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <dc:creator><![CDATA[Andrea Amparore]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 00:31:59 GMT</pubDate>
            <atom:updated>2020-04-27T12:03:21.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKLoEI1OZWBdlzk_wVbitw.png" /></figure><blockquote>When will the epidemic end in my region?</blockquote><p>The map below is the result of series of data analyses and modeling of the Italian COVID-19 epidemic. For each region, it shows the expected date of the epidemic end, expressed in number of days remaining before having zero deaths and zero patients in critic conditions. For understanding how I predicted those dates and how I mapped them, we need to go few steps backwards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9c6i00Jqm66oi9pYLqgD4A.png" /></figure><p>In <a href="https://towardsdatascience.com/modeling-covid-19-epidemic-with-python-bed21b8f6baf">this article</a> published on April 21st, I showed how to use Python with data science libraries for analyzing and modeling COVID-19 data. For my analyses I used the dataset published daily by the Italian Civil Protection and available on the official <a href="https://github.com/pcm-dpc/COVID-19">GitHub repository</a>.</p><p>After having identified several potential sources of bias in the sampling methods, I demonstrated that the sum of daily deaths with the number of patients in intensive care units (a variable that I named deaths_ICU ) is decreasing following a linear trend, after the peak registered on April 1st.</p><p>Therefore, using that derived variable, it has been possible to create a <a href="https://en.wikipedia.org/wiki/Regression_analysis">Linear Regression Model</a> in order to estimate the end of the severe epidemic in Italy, given by the date when the sum of daily deaths with the number of patients in intensive care is expected to be zero.</p><p>As shown in the chart below, the trend is continuing regularly five days after the article has been published, and the results of the model are still valid today (April 26th).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rgbaOGqTZW43yGts_U8zlQ.png" /><figcaption>Evolution of the derived variable deaths_ICU over time</figcaption></figure><h4>Looking more closely</h4><p>According the model, the end of the epidemic should occur <strong>between 19th and 22nd May 2020</strong>, considering the country as a whole. However, we know that northern regions have been by far the worst affected since the beginning of the outbreak; moreover, some regions may recover faster than others. The date predicted by the model could be a sort of average of the 20 regions’ dates.</p><blockquote>For this reason, <strong>today we will push the analysis a little bit further</strong> by developing a separate model for each Italian region.</blockquote><p>Then, we will join the temporal information (<em>when it will end?</em>) with the spatial component (<em>where it will end first?</em>), and create a composite regional map showing the time-table of the epidemic end.</p><h4>Importing and cleaning the data</h4><p>First, let’s import the necessary libraries and the COVID-19 regional breakdown provided by the Italian Civil Protection</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d79c5483eed4cf897862fa5dd3f79dd3/href">https://medium.com/media/d79c5483eed4cf897862fa5dd3f79dd3/href</a></iframe><p>This dataset contains already about 1200 rows. Unfortunately, the data is not exactly provided in the format we need. In fact, because of some institutional reasons only 19 regions out of 20 are providing daily updates to the Civil Protection. <em>Trentino Alto Adige</em> (region n. 4 in the dataset) is represented by its 2 provinces separately (<em>Provincia Autonoma di Bolzano</em> and <em>Provincia Autonoma di Trento</em>). As a consequence, the dataset reports data for 19 regions and 2 provinces. Therefore, the first thing to do, is to exclude all the rows referring to region 4 from the dataset. Then, we create a second <em>DataFrame</em> that, on the contrary, contains only the rows for the two provinces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e282989f06420166af5c7e6a11b904d/href">https://medium.com/media/0e282989f06420166af5c7e6a11b904d/href</a></iframe><p>Now we sum the data of the two provinces, in order to calculate the deaths and the ICU patients for the whole region of <em>Trentino Alto Adige</em>. Finally, we attach the two tables together in order to have a <em>DataFrame</em> containing clean data for each of the 20 regions, which is finally the desired format for the analysis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4da53e46e7285f5ef6b5338767c1224d/href">https://medium.com/media/4da53e46e7285f5ef6b5338767c1224d/href</a></iframe><h4>Splitting the dataset in 20 parts</h4><p>Given that we want to build and train 20 different models, one for each Italian region, we need also to split the main dataset in 20 parts. While we do this, we we also calculate the derived variable deaths_ICU that will be used for training the models. All 20 datasets are then appended to a list namedregional_df_list.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5e0e5348d9eb3310544a5e67f747bfc/href">https://medium.com/media/c5e0e5348d9eb3310544a5e67f747bfc/href</a></iframe><h4>Defining algebraic functions</h4><p>The next step consists in defining some functions that will be used in the main script later on. Those functions will perform the algebraic operations needed for estimating the intersection between the regression line and the X axis.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a586248fc8360e2c9785ea89ee3df5a/href">https://medium.com/media/9a586248fc8360e2c9785ea89ee3df5a/href</a></iframe><h4>Build and train 20 models</h4><p>We now have all we need for iterating through each region’s dataset, creating a model, training it, and estimating the epidemic from north to south Italy. While we iterate, we store the models’ outputs in a new data frame named model_outputs_df. It will contain not only the predicted dates, but also the coefficients of determination R² of each region’s model. R² will give some information about the performance of the model. An R² of 1 indicates that the regression predictions perfectly fit the data, therefore the closer the value gets to 1, the more we can trust our model.</p><p>If you are curious about details of the following script, you can read more in <a href="https://towardsdatascience.com/modeling-covid-19-epidemic-with-python-bed21b8f6baf">my previous article</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ce9eab8db2c51d4d0b4afcc483c4bec/href">https://medium.com/media/5ce9eab8db2c51d4d0b4afcc483c4bec/href</a></iframe><h4>Understanding models’ outputs</h4><p>We are almost done! This is how model_outputs_df looks like for the first 5 regions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CR6v5fB4oYGHqEIAID-XMA.png" /></figure><p>The column model_score is particularly important, it is the R² coefficient that tells us how well the models performed, therefore how trustworthy and reliable are the predictions for every region.</p><p><strong>Mapping models’ performance</strong></p><p>Now the geospatial geek who lives inside of me can finally get some satisfaction: the best way to visualize the different reliabilities of the regional models is to display them on a map, and we will do that using geopandas and mapclassify libraries. Boundaries of Italian Regions can be downloaded as a <em>shapefile</em> from the Italian National Institute of Statistics’ <a href="https://www4.istat.it/it/archivio/209722">website</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0d92594565593a01effa96df5b6281b/href">https://medium.com/media/c0d92594565593a01effa96df5b6281b/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KqLBhLu7h87y4zAVGBRP1A.png" /></figure><p>The above map shows how the models’ reliability varies considerably according the region. The best performing model among the ones we built and trained is the one associated to <em>Lombardia</em> region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BbxVohxBCsftwwc9fIm89A.png" /></figure><p>With its R² higher than 0.99, the model perfectly follows the data series, and we can expect the estimation to be fairly reliable also in the future. On the opposite side of spectrum we find <em>Lazio</em> region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ogs8W_Ch5bHOGcxMijs4TQ.png" /></figure><p>In this case, the coefficients of determination R² is only about 0.35. As a consequence, the predictions are less reliable and associated with a particularly high margin of error. This is mainly due to the fact that the epidemic trend in this region is not following a linear trend, therefore the predictions provided by the model shouldn’t be considered valid.</p><h4>Mapping models’ predictions</h4><p>The key information provided by our models is the prediction of the epidemic end for each Italian region, expressed with the number of days needed before the variable deaths_ICU becomes equal to zero. Before even considering the reliability of our models, let’s draw a map of their predictions across the country.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa3e33ece07460e3d9dfa7fa2639d40d/href">https://medium.com/media/aa3e33ece07460e3d9dfa7fa2639d40d/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ks67l3S-Q1EPiJBrmj3rHw.png" /></figure><h4>Combining predictions with models reliability</h4><p>The very last step consists in combining the predictions of the regional models with their reliability scores. In other words, <strong>we want to exclude from our final map all the regions where our models didn’t perform well</strong>. For doing this, we set an arbitrary threshold for the minimum acceptable model_score, and we display on the map only the regions for which our predictions are more reliable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/454a0613c1fcb6077ea2eac0ba99ea54/href">https://medium.com/media/454a0613c1fcb6077ea2eac0ba99ea54/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9c6i00Jqm66oi9pYLqgD4A.png" /></figure><h4>Conclusions</h4><p>The predictions of the regional <em>Linear Regression</em> models we built and trained in this exercise are summarized in the table below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58637bf98c7e8b0731b6a12eb41284df/href">https://medium.com/media/58637bf98c7e8b0731b6a12eb41284df/href</a></iframe><p>As explained before, the higher the model score and the more reliable is the prediction. For this reason, outputs of low scoring models have been excluded from this recap table and from the final map.</p><p>This article aimed at predicting the end of COVID-19 epidemic in Italy, taking in consideration the regional differences and trends. Like for any modeling exercise, we have to consider that any new external factor can change the effective evolution of the epidemic. Models can not take into account unexpected changes in the system, such as the gradual loosening of lockdown restrictions (expected in Italy after May 4th), or the effects of warmer temperature over the virus spread. <strong>Such changes in the system could have an impact and change the linear trends we have observed</strong>.</p><p>From a more general perspective, the results of our analyses highlight the great heterogeneity of the COVID outbreak in Italy, with some regions recovering much faster than others. Moreover, visualizing those predictions on a map gives us a clearer overview and helped us to get a better understanding of the epidemic situation.</p><p>All the code I developed for the analyses, models and maps displayed in this article are available on my <a href="https://github.com/Andrampa/covid_analysis/blob/master/Modeling_COVID19_epidemic_regional_breakdown.ipynb">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=89f4415300f7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/modeling-and-mapping-regional-covid-19-trends-with-python-89f4415300f7">Modeling regional COVID-19 epidemic with Python</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[Modeling COVID-19 epidemic with Python]]></title>
            <link>https://medium.com/data-science/modeling-covid-19-epidemic-with-python-bed21b8f6baf?source=rss-d7f3886e4d68------2</link>
            <guid isPermaLink="false">https://medium.com/p/bed21b8f6baf</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[covid19]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[towards-data-science]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Andrea Amparore]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 06:55:30 GMT</pubDate>
            <atom:updated>2020-05-02T12:50:32.500Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*J0qYEcZGNUFNpK6wJPZ6OQ.png" /></figure><p>Because of the country lockdown currently enforced in Italy, also this weekend I had to stay at home, like billions of other people in this world. So, I decided to make use of this time for playing with data on COVID-19 pandemics in Italy, which is released daily by the Italian Civil Protection Department.</p><p>In this article I will show how to inspect the data, represent it on chart and model future trends with Python, using some open source data science libraries such as Pandas, Matplotlib and Scikit-learn.</p><p>I really appreciate the effort made by the Civil Protection to publish daily data at different scales (national, regional and provincial base), and especially to release it in machine-readable format through their official <a href="https://github.com/pcm-dpc/COVID-19">GitHub repository</a>. As usual, Open Data approach facilitates scientific collaboration, enriches collaborative research and can improve collective analytical capacity to ultimately inform decisions.</p><p>This work has been developed with Python-3.7.1 on macOS, and it has been inspired by similar papers that I found online. The full version of the code is available on my <a href="https://github.com/Andrampa/covid_analysis/blob/master/Modeling_COVID19_epidemic_with_Python.ipynb">GitHub repository</a>.</p><p>It would be interesting to apply the proposed methodology also to datasets related to other COVID affected countries, such as <a href="https://github.com/datadista/datasets/tree/master/COVID%2019">Spain</a> or <a href="https://github.com/opencovid19-fr/data">France</a>.</p><h4>Installing necessary libraries</h4><p>The standard Python distribution does not come with the modules used in this tutorial. To use these third party modules, we must install them.</p><pre>pip install pandas matplotlib scikit-learn<br>or<br>conda install -c anaconda pandas matplotlib scikit-learn</pre><h4>Importing data and extracting fields</h4><p>First, we import all the necessary libraries, then we import the latest version of the Italian COVID dataset from the Civil Protection GitHub account and we store it in a <em>Pandas</em> <em>Data Frame</em>. Then, we explore the structure of the table, in order to have a clearer view on the variables, and eventually identify the one we should consider for the epidemic modeling.</p><pre>import pandas as pd<br>from datetime import datetime, timedelta<br>import matplotlib.pyplot as plt<br>from matplotlib.dates import DateFormatter<br>import matplotlib.dates as mdates</pre><pre>data = pd.read_csv(“<a href="https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv">https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-andamento-nazionale/dpc-covid19-ita-andamento-nazionale.csv</a>&quot;)</pre><pre>print (data.columns)</pre><p>We obtained a list of all the fields contained in the data frame.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vavD1GrnzaqllgmqyfM0MQ.png" /></figure><p>In particular, deceduti and tamponi report respectively the cumulative numbers of deaths and medical swab (tests) recorded since the beginning of the crisis. In order to calculate the daily increase of those two variables, we run a simple pandas function and we save the outputs into two new fields: diff_deceduti and diff_tamponi. Then, we create a list containing all the dates and we convert them from string to a more suitable datetime format.</p><pre>data[‘diff_deceduti’] = data[‘deceduti’].diff()<br>data[‘diff_tamponi’] = data[‘tamponi’].diff()<br>dates = data[‘data’]<br>date_format = [pd.to_datetime(d) for d in dates]</pre><h4>Visualizing the data</h4><p>We are now ready to create our first scatter plot, and display the variable that intuitively, at first glance, seems to be the most important for estimating the epidemic progression: the number of daily new positive cases (nuovi_positivi).</p><pre>variable = ‘nuovi_positivi’<br>fig, ax = plt.subplots(figsize=(12, 5))<br>ax.grid()<br>ax.scatter(date_format,data[variable])<br>ax.set(xlabel=”Date”,ylabel=variable,title=variable)<br>date_form = DateFormatter(“%d-%m”)<br>ax.xaxis.set_major_formatter(date_form)<br>ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))<br>fig.savefig(variable + ‘.png’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4R5HdDdHaYBT5BKsOQoLCQ.png" /></figure><p>There is a recurrent pattern in the plot above, which is given by the anomalies occurring just after every weekend: it seems that the epidemic slows down on Mondays and Tuesdays. This is caused by the fact that during weekends (and public holidays in general such as Easter Monday) a considerably smaller number of swabs is processed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*iacri6dXky6kmVLRvFoakQ.jpeg" /></figure><h4>Correcting biases</h4><p>A possible methodology for correcting this systematic bias consists in the calculation of the moving average, which is normally used to analyze time-series by calculating averages of different subsets of the complete dataset, in our case 7 days.</p><p>The first moving average is calculated by averaging the first subset of 7 days, and then the subset is changed by <strong>moving forward</strong> to the next fixed subset, and so on. In general, the moving average smoothens the data, and it reduces anomalies like our weekend bias.</p><pre>rolling_average_days = 7</pre><pre>data[‘nuovi_positivi_moving’] = data[‘nuovi_positivi’].rolling(window=rolling_average_days).mean()<br></pre><pre>variable = ‘nuovi_positivi_moving’<br>fig, ax = plt.subplots(figsize=(12, 5))<br>ax.grid()<br>ax.scatter(date_format,data[variable])<br>ax.set(xlabel=”Date”,ylabel=variable,title=variable)<br>date_form = DateFormatter(“%d-%m”)<br>ax.xaxis.set_major_formatter(date_form)<br>ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))<br>fig.savefig(variable + ‘.png’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zpVQyQ_5tfI9EpDHpinfPQ.png" /></figure><p>The chart above represents the trend of new cases averaged over a 7-days period, masking out weekend anomalies. Nevertheless, the effect of the daily number of swabs tested every day is not fully compensated yet. Clearly, the number of positive cases is strictly correlated with the quantity of tests performed. Let’s take a look to the trend of daily tests performed in Italy (tamponi):</p><pre>data[&#39;diff_tamponi_moving&#39;] = data[&#39;tamponi&#39;].diff().rolling(window=rolling_average_days).mean()</pre><pre>variable = &#39;diff_tamponi_moving&#39;<br>fig, ax = plt.subplots(figsize=(12, 5))<br>ax.grid()<br>ax.scatter(date_format,data[variable])<br>ax.set(xlabel=&quot;Date&quot;,ylabel=variable,title=variable)<br>date_form = DateFormatter(&quot;%d-%m&quot;)<br>ax.xaxis.set_major_formatter(date_form)<br>ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))<br>fig.savefig(variable + &#39;.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-8VZAIqt3-p4voOa8K-DuQ.png" /></figure><p>Our doubts have been confirmed: at the end our time series, the number of daily swabs is about 20 times higher than the beginning, therefore the variable nuovi_positivi is suffering from this important bias. In order to find a more representing trend, we now calculate the percentage of new positive over the total daily tests, and we inspect the variation over time.</p><pre>data[‘perc_positive’] = ((data[‘nuovi_positivi_moving’])/(data[‘diff_tamponi_moving’])*100)</pre><pre>variable = ‘perc_positive’<br>fig, ax = plt.subplots(figsize=(12, 5))<br>ax.grid()<br>ax.scatter(date_format,data[variable])<br>ax.set(xlabel=”Date”,ylabel=variable,title=variable)<br>date_form = DateFormatter(“%d-%m”)<br>ax.xaxis.set_major_formatter(date_form)<br>ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))<br>fig.savefig(variable + ‘.png’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NO809wUDCQMwMXXsx7ov2w.png" /></figure><p>The derived variable perc_positive provides a more reliable representation of the epidemic progression, since it fixes the two systematic biases identified before: weekend fluctuations and overall number of tests. Unfortunately, there are still several unconsidered factors that undermines the validity of this analysis. Just to mention some of these: testing procedures have changed considerably over time, ranging from testing only severe symptomatic patients to mass testing of entire populations in specific districts, and the swabs methodology varies region by region. Moreover, data on new positive cases can refer to tests conducted in previous days, from 1 up to 7 days before. And just to make things even more complicated, some patients can also be tested multiple times, and there is no way to detect this from our dataset. For those and other reasons, perc_positive is not yet the variable we need for modeling the epidemic trend, and ultimately for forecasting its evolution.</p><p>There are other important fields that we should further inspect: in particular, let’s take a closer look to terapia_intensiva and diff_deceduti ( intensive care and daily deaths, respectively).</p><pre>variable = ‘terapia_intensiva’<br>fig, ax = plt.subplots(figsize=(12, 5))<br>ax.grid()<br>ax.scatter(date_format,data[variable])<br>ax.set(xlabel=”Date”,ylabel=variable,title=variable)<br>date_form = DateFormatter(“%d-%m”)<br>ax.xaxis.set_major_formatter(date_form)<br>ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))<br>fig.savefig(variable + ‘.png’)<br>plt.show()</pre><pre>variable = ‘diff_deceduti’<br>fig, ax = plt.subplots(figsize=(12, 5))<br>ax.grid()<br>ax.scatter(date_format,data[variable])<br>ax.set(xlabel=”Date”,ylabel=variable,title=variable)<br>date_form = DateFormatter(“%d-%m”)<br>ax.xaxis.set_major_formatter(date_form)<br>ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))<br>fig.savefig(variable + ‘.png’)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PC-xtELxJxCaMRCtt70RqA.png" /></figure><p>As shown in the chart above, the number of patients currently in intensive care seems to follow a more regular trend. In fact, it refers to an easily measurable information which doesn’t suffer from sampling methodology or weekly fluctuations. Surely it is not perfect, since it can also be prone to underestimation, mostly during the acute peak of the crisis where the health system was stressed and hospitals saturated. But after that critical phase it should reflect pretty well the number of patients that are affected most severely by the virus. However, probably we are still missing something: are we sure that a decreasing number of intensive cares always corresponds to an improvement of the situation? In fact, it could be that this number is lowering as a consequence of an increasing number of daily deaths.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WhjqW3u5Qu7OIW-FBec9BA.png" /></figure><p>The above charts shows that daily deaths have been increasing until march 28th, and then it started decreasing at a slower pace.</p><h4>Creating derived variable for the model</h4><p>The main assumption of this paper is that the combined value of intensive care and daily deaths can be a reliable variable for estimating the current epidemic progression, and for modeling future trends. Let’s create a new field gravi_deceduti, calculate the sum of patients in severe distress with daily deaths, and plot the resulting values.</p><pre>data[‘gravi_deceduti’] = data[‘diff_deceduti’] + data[‘terapia_intensiva’]</pre><pre>variable = &#39;gravi_deceduti&#39;<br>fig, ax = plt.subplots(figsize=(12, 5))<br>ax.grid()<br>ax.scatter(date_format,data[variable])<br>ax.set(xlabel=&quot;Date&quot;,ylabel=variable,title=variable)<br>date_form = DateFormatter(&quot;%d-%m&quot;)<br>ax.xaxis.set_major_formatter(date_form)<br>ax.xaxis.set_major_locator(mdates.DayLocator(interval = 3))<br>ax.axvline(datetime(2020, 4, 1), c=&quot;green&quot;, zorder=0)<br>fig.savefig(variable + &#39;.png&#39;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ddl3mAjB0Hv-SCw4MeCdbg.png" /></figure><p>We explained how both terapia_intensiva and diff_deceduti do not suffer from major systemic bias, and how the latter compensates the former in case of increase of daily deaths. The combination of the two variables can now be used for modeling the trend of the epidemic in Italy, since this derived number suffers from fewer systematic bias. We added a green line on the chart in order to highlight the day the peak, which is the point where the descending trend has started.</p><h4>Modeling the epidemic trend</h4><p>We now can build a Linear Regression model and train it with the data of gravi_decedutistarting from that date, April 1st.</p><p>Linear Regression is one of the most popular classical machine learning algorithms for supervised learning. This algorithm is relatively easy to implement and works well when the relationship to between covariates and response variable is known to be linear (in our case: date VS gravi_deceduti). A clear disadvantage is that Linear Regression over simplifies many real world problems.</p><p>The code below is an adaptation of some parts of the work done by <a href="https://medium.com/@angelica.loduca/predicting-the-end-of-the-coronavirus-epidemics-in-italy-8da9811f7740">Angelica Lo Duca</a> on March 31st, in her attempt of modeling the epidemic using the number of positive cases.</p><p>First we import linear_model from sklearn module. Then we exclude from X and y all data for the period before the epidemic peak registered on April 1st, and we fit the LinearRegression model with X and y. Finally, we evaluate the model by running the function score() , which returns the coefficient of determination R² of the prediction (the proportion of the variance in the dependent variable that is predictable from the independent variable). R² will give some information about the <a href="https://en.wikipedia.org/wiki/Goodness_of_fit">goodness of fit</a> of a model. In regression, the R² coefficient of determination is a statistical measure of how well the regression predictions approximate the real data points. An R² of 1 indicates that the regression predictions perfectly fit the data, therefore the closer the value gets to 1, the more we can trust our model.</p><pre>import numpy as np<br>from sklearn import linear_model<br># prepare the lists for the model<br>X = date_format<br>y = data[&#39;gravi_deceduti&#39;].tolist()[1:]<br># date format is not suitable for modeling, let&#39;s transform the date into incrementals number starting from April 1st<br>starting_date = 37  # April 1st is the 37th day of the series<br>day_numbers = []<br>for i in range(1, len(X)):<br>    day_numbers.append([i])<br>X = day_numbers<br># # let&#39;s train our model only with data after the peak<br>X = X[starting_date:]<br>y = y[starting_date:]<br># Instantiate Linear Regression<br>linear_regr = linear_model.LinearRegression()<br># Train the model using the training sets<br>linear_regr.fit(X, y)<br>print (&quot;Linear Regression Model Score: %s&quot; % (linear_regr.score(X, y)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*rlmaVec79JVRvAOSxSWs_w.png" /></figure><h4>Predict future trend</h4><p>Now that we have fitted the model and evaluated positively its R² score, we are ready for predicting the evolution of gravi_deceduti in the future. For doing this, we call the function predict() and we keep track of the the maximum error done by the model with the function max_error(). Using that value, we will create two lines that will depict the tolerance buffer, with both minimum and maximum errors of the model’s predictions.</p><pre># Predict future trend<br>from sklearn.metrics import max_error<br>import math<br>y_pred = linear_regr.predict(X)<br>error = max_error(y, y_pred)</pre><p>The model is now ready for predicting gravi_deceduti for next days. We define a variable X_test, which contains both past and future days. We also create the variable future_days containing the number of days for which we want to estimate the epidemic trend. Then we apply our model to X_test.</p><pre>X_test = []<br>future_days = 55<br>for i in range(starting_date, starting_date + future_days):<br>    X_test.append([i])<br>y_pred_linear = linear_regr.predict(X_test)</pre><p>The variable y_pred_linear contains the predicted gravi_deceduti for next 55 days. In order to consider the errors made by the model, we define y_pred_max and y_pred_min containing the y_pred + error and y_pred - error, respectively.</p><pre>y_pred_max = []<br>y_pred_min = []<br>for i in range(0, len(y_pred_linear)):<br>    y_pred_max.append(y_pred_linear[i] + error)<br>    y_pred_min.append(y_pred_linear[i] - error)</pre><h4>Plot the forecast</h4><p>We have three output variables ready to be displayed on a chart: y_pred, y_pred_max and y_pred_min, containing the predictions, the maximum error and minimum error, respectively. In order to make the plot more appealing, we should convert numbers (represented by the X_test variable) to dates.</p><pre># convert date of the epidemic peak into datetime format<br>from datetime import datetime, timedelta<br>date_zero = datetime.strptime(data[&#39;data&#39;][starting_date], &#39;%Y-%m-%dT%H:%M:%S&#39;)<br># creating x_ticks for making the plot more appealing<br>date_prev = []<br>x_ticks = []<br>step = 5<br>data_curr = date_zero<br>x_current = starting_date<br>n = int(future_days / step)<br>for i in range(0, n):<br>    date_prev.append(str(data_curr.day) + &quot;/&quot; + str(data_curr.month))<br>    x_ticks.append(x_current)<br>    data_curr = data_curr + timedelta(days=step)<br>    x_current = x_current + step</pre><p>Now we can plot the known data together with the forecast and the error lines</p><pre># plot known data<br>plt.grid()<br>plt.scatter(X, y)<br># plot linear regression prediction<br>plt.plot(X_test, y_pred_linear, color=&#39;green&#39;, linewidth=2)<br># plot maximum error<br>plt.plot(X_test, y_pred_max, color=&#39;red&#39;, linewidth=1, linestyle=&#39;dashed&#39;)<br>#plot minimum error<br>plt.plot(X_test, y_pred_min, color=&#39;red&#39;, linewidth=1, linestyle=&#39;dashed&#39;)<br>plt.xlabel(&#39;Days&#39;)<br>plt.xlim(starting_date, starting_date + future_days)<br>plt.xticks(x_ticks, date_prev)<br>plt.ylabel(&#39;gravi_deceduti&#39;)<br>plt.yscale(&quot;log&quot;)<br>plt.savefig(&quot;prediction.png&quot;)<br>plt.show()</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SU-q82IGTJn97qiwnxzFZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dn2Y3Yd9r8pjZ-D3PGMoOg.png" /></figure><h4>Regional trends</h4><p>The above analysis is treating Italian COVID-19 epidemic on a national basis, but it is known that regions of <em>Lombardia</em>, <em>Piemonte</em>, <em>Veneto</em> and <em>Emilia-Romagna</em> have been affected more severely then the others. In order to quantify this, we can inspect the regional COVID-19 dataset provided by the Civil Protection, and calculate the proportion of the deaths registered in those regions (we call them <em>Zone 1</em>)</p><pre>data = pd.read_csv(&quot;https://raw.githubusercontent.com/pcm-dpc/COVID-19/master/dati-regioni/dpc-covid19-ita-regioni.csv&quot;)<br>zone1_df = data[data.denominazione_regione.isin([&#39;Piemonte&#39;,&#39;Emilia-Romagna&#39;,&#39;Veneto&#39;,&#39;Lombardia&#39;])]<br>zone1_df[&#39;deceduti&#39;].sum()<br>print(&quot;Zone 1 accounts for %s percent of the total deaths&quot; % (round(zone1_df[&#39;deceduti&#39;].sum() / data[&#39;deceduti&#39;].sum() * 100,2)))</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*7eDu1DfzFwRP00V2KzWYkA.png" /></figure><p>If just those 4 regions (out of 20) account for more than 80% of the total deaths, having a single model that predicts the trend for the whole country is a major oversimplification. In fact, the situation varies considerably from region to region, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJkLnwZWvP7mBjvCP29QSg.png" /></figure><p>For each region a different model should be applied, in order to better understand the epidemic trends in the different areas of the country. Given that the Civil Protection provides <a href="https://github.com/pcm-dpc/COVID-19/tree/master/dati-province">data also on a provincial basis</a>, it would be possible to model the situation even better than this.</p><h4>Conclusions</h4><p>Our model tells us that the COVID-19 epidemic will end in Italy <strong>between 19th and 22nd May 2020</strong>, if the current trend is maintained over time.</p><p>Regional differences apart, we have to consider that any new external factor can change the effective trend of the epidemic. The current model can not take into account unexpected changes in the system, such as the gradual loosening of lockdown restrictions, or the effects of warmer temperature over the virus spread.</p><p><a href="https://towardsdatascience.com/modeling-and-mapping-regional-covid-19-trends-with-python-89f4415300f7">In my next article</a> I will create different models for every region separately, and I will upload the code on <a href="https://github.com/Andrampa/covid_analysis/blob/master/Modeling_COVID19_epidemic_with_Python.ipynb">my GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bed21b8f6baf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/modeling-covid-19-epidemic-with-python-bed21b8f6baf">Modeling COVID-19 epidemic with Python</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>