Advertisement
Guest User

jezykr2

a guest
Apr 26th, 2018
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.12 KB | None | 0 0
  1. library(genalg)
  2. #library(ggplot2)
  3.  
  4. dataset <- data.frame(item = c("pocketknife", "beans", "potatoes", "unions",
  5. "sleeping bag", "rope", "compass"), survivalpoints = c(10, 20, 15, 2, 30,
  6. 10, 30), weight = c(1, 5, 10, 1, 7, 5, 1))
  7. weightlimit <- 20
  8.  
  9. chromosome = c(1, 0, 0, 1, 1, 0, 0)
  10. dataset[chromosome == 1, ]
  11.  
  12. cat(chromosome %*% dataset$survivalpoints)
  13.  
  14.  
  15. evalFunc <- function(x) {
  16. current_solution_survivalpoints <- x %*% dataset$survivalpoints
  17. current_solution_weight <- x %*% dataset$weight
  18.  
  19. if (current_solution_weight > weightlimit)
  20. return(0) else return(-current_solution_survivalpoints)
  21. }
  22.  
  23.  
  24. iter = 100
  25. GAmodel <- rbga.bin(size = 7, popSize = 200, iters = iter, mutationChance = 0.01,
  26. elitism = T, evalFunc = eval)
  27. cat(summary.rbga(GAmodel))
  28. solution = c(1, 1, 1, 1, 1, 0, 1)
  29. dataset[solution == 1, ]
  30. plot(-GAmodel$best,type = "l",col="red")
  31. lines(-GAmodel$mean,col="blue")
  32.  
  33. c(1,0,0,0,1,0)
  34. "10010"
  35. a <- "0"
  36. b <- "1"
  37. b <- paste(a,b,sep="")
  38.  
  39. strtoi("001111000000", base = 2)
  40. eval <- function(x){
  41. x <- c(0,0,1,1)
  42. xx <- ""
  43. for(a in 1:lenght(x))
  44. {
  45. xx <- paste(xx,x[a],sep= "")
  46. }
  47. xx.val <- strtoi(xx,base = 2)
  48. return ((xx.val-2)^2)}
  49.  
  50. iter = 100
  51. GAmodel <- rbga.bin(size = 7, popSize = 200, iters = iter, mutationChance = 0.01,
  52. elitism = T, eval = eval)
  53. cat(summary(GAmodel))
  54. #solution = c(1, 1, 1, 1, 1, 0, 1)
  55. #dataset[solution == 1, ]
  56. #plot(-GAmodel$best,type = "l",col="red")
  57. #lines(-GAmodel$mean,col="blue")
  58.  
  59.  
  60. animate_plot <- function(x) {
  61. for (i in seq(1, iter)) {
  62. temp <- data.frame(Generation = c(seq(1, i), seq(1, i)), Variable = c(rep("mean",
  63. i), rep("best", i)), Survivalpoints = c(-GAmodel$mean[1:i], -GAmodel$best[1:i]))
  64.  
  65. pl <- ggplot(temp, aes(x = Generation, y = Survivalpoints, group = Variable,
  66. colour = Variable)) + geom_line() + scale_x_continuous(limits = c(0,
  67. iter)) + scale_y_continuous(limits = c(0, 110)) + geom_hline(y = max(temp$Survivalpoints),
  68. lty = 2) + annotate("text", x = 1, y = max(temp$Survivalpoints) +
  69. 2, hjust = 0, size = 3, color = "black", label = paste("Best solution:",
  70. max(temp$Survivalpoints))) + scale_colour_brewer(palette = "Set1") +
  71. opts(title = "Evolution Knapsack optimization model")
  72.  
  73. print(pl)
  74. }
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement