问题
Assume I have:
chromosome_1 <- c('0010000001010000')
chromosome_2 <- c('0100000001001010')
How can I implement step 3-5 ?
- Evaluate
- NC1 = no. of 1's in
chromosome_1
- NC2 = no. of 1's in
chromosome_2
- M =
min(NC1, NC2)
- NC1 = no. of 1's in
- Generate a random integer
NC
fromrange(1, M)
Randomly select
NC
gene positions among the genes with allele “1” fromchromosome_1
and form a sets1
of indices of such selected positions.Randomly select
NC
gene positions among the genes with allele “1” fromchromosome_2
and form a sets2
of indices of such selected positions.s = union(s1, s2)
Assumes = 2, 3, 10, 15
for each index
i
ins
Exchange the alleles of chromosomes
chromosome_1
andchromosome_2
at gene positioni
.
The following illustrates the outcome:
I would really really appreciate any help!
回答1:
You can try with GA package:
In Manual (page 5), there is an example.
ga(type = c("binary", "real-valued", "permutation"),
fitness, ...,
min, max, nBits,
population = gaControl(type)$population,
selection = gaControl(type)$selection,
crossover = gaControl(type)$crossover,
mutation = gaControl(type)$mutation,
popSize = 50,
pcrossover = 0.8,
pmutation = 0.1,
elitism = base::max(1, round(popSize*0.05)),
updatePop = FALSE,
postFitness = NULL,
maxiter = 100,
run = maxiter,
maxFitness = Inf,
names = NULL,
suggestions = NULL,
optim = FALSE,
optimArgs = list(method = "L-BFGS-B",
poptim = 0.05,
pressel = 0.5,
control = list(fnscale = -1, maxit = 100)),
keepBest = FALSE,
parallel = FALSE,
monitor = if(interactive())
{ if(is.RStudio()) gaMonitor else gaMonitor2 }
else FALSE,
seed = NULL)
In example, population, selection, crossover, mutation and monitor operators assign new functions. In my study, I used own mutation and monitor functions. For example;
myga <- ga(type = "binary",
fitness, ...,
min, max, nBits,
mutation = myMutationFunction
popSize = 50,
pcrossover = 0.8,
pmutation = 0.1,
maxiter = 100,
run = maxiter,
monitor = myMonitorFunction
myMutationFunction <- function (x) {
#...
}
myMonitorFunction <- function (x) {
#...
}
So, you just define your own function and give the function name to ga function. In order to be reference, you can see default functions. You can see necessary parameters and return values in default functions.
回答2:
Might not be the simplest solution, but it works
set.seed(12345)
## Step 1
a <- c(0,0,1,0,0,0,0,0,0,1,0,1,0,0,0,0)
b <- c(0,1,0,0,0,0,0,0,0,1,0,0,1,0,1,0)
m <- min(sum(a==1), sum(b==1))
## Step 2
random_int <- sample(1:m, 1)
## Step 3
random_a <- sample(which(a == 1), random_int)
random_b <- sample(which(b == 1), random_int)
#all <- sort(union(random_a, random_b))
## Step 4
## for demo purpose (assume it as the random output)
all <- c(2,3,10,15)
temp_a <- a[all]
temp_b <- b[all]
## Step 5
##crossover
b[all] <- temp_a
a[all] <- temp_b
## Output
> a
[1] 0 1 0 0 0 0 0 0 0 1 0 1 0 0 1 0
> b
[1] 0 0 1 0 0 0 0 0 0 1 0 0 1 0 0 0
来源:https://stackoverflow.com/questions/41760637/exchanging-elements-crossover-between-two-vectors