2014-09-25 159 views
1

我是R(第一次使用它)的新手。我正在按照本教程http://www.walkingrandomly.com/?p=5254試圖繪製曲線並發現最適合我的數據的函數。到目前爲止,我已經tryed:R中的非線性最小二乘曲線擬合

> xdata = c(1 ,5, 10, 20, 100) 
> ydata = c(23.83333333, 210.3666667, 545.3666667, 1756.866667, 38595.7) 
> plot(xdata,ydata) 

所以我得到這樣的:

enter image description here

然後我嘗試:

> p1 = 1 
> p2 = 0.2 
> fit = nls(ydata ~ xdata^2, start=list(p1=p1,p2=p2)) 

而且我得到這個錯誤:

Error in nlsModel(formula, mf, start, wts) : 
    singular gradient matrix at initial parameter estimates 

我在做什麼NG? 謝謝

回答

7

nls功能不會自動包含所有模型中的參數等係數。你必須明確地將它們包含在公式中。我不完全知道你在哪裏想p1p2從你的描述

p1 <- 1 
p2 <- 0.2 
fit <- nls(ydata ~ p1+p2*xdata^2, start=list(p1=p1,p2=p2)) 
fit 

# Nonlinear regression model 
# model: ydata ~ p1 + p2 * xdata^2 
# data: parent.frame() 
#  p1  p2 
# 127.216 3.847 
# residual sum-of-squares: 21037 
# 
# Number of iterations to convergence: 1 
# Achieved convergence tolerance: 5.774e-08 

被包括在模型中,但至少在這個形式的這仍然是一個線性模型。你可以得到相同的契合

fit2 <- lm(ydata ~ I(xdata^2)) 
fit2 

# Call: 
# lm(formula = ydata ~ I(xdata^2)) 
# 
# Coefficients: 
# (Intercept) I(xdata^2) 
#  127.216  3.847 
+0

如何繪製曲線? – fredcrs 2014-09-25 19:47:15

+2

繪圖是一個完全獨立的問題。但是如果你有一個合適的模型('fit'或'fit2'),你可以使用'xs <-seq(min(xdata),max(xdata),length.out = 100);情節(XDATA,YDATA);行(xs,predict(fit,data.frame(xdata = xs)))'。 – MrFlick 2014-09-25 19:51:20

+1

擬合值已經在擬合對象中:'fit(fit)'或'fit $ m $ fitted'。如果您提供的是新數據參數,則只需要使用預測。 – 2014-09-25 20:01:22

4

您的公式中沒有參數。你需要將它們包括但您認爲合適的:

nls(ydata ~ p1 * xdata^2 + p2, start=list(p1=p1,p2=p2)) 
6

爲了完整起見,你可以包括閱兵式O解決方案ggplot2框架內,以獲得平滑的解決方案的情節和檢查結果的圖形:

library(ggplot2) 
ggplot(dat,aes(x=xdata,y=ydata)) + 
    geom_point() + 
    geom_smooth(method="nls", formula=y ~ p1+p2*x^2, se=FALSE, 
       start=list(p1=p1,p2=p2)) 

enter image description here

+1

@fredcrs你要去那裏的朋友圈 – 2014-09-25 20:35:40

+0

你可以在R studio中使用R markdown來編織HTML或Word,它會將所有代碼及其輸出與圖一起打印出來 – technOslerphile 2014-09-26 01:27:53