#     such as 'range()' and 'sort()':
apply(m, 2, range)
m
#     There are complications with "apply(m, 1, range)":
#     the result is 2xnrow(m), not nrow(m)x2, as one would expect.
#     This requires transposition, 't()', to get the expected matrix:
t(apply(m, 1, range))
# * ARRAYS: the generalization of matrices to more than 2 indexes
#
a <- array(1:24, c(2,3,4))
a
#   - repeat-loop: needs a "break" for termination.
repeat{ print("Trying..."); rnum <- runif(1);
if(rnum > 0.9) { print(c("Found one:",rnum)); break } }
#   - while-loop:
while(runif(1) < 0.99) { print("Not yet...") }; print("Finally...")
#  Repeat the same random number
runif(1)
runif(1)
set.seed(101)
runif(1)
set.seed(101)
runif(1)
#     Examples:
sample(1:10, 5)                  # Samples w/o replacement (default).
sample(1:10, 5, replace=T)       # Samples with replacement
# Some artificial data:
x <- runif(100)
y <- x^2
plot(x,y)
# Why are points so random?  Because the x values are random.
# Redo the same with evenly spaced x values:
x <- seq(0,1,len=100);    y <- x^2;    plot(x,y)
#
# Too boring, let's add some error...
err <- rnorm(100,0,.05)    # Mean=0, stdev=0.2
y <- x^2 + err
plot(x,y)
plot(x, x^2+err)          # Same, but the y-label changes.
#
# Another Example: Australian Institute of Sport
#
ais <- read.table("ais.dat", header=T)
# Matrix Plot
plot(ais)
# * Writing your own functions
#
# The general syntax for defining a function is
#
# > name <- function(arg1, arg2, ...) expr1
#
# The function is called by using
#
# > name(...)
# Simple Example
add <- function(a,b) a+b
add(5,6)
#
# An Approximate Miles to Kilometers Conversion
miles.to.km <- function(miles)miles*8/5
miles.to.km(97)  # Approximate distance to Houston
#
# Another example: cubic plot a(x^3)+b(x^2)+c(x)+d
poly.plot <- function(a=0,b=0,c=0,d=0) {
x <- (-10:10);
plot(x,a*x^3+b*x^2+c*x+d,type="b");
}
poly.plot(a=1,b=0,c=0,d=0);
poly.plot(0,1,0,0);
poly.plot(d=5);
poly.plot(0,-1);
doors <- c("goat.1","goat.2","car");
prob <- c(1/3,1/3,1/3)
choice <- sample(doors,1,prob=prob)
choice
monty.hall.1 <- function(nreps=10000) {
#Possibilities, Probabilities and Strategies
doors <- c("goat.1","goat.2","car");
prob <- c(1/3,1/3,1/3)
switch <- numeric(); 	  not.switch <- numeric();
#Run Simulation
for (i in 1:nreps) {
choice <- sample(doors,1,prob=prob)
if (choice=="goat.1") {
not.switch <- c(not.switch,0)
switch <- c(switch,1)
}
if (choice=="goat.2") {
not.switch <- c(not.switch,0)
switch <- c(switch,1)
}
if (choice=="car") {
not.switch <- c(not.switch,1)
switch <- c(switch,0)
}
}
return(list(switch=switch,not.switch=not.switch))
}
#
simul <- monty.hall.1();
simul
mean(simul$switch)
mean(simul$not.switch)
monty.hall.2 <- function(nreps=10000) {
#Possibilities, Probabilities and Choices
doors <- c("goat.1","goat.2","car")
prob <- c(1/3,1/3,1/3)
choices <- sample(doors,nreps,replace=T,prob)
#Defigning two different arrays for different strategies.
switch <- numeric(nreps)
not.switch <- numeric(nreps)
#Decisions
not.switch[choices=="car"] <- 1
switch[choices!="car"] <- 1
return(list(switch=switch,not.switch=not.switch))
}
#
simul <- monty.hall.2();
simul
mean(simul$switch)
mean(simul$not.switch)
#
# To compare the performances
#
system.time(monty.hall.1(100000))
system.time(monty.hall.2(1000000))
A <- matrix(c(1,2,4,3,6,15), nc=2)
A
qr(A)$rank
A <- matrix(c(1,2,5,3,6,15), nc=2)
qr(A)$rank
A <- matrix(c(1,2,7,5,4,8,2,9,8,11,6,4,13,2,9,3), nc=4)
A
A <- matrix(c(1,2,7,5,4,8,2,9,8,11,6,4,13,2,9,3), nc=4, byrow=T)
A
A <- matrix(c(3,4,4,7,1,5),nc=3);
B <- matrix(c(1,6,3,2,1,4),nc=2)
A
B
A%*%B
B%*%A
n <- 100; p <- 5
X <- matrix(rnorm(n*p),nr=n)
dim(X)
X <- scale(X, center = T, scale = F)
X <- scale(X, center = T, scale = F)
S <- cov(X)                  # t(X)%*%X/(n-1)
t(X)%*%X/(n-1)
S
eigen(S)
chol(S)
t(chol(S))%*%chol(S)
S
svdX <- svd(X)
svdX
svdX$u%*%diag(svdX$x)%*%t(svdX$v)
svdX$u%*%diag(svdX$d)%*%t(svdX$v)
X-svdX$u%*%diag(svdX$d)%*%t(svdX$v)
rnorm(1)
rnorm(1, mean = 5,sd=3)
rnorm(100)
rnorm(100, mean = 5,sd=3)
library(mvtrnorm)
install.packages("mvtrnorm"
)
library("mvtrnorm")
library("mvtnorm")
install.packages("mvtnorm")
library
library("mvtnorm")
diag(1,3)
rmvnorm(1,mu=c(0,0,0),diag(1,3))
rmvnorm(1,mean = c(0,0,0),sigma = diag(1,3))
rnorm(3)
rmvnorm(1000,mean = c(1,-1,-2),sigma = diag(1,3))
x <- -30:30/10
x
dnorm(x)
plot(x, dnorm(x), type="l")
pnorm(x)
plot(x, pnorm(x), type="l")
sample <- rnorm(100, mean=55, sd=5)
hist(sample)
mu.mle <- mean(sample)
sigma2.mle <- sum((sample-mu.mle)^2)/100
logL.mu <- function(mus) {
result <- 0;
for (i in 1:length(mus)) result[i] <- -.5*sum((sample-mus[i])^2)
return(result)
}
mus <- 0:100
plot(mus,logL.mu(mus), main="logL(mu)", type="l")
abline(v=mu.mle, col=2)
mus <- 0:100
mus
plot(mus,logL.mu(mus), main="logL(mu)", type="l")
abline(v=mu.mle, col=2)
logL.s2 <- function(s2s) {
result <- 0; n <- length(sample)
for (i in 1:length(s2s)) {
result[i] <- -n*log(s2s[i])/2 - sum((sample-mean(sample))^2)/(2*s2s[i])
}
return(result)
}
s2s <- 1:50
plot(s2s,logL.s2(s2s), main="logL(s2)",type="l")
s2s <- 10:50
plot(s2s,logL.s2(s2s), main="logL(s2)",type="l")
abline(v=sigma2.mle, col=2)
sigma2.mle
mu.mle
sqrt(sigma2.mle)
set.seed(1)
n <- 100;
p <- 98;
lambda <- 100
beta <- rnorm(p+1)
X <- cbind(1,matrix(rnorm(n*p), nrow=n))
y <- X%*%beta+rnorm(n)
beta.hat <- NA; beta.hat <- solve(t(X)%*%X)%*%t(X)%*%y
beta.ridge <- solve(t(X)%*%X+diag(lambda,p+1))%*%t(X)%*%y
ts.plot(cbind(beta,beta.hat,beta.ridge),col=1:3,xlab="coefficients",lty=1:3,lwd=2,gpars = list(xaxt="n"),type="b")
abline(h=0,lty=4, col="gray")
legend("bottomright",c("TRUE","LS","RIDGE"),col=1:3, lty=1:3,lwd=2)
axis(1,1:(p+1),paste0("b",0:p))
set.seed(1)
n <- 100;
p <- 200;
lambda <- 100
beta <- rnorm(p+1)
X <- cbind(1,matrix(rnorm(n*p), nrow=n))
y <- X%*%beta+rnorm(n)
beta.hat <- NA; beta.hat <- solve(t(X)%*%X)%*%t(X)%*%y
beta.ridge <- solve(t(X)%*%X+diag(lambda,p+1))%*%t(X)%*%y
ts.plot(cbind(beta,beta.hat,beta.ridge),col=1:3,xlab="coefficients",lty=1:3,lwd=2,gpars = list(xaxt="n"),type="b")
abline(h=0,lty=4, col="gray")
legend("bottomright",c("TRUE","LS","RIDGE"),col=1:3, lty=1:3,lwd=2)
axis(1,1:(p+1),paste0("b",0:p))
################# Lasso vs Ridge Constraint ############
model <- "ridge"
nx <- 200; ny <- 200; x0 <- -10; x1 <- 10; y0 <- -10; y1 <- 10
a <- 5; b <- 2.5; rho <- -.5
x <- seq(x0, x1, len = nx)
y <- seq(y0, y1, len = ny)
z <- outer((x-a)^2,(y-b)^2,"+")-2*rho*outer((x-a),(y-b),"*"); z <- (-.5*(z)/(1-rho))
if (model=="lasso") z2 <- outer(abs(x),abs(y),"+") else z2 <- outer(x^2/3,y^2/3,"+")+1.25
rgl::persp3d(x=x,y=y,z=z,col=2)
rgl::persp3d(x=x,y=y,z=z2-2.5,add=T,col=4);
rgl::persp3d(x=x,y=y,z=rep(0,nx*ny),col=3,add=T)
for (i in 1:6*1)
rgl::persp3d(x=x,y=y,z=z+i,col=2,add=T)
model <- "lasso"
nx <- 200; ny <- 200; x0 <- -10; x1 <- 10; y0 <- -10; y1 <- 10
a <- 5; b <- 2.5; rho <- -.5
x <- seq(x0, x1, len = nx)
y <- seq(y0, y1, len = ny)
z <- outer((x-a)^2,(y-b)^2,"+")-2*rho*outer((x-a),(y-b),"*"); z <- (-.5*(z)/(1-rho))
if (model=="lasso") z2 <- outer(abs(x),abs(y),"+") else z2 <- outer(x^2/3,y^2/3,"+")+1.25
rgl::persp3d(x=x,y=y,z=z,col=2)
rgl::persp3d(x=x,y=y,z=z2-2.5,add=T,col=4);
rgl::persp3d(x=x,y=y,z=rep(0,nx*ny),col=3,add=T)
for (i in 1:6*1)
rgl::persp3d(x=x,y=y,z=z+i,col=2,add=T)
install.packages("INLA",repos=c(getOption("repos"),INLA="https://inla.r-inla-download.org/R/stable"), dep=TRUE)
##########################Regular grid, tensor spline#########################
rm(list=ls()); require("splines"); library("scatterplot3d")
if (.Platform[[1]]=="unix") setwd("/Users/mehdi/Dropbox/Projects/SLIDES/FDA/Code&Data/2D-Basis/") else setwd("C:/Dropbox/Projects/SLIDES/FDA/Code&Data/2D-Basis")
set.seed(70); x.range <- y.range <- c(-180,180); n <- 20; basis <- "poly"; df <- 8; grid <- "regular"; model <- 2;
if (grid=="regular") {
t.x <- seq(x.range[1],x.range[2],length.out=n)/180*pi;  t.y <- seq(y.range[1],y.range[2],length.out=n)/180*pi;
t.data <- cbind(rep(t.x,each=length(t.y)),rep(t.y,length(t.x))); x <- t.data[,1]; y <- t.data[,2];
} else {
# Does not work with tensor product
x <- runif(n^2,x.range[1],x.range[2])/180*pi; y <- runif(n^2,y.range[1],y.range[2])/180*pi; t.data <- cbind(x,y)
}
if (model==1) {
t.z <- matrix(pi^2-t.data[,1]^2-t.data[,2]^2,nr=n);  z <- pi^2-x^2-y^2+rnorm(n^2,0,2);  labl <- "TRUE Model: z = pi^2 - x^2 - y^2"
} else {
t.z <- matrix(sin(t.data[,2]),nr=n);  z <- sin(y)+rnorm(n^2,0,0.2);  labl <- "TRUE Model: z = sin(y)"
}
data <- cbind(x,y);
scatterplot3d(x,y,z)
if (basis=="poly") {
B <- outer(t.x,0:(df-1),"^"); tB <- outer(t.x,0:(df-1),"^");
} else {
B <- bs(t.x, df = df); tB <- bs(t.x, df = df);
}
B <- B%x%B; tB <- tB%x%tB
plot(t.data)
dim(B)
image(tB); kappa((t(B)%*%B),exact=TRUE)
for (i in 2:ncol(B)) persp(matrix(B[,i],nr=length(t.x)))
est <- solve(t(B)%*%B)%*%t(B)%*%z
#pdf(file=paste(model+2,"test.pdf",sep=""),width=12,height=6);
par(mfrow=c(1,2),mgp=c(1.5,.5,0),mar=c(3,3,1.5,.5),cex=1)
persp(t.x*180/pi,t.y*180/pi,t.z,theta=-40,phi=40,zlim=range(z),xlab="x",ylab="y",zlab="z",main=labl);
contour(t.x*180/pi,t.y*180/pi,t.z,xlab="x",ylab="y",col=2)
persp(t.x*180/pi,t.y*180/pi,matrix(B%*%est,nr=length(t.x)),theta=-40,phi=40,zlim=range(z),xlab="x",ylab="y",zlab="z",main="\n LSE: Based on 400 samples + Gaussian noise");
contour(t.x*180/pi,t.y*180/pi,matrix(B%*%est,nr=length(t.x)),xlab="x",ylab="y",col=2)
##########################Regular grid, tensor spline#########################
rm(list=ls()); require("splines"); library("scatterplot3d")
if (.Platform[[1]]=="unix") setwd("/Users/mehdi/Dropbox/Projects/SLIDES/FDA/Code&Data/2D-Basis/") else setwd("C:/Dropbox/Projects/SLIDES/FDA/Code&Data/2D-Basis")
set.seed(70); x.range <- y.range <- c(-180,180); n <- 20; basis <- "poly"; df <- 8; grid <- "iregular"; model <- 2;
if (grid=="regular") {
t.x <- seq(x.range[1],x.range[2],length.out=n)/180*pi;  t.y <- seq(y.range[1],y.range[2],length.out=n)/180*pi;
t.data <- cbind(rep(t.x,each=length(t.y)),rep(t.y,length(t.x))); x <- t.data[,1]; y <- t.data[,2];
} else {
# Does not work with tensor product
x <- runif(n^2,x.range[1],x.range[2])/180*pi; y <- runif(n^2,y.range[1],y.range[2])/180*pi; t.data <- cbind(x,y)
}
plot(t.data)
if (model==1) {
t.z <- matrix(pi^2-t.data[,1]^2-t.data[,2]^2,nr=n);  z <- pi^2-x^2-y^2+rnorm(n^2,0,2);  labl <- "TRUE Model: z = pi^2 - x^2 - y^2"
} else {
t.z <- matrix(sin(t.data[,2]),nr=n);  z <- sin(y)+rnorm(n^2,0,0.2);  labl <- "TRUE Model: z = sin(y)"
}
data <- cbind(x,y);
scatterplot3d(x,y,z)
if (basis=="poly") {
B <- outer(t.x,0:(df-1),"^"); tB <- outer(t.x,0:(df-1),"^");
} else {
B <- bs(t.x, df = df); tB <- bs(t.x, df = df);
}
B <- B%x%B; tB <- tB%x%tB
rm(list=ls()); gc(); library(INLA); source("BBP.R")
### Obtaining Triangles ###
x.range <- y.range <- c(-180,180)
loc.bnd = matrix(c(x.range[1],y.range[1], x.range[2],y.range[1], x.range[2],y.range[2], x.range[1],y.range[2]), 4, 2, byrow=TRUE);
segm.bnd = inla.mesh.segment(loc.bnd)
ell = max(x.range[2]-x.range[1],y.range[2]-y.range[1])
mes <- round(c(sqrt(2*ell^2)+.01,ell+.01,sqrt(2*(ell/2)^2)+.01,(ell/2)+.01,sqrt(2*(ell/4)^2)+.01,(ell/4)+.01,sqrt(2*(ell/8)^2)+.01,(ell/8)+.01,sqrt(2*(ell/16)^2)+.01),3); mesh <- list();
for (i in 1:length(mes)) {mesh[[i]] = inla.mesh.create(boundary=segm.bnd,refine=list(max.edge=mes[i]))}
par(mfrow=c(3,3),mgp=c(-1,0,0),mar=c(1,0,3,0),cex=.75)
for (i in 1:9) {plot(mesh[[i]]); mtext(paste(mesh[[i]]$n,"vertices,",nrow(mesh[[i]]$graph$tv),"triangles for max.edge",mes[i]))}
set.seed(70); d <- 3; r <- 1; n <- 400; mesh1 <- mesh[[2]]; mesh2 <- mesh[[3]]; model <- 1
t.x <- 0.99*seq(x.range[1],x.range[2],16)/180*pi; t.y <- seq(y.range[1],y.range[2],16)/180*pi;
t.data <- cbind(rep(t.x,each=length(t.y)),rep(t.y,length(t.x)))
x <- runif(n,x.range[1],x.range[2])/180*pi; y <- runif(n,y.range[1],y.range[2])/180*pi;
if (model==1) {
t.z <- matrix(pi^2-t.data[,1]^2-t.data[,2]^2,nr=length(t.x));  z <- pi^2-x^2-y^2+rnorm(n,0,2);  labl <- "TRUE Model: z = pi^2 - x^2 - y^2"
} else {
t.z <- matrix(sin(t.data[,2]),nr=length(t.x));  z <- sin(y)+rnorm(n,0,0.2);  labl <- "TRUE Model: z = sin(y)"
}
data <- cbind(x,y); plot(data)
scatterplot3d(x,y,z)
plot(mesh1)
plot(mesh2)
tB1 <- basis(mesh1,d,t.data)
tB2 <- basis(mesh2,d,t.data)
##########################Regular grid, tensor spline#########################
rm(list=ls()); require("splines"); library("scatterplot3d")
if (.Platform[[1]]=="unix") setwd("/Users/mehdi/Dropbox/Projects/SLIDES/FDA/Code&Data/2D-Basis/") else setwd("C:/Dropbox/Projects/SLIDES/FDA/Code&Data/2D-Basis")
set.seed(70); x.range <- y.range <- c(-180,180); n <- 20; basis <- "poly"; df <- 8; grid <- "iregular"; model <- 2;
if (grid=="regular") {
t.x <- seq(x.range[1],x.range[2],length.out=n)/180*pi;  t.y <- seq(y.range[1],y.range[2],length.out=n)/180*pi;
t.data <- cbind(rep(t.x,each=length(t.y)),rep(t.y,length(t.x))); x <- t.data[,1]; y <- t.data[,2];
} else {
# Does not work with tensor product
x <- runif(n^2,x.range[1],x.range[2])/180*pi; y <- runif(n^2,y.range[1],y.range[2])/180*pi; t.data <- cbind(x,y)
}
if (model==1) {
t.z <- matrix(pi^2-t.data[,1]^2-t.data[,2]^2,nr=n);  z <- pi^2-x^2-y^2+rnorm(n^2,0,2);  labl <- "TRUE Model: z = pi^2 - x^2 - y^2"
} else {
t.z <- matrix(sin(t.data[,2]),nr=n);  z <- sin(y)+rnorm(n^2,0,0.2);  labl <- "TRUE Model: z = sin(y)"
}
data <- cbind(x,y);
scatterplot3d(x,y,z)
if (basis=="poly") {
B <- outer(t.x,0:(df-1),"^"); tB <- outer(t.x,0:(df-1),"^");
} else {
B <- bs(t.x, df = df); tB <- bs(t.x, df = df);
}
B <- B%x%B; tB <- tB%x%tB
image(tB); kappa((t(B)%*%B),exact=TRUE)
for (i in 2:ncol(B)) persp(matrix(B[,i],nr=length(t.x)))
est <- solve(t(B)%*%B)%*%t(B)%*%z
#pdf(file=paste(model+2,"test.pdf",sep=""),width=12,height=6);
par(mfrow=c(1,2),mgp=c(1.5,.5,0),mar=c(3,3,1.5,.5),cex=1)
persp(t.x*180/pi,t.y*180/pi,t.z,theta=-40,phi=40,zlim=range(z),xlab="x",ylab="y",zlab="z",main=labl);
contour(t.x*180/pi,t.y*180/pi,t.z,xlab="x",ylab="y",col=2)
persp(t.x*180/pi,t.y*180/pi,matrix(B%*%est,nr=length(t.x)),theta=-40,phi=40,zlim=range(z),xlab="x",ylab="y",zlab="z",main="\n LSE: Based on 400 samples + Gaussian noise");
contour(t.x*180/pi,t.y*180/pi,matrix(B%*%est,nr=length(t.x)),xlab="x",ylab="y",col=2)
#dev.off()
################################# Triangulation ##################################
rm(list=ls()); gc(); library(INLA); source("BBP.R")
### Obtaining Triangles ###
x.range <- y.range <- c(-180,180)
loc.bnd = matrix(c(x.range[1],y.range[1], x.range[2],y.range[1], x.range[2],y.range[2], x.range[1],y.range[2]), 4, 2, byrow=TRUE);
segm.bnd = inla.mesh.segment(loc.bnd)
ell = max(x.range[2]-x.range[1],y.range[2]-y.range[1])
mes <- round(c(sqrt(2*ell^2)+.01,ell+.01,sqrt(2*(ell/2)^2)+.01,(ell/2)+.01,sqrt(2*(ell/4)^2)+.01,(ell/4)+.01,sqrt(2*(ell/8)^2)+.01,(ell/8)+.01,sqrt(2*(ell/16)^2)+.01),3); mesh <- list();
for (i in 1:length(mes)) {mesh[[i]] = inla.mesh.create(boundary=segm.bnd,refine=list(max.edge=mes[i]))}
par(mfrow=c(3,3),mgp=c(-1,0,0),mar=c(1,0,3,0),cex=.75)
for (i in 1:9) {plot(mesh[[i]]); mtext(paste(mesh[[i]]$n,"vertices,",nrow(mesh[[i]]$graph$tv),"triangles for max.edge",mes[i]))}
set.seed(70); d <- 3; r <- 1; n <- 400; mesh1 <- mesh[[2]]; mesh2 <- mesh[[3]]; model <- 1
t.x <- 0.99*seq(x.range[1],x.range[2],16)/180*pi; t.y <- seq(y.range[1],y.range[2],16)/180*pi;
t.data <- cbind(rep(t.x,each=length(t.y)),rep(t.y,length(t.x)))
x <- runif(n,x.range[1],x.range[2])/180*pi; y <- runif(n,y.range[1],y.range[2])/180*pi;
if (model==1) {
t.z <- matrix(pi^2-t.data[,1]^2-t.data[,2]^2,nr=length(t.x));  z <- pi^2-x^2-y^2+rnorm(n,0,2);  labl <- "TRUE Model: z = pi^2 - x^2 - y^2"
} else {
t.z <- matrix(sin(t.data[,2]),nr=length(t.x));  z <- sin(y)+rnorm(n,0,0.2);  labl <- "TRUE Model: z = sin(y)"
}
data <- cbind(x,y); plot(data)
scatterplot3d(x,y,z)
tB1 <- basis(mesh1,d,t.data)
tB2 <- basis(mesh2,d,t.data)
library(INLA);
getwd()
setwd("C:/Users/mehdi/Marquette University/MSSC 6250 101 Statistical Machine Learning [Spring 22] - General/Lecture Notes/R-codes/2D-Basis")
source("BBP.R")
tB1 <- basis(mesh1,d,t.data)
tB2 <- basis(mesh2,d,t.data)
dim(tB1)
dim(tB2)
plot(mesh1)
plot(mesh2)
B <- basis(mesh1,d,data)
est <- (solve(t(B)%*%B)%*%t(B)%*%z)
B <- basis(mesh2,d,data)
H <- smoothness(mesh2,d,r,type="regular",intercept=FALSE)
qrdecom=qr(t(H));	Q=qr.Q(qrdecom,TRUE); C=Q[,(qrdecom$rank+1):ncol(Q)]
BC <- B%*%C; tBc <- tB2%*%C;
estC <- (solve(t(BC)%*%BC)%*%t(BC)%*%z)
aH <- smoothness(mesh2,d,r,type="angular",intercept=FALSE)
qrdecom=qr(t(aH)); Q=qr.Q(qrdecom,TRUE); A=Q[,(qrdecom$rank+1):ncol(Q)]
BA <- B%*%A; tBa <- tB2%*%A;
estA <- (solve(t(BA)%*%BA)%*%t(BA)%*%z)
z.lim <- range(z); nrz <- nrow(z); ncz <- ncol(z);
#pdf(file=paste(model,"test.pdf",sep=""),width=12,height=6);
par(mfrow=c(1,2),mgp=c(1.5,.5,0),mar=c(3,3,1.5,.5),cex=1)
persp(t.x*180/pi,t.y*180/pi,t.z,theta=-40,phi=40,zlim=z.lim,xlab="x",ylab="y",zlab="z",main=labl);
contour(t.x*180/pi,t.y*180/pi,t.z,xlab="x",ylab="y",col=2,asp=1,xaxt="n",yaxt="n")
plot(mesh1,add=T); axis(c(1,2), c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2)); axis(2, c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2))
persp(t.x*180/pi,t.y*180/pi,matrix(tB1%*%est,nr=length(t.x)),theta=-40,phi=40,zlim=z.lim,xlab="x",ylab="y",zlab="z",main="\n LSE: No Boundary Conditions\n Based on 100 samples + Gaussian noise");
contour(t.x*180/pi,t.y*180/pi,matrix(tB1%*%est,nr=length(t.x)),xlab="x",ylab="y",col=2,asp=1,xaxt="n",yaxt="n")
plot(mesh1,add=T); axis(c(1,2), c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2)); axis(2, c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2))
B <- basis(mesh2,d,data)
H <- smoothness(mesh2,d,r,type="regular",intercept=FALSE)
qrdecom=qr(t(H));	Q=qr.Q(qrdecom,TRUE); C=Q[,(qrdecom$rank+1):ncol(Q)]
BC <- B%*%C; tBc <- tB2%*%C;
estC <- (solve(t(BC)%*%BC)%*%t(BC)%*%z)
persp(t.x*180/pi,t.y*180/pi,matrix(tB1%*%est,nr=length(t.x)),theta=-40,phi=40,zlim=z.lim,xlab="x",ylab="y",zlab="z",main="\n LSE: No Boundary Conditions\n Based on 100 samples + Gaussian noise");
contour(t.x*180/pi,t.y*180/pi,matrix(tB1%*%est,nr=length(t.x)),xlab="x",ylab="y",col=2,asp=1,xaxt="n",yaxt="n")
plot(mesh1,add=T); axis(c(1,2), c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2)); axis(2, c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2))
persp(t.x*180/pi,t.y*180/pi,matrix(tBc%*%estC,nr=length(t.x)),theta=-40,phi=40,zlim=z.lim,xlab="x",ylab="y",zlab="z",main="LSE: Interior Boundary Conditions");
contour(t.x*180/pi,t.y*180/pi,matrix(tBc%*%estC,nr=length(t.x)),xlab="x",ylab="y",col=2,asp=1,xaxt="n",yaxt="n")
plot(mesh1,add=T); axis(c(1,2), c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2)); axis(2, c(-180,-90,0,90,180), round(c(-pi,-pi/2,0,pi/2,pi),2))
setwd("C:/Users/mehdi/Marquette University/MSSC 6250 101 Statistical Machine Learning [Spring 22] - General/Lecture Notes/R-codes/SVD")
library(bmp); library(jpeg)
pic <- read.bmp("chess.bmp")
image(pic)
dim(pic)
svd.pic <- svd(pic)
dim(svd.pic$u)
dim(svd.pic$v)
(svd.pic$d)
par(mfrow=c(2,2))
ts.plot(svd.pic$u[,1:2],col=1:2, main="U[,1:2]")
ts.plot(svd.pic$v[,1:2],col=1:2, main="V[,1:2]")
plot(svd.pic$d^2/sum(svd.pic$d^2), main="Scree Plot", type="b")
hist(as.vector(pic))
pic.compress <-  svd.pic$u[,1:2] %*% diag(svd.pic$d[1:2]+10^-8) %*% t(svd.pic$v[,1:2])
writeJPEG(pic.compress,"chess-comp.jpg")
noisy.pic <- pic + rnorm(prod(dim(pic)))
image(noisy.pic)
image(noisy.pic)
writeJPEG(noisy.pic,"chess-noisy.jpg")
svd.npic <- svd(noisy.pic)
plot(svd.npic$d^2/sum(svd.npic$d^2), main="Scree Plot", log="y", type="b")
pic.compress <-  svd.npic$u[,1:2] %*% diag(svd.npic$d[1:2]) %*% t(svd.npic$v[,1:2])
writeJPEG(pic.compress,"chess-comp.jpg")
writeJPEG(pic.compress,"chess-comp.jpg")
pic <- readJPEG('pic.jpg')
dim(pic)
pic.r.svd <- svd(r)
r <- pic[,,1]
g <- pic[,,2]
b <- pic[,,3]
pic.r.svd <- svd(r)
pic.g.svd <- svd(g)
pic.b.svd <- svd(b)
plot(pic.r.svd$d^2/sum(pic.r.svd$d^2), main="Scree Plot", log="y", type="b")
rgb.svds <- list(pic.r.svd, pic.g.svd, pic.b.svd)
seq(3, nrow(pic), length.out = 8)
floor(seq(3, nrow(pic), length.out = 8))
for (j in floor(seq(3, nrow(pic), length.out = 8))) {
a <- sapply(rgb.svds, function(i) {
pic.compress <- i$u[,1:j] %*% diag(i$d[1:j]) %*% t(i$v[,1:j])
}, simplify = 'array')
writeJPEG(a, paste('compressed/pic_compressed', '_svd_rank_', round(j,0), '.jpg', sep=''))
}
setwd("C:/Users/mehdi/Marquette University/MSSC 6250 101 Statistical Machine Learning [Spring 22] - General/Lecture Notes/R-codes/ICA")
setwd("~/")
sensors <- as.matrix(read.csv("data.csv", header=FALSE));
data <- t(sensors); data <- scale(data);
setwd("C:/Users/mehdi/Marquette University/MSSC 6250 101 Statistical Machine Learning [Spring 22] - General/Lecture Notes/R-codes/ICA")
library("fastICA"); ncomp=4
sensors <- as.matrix(read.csv("data.csv", header=FALSE));
data <- t(sensors); data <- scale(data);
ts.plot(data)
ts.plot(t(data))
ica <- fastICA(data,ncomp)
pca <- princomp(data,ncomp, corr=FALSE)
SVD <- svd(data)
plot(pca$loadings[,1],pca$loadings[,2])
par(mfrow=c(2,2))
for(i in 1:ncomp) plot(ica$S[,i],type="l")
for(i in 1:ncomp) plot(ica$A[i,],type="l")
library(shiny); runApp('C:/Users/mehdi/Marquette University/MSSC 6250 101 Statistical Machine Learning [Spring 22] - General/Lecture Notes/R-codes/Shiny/Example.R')
runApp('C:/Users/mehdi/Marquette University/MSSC 6250 101 Statistical Machine Learning [Spring 22] - General/Lecture Notes/R-codes/FDA/FDA.R')
runApp('C:/Users/mehdi/Marquette University/MSSC 6250 101 Statistical Machine Learning [Spring 22] - General/Lecture Notes/R-codes/FDA/FDA.R')
