Predict X value from Y value with a fitted model [duplicate]

孤街醉人 提交于 2019-12-13 15:26:26

问题


I need to predict the corresponding x value of a new y value using a fitted model.

The usual case of predicting the y value from a new x value is straightforward by using the predict function, but I cannot figure out how to do the reverse.

For cases with multiple x solutions, I wish to obtain all solutions within the range of x values, i.e. 1-10. And the new y will always be within the range of y values used for fitting the model.

See below for an example code, where I need to find new x value (new_x).

x = seq(1:10)
y = c(60,30,40,45,35,20,10,15,25,10)

fit = lm(y ~ poly(x, 3, raw=T))

plot(x, y)
lines(sort(x), predict(fit)[order(x)], col='red') 

new_y = 30
new_x = predict(fit, data.frame(y=new_y)) #This line does not work as intended.

Edit 1: Inversed fitting

Fitting the inversed relationship will not give the same model, since we get a different model/fitted line.

rev_fit = lm(x ~ poly(y, 3, raw=T))

plot(x, y)
lines(sort(x), predict(fit)[order(x)], col='red') 
lines(predict(rev_fit)[order(y)], sort(y), col='blue', lty=2) 


回答1:


As hinted at in this answer you should be able to use approx() for your task. E.g. like this:

xval <- approx(x = fit$fitted.values, y = x, xout = 30)$y

points(xval, 30, col = "blue", lwd = 5)

Gives you:



来源:https://stackoverflow.com/questions/43322568/predict-x-value-from-y-value-with-a-fitted-model

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!