I am trying to fit electrophysiological data with a Boltzmann functon. When using real data, the predicted values returned by the nls function nicely match the input data, however, the retuned fitting coefficients are totally off.
I first tested my function using simulated data. Doing so predicted values and fitting coefficients are acurate.
# generate sample data
V<-seq(-60,40,5)
Vhalf=-20
k=10
G<- (1/(1 + exp((Vhalf - V) / k)) + rnorm(length(V), sd = 0.05))
# normalization
normalize <- function(x, range = c(0, 1)) {
if (!is.numeric(x)) {
stop("Input x must be a numeric vector")
}
min_x <- min(x)
max_x <- max(x)
normalized_x <- (x - min_x) / (max_x - min_x)
min_range <- range[1]
max_range <- range[2]
normalized_x * (max_range - min_range) + min_range
}
G <- normalize(G)
# fit function
boltzmann_eqn <- function(V, Vhalf, k) {
(1 / (1 + exp((Vhalf - V) / k)))
}
# starting parameters and fit
start_Vhlaf=-10
start_k=10
fit <- nls(
G ~ boltzmann_eqn(V, Vhalf, k),
start = list(Vhalf = start_Vhlaf, k = start_k),
algorithm = "port",
control = list(
maxiter = 1000,
tol = abs(min(V)) * 1e-05,
minFactor = abs(min(V)) * 1e-05
)
)
coef(fit)
predicted.value<-predict(fit)
# plot actual and fitted values
library(ggplot2)
data<-data.frame(V,G,predicted.value)
ggplot(data,aes(x=V,y=G))+
geom_point()+
geom_line(aes(y=predicted.value))
however, if I now use real data, the fitting coefficients are totally off:
# real data for G
V<-seq(-60,40,5)
G <-
c(
2.886126e-10,
2.299096e-10,
3.479653e-10,
3.854844e-10,
5.786606e-10,
6.859901e-10,
9.479952e-10,
1.107524e-09,
1.569197e-09,
1.685586e-09,
2.163985e-09,
2.231026e-09,
3.036547e-09,
3.402246e-09,
3.396888e-09,
4.070637e-09,
4.297097e-09,
4.218705e-09,
4.651377e-09,
5.019147e-09,
5.336356e-09
)
# normalization
normalize <- function(x, range = c(0, 1)) {
if (!is.numeric(x)) {
stop("Input x must be a numeric vector")
}
min_x <- min(x)
max_x <- max(x)
normalized_x <- (x - min_x) / (max_x - min_x)
min_range <- range[1]
max_range <- range[2]
normalized_x * (max_range - min_range) + min_range
}
G <- normalize(G)
# fit function
boltzmann_eqn <- function(V, Vhalf, k) {
(1 / (1 + exp((Vhalf - V) / k)))
}
# starting parameters and fit
start_Vhlaf=-10
start_k=10
fit <- nls(
G ~ boltzmann_eqn(V, Vhalf, k),
start = list(Vhalf = start_Vhlaf, k = start_k),
algorithm = "port",
control = list(
maxiter = 1000,
tol = abs(min(V)) * 1e-05,
minFactor = abs(min(V)) * 1e-05
)
)
coef(fit)
predicted.value<-predict(fit)
# plot actual and fitted values
library(ggplot2)
data<-data.frame(V,G,predicted.value)
ggplot(data,aes(x=V,y=G))+
geom_point()+
geom_line(aes(y=predicted.value))
I am not seeing any obvious difference between my simulated and the real data, possibly the real data doesnt fully saturate. However, I think that cant really explain why coefficients are off whil prediciton seems to work well. I was under the impression that both should be linked.
any suggestions are highly appreciated! Thanks for the help!