Python‎实战-预测未来30天新冠病例

在本文中,我将向您介绍一个关于未来 30 天使用 Python 预测 Covid-19 病例的机器学习项目。这些类型的预测模型有助于提供对流行病的准确预测,这对于获取有关传染病可能传播和后果的信息至关重要。

政府和其他立法机构依靠这些类型的机器学习预测模型和想法来提出新政策并评估应用政策的有效性。

在接下来的 30 天内,我将通过导入必要的 Python 库和数据集来开始使用 Python 进行 Covid-19 病例预测的任务:

下载数据集
链接:https://pan.baidu.com/s/1hyxdmjcT1BdkOvvL7molZA
提取码:c5t8
数据集二
链接: https://pan.baidu.com/s/15cyAoNSrqHdSm29ORPU4pw
提取码: wvvs

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import plotly.express as px

from fbprophet import Prophet
from sklearn.metrics import r2_score

plt.style.use("ggplot")

df0 = pd.read_csv("CONVENIENT_global_confirmed_cases.csv")
df1 = pd.read_csv("CONVENIENT_global_deaths.csv")

数据准备

现在下一步是数据准备,我将简单地通过组合上述数据集来准备新数据,然后我们将以可视化数据的地理图方式,查看我们将要使用的内容:

world = pd.DataFrame({"Country":[],"Cases":[]})
world["Country"] = df0.iloc[:,1:].columns
cases = []
for i in world["Country"]:
    cases.append(pd.to_numeric(df0[i][1:]).sum())
world["Cases"]=cases

country_list=list(world["Country"].values)
idx = 0
for i in country_list:
    sayac = 0
    for j in i:
        if j==".":
            i = i[:sayac]
            country_list[idx]=i
        elif j=="(":
            i = i[:sayac-1]
            country_list[idx]=i
        else:
            sayac += 1
    idx += 1
world["Country"]=country_list
world = world.groupby("Country")["Cases"].sum().reset_index()
world.head()
continent=pd.read_csv("continents2.csv")
continent["name"]=continent["name"].str.upper()

| |

国家
0 阿富汗
1 阿尔巴尼亚
2 阿尔及利亚
3 安道尔
4 安哥拉

数据可视化

现在在这里我将准备三个可视化。一种是地理可视化,用于可视化 Covid-19 的全球传播。然后下一个可视化将是看看世界上 Covid-19 的日常病例。然后最后一个可视化将是看看世界上每天的 Covid-19 死亡案例。

现在让我们通过查看 Covid-19 的全球传播来开始数据可视化:

world["Cases Range"]=pd.cut(world["Cases"],[-150000,50000,200000,800000,1500000,15000000],labels=["U50K","50Kto200K","200Kto800K","800Kto1.5M","1.5M+"])
alpha =[]
for i in world["Country"].str.upper().values:
    if i == "BRUNEI":
        i="BRUNEI DARUSSALAM"
    elif  i=="US":
        i="UNITED STATES" 
    if len(continent[continent["name"]==i]["alpha-3"].values)==0:
        alpha.append(np.nan)
    else:
        alpha.append(continent[continent["name"]==i]["alpha-3"].values[0])
world["Alpha3"]=alpha

fig = px.choropleth(world.dropna(),
                   locations="Alpha3",
                   color="Cases Range",
                    projection="mercator",
                    color_discrete_sequence=["white","khaki","yellow","orange","red"])
fig.update_geos(fitbounds="locations", visible=False)
fig.update_layout(margin={"r":0,"t":0,"l":0,"b":0})
fig.show()

现在让我们来看看世界各地的日常案例:

count = []
for i in range(1,len(df0)):
    count.append(sum(pd.to_numeric(df0.iloc[i,1:].values)))

df = pd.DataFrame()
df["Date"] = df0["Country/Region"][1:]
df["Cases"] = count
df=df.set_index("Date")

count = []
for i in range(1,len(df1)):
    count.append(sum(pd.to_numeric(df1.iloc[i,1:].values)))

df["Deaths"] = count

df.Cases.plot(title="Daily Covid19 Cases in World",marker=".",figsize=(10,5),label="daily cases")
df.Cases.rolling(window=5).mean().plot(figsize=(10,5),label="MA5")
plt.ylabel("Cases")
plt.legend()
plt.show()

现在让我们来看看 Covid-19 的每日死亡案例:

df.Deaths.plot(title="Daily Covid19 Deaths in World",marker=".",figsize=(10,5),label="daily deaths")
df.Deaths.rolling(window=5).mean().plot(figsize=(10,5),label="MA5")
plt.ylabel("Deaths")
plt.legend()
plt.show()

使用 Python 预测未来 30 天的 Covid-19 病例

现在,我将在接下来的 30 天内使用 Facebook 先知模型和 Python 进行 Covid-19 病例预测任务。Facebook 先知模型使用时间序列方法进行预测。

class Fbprophet(object):
    def fit(self,data):
        
        self.data  = data
        self.model = Prophet(weekly_seasonality=True,daily_seasonality=False,yearly_seasonality=False)
        self.model.fit(self.data)
    
    def forecast(self,periods,freq):
        
        self.future = self.model.make_future_dataframe(periods=periods,freq=freq)
        self.df_forecast = self.model.predict(self.future)
        
    def plot(self,xlabel="Years",ylabel="Values"):
        
        self.model.plot(self.df_forecast,xlabel=xlabel,ylabel=ylabel,figsize=(9,4))
        self.model.plot_components(self.df_forecast,figsize=(9,6))
        
    def R2(self):
        return r2_score(self.data.y, self.df_forecast.yhat[:len(df)])
        
df_fb  = pd.DataFrame({"ds":[],"y":[]})
df_fb["ds"] = pd.to_datetime(df.index)
df_fb["y"]  = df.iloc[:,0].values

model = Fbprophet()
model.fit(df_fb)
model.forecast(30,"D")
model.R2()

forecast = model.df_forecast[["ds","yhat_lower","yhat_upper","yhat"]].tail(30).reset_index().set_index("ds").drop("index",axis=1)
forecast["yhat"].plot(marker=".",figsize=(10,5))
plt.fill_between(x=forecast.index, y1=forecast["yhat_lower"], y2=forecast["yhat_upper"],color="gray")
plt.legend(["forecast","Bound"],loc="upper left")
plt.title("Forecasting of Next 30 Days Cases")
plt.show()

我希望您喜欢这篇关于使用 Python 对未来 30 天的 Covid-19 病例进行预测的文章。

来源:程序员石磊

物联沃分享整理
物联沃-IOTWORD物联网 » Python‎实战-预测未来30天新冠病例

发表评论