Tokyo Corona: Try to make a simple prediction from open data with the exponential function curve_fit

Corona infection is widespread. If no measures are taken (or have no effect), the number of infected people generally increases along the exponential function.

The actual number of infections is announced daily on the Tokyo Corona Site, but no forecast has been made.

The exponential function curve_fit is used to calculate future forecast values and draw a graph here. (Of course, I don't want the result to be as good as possible, and I sincerely hope that the measures will be taken to converge as soon as possible.

Well, it's bad. Intuition that fits the exponential function quite well. The coefficient of determination will be calculated separately. TokyoCorona_20200403.png

Data is from the official website. https://stopcovid19.metro.tokyo.lg.jp/

It seems that it is usually updated at night, but it is a prerequisite for graph drawing the next day. The number on Monday tends to be much smaller than the actual number because there are many places where the inspection agency is closed on the previous Sunday. It may be removed as a periodic factor, but here I will draw it as it is.

import pandas as pd
from pathlib import Path
from datetime import datetime
BASEDIR = Path('.')
FILE_PATH = 'https://stopcovid19.metro.tokyo.lg.jp/data/130001_tokyo_covid19_patients.csv'
df = pd.read_csv(str(FILE_PATH))
#Prediction interval
TO_PERIODS = 7

#Generates various things for graph drawing
target_columns = ['Published_date','patient_Age']
df_select = df[target_columns]
list_now = list(df_select.groupby('Published_date').count().index)
today = datetime.today()
today.strftime('%Y-%m-%d')

list_to = list(pd.date_range(today.strftime('%Y-%m-%d'), periods=TO_PERIODS, freq='D').strftime('%Y-%m-%d'))
list_total = list_now + list_to

Operate as an exponential function fit premise using curve_fit

from scipy.optimize import curve_fit
import numpy as np
import matplotlib.pyplot as plt

#Definition of approximate expression
def nonlinear_fit(x, a, b):
    return a * x ** b

#Generate temporary x-axis data once
array_now_x = np.linspace(0, len(list_now)-1, len(list_now))

#Curve assuming an exponential function_fit run
param, cov = curve_fit(nonlinear_fit, array_now_x, array_now_y,maxfev=1000)

Calculate future date value with parameters obtained by exponential fit processing

list_total_y = []
for num, values in enumerate(list_total):
    list_total_y.append(nonlinear_fit(num, param[0], param[1]))

#Calculate the number of infected people on a daily basis from published data
array_now_y = df_select.groupby('Published_date').count()['patient_Age'].values

Draw a graph.

import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
sns.set_style('whitegrid')

fig, ax = plt.subplots(1, 1, figsize=(15, 10))
ax.bar(list_total, list_total_y, color='blue')
ax.bar(list_now, array_now_y, color='red',alpha=0.75)
plt.xticks(rotation=90)
plt.show()

Recommended Posts

Tokyo Corona: Try to make a simple prediction from open data with the exponential function curve_fit
Try to create a battle record table with matplotlib from the data of "Schedule-kun"
Try to make a "cryptanalysis" cipher with Python
Try to make a dihedral group with Python
A simple workaround for bots to try to post tweets with the same content
WEB scraping with python and try to make a word cloud from reviews
Try using COVID-19's open data from Yokohama / Tokyo / Osaka
I tried to make a function to retrieve data from database column by column using sql with sqlite3 of python [sqlite3, sql, pandas]
Try to make a command standby tool with python
Make a function to describe Japanese fonts with OpenCV
Try to specify the axis with PyTorch's Softmax function
Try scraping the data of COVID-19 in Tokyo with Python
[Linux] Copy data from Linux to Windows with a shell script
How to make a simple Flappy Bird game with pygame
[Introduction to Python] How to get data with the listdir function
Try to extract the features of the sensor data with CNN
Rubyist tried to make a simple API with Python + bottle + MySQL
[Introduction to Python] How to split a character string with the split function
How to make a command to read the configuration file with pyramid
Try to extract a character string from an image with Python3
Rails users try to create a simple blog engine with Django
Try to make a web service-like guy with 3D markup language
Try to solve the shortest path with Python + NetworkX + social data
From "drawing" to "writing" the configuration diagram: Try drawing the AWS configuration diagram with Diagrams
[Python] A simple function to find the center coordinates of a circle
How to make a recursive function
[Python] Make the function a lambda function
Introduction and usage of Python bottle ・ Try to set up a simple web server with login function
How to divide and process a data frame using the groupby function
[Python] Explains how to use the range function with a concrete example
Try to make a capture software with as high accuracy as possible with python (2)
Try to image the elevation data of the Geographical Survey Institute with Python
I came up with a way to make a 3D model from a photo.
Try to solve the traveling salesman problem with a genetic algorithm (Theory)
[Introduction to Python] How to write a character string with the format function
Make a decision tree from 0 with Python and understand it (4. Data structure)
Extract the Azure SQL Server data table with pyodbc and try to make it numpy array / pandas dataframe
Try to make a kernel of Jupyter
A simple IDAPython script to name a function
Let's make a simple language with PLY 1
Try converting to tidy data with pandas
Function to extract the maximum and minimum values ​​in a slice with Go
Try to solve the traveling salesman problem with a genetic algorithm (Python code)
Try to beautify with Talking Head Anime from a Single Image [python preparation]
Let's make an A to B conversion web application with Flask! From scratch ...
Try to solve the traveling salesman problem with a genetic algorithm (execution result)
I tried to make a simple mail sending application with tkinter of Python
Machine learning beginners tried to make a horse racing prediction model with python
[Python] Smasher tried to make the video loading process a function using a generator
SSH login to the target server from Windows with a click of a shortcut
Load a photo and make a handwritten sketch. With zoom function. Tried to make it.
[Verification] Try to align the point cloud with the optimization function of pytorch Part 1
[Python] I tried to get the type name as a string from the type function
I tried to make a simple image recognition API with Fast API and Tensorflow
[Introduction to Python] How to get the index of data with a for statement