forked from luiseduardogfranca/workshop-tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
490 lines (406 loc) · 17.3 KB
/
index.html
File metadata and controls
490 lines (406 loc) · 17.3 KB
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./revealjs/css/reveal.css">
<link rel="stylesheet" href="./revealjs/css/theme/white.css">
<link rel="stylesheet" href="./css/style.css">
<link rel="stylesheet" href="./highlight/styles/vs2015.css">
<script src="./highlight/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<style media="screen">
.panel{
background-color: rgb(228, 228, 237);
padding: 20px !important;
border-radius: 10px;
}
img{
border-style: none !important;
box-shadow: none !important;
background-color: transparent !important;
}
pre{
border-style: none !important;
box-shadow: none !important;
background-color: transparent !important;
width: 100% !important;
}
</style>
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides" style="width:70%;">
<section data-background-image="./images/background-slide2.jpeg">
<div style="">
<p class="subtitle">Workshop com</p>
<div class=" ">
<!-- <img src="./images/image-t-k.png" alt=""> -->
<h1 class="title" style="text-transform: none;">TensorFlow e Keras</h1>
</div>
<!-- <h1 style="color: white;">TensorFlow <br> <i>+</i> <br> Keras</h1> -->
</div>
<!-- <h1 class="title">Deep Learning</h1> -->
</section>
<section>
<table style="color:rgb(29, 35, 38); font-size:20pt;">
<tr>
<td>
<div class="panel">
<p><span class="icons"> </span>Émerson Silva</p>
<p><span class="icons"> </span>Universidade Federal de Alagoas</p>
<p><span class="icons"> </span>emersonjose877@gmail.com</p>
<p><span class="icons"> </span> <a href="https://www.github.com/silvaemerson">silvaemerson</a></p>
</div>
</td>
<td>
<div class="panel">
<p><span class="icons"> </span>Luís Eduardo G. França</p>
<p><span class="icons"> </span>Universidade Federal de Alagoas</p>
<p><span class="icons"> </span>luiseduardogfranca@gmail.com</p>
<p><span class="icons"> </span> <a href="https://www.github.com/luiseduardogfranca"> luiseduardogfranca</a></p>
</div>
</td>
</tr>
</table>
</section>
<section>
<section>
<div style="text-align:justify;">
<h2 style="margin-left:23%; display:inline; margin-bottom:0;">Instalação</h2><br>
<p style="margin-left:23%; display:inline; font-size:20pt; " class="text-justify">para <strong>Linux</strong> </p>
</div>
</section>
<section>
<div class="text-justify">
<p class="fragment fade-up"><a href="https://pandas.pydata.org/">Pandas</a>: Biblioteca para análise de dados;</p>
<p class="fragment fade-up"><a href="http://www.numpy.org/">Numpy</a>: Operações matemáticas em arrays e matrizes multidimensionais;</p>
<p class="fragment fade-up"><a href="https://matplotlib.org/">Matplotlib</a>: Biblioteca de Visualização 2D e 3D;</p>
<p class="fragment fade-up"><a href="https://seaborn.pydata.org/">Seaborn</a>: Criação de gráficos estatísticos atraentes;</p>
</div>
</section>
<section>
<p>Instalação dos pacotes auxiliares...</p>
<pre class="bash" data-trim contenteditable>
<code>
<span class="icons"></span> pip3 install pandas seaborn matplotlib numpy
</code>
</pre>
</section>
<section>
<p>Instalação do TensorFlow e Keras</p>
<pre>
<code class="bash" data-trim contenteditable>
<span class="icons"></span> sudo apt install python3-pip
<span class="icons"></span> pip3 install virtualenv
<span class="icons"></span> virtualenv -p python3 TensorKeras
<span class="icons"></span> source TensorKeras/bin/activate
<span class="icons"></span> pip3 install tensorflow=1.5 keras
</code>
</pre>
</section>
</section>
<section>
<section>
<h2>Implementação</h2>
</section>
<section>
<div class="text-justify">
<p class="fragment fade-up">Classificação de vinhos em 3 classes com o <strong>TensorFlow</strong> e <strong>Keras</strong>; </p>
<p class="fragment fade-up">Dataset: <a href="https://archive.ics.uci.edu/ml/datasets/wine">Wine Data Set</a> </p>
</div>
</section>
<section>
<p>Librarys para manipulação e visualização: </p>
<pre>
<code class="python" data-trim contenteditable>
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
</code>
</pre>
</section>
<section>
<!-- <button class="btn" type="button" name="open-img"><span class="icons"> </span> </button> -->
<p>Seleção de atributos: </p>
<pre>
<code class="python" data-trim contenteditable>
#Criação das colunas para tabela
columns = [i-1 for i in range(1,15)]
columns[0] = 'Class'
#Leitura do dataset com pandas
df = pd.read_csv('wine.data.txt')
#Recriação de dataframe com as colunas criadas
df = pd.DataFrame(df.values.tolist(), columns=columns)
#Visualização das correlações em um mapa de calor
plt.figure(figsize=(10, 10))
sns.heatmap(df.iloc[:, 1:].corr(), annot=True)
#Lista com atributos de menor correlação
selected_columns = [3, 2, 4, 2, 13, 2, 4, 13, 6, 13, 6, 12]
selected_columns = set(selected_columns)
selected_columns.add('Class')
#Configura o tipo de dados
df = df.astype('float32')
#Função para selecionar um percentil do conjunto de dados
def split_data(data, percent=0.8):
index = int(percent * len(data))
return data[:index], data[index:]
#Resolver problemas com as classes ([1, 2, 3] -> [0, 1, 2])
df['Class'] = df['Class'] - 1
#Separa as classes do conjunto de dados
labels = df.iloc[:, 0].values
#Seleciona os atributos fracamente correlacionados
features = df[list(selected_columns)].values
#Separa o conjunto de dados com a função 'split_data'
X_train, X_test = split_data(features)
Y_train, Y_test = split_data(labels)
np.save('X_train', X_train)
np.save('X_test', X_test)
np.save('Y_train', Y_train)
np.save('Y_test', Y_test)
</code>
</pre>
</section>
<section>
<p>Visualização do mapa de correlação</p>
<img src="./images/heat-map.png" alt="Mapa de correlação" width="500">
</section>
</section>
<section>
<img src="./images/keras-logo.png" alt="Keras" width="500">
<!-- <h1 class="title">Deep Learning</h1> -->
</section>
<section>
<section>
<h2>O que é Keras?</h2>
</section>
<section>
<div style="text-align:justify;">
<p class="fragment highlight-transparent"> <span class="icons"> </span>É uma API de alto nível para a criação de redes neurais</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span>Pode usar TensorFlow, CNTK ou Theano como backend</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span>Muito usada por pesquisadores devido à facilidade de criação de modelos</p>
</section>
</section>
<section>
<section>
<h2>Implementação com Keras</h2>
</section>
<section>
<p>Importe as libs nescessárias</p>
<pre>
<code class="python" data-trim contenteditable>
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
import matplotlib.pyplot as plt
from keras.optimizers import Adam
from keras.initializers import TruncatedNormal
</code>
</pre>
</section>
<section>
<p>Recuperando dados e configurando a rede</p>
<pre>
<code class="python" data-trim contenteditable>
#Carrega os dados salvos no pré-processamento com numpy
X_train, X_test = np.load('X_train.npy'), np.load('X_test.npy')
Y_train, Y_test = np.load('Y_train.npy'), np.load('Y_test.npy')
#Criando uma matriz binária '[1,0,0]'
Y_train, Y_test = to_categorical(Y_train), to_categorical(Y_test)
#Recupera a quantidade de valores armazenados
input_dim = len(X_train[0, :])
classes_num = len(Y_train[0, :])
model = Sequential()
init = TruncatedNormal(stddev=0.01, seed=10)
#Configurando modelo da rede
model.add(Dense(units=50, activation='relu', input_dim=input_dim,
kernel_initializer=init))
model.add(Dense(units=classes_num, activation='softmax',
kernel_initializer=init))
#Inicializando o otimizador
adam = Adam(lr=0.007)
#Configurando a forma de compilação da rede
model.compile(loss='categorical_crossentropy',
optimizer=adam,
metrics=['accuracy'])
#Treino da rede
history = model.fit(X_train, Y_train, epochs=800,
validation_data=(X_test, Y_test), shuffle=False)
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='best')
plt.show()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='best')
plt.show()
</code>
</pre>
</section>
<section>
<p>Gráfico de acurácia e perda</p>
<figure style="display:inline-block; float:left">
<img class="transition-element" src="./images/accuracy-keras.jpeg" width="450" alt="Acurácia com Keras">
<figcaption>Acurácia com Keras</figcaption>
</figure>
<figure style="display:inline-block; float:right">
<img class="transition-element" src="./images/loss-keras.jpeg" width="450" alt="Perda com Keras">
<figcaption>Perda com Keras</figcaption>
</figure>
</section>
</section>
<section>
<img src="./images/tensorflow-logo.png" alt="TensorFlow logo" width="500">
</section>
<section>
<section>
<h2>O que é TensorFlow?</h2>
</section>
<section>
<div style="text-align:justify;">
<p class="fragment highlight-transparent"> <span class="icons"> </span>Biblioteca open source para computação númerica (não somente para machine learning);</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span>Permite criar modelos preditivos de forma mais eficiente e que requisite menos processamento para a aplicação;</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span> Desenvolvida em <strong>C++</strong>, porém com disponibilidade de comunicação em <strong>Python</strong> por meio da API TensorFlow;</p>
</section>
<section>
<div style="text-align:justify;">
<p class="fragment highlight-transparent"> <span class="icons"> </span>TensorFlow vai dispor de várias outras aplicações, como: API TensorFlow, TensorBoard e TensorServing;</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span>Algumas empresas utilizam o TensorFlow: Google, OpenAI, DeepMind, Snapchat, Airbus, Uber, Dropbox e etc. </p>
</section>
</section>
<section>
<section>
<h2>Conceitos</h2>
</section>
<section>
<div style="text-align:justify;">
<p class="fragment highlight-transparent"> <span class="icons"> </span>TensorFlow usa de grafos para representar o fluxo de dados(tensores) e as suas operações;</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span>Tensor: Um array n-dimensional;</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span>Nós: Onde ocorre as operações entre os tensores;</p>
<p class="fragment highlight-transparent"> <span class="icons"> </span>Session: É o objeto que encapsula o ambiente onde as operações são executadas e as variáveis inicializadas;</p>
</div>
</section>
</section>
<section>
<section>
<h2>Implementação com TensorFlow</h2>
</section>
<section>
<p>Importe o TensorFlow</p>
<pre>
<code class="python" data-trim contenteditable>
import tensorflow as tf
</code>
</pre>
</section>
<section>
<p>Criando modelo</p>
<pre>
<code class="python" data-trim contenteditable>
Y_train, Y_test = tf.keras.utils.to_categorical(Y_train), tf.keras.utils.to_categorical(Y_test)
features_num = len(X_train[0])
l1 = 50
l2 = len(Y_train[0])
tf.set_random_seed(10)
#Criando entrada para os dados e classes
X = tf.placeholder(shape=[None, features_num], dtype=tf.float32, name="Input")
labels = tf.placeholder(shape=[None, l2], dtype=tf.float32, name="Labels")
with tf.name_scope("Hidden_Layer") as scope:
#Criando pesos e bias da camada intermediária
W1 = tf.Variable(tf.truncated_normal([features_num, l1], stddev=0.01), name="W1")
B1 = tf.Variable(tf.zeros([l1]), name="B1")
#Calculando saída da camada intermediária
l1_activation = tf.nn.relu(tf.matmul(X, W1) + B1, name="l1_activation")
</code>
</pre>
</section>
<section>
<p>Grafo da Camada Intermediária</p>
<img src="./images/first-image-tensorflow.png" alt="First Step" width="650">
</section>
<section>
<p></p>
<pre>
<code class="python" data-trim contenteditable>
with tf.name_scope("Final_Layer") as scope:
#Criando pesos e bias da camada de saída
W2 = tf.Variable(tf.truncated_normal([l1, l2], stddev=0.01), name="W2")
B2 = tf.Variable(tf.zeros([l2]), name="B2")
#Calculando saída da camada de saída
final_result = tf.nn.softmax(tf.matmul(l1_activation, W2) + B2, name="result")
</code>
</pre>
</section>
<section>
<p>Grafo da Camada Final</p>
<img src="./images/second-image-tensorflow.png" alt="Second Step" width="650">
</section>
<section>
<p></p>
<pre>
<code class="python" data-trim contenteditable>
with tf.name_scope("Loss_function") as scope:
#Criando a entropia cruzada
loss_func = -tf.reduce_sum(labels * tf.log(final_result))
</code>
</pre>
</section>
<section>
<p>Grafo da Função de Custo</p>
<img src="./images/third-image-tensorflow.png" alt="Third Step" width="650">
</section>
<section>
<pre>
<code class="python" data-trim contenteditable>
with tf.name_scope('Accuracy') as scope:
#Verificando se a classe predita é igual à real [1, 0, 0] [0.1, 0.9, 0.0]
is_correct = tf.equal(tf.argmax(final_result, axis=1), tf.argmax(labels, axis=1))
#Calculando a acurácia
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
</code>
</pre>
</section>
<section>
<p>Grafo da acurácia</p>
<img src="./images/fourth-image-tensorflow.png" alt="Fourth Step" width="650">
</section>
</section>
<section>
<section>
<h2>Referências</h2>
</section>
<section>
<div style="text-align:justify;">
<span class="icons"> </span><a href="https://keras.io/">Keras Documentation</a><br>
<span class="icons"> </span><a href="https://www.tensorflow.org/">TensorFlow.org</a><br>
</div>
</section>
</section>
</div>
</div>
<script src="./revealjs/lib/js/head.min.js"></script>
<script src="./revealjs/js/reveal.js"></script>
<script type="text/javascript">
Reveal.initialize({
controls: true,
progress: true,
center: true,
transition: 'slide'
})
// Reveal.configure({backgroundTransition: 'zoom'})
</script>
</body>
</html>