python-微分方程计算

首先导入数据

python 复制代码
import numpy as np
from scipy.integrate import odeint
from scipy.optimize import minimize
import matplotlib.pyplot as plt

data = np.array([
    [30, 4],
    [47.2, 6.1],
    [70.2, 9.8],
    [77.4, 35.2],
    [36.3, 59.4],
    [20.6, 41.7],
    [18.1, 19],
    [21.4, 13],
    [22, 8.3],
    [25.4, 9.1],
    [27.1, 7.4],
    [40.3, 8],
    [57, 12.3],
    [76.6, 19.5],
    [52.3, 45.7],
    [19.5, 51.1],
    [11.2, 29.7],
    [7.6, 15.8],
    [14.6, 9.7],
    [16.2, 10.1],
    [24.7, 8.6]
])

设置参数和定义函数

python 复制代码
# Set initial parameters to small random values or default values
initial_guess = [0.1, 0.1, 0.1, 0.1, 0.1, 0.1]

# Define ordinary differential equations
def model(y, t, a, b, c, d, e, f):
    x, z = y
    dxdt = a * x - b * x * z - e * x**2
    dydt = -c * z + d * x * z - f * z**2
    return [dxdt, dydt]

#Define error function
def error(params):
    a, b, c, d, e, f = params
    t = np.linspace(0, 1, len(data))  
    y0 = [data[0, 0], data[0, 1]]  
    y_pred = odeint(model, y0, t, args=(a, b, c, d, e, f))
    x_pred, z_pred = y_pred[:, 0], y_pred[:, 1]
    error_x = np.sum((x_pred - data[:, 0])**2)
    error_y = np.sum((z_pred - data[:, 1])**2)
    total_error = error_x + error_y
    return total_error

# Use least squares method to fit parameters
result = minimize(error, initial_guess, method='Nelder-Mead')

# Get the fitting parameter values
a_fit, b_fit, c_fit, d_fit, e_fit, f_fit = result.x

# Simulate the fitted trajectory
t_fit = np.linspace(0, 1, len(data))
y0_fit = [data[0, 0], data[0, 1]]
y_fit = odeint(model, y0_fit, t_fit, args=(a_fit, b_fit, c_fit, d_fit, e_fit, f_fit))
x_fit, z_fit = y_fit[:, 0], y_fit[:, 1]

# Plot the fitting results against the original data points
plt.figure(figsize=(10, 6))
plt.scatter(data[:, 0], data[:, 1], label='Raw data', marker='o', color='blue')
plt.plot(x_fit, z_fit, label='Fitting results', linestyle='-', color='red')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()

进一步优化

python 复制代码
import matplotlib.pyplot as plt


# Different optimization methods
methods = ['Nelder-Mead', 'Powell', 'BFGS', 'L-BFGS-B']

for method in methods:
    result = minimize(error, initial_guess, method=method)
    a_fit, b_fit, c_fit, d_fit, e_fit, f_fit = result.x

  # Simulate the fitted trajectory
    t_fit = np.linspace(0, 1, len(data))
    y0_fit = [data[0, 0], data[0, 1]]
    y_fit = odeint(model, y0_fit, t_fit, args=(a_fit, b_fit, c_fit, d_fit, e_fit, f_fit))
    x_fit, z_fit = y_fit[:, 0], y_fit[:, 1]

# Plot the fitting results against the original data points
    plt.figure(figsize=(10, 6))
    plt.scatter(data[:, 0], data[:, 1], label='Raw data', marker='o', color='blue')
    plt.plot(x_fit, z_fit, label=f'Fitting results ({method})', linestyle='-', color='red')
    plt.xlabel('x')
    plt.ylabel('y')
    plt.legend()
    plt.grid()
    plt.show()

    print(f"Parameter values fitted using {method} method:a={a_fit}, b={b_fit}, c={c_fit}, d={d_fit}, e={e_fit}, f={f_fit}")
复制代码
Parameter values fitted using Nelder-Mead method:a=1.2173283165346425, b=0.42516102725023064, c=19.726779624261006, d=0.7743814851338301, e=-0.19482192444374966, f=0.37455729849779884
复制代码
Parameter values fitted using Powell method:a=32.49329459442917, b=0.6910719576651617, c=58.98701472032894, d=1.3524516626786816, e=0.47787798383104335, f=-0.5344483269192019
复制代码
Parameter values fitted using BFGS method:a=1.2171938888848015, b=0.04968374479958104, c=0.9234835772585344, d=0.947268540340848, e=0.010742224447412019, f=0.7985132960108715
复制代码
Parameter values fitted using L-BFGS-B method:a=1.154759061832585, b=0.32168624538800344, c=0.9455699334793284, d=0.9623931795647013, e=0.2936335531513881, f=0.8566315817923148

