[英]Fitting differential equations: how to fit a set of data to a differential equation in R
帶有數據集:
conc <- data.frame(time = c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration = c(170, 122, 74, 45, 28, 17, 10))
我想將這些數據擬合到下面的微分方程中:
dC/dt= -kC
其中C是濃度,時間t是數據集中的時間。 這也將得出k的結果。 有人可以給我一個提示,以了解如何在R中執行此操作嗎? 謝謝。
首先使用變量分離來求解微分方程。 這樣得出log(C)=-k * t + C0。
繪制數據:
plot(log(concentration) ~ time,data=conc)
擬合線性模型:
fit <- lm(log(concentration) ~ time,data=conc)
summary(fit)
# Coefficients:
# Estimate Std. Error t value Pr(>|t|)
# (Intercept) 5.299355 0.009787 541.4 4.08e-13 ***
# time -0.992208 0.005426 -182.9 9.28e-11 ***
# ---
# Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1
#
# Residual standard error: 0.01388 on 5 degrees of freedom
# Multiple R-squared: 0.9999, Adjusted R-squared: 0.9998
# F-statistic: 3.344e+04 on 1 and 5 DF, p-value: 9.281e-11
繪制預測值:
lines(predict(fit)~conc$time)
提取k:
k <- -coef(fit)[2]
#0.9922081
這可能是一個解決方案:
require('deSolve')
conc <- data.frame(time <- c(0.16, 0.5, 1.0, 1.5, 2.0, 2.5, 3), concentration <- c(170, 122, 74, 45, 28, 17, 10))
##"Model" with differential equation
model <- function(t, C, k){
list(-k * C)
}
##Cost function with sum of squared residuals:
cost <- function(k){
c.start <- 170
out <- lsoda(c(C=c.start), conc$time, model, k)
c <- sum( (conc$concentration - out[,"C"])^2)
c
}
##Initial value for k
k <- 3
## Use some optimization procedure
opt <- optim(k, cost, method="Brent", lower=0, upper=10)
k.fitted <- opt$par
也許這有點天真,因為使用lsoda似乎對於只用一個微分方程進行計算來說有點過頭了……但是它肯定會優化您的k。 您可能要檢查積分的C起始值,我在此處將其設置為170,您是否沒有t = 0的值?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.