# NOT RUN {
# a very simplistic optimization
evaluate <- function(string=c()) {
returnVal = 1 / sum(string);
returnVal
}
rbga.results = rbga.bin(size=10, mutationChance=0.01, zeroToOneRatio=0.5,
evalFunc=evaluate)
plot(rbga.results)
# in this example the four variables in the IRIS data
# set are complemented with 36 random variables.
# Variable selection should find the four original
# variables back (example by Ron Wehrens).
# }
# NOT RUN {
data(iris)
library(MASS)
X <- cbind(scale(iris[,1:4]), matrix(rnorm(36*150), 150, 36))
Y <- iris[,5]
iris.evaluate <- function(indices) {
result = 1
if (sum(indices) > 2) {
huhn <- lda(X[,indices==1], Y, CV=TRUE)$posterior
result = sum(Y != dimnames(huhn)[[2]][apply(huhn, 1,
function(x)
which(x == max(x)))]) / length(Y)
}
result
}
monitor <- function(obj) {
minEval = min(obj$evaluations);
plot(obj, type="hist");
}
woppa <- rbga.bin(size=40, mutationChance=0.05, zeroToOneRatio=10,
evalFunc=iris.evaluate, verbose=TRUE, monitorFunc=monitor)
# }
# NOT RUN {
# another realistic example: wavelenght selection for PLS on NIR data
# }
# NOT RUN {
library(pls.pcr)
data(NIR)
numberOfWavelenghts = ncol(NIR$Xtrain)
evaluateNIR <- function(chromosome=c()) {
returnVal = 100
minLV = 2
if (sum(chromosome) < minLV) {
returnVal
} else {
xtrain = NIR$Xtrain[,chromosome == 1];
pls.model = pls(xtrain, NIR$Ytrain, validation="CV", grpsize=1,
ncomp=2:min(10,sum(chromosome)))
returnVal = pls.model$val$RMS[pls.model$val$nLV-(minLV-1)]
returnVal
}
}
monitor <- function(obj) {
minEval = min(obj$evaluations);
filter = obj$evaluations == minEval;
bestObjectCount = sum(rep(1, obj$popSize)[filter]);
# ok, deal with the situation that more than one object is best
if (bestObjectCount > 1) {
bestSolution = obj$population[filter,][1,];
} else {
bestSolution = obj$population[filter,];
}
outputBest = paste(obj$iter, " #selected=", sum(bestSolution),
" Best (Error=", minEval, "): ", sep="");
for (var in 1:length(bestSolution)) {
outputBest = paste(outputBest,
bestSolution[var], " ",
sep="");
}
outputBest = paste(outputBest, "\n", sep="");
cat(outputBest);
}
nir.results = rbga.bin(size=numberOfWavelenghts, zeroToOneRatio=10,
evalFunc=evaluateNIR, monitorFunc=monitor,
popSize=200, iters=100, verbose=TRUE)
# }
Run the code above in your browser using DataLab