2744557306 发表于 2024-3-16 18:54

使用 Logistic 模型拟合人口数据

这段代码执行了如下操作:

1.导入模块:

   import numpy as np
   import pandas as pd
   from scipy.optimize import curve_fit


2.导入了 NumPy、Pandas 和 SciPy 中的 curve_fit 函数。


3.准备数据:

   df = pd.DataFrame({
       'year': ,
       'population': ,
   })
   x0 = float(df['population'])
   t0 = float(df['year'])


4.创建了一个 Pandas DataFrame 来存储年份和人口数据。
5.提取了初始年份和初始人口数。


6.定义 Logistic 模型函数:

   def x(t, r, xm):
       return xm / (1 + (xm/x0-1)*np.exp(-r*(t-t0)))


7.定义了 Logistic 函数,该函数接受时间 t、增长率 r 和最大人口数 xm 作为参数,并返回人口数。


8.拟合参数:

   popt, pcov = curve_fit(x, df['year'], df['population'], bounds=((0, 1), (.1, np.inf)))
   r, xm = popt, popt


9.使用 curve_fit 函数拟合了 Logistic 函数的参数 r 和 xm,以最小化实际人口数据与 Logistic 模型的拟合误差。


10.预测 1900 年人口:

   print('population in 1900 =', x(1900, r, xm))


11.使用拟合的参数预测了 1900 年的人口数。


12.绘制预测曲线:

   year = np.linspace(1790, 2000, 21)
   population =
   plt.scatter(df['year'], df['population'], label='actual')
   plt.plot(year, population, label='predict', color='coral')
   plt.legend()


13.创建了一个时间范围 year,并使用拟合的参数计算了对应的人口数。
14.使用 Matplotlib 绘制了实际人口数据的散点图和 Logistic 模型的预测曲线,并添加了图例。

这段代码的核心是使用 Logistic 模型拟合了给定的人口数据,并利用拟合的参数进行了未来人口的预测。


页: [1]
查看完整版本: 使用 Logistic 模型拟合人口数据