进一步优化

python 复制代码
#Set parameter search range (interval)
bounds = [(-5, 25), (-5, 25), (-5, 25), (-5, 25), (-5, 25), (-5, 25)]

# Use interval search to set initial parameter values
result = differential_evolution(error, bounds)

a_fit, b_fit, c_fit, d_fit, e_fit, f_fit = result.x

# Simulate the fitted trajectory
t_fit = np.linspace(0, 1, len(data))
y0_fit = [data[0, 0], data[0, 1]]
y_fit = odeint(model, y0_fit, t_fit, args=(a_fit, b_fit, c_fit, d_fit, e_fit, f_fit))
x_fit, z_fit = y_fit[:, 0], y_fit[:, 1]

# Plot the fitting results against the original data points
plt.figure(figsize=(10, 6))
plt.scatter(data[:, 0], data[:, 1], label='Raw data', marker='o', color='blue')
plt.plot(x_fit, z_fit, label='Fitting results', linestyle='-', color='red')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()

print(f"Fitting parameter values:a={a_fit}, b={b_fit}, c={c_fit}, d={d_fit}, e={e_fit}, f={f_fit}")
复制代码
Fitting parameter values:a=-0.04946907994199101, b=5.5137169943224755, c=0.6909170053541569, d=10.615879287885402, e=-3.1585499451409937, f=18.4110095977882
发现效果竟然变差了
python 复制代码
#Set parameter search range (interval)
bounds = [(-0.1, 10), (-0.1, 10), (-0.1, 10), (-0.1,10), (-0.1, 10), (-0.1, 10)]

# Use interval search to set initial parameter values
result = differential_evolution(error, bounds)

a_fit, b_fit, c_fit, d_fit, e_fit, f_fit = result.x

# Simulate the fitted trajectory
t_fit = np.linspace(0, 1, len(data))
y0_fit = [data[0, 0], data[0, 1]]
y_fit = odeint(model, y0_fit, t_fit, args=(a_fit, b_fit, c_fit, d_fit, e_fit, f_fit))
x_fit, z_fit = y_fit[:, 0], y_fit[:, 1]

# Plot the fitting results against the original data points
plt.figure(figsize=(10, 6))
plt.scatter(data[:, 0], data[:, 1], label='Raw data', marker='o', color='blue')
plt.plot(x_fit, z_fit, label='Fitting results', linestyle='-', color='red')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid()
plt.show()

print(f"Fitting parameter values:a={a_fit}, b={b_fit}, c={c_fit}, d={d_fit}, e={e_fit}, f={f_fit}")

最终优化结果为:

复制代码
Fitting parameter values:a=10.0, b=0.6320729493793303, c=10.0, d=0.4325244090515547, e=-0.07495645186059174, f=0.18793803443302332

完整代码

创作不易,希望大家多点赞关注评论!!!

相关推荐
小蜗牛慢慢爬行3 分钟前
有关异步场景的 10 大 Spring Boot 面试问题
java·开发语言·网络·spring boot·后端·spring·面试
Algorithm157613 分钟前
云原生相关的 Go 语言工程师技术路线(含博客网址导航)
开发语言·云原生·golang
岑梓铭13 分钟前
(CentOs系统虚拟机)Standalone模式下安装部署“基于Python编写”的Spark框架
linux·python·spark·centos
shinelord明22 分钟前
【再谈设计模式】享元模式~对象共享的优化妙手
开发语言·数据结构·算法·设计模式·软件工程
游客52027 分钟前
opencv中的各种滤波器简介
图像处理·人工智能·python·opencv·计算机视觉
Monly2129 分钟前
Java(若依):修改Tomcat的版本
java·开发语言·tomcat
boligongzhu30 分钟前
DALSA工业相机SDK二次开发(图像采集及保存)C#版
开发语言·c#·dalsa
Eric.Lee202130 分钟前
moviepy将图片序列制作成视频并加载字幕 - python 实现
开发语言·python·音视频·moviepy·字幕视频合成·图像制作为视频
7yewh32 分钟前
嵌入式Linux QT+OpenCV基于人脸识别的考勤系统 项目
linux·开发语言·arm开发·驱动开发·qt·opencv·嵌入式linux
Dontla34 分钟前
vscode怎么设置anaconda python解释器(anaconda解释器、vscode解释器)
ide·vscode·python