Linear/Nonlinear Regression fitting example using R language (1) _ Data analysis

Source: Internet
Author: User
Tags rand

A linear/Nonlinear regression fitting example using R language (1)

1. Generate a set of data

vector<float>xxvec;

vector<float>yyvec;

Ofstreamfout ("Data2.txt");

for (int i =1;i<200;i++)

{

float x =i*0.8;

Float randdnum= rand ()%10 * 10;

Floatrandomflag = (rand ()%10)%2==0? (1):(-1);

Float y = 3 *x*x + 2*x + 5 + randomflag*randdnum;

fout<<x<< "" <<y<<endl;

Xxvec.push_back (x);

Yyvec.push_back (y);

}

Fout.close ();

Save the generated data as a TXT file, named "Data1"

2. Linear Fitting

#-------------------------------------------------------------#载入数据

> Fire <-read.table (' d:/data.txt ', header = TRUE)

#-------------------------------------------------------------#回归分析

> Plot (fire$y ~ fire$x)


> Fire.reg <-lm (fire$y ~ fire$x,data = fire) #回归拟合

> Data1.reg

Call:

LM (formula = Data1$y ~ data1$x, data = data1)

Coefficients:

(Intercept) data1$x

6.202 3.003

>summary (Data1.reg) #回归分析表

Call:

LM (formula = Data1$y ~ data1$x, data = data1)

Residuals:

Min 1Q Median 3Q Max

-93.345-42.929-1.948 46.717 88.793

Coefficients:

Estimate Std. Error TValue Pr (>|t|)

(Intercept) 6.202084 3.352055 1.85 0.0646.

data1$x 3.002826 0.007259 413.66 <2e-16 * * *

The red number is the linear regression coefficient, because the data generated by adding a random number, so the line to fit it is:

y=3.002826 x+6.202084

---

Signif. codes:0 ' * * * 0.001 ' * * ' 0.01 ' * ' 0.05 '. ' 0.1 "' 1

Residual standard error:52.93 on 997 degrees of freedom

Multiple r-squared:0.9942, adjusted r-squared:0.9942

F-statistic:1.711e+05 on 1 and 997 DF, P-value: < 2.2e-16

>anova (Data1.reg) #方差分析表

Analysis of Variance Table

Response:data1$y

Df Sum Sq Mean sq F value Pr (>f)

data1$x 1479462873 479462873 171112 < 2.2e-16***

Residuals 997 2793641 2802

Signif. codes:0 ' * * * 0.001 ' * * ' 0.01 ' * ' 0.05 '. ' 0.1 "' 1

>abline (Data1.reg, col = 2, lty = 2) #拟合直线


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.