-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProstate.R
258 lines (193 loc) · 7.68 KB
/
Prostate.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# EDA
# Scatter plot
library(ElemStatLearn)
# Part a
# data = prostate
# data.train = data[which(data$train == TRUE),]
data = prostate[,1:9]
# 1. How many predictors, types of predictors quantitive or qualitative, how many observations
dim(data) # 97 observations and 9 predictors,
str(data) # 'train' is a response (logical)
head(data) # view few observations
# 2. Check for missing data
sum(is.na(data)) # counting the number of missing values in the column
# 3. Observa the summary of each predictor / repsonse to have a first glance to the data
# e.g: how many catergory / mean, median, min max
summary(data$lcavol)
summary(data$train)
# Histogram
for (j in 1:9) {
hist(data[,j], xlab=colnames(data)[j],
main=paste("Histogram of",colnames(data[j])),
col="lightblue",breaks=20)
}
# Correlations
pairs(data)
pros.cor = cor(data)
round(pros.cor,3)
pros.cor[upper.tri(pros.cor,diag=T)] = 0
pros.cor.sorted = sort(abs(pros.cor),decreasing=T)
for (i in 1:5){
vars.big.cor = arrayInd(which(abs(pros.cor)==pros.cor.sorted[i]),
dim(pros.cor))
print(colnames(data)[vars.big.cor])
}
svi = factor(data$svi)
plot(svi, data$lcp, main="lcp versus svi",xlab="SVI? Yes or no", ylab="log of capsular penetration")
plot(svi, data$lpsa, main="lpsa versus svi",xlab="SVI? Yes or no", ylab="log PSA score")
t.test(data$lpsa[data$svi==0], data$lpsa[data$svi==1])
plot(svi, data$lcavol, main="lcavol versus svi",xlab="SVI? Yes or no", ylab="Log cancer volume")
t.test(data$lcavol[data$svi==0], data$lcavol[data$svi==1])
# round(pros.cor,3)
############################################################
# k-fold cross validation
cv.k.fold = function(formula = lpsa ~ .,data,name,bestlam = 0, k){
library(glmnet)
library (pls)
set.seed(1)
# formula = as.formula(str.formula)
length = nrow(data)
size.fold = floor(length / k)
index = seq(1,length)
trunc_index = index
# acc_error = vector("numeric",length = k)
acc_error = 0
for (i in 1:k){
# Get length(data) / 10 random number in index
sample = sample(trunc_index,size.fold,replace = F)
# validation set: those data whose index obtained from sampling
validation = data[sample,]
# train set: the remaining data
train = data[which(! index %in% sample),]
# train data and predict model with validation set.
# fit = 0
# fit.pred = predict(model,validation)
# if (name == "lm"){
#
# }
if (name == "glm"){
fit = glm(formula, data=train)
fit.pred = predict(fit, s = bestlam, newdata = validation)
}
x = model.matrix(formula, train)[, -1]
y = train$lpsa
x.val = model.matrix(formula, validation)[, -1]
if (name == "ridge"){
fit = glmnet(x,y,alpha = 0,lambda = bestlam)
fit.pred = predict(fit, s = bestlam, newx = x.val)
}
if (name == "lasso"){
fit = glmnet(x,y,alpha = 1,lambda = bestlam)
fit.pred = predict(fit, s = bestlam, newx = x.val)
}
if (name == "pcr"){
fit = pcr(formula, data = train , scale =TRUE ,validation ="CV")
fit.pred = predict(fit ,x.val, ncomp = bestlam)
}
if (name == "pls"){
fit = plsr(formula, data = train , scale =TRUE ,validation ="CV")
fit.pred = predict(fit ,x.val, ncomp = bestlam)
}
acc_error = acc_error + mean((fit.pred - validation[, 9])^2)
# truncate index
trunc_index = trunc_index[! trunc_index %in% sample]
}
MSE = acc_error / k
return(MSE)
}
###############################################
# ------------------------- PART B -----------------------------------
# Fit a linear model with all predictors using the usual least squares
model.LQ = lm(lpsa ~ ., data)
summary(model.LQ)
# Estimate the test error using 10-fold cross validation
err.LQ = cv.k.fold(data = data,name = "glm",k=10)
err.LQ
# --------------------------------------------------------------------
# ------------------------ PART C ------------------------------------
# Repeat (b) using best-subset selection
library(leaps)
par(mfrow = c(1, 1))
model.BSS = regsubsets(lpsa ~ ., data) #need to add nvmax in case you want more predictors
model.BSS.summary = summary(model.BSS)
# Plot Adjusted R^2 against number of variables and pick the best num of variables
plot(model.BSS.summary$adjr2, xlab = "Number of Variables", ylab = "Adjusted RSq", type = "l")
optimal.var = which.max(model.BSS.summary$adjr2)
points(optimal.var, model.BSS.summary$adjr2[optimal.var], col = "red", cex = 2, pch = 20)
plot(model.BSS, scale = "adjr2")
# Get coefficients of best model for a given size
coefi = coef(model.BSS, optimal.var)
# Fit model with selected variables
model.BSS = lm(lpsa ~ .-gleason,data)
summary(model.BSS)
# Estimate the test error using 10-fold cross validation
err.BSS = cv.k.fold(lpsa ~ .-gleason,data=data,name = "glm",k=10)
err.BSS
# --------------------------------------------------------------------
# ------------------------ PART D ------------------------------------
# part d: Ridge regression
library(glmnet)
# Set up a grid of lambda values (from 10^10 to 10^(-2)) in decreasing sequence
grid = 10^seq(10, -2, length = 100)
# Fit ridge regression for each lambda on the grid
x = model.matrix(lpsa ~ ., data)[, -1]
y = data$lpsa
ridge.mod = glmnet(x, y, alpha = 0, lambda = grid)
plot(ridge.mod, xvar = "lambda")
# Use cross-validation to estimate test MSE from training data
set.seed(1)
cv.out = cv.glmnet(x, y, alpha = 0)
plot(cv.out)
bestlam.ridge = cv.out$lambda.min
# out = glmnet(x,y,alpha = 0,lambda = bestlam)
out = glmnet(x,data$lpsa,alpha = 0)
# out = glmnet(x,y,alpha = 0)
predict(out , type ="coefficients",s= bestlam.ridge)[1:9,]
# Calculate the error
err.ridge = cv.k.fold(lpsa ~ .,data=data,name = "ridge",bestlam = bestlam.ridge,k=10)
err.ridge
# --------------------------------------------------------------------
# ------------------------ PART E ------------------------------------
# part e: Lasso
lasso.mod = glmnet(x, y, alpha = 1, lambda = grid)
plot(lasso.mod, xvar = "lambda")
# Use cross-validation to estimate test MSE from training data
set.seed(1)
cv.out = cv.glmnet(x, y, alpha = 1)
plot(cv.out)
bestlam.lasso = cv.out$lambda.min
# lasso.pred = predict(lasso.mod, s = bestlam.lasso, newx = x)
out = glmnet(x,y,alpha = 1)
predict(out , type ="coefficients",s= bestlam.lasso)[1:9,]
err.lasso = cv.k.fold(lpsa ~ .,data=data,name = "lasso",bestlam = bestlam.lasso,k=10)
err.lasso
# --------------------------------------------------------------------
# ------------------------ PART F ------------------------------------
# Part f: PCR
library (pls)
set.seed(2)
pcr.fit = pcr(lpsa ~ ., data = data , scale =TRUE ,validation ="CV")
summary(pcr.fit)
validationplot(pcr.fit ,val.type ="MSEP")
optimal.pcr.ncomp = as.numeric(which.min(MSEP(pcr.fit)$val[1, 1,]) - 1)
err.pcr = cv.k.fold(lpsa ~ .,data=data,name = "pcr",bestlam = optimal.pcr.ncomp,k=10)
err.pcr
pcr.fit$coefficients[,,optimal.pcr.ncomp]
coefi = pcr.fit$coefficients[,,optimal.pcr.ncomp]
test.mat <- model.matrix(lpsa ~ ., data = data)
# coefi = coef(fit.best, id = i) # Coefficients of best model of size i
pred = test.mat[, names(coefi)] %*% coefi # Predictions from this model
intercept = mean(data[,9] - pred)
# --------------------------------------------------------------------
# ------------------------ PART G ------------------------------------
# Part g: PLS
pls.fit = plsr(lpsa ~ ., data = data , scale =TRUE ,validation ="CV")
summary(pls.fit)
validationplot(pls.fit ,val.type ="MSEP")
MSEP(pls.fit)
sqrt(MSEP(pls.fit)$val[1, 1,])
which.min(MSEP(pls.fit)$val[1, 1,])
optimal.pls.ncomp = as.numeric(which.min(MSEP(pls.fit)$val[1, 1,]) - 1)
err.pls = cv.k.fold(lpsa ~ .,data=data,name = "pls",bestlam = optimal.pls.ncomp,k=10)
err.pls
pls.fit$coefficients[,,optimal.pls.ncomp]