From 6eb711beb4a789d262fcd791b6a0bb1f19064fc1 Mon Sep 17 00:00:00 2001
From: Hui Lan <lanhui@zjnu.edu.cn>
Date: Thu, 11 Apr 2019 09:26:58 +0800
Subject: Initial commit Lecture Notes on Artifical Intelligence

---
 polynomial_regression2.R | 39 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 39 insertions(+)
 create mode 100644 polynomial_regression2.R

(limited to 'polynomial_regression2.R')

diff --git a/polynomial_regression2.R b/polynomial_regression2.R
new file mode 100644
index 0000000..321206e
--- /dev/null
+++ b/polynomial_regression2.R
@@ -0,0 +1,39 @@
+# polynomial_regression2.R
+# Purpose: to demonstrate polynomial regression using poly()
+#
+#
+# Created by Hui Lan on 26 April 2018
+
+
+### Functions ###
+
+f <- function(x)
+{
+    # the true function
+    # y <- 0.5 + 1.5*x + 0.5*x^2  # also try quadratic function
+    y <- 0.5 + 1.5*x  # y is implicitly returned. don't need a return statement
+}
+
+
+
+### main ###
+sd.err <- 2
+N <- 12
+x1 <- rnorm(N, mean=5, sd=3)  # my data for the the predictor variable X1
+e = rnorm(N, mean=0, sd=sd.err) # error term
+y  <- f(x1) + e   # my data for the response variable Y
+
+
+model <- lm(y~x1) # call linear model fit. use ?lm to get details of this function
+model
+summary(model)
+
+D <- data.frame(Y=y, X1=x1)
+model.polynomial <- lm(Y ~ poly(X1,11), data=D)
+par(mfrow=c(1,1))
+plot(x1, y, pch='+')
+abline(model, lwd=1, col='green')
+curve(f, from=min(x1), to=max(x1), col='red', add=T)
+num.interval <- 100
+new.x <- seq(min(x1),max(x1),length=num.interval)
+lines(new.x,predict(model.polynomial, data.frame(X1=new.x)), col="blue")
-- 
cgit v1.2.1