增长预测模型之逻辑斯蒂模型

调用了macOS的系统部分来实现语音播报,这只是整个大看板中的初始部分,却是很能帮助理解指数增长和指数现象的规律以及sigmoid函数实际意义

from datetime import datetime,timedelta
from sklearn.metrics import mean_squared_error
from scipy.optimize import curve_fit
from scipy.optimize import fsolve
import matplotlib.pyplot as plt
from json import loads

USA = to_table('美国')#<爬虫摘取数据就可以了>

def logistic_model(x,a,b,c):
    '''
    a为感染速度
    b为感染发生最多的一天
    c是在感染结束时记录的感染者总数
    '''
    return c/(1+np.exp(-(x-b)/a))

len_ = USA.confirmedCount.values.shape[0]
x = list(range(len_))
y = list(USA.confirmedCount)
fit = curve_fit(logistic_model,x,y,p0=[2,100,20000])
a,b,c= tuple(fit[0])

def translate(word):
    #>>> 翻译模块^!^不发布 <<<
    response = requests.post(url, data=key)
    # 判断服务器是否相应成功
    if response.status_code == 200:
        # 然后相应的结果
        return loads(response.text)['translateResult'][0][0]['tgt']
    else:
        # 相应失败就返回空
        return None

def plot_logistic_model(other_name):
    __import__('os').system('say 正在构建'+other_name+'的逻辑斯蒂模型,请稍后')
    logistic_model = lambda x,a,b,c : c/(1+np.exp(-(x-b)/a))
    '''
    a为感染速度
    b为感染发生最多的一天
    c是在感染结束时记录的感染者总数
    '''
    example = to_table(other_name)

    len_ = example.confirmedCount.values.shape[0]
    x = list(range(len_))
    y = list(example.confirmedCount)
    fit = curve_fit(logistic_model,x,y,p0=[2,100,20000])
    a,b,c= tuple(fit[0])
    sol = int(fsolve(lambda x : logistic_model(x,a,b,c) - int(c),b))

    date = list(example.dateId)
    plt.figure(figsize=(16,6))
    logistic_number = logistic_model(x,a,b,c)
    plt.plot(logistic_number,c='r')
    plt.plot(np.gradient(y)*10,c='g')
    plt.scatter(x,y)
    plt.xticks(x,date,rotation='vertical')
    plt.title(translate(other_name))
 
    errors = [np.sqrt(fit[1][i][i]) for i in [0,1,2]]
    results = {"感染速度":a,"感染最多的一天":b,"预测最终感染人数":c-errors[-1],'预计剩余结束天数':sol-x[-1]}
    __import__('os').system('say'+" 感染速度为"+str(a)+"感染最多的一天是第"+str(int(b))+"天,预测最终感染人数为"+str(int(c-errors[-1]))+'人'+',预计剩余结束天数为'+str(sol-x[-1])+'天')
    return results,example

plot_logistic_model("美国")

版权声明:本文为weixin_43069769原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。