Reputation: 29
I have 4 points of the train set, I use "nls" to fit the train set, then predict the response of test set which contains 2 points. However, the "predict" command always returns values of the train set.
The code is attached below:
##Following is train set
HD = c(714,715,716.6,717.6)
p_l = c(0.5,0.1,0.05826374, 0.005982334)
##Fitting with nls
raw_data = data.frame(HD,p_l)
exp_fit = nls(p_l~exp(a+b*HD),data = raw_data,trace = T,start = list(a = 0,b
= 0))
##Following is test set
HD_test = c(718.2,719.17)
p_l_test = predict(exp_fit,newdata = HD_test)
Upvotes: 0
Views: 664
Reputation: 21264
You need to pass either a data frame or a named list as newdata
.
Use the same name as your original predictor (HD
). Otherwise, newdata
is treated as missing, and fitted values from the original training data are returned.
From the nls docs:
newdata
A named list or data frame in which to look for variables with which to predict. If newdata is missing the fitted values at the original data points are returned.
HD_test = data.frame(HD = c(718.2,719.17)) # wrap in data frame, name "HD"
p_l_test = predict(exp_fit, newdata = HD_test)
p_l_test
[1] 0.0009320202 0.0002184518
Upvotes: 1