-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.Rmd
232 lines (157 loc) · 6.17 KB
/
index.Rmd
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
---
title: "Problema da Mochila"
subtitle: "Uma solução com Python"
author: "Beatriz Lima, Vitória Sesana e Matheus Monteiro"
#institute: ""
date: "06/06/2024"
output:
xaringan::moon_reader:
lib_dir: libs
nature:
highlightStyle: github
highlightLines: true
countIncrementalSlides: false
---
```{r setup, include=FALSE}
options(htmltools.dir.version = FALSE)
# Para utilizar python
library(reticulate)
use_condaenv("r-reticulate", required = TRUE)
```
# Apresentando o Problema
A proposta do problema da mochila é preencher uma mochila com objeto de diferentes valores e pesos de tal forma que a soma dos valores dos objetos escolhidos seja a maior possivel, sem ultrapassar o peso minimo da mochila.
![Imagem Ilustrativa](imagem ilustrativa.png)
---
# O Problema da Mochila como um Algoritmo Genético
- **O que é o indivíduo?** É uma solução candidata para o problema, ou seja, uma combinação de objetos que podem ser colocados na mochila.
- **O que é o gene do indivíduo?** São os itens escolhidos pelo mochileiro, sendo que cada item possui seu valor e peso.
- **O que é a população?** É o conjunto de N mochilas (indivíduos) geradas aleatóriamente. Sendo assim, temos N possiveis combinações.
- **Função objetivo:** Maximizar o valor total dos itens da mochila.
- **Função aptidão:** Verifica se o indivíduo está próximo do objetivo, ou seja, se o valor total dos objetos é alto e simultânemente respeita a capacidade.
- **Função crossover:** Gera o filho, ou seja, seleciona configurações de itens para a mochila
- **Função mutação:** Adicionar ou remover algum item aleatório na mochila.
---
# Bibliotecas utilizadas
```{python, engine='python'}
import numpy as np
import pandas as pd
import random
from functools import partial
```
# Função objetivo
```{python, engine='python'}
def f_objetivo(df):
valor_total = df['Valor'].sum()
peso_total = df['Peso'].sum()
return valor_total, peso_total
```
---
# Geração do gene do indivíduo aleatório e função aptidão
```{python, engine='python'}
def f_aleatorio(df):
n_aleatorio = np.random.randint(1, df.shape[0]+1)
df_aleatorio = df.sample(n = n_aleatorio)
return df_aleatorio
```
```{python, engine='python'}
def f_aptidao(df_gene, capacidade):
valor = f_objetivo(df_gene)[0]
peso = f_objetivo(df_gene)[1]
if peso <= capacidade:
podenracao = 1
else:
podenracao = 0
aptidao = podenracao*(valor + peso)
return aptidao
```
---
# Exemplificando f_aleatorio e f_aptidao
Considere $\text{mochila}_i$ e $\text{mochila}_j$ como os indivíduos que <tt> f_aleatorio </tt> gerou. Ao aplicar <tt> f_aptidao </tt> nesses dois indivíduos obtemos sua aptidão:
$$\text{mochila}_i=\left[ \begin{matrix}
1 & 12 & 4 \\
2 & 2 & 2 \\
3 & 1 & 1 \\ \end{matrix} \right] \Rightarrow f_{\text{apt}}=21 \text{,}$$
$$\text{mochila}_j= \left[ \begin{matrix}
3 & 1 & 1 \\
4 & 1 & 2 \\
5 & 4 & 10 \\
2 & 2 & 2 \\ \end{matrix} \right] \Rightarrow f_{\text{apt}}=23 \text{.}$$
O próximo passo será fazer o Crossover.
---
# Crossover
```{python, engine='python'}
def f_crossover(df_pai_1, df_pai_2):
df_gene_pai_1_aleatorio = f_aleatorio(df_pai_1)
df_gene_pai_2_aleatorio = f_aleatorio(df_pai_2)
df_concat = pd.concat([df_gene_pai_1_aleatorio,df_gene_pai_2_aleatorio])
df_gene_filho = df_concat.drop_duplicates()
return df_gene_filho
```
Considerando ainda a $\text{mochila}_i$ e a $\text{mochila}_j$, suponha que elas são os pais selecionados. Em <tt> df_gene_pai_1_aleatorio </tt> será selecionada uma parte aleatória do gene do pai 1 (mochila i), dada nesse caso por:
$$\text{parte do gene da mochila i}= \left[ \begin{matrix}
2 & 2 & 2 \\
3 & 1 & 1 \\ \end{matrix} \right] \text{,}$$
Em <tt> df_gene_pai_2_aleatorio </tt> será selecionada uma parte aleatória do gene do pai 2 (mochila j), dada nesse caso por:
$$\text{parte do gene da mochila j}= \left[ \begin{matrix}
3 & 1 & 1 \\
4 & 1 & 2 \\
5 & 4 & 10 \\ \end{matrix} \right] \text{.}$$
---
# Crossover
Em <tt> df_concat </tt> será realizada a junção dos genes de cada pai. Em seguida, <tt> df_gene_filho </tt> realizará a exclusão das linhas repetidas. Após esse processo temos:
$$\text{novo gene}= \left[ \begin{matrix}
2 & 2 & 2 \\
3 & 1 & 1 \\
4 & 1 & 2 \\
5 & 4 & 10 \\ \end{matrix} \right] \text{.}$$
O próximo passo será fazer a mutação.
---
# Função para realizar a mutação
```{python, engine='python'}
def f_mutacao(df_gene, df_mochileiro):
linha = np.random.randint(0, df_gene.shape[0])
mutacao = df_mochileiro.sample(n = 1)
df_gene.iloc[linha] = mutacao
df_gene = df_gene.drop_duplicates()
return df_gene
```
Supondo que a mutação ocorreu na linha 1...
$$filho=f_{\text{mutação}}(\text{novo gene})= \left[ \begin{matrix}
4' & 1' & 2' \\
3 & 1 & 1 \\
4 & 1 & 2 \\
5 & 4 & 10 \\ \end{matrix} \right] \text{.}$$
Logo,
$$filho=\left[ \begin{matrix}
4 & 1 & 2 \\
3 & 1 & 1 \\
5 & 4 & 10 \\ \end{matrix} \right]$$
---
# Algoritmo genético
```{python, engine = 'python'}
def algoritmo_genetico(df_mochileiro, capacidade):
populacao = [f_aleatorio(df_mochileiro) for _ in range(50)]
for _ in range(100):
aptidao_populacao = [f_aptidao(df_gene = x, capacidade = capacidade) for x in populacao]
parentes = random.choices(populacao, weights = aptidao_populacao, k = 100)
nova_geracao = [f_mutacao(df_gene = f_crossover(random.choice(parentes),
random.choice(parentes)),
df_mochileiro = df_mochileiro)
for _ in range(50)]
populacao = nova_geracao
f_aptidao_fixando_capacidade = partial(f_aptidao, capacidade = capacidade)
resultado = max(populacao, key = f_aptidao_fixando_capacidade)
return resultado
```
---
# Aplicação
```{python, engine = 'python'}
dado = {'Item': [1, 2, 3, 4, 5],
'Valor': [4, 2, 1, 2, 10],
'Peso': [12, 2, 1, 1, 4]}
df = pd.DataFrame(dado)
capacidade_max = 15
resultado = algoritmo_genetico(df_mochileiro = df,
capacidade = capacidade_max)
print(resultado)
```