1
Introdução a Machine Learning e
TensorFlow
Guilherme Campos
2
Agenda
Conceitos
• Machine Learning
• Tipos de aprendizado
• Deep Learning
TensorFlow
• O que é?
• Grafos de execução
• APIs
• Tensorboard
3
Conceitos
4
Machine Learning
Machine
Learning
Inteligência
Artificial
Deep
Learning
5
Exemplo
• Como classificar uma imagem como Maçã ou Laranja?
6
Exemplo
7
Exemplo
8
Exemplo
99
Novo problema? Comece tudo de novo!
10
Machine Learning
11
Machine Learning – Aprendizagem de Máquina
• Aprendizagem Supervisionado
• Aprendizagem Não-supervisionado
• Aprendizagem por Reforço
12
Aprendizagem supervisionada
Caracteristicas Rotulo
1.jpg Maçã
2.jpg Laranja
... ...
Classificador
Buscar um padrão
Conjunto de dados
13
Aprendizagem supervisionada
• Árvores de decisão
• Regressão Linear/Logística
• Support Vector Machines
• Redes Neurais
• K- Vizinhos mais próximos
14
from sklearn import datasets, svm, metrics
import matplotlib.pyplot as plt
# Carrega o dataset
digits = datasets.load_digits()
# transforma a imagem em vetor
n_samples = len(digits.images)
data = digits.images.reshape((n_samples, -1))
x_train = data[:n_samples / 2]
y_train = digits.target[:n_samples / 2]
# cria um classificador SVM
classifier = svm.SVC(gamma=0.001)
# realiza o ajuste dos dados
classifier.fit(x_train, y_train)
esperado = digits.target[n_samples / 2:]
predito = classifier.predict(data[n_samples / 2:])
15
Aprendizagem não supervisionada
Caracteristicas Rotulo
1.jpg ?
2.jpg ?
... ???
Conjunto de dados
Agrupamento
Buscar um padrão
16
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
n_samples = 1500
random_state = 170
X, y = make_blobs(n_samples=n_samples, random_state=random_state)
y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X)
plt.subplot(211)
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.title("Iniciado com 3 centroides")
y_pred = KMeans(n_clusters=2, random_state=random_state).fit_predict(X)
plt.subplot(212)
plt.scatter(X[:, 0], X[:, 1], c=y_pred)
plt.title("Iniciado com 2 centroides")
plt.show()
17
Aprendizagem por reforço
Estado Ação Recompensa
??? ? ?
??? ? ?
... ??? ???
Conjunto de estados
Realiza uma ação
Estado Ação Recompensa
1 UP 0
??? ? ?
... ??? ???
Conjunto de estados
18
Aprendizagem por reforço
• oi
MarI/O
OpenAI Gym
19
Deep Learning
20
14/09/2014
21
O você vê.
50 68 78 95
...
67 21 23 42
71 59 58 31
47 19 29 39
...
O que o computador “vê”.
pixels
22
import numpy as np
import keras
from keras.preprocessing import image
from keras.applications.inception_v3 import preprocess_input,
decode_predictions
model = keras.applications.InceptionV3(weights='imagenet')
img_path = 'aracari_castanho.jpg'
img = image.load_img(img_path, target_size=(299,299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
# decode
print('Predicted:', decode_predictions(preds, top=3)[0])
Toucan 71,27%
Hornbill 16,84%
School Bus 1,65%
Predicted: [('n01843383', 'toucan', 0.71278381), ('n01829413', 'hornbill', 0.16843531), ('n04146614', 'school_bus', 0.01657751)]
23
import numpy as np
import keras
from keras.preprocessing import image
from keras.applications.inception_v3 import preprocess_input,
decode_predictions
model = keras.applications.InceptionV3(weights='imagenet')
img_path = 'arvore.jpg'
img = image.load_img(img_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
# decode
print('Predicted:', decode_predictions(preds, top=3)[0])
Lakeside 21,76%
Church 8,03%
Valley 7,81%
Predicted: [('n09332890', 'lakeside', 0.21762265), ('n03028079', 'church', 0.080397919), ('n09468604', 'valley', 0.078168809)]
24
import numpy as np
import keras
from keras.preprocessing import image
from keras.applications.inception_v3 import preprocess_input,
decode_predictions
model = keras.applications.InceptionV3(weights='imagenet')
img_path = 'alvaro.jpg'
img = image.load_img(img_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
# decode
print('Predicted:', decode_predictions(preds, top=3)[0])
Jersey 51,26%
Wig 2,58%
Drumstick 2,12%
Predicted: [('n03595614', 'jersey', 0.51262307), ('n04584207', 'wig', 0.025850503), ('n03250847', 'drumstick', 0.021243958)]
25
O que é deep learning?
• Aprendizagem de representação dos dados.
• Utiliza algoritmos hierárquicos com varias camadas.
• Se alimentado com muitos dados consegue generalizar o problema.
26
Curto histórico
27
28
29
Deep Learning
Mais
Processamento
Mais dados Novos
Modelos
MNIST
YouTube-8M
30
Deep Learning - Aplicações
• Reconhecimento de voz
• Visão computacional
• Processamento de linguagem natural
31
Reconhecimento de voz
32
Visão Computacional
33
Processamento de linguagem natural
34
TensorFlow
35
TensorFlow Playground - http://playground.tensorflow.org/
36
TensorFlow
•Biblioteca de machine Learning Open Source
•Funções especificas para Deep Learning
•O seu uso vai do desenvolvimento a produção
37
TensorFlow
• Portável e escalável
Laptop Datacenters Android iOS Raspberry Pi
38
Um vetor multidimensional
Grafo de operações
39
• Vetor n-dimensional, onde n = [0, 1, 2, 3, ...]
Escalar S = 42
Vetor V = [1, 2, 3, 4]
Matriz M = [[1, 0],[0, 1]]
Cubo ...
40
• Grafo de operações realizados nos tensores
• Grafo acíclico dirigido
• Grafo é definido em uma linguagem de nível mais alto (Python)
• Grafo é compilado e otimizado
• Grafo é executado nos dispositivos disponíveis (CPU, GPU)
• Dados (tensores) fluem através do grafo
41
Exemplo de criação do grafo
import tensorflow as tf
42
Exemplo de criação do grafo
Constant
(2.0)
a = 2
import tensorflow as tf
a = tf.constant(2.0)
43
Exemplo de criação do grafo
Constant
(2.0)
a = 2
Constant
(3.0)
b = 3
import tensorflow as tf
a = tf.constant(2.0)
b = tf.constant(3.0)
44
Exemplo de criação do grafo
Constant
(2.0)
a = 2
Constant
(3.0)
b = 3
Operação
Multiplicação
c = a * b
import tensorflow as tf
a = tf.constant(2.0)
b = tf.constant(3.0)
c = tf.multiply(a, b)
45
Exemplo de criação do grafo
import tensorflow as tf
a = tf.constant(2.0)
b = tf.constant(3.0)
c = tf.multiply(a, b)
with tf.Session() as sess:
print(sess.run(c))
Constant
(2.0)
a = 2
Constant
(3.0)
b = 3
Operação
Multiplicação
c = a * b
Output Retorna 6
46
Qual problema o TensorFlow resolve?
• Usar varias CPU e GPUs para treinar os modelos
• Problema: Escrever código otimizado e distribuído é difícil!
• Como resolver?
47
Arquitetura do TensorFlow
TensorFlow Core Execution Engine (C++)
CPU GPU Android iOS ...
Python Frontend C++ Frontend Java Frontend ...
48
Vamos ver um exemplo
MNIST
28x28
pixels
784 neurônios
na entrada
Input Layer Hidden Layers Output Layer
3 camadas:
32 neurônios
128 neurônios
32 neurônios
10 neurônios
na saída
49
Low Level API
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
mnist = read_data_sets("MNIST_data/", one_hot=True)
def create_layer(name, x_tensor, num_outputs):
shape = x_tensor.get_shape().as_list()[1:]
with tf.name_scope(name):
weights = tf.Variable(tf.random_normal([shape[0], num_outputs], stddev=0.1), name='Weights')
bias = tf.Variable(tf.zeros(num_outputs), name='biases')
fc = tf.add(tf.matmul(x_tensor, weights), bias)
fc = tf.nn.relu(fc)
tf.summary.histogram('histogram', fc)
return fc
sess = tf.InteractiveSession()
50
Low Level API
x = tf.placeholder(tf.float32, shape=[None,784])
y_ = tf.placeholder(tf.float32, shape=[None,10])
with tf.name_scope('dnn'):
h0 = create_layer('hidden_0', x, 32)
h1 = create_layer('hidden_1', h0, 128)
h2 = create_layer('hidden_2', h1, 32)
with tf.name_scope('logit'):
W = tf.Variable(tf.zeros([32, 10]), name='weights')
b = tf.Variable(tf.zeros([10]),name='biases')
y = tf.matmul(h2,W) + b
tf.summary.histogram('histogram', y)
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_))
51
Low Level API
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1), name='correct_prediciton')
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy')
tf.summary.scalar('accuracy',accuracy)
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter('/tmp/test/train',sess.graph)
test_writer = tf.summary.FileWriter('/tmp/test/test')
sess.run(tf.global_variables_initializer())
52
Low Level API
for i in range(2000):
if i%10 ==0:
summary, acc = sess.run([merged, accuracy],feed_dict={x: mnist.test.images, y_: mnist.test.labels})
test_writer.add_summary(summary,i)
print('Step: {}, Accuracy: {}'.format(i,acc))
else:
batch = mnist.train.next_batch(100)
summary, _ = sess.run([merged, train_step], feed_dict={x: batch[0], y_: batch[1]})
train_writer.add_summary(summary, i)
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
Acurácia final: 0.9645
53
High Level API
def generate_input_fn(dataset, batch_size=BATCH_SIZE):
def _input_fn():
X = tf.constant(dataset.images)
Y = tf.constant(dataset.labels.astype(numpy.int64))
image_batch, label_batch = tf.train.shuffle_batch([X,Y], batch_size=batch_size, capacity=8*batch_size,
min_after_dequeue=4*batch_size, enqueue_many=True)
return {'pixels': image_batch} , label_batch
return _input_fn
mnist = read_data_sets("MNIST_data/", one_hot=False)
feature_columns = [tf.contrib.layers.real_valued_column("pixels", dimension=784)]
classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, hidden_units=[32, 128, 32],
n_classes=10, model_dir="/tmp/mnist_model_2")
classifier.fit(input_fn=generate_input_fn(mnist.train, batch_size=100), steps=2000)
accuracy_score = classifier.evaluate(input_fn=generate_input_fn(mnist.test, batch_size=100), steps=2000)['accuracy']
print('DNN Classifier Accuracy: {0:f}'.format(accuracy_score))
DNN Classifier Accuracy: 0.9635
54
Keras
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import RMSprop
from tensorflow.contrib.learn.python.learn.datasets
.mnist import read_data_sets
mnist = read_data_sets("MNIST_data/", one_hot=True)
batch_size = 100
epochs = 20
x_train, y_train = mnist.train.next_batch(50000)
x_test, y_test = mnist.test.next_batch(10000)
model = Sequential()
model.add(Dense(32, activation='relu', input_shape=(784,)))
model.add(Dense(128, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(10, activation='softmax'))
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy'])
history = model.fit(x_train, y_train, batch_size=batch_size,
verbose=1, validation_data=(x_test, y_test))
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
Test accuracy: 0.9685
55
TensorBoard
5656
Obrigado!
57
Referências e links
• http://playground.tensorflow.org/
• https://www.tensorflow.org/
• https://br.udacity.com/
• Machine Learning and TensorFlow:
• https://pt.slideshare.net/jpapo/machine-learning-tensor-flow
• Hands-on Tensorboard:
• https://www.youtube.com/watch?v=eBbEDRsCmv4&t=5s
• Intro to TensorFlow @ GDG global summit 2016:
• https://www.youtube.com/watch?v=SMltx_mHFsY&t=2s
• Adam Geitgey: Machine Learning is Fun!
• https://medium.com/@ageitgey/machine-learning-is-fun-80ea3ec3c471#.khzmtikoz

Introdução a Machine Learning e TensorFlow

  • 1.
    1 Introdução a MachineLearning e TensorFlow Guilherme Campos
  • 2.
    2 Agenda Conceitos • Machine Learning •Tipos de aprendizado • Deep Learning TensorFlow • O que é? • Grafos de execução • APIs • Tensorboard
  • 3.
  • 4.
  • 5.
    5 Exemplo • Como classificaruma imagem como Maçã ou Laranja?
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
    11 Machine Learning –Aprendizagem de Máquina • Aprendizagem Supervisionado • Aprendizagem Não-supervisionado • Aprendizagem por Reforço
  • 12.
    12 Aprendizagem supervisionada Caracteristicas Rotulo 1.jpgMaçã 2.jpg Laranja ... ... Classificador Buscar um padrão Conjunto de dados
  • 13.
    13 Aprendizagem supervisionada • Árvoresde decisão • Regressão Linear/Logística • Support Vector Machines • Redes Neurais • K- Vizinhos mais próximos
  • 14.
    14 from sklearn importdatasets, svm, metrics import matplotlib.pyplot as plt # Carrega o dataset digits = datasets.load_digits() # transforma a imagem em vetor n_samples = len(digits.images) data = digits.images.reshape((n_samples, -1)) x_train = data[:n_samples / 2] y_train = digits.target[:n_samples / 2] # cria um classificador SVM classifier = svm.SVC(gamma=0.001) # realiza o ajuste dos dados classifier.fit(x_train, y_train) esperado = digits.target[n_samples / 2:] predito = classifier.predict(data[n_samples / 2:])
  • 15.
    15 Aprendizagem não supervisionada CaracteristicasRotulo 1.jpg ? 2.jpg ? ... ??? Conjunto de dados Agrupamento Buscar um padrão
  • 16.
    16 import matplotlib.pyplot asplt from sklearn.cluster import KMeans from sklearn.datasets import make_blobs n_samples = 1500 random_state = 170 X, y = make_blobs(n_samples=n_samples, random_state=random_state) y_pred = KMeans(n_clusters=3, random_state=random_state).fit_predict(X) plt.subplot(211) plt.scatter(X[:, 0], X[:, 1], c=y_pred) plt.title("Iniciado com 3 centroides") y_pred = KMeans(n_clusters=2, random_state=random_state).fit_predict(X) plt.subplot(212) plt.scatter(X[:, 0], X[:, 1], c=y_pred) plt.title("Iniciado com 2 centroides") plt.show()
  • 17.
    17 Aprendizagem por reforço EstadoAção Recompensa ??? ? ? ??? ? ? ... ??? ??? Conjunto de estados Realiza uma ação Estado Ação Recompensa 1 UP 0 ??? ? ? ... ??? ??? Conjunto de estados
  • 18.
  • 19.
  • 20.
  • 21.
    21 O você vê. 5068 78 95 ... 67 21 23 42 71 59 58 31 47 19 29 39 ... O que o computador “vê”. pixels
  • 22.
    22 import numpy asnp import keras from keras.preprocessing import image from keras.applications.inception_v3 import preprocess_input, decode_predictions model = keras.applications.InceptionV3(weights='imagenet') img_path = 'aracari_castanho.jpg' img = image.load_img(img_path, target_size=(299,299)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode print('Predicted:', decode_predictions(preds, top=3)[0]) Toucan 71,27% Hornbill 16,84% School Bus 1,65% Predicted: [('n01843383', 'toucan', 0.71278381), ('n01829413', 'hornbill', 0.16843531), ('n04146614', 'school_bus', 0.01657751)]
  • 23.
    23 import numpy asnp import keras from keras.preprocessing import image from keras.applications.inception_v3 import preprocess_input, decode_predictions model = keras.applications.InceptionV3(weights='imagenet') img_path = 'arvore.jpg' img = image.load_img(img_path, target_size=(299, 299)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode print('Predicted:', decode_predictions(preds, top=3)[0]) Lakeside 21,76% Church 8,03% Valley 7,81% Predicted: [('n09332890', 'lakeside', 0.21762265), ('n03028079', 'church', 0.080397919), ('n09468604', 'valley', 0.078168809)]
  • 24.
    24 import numpy asnp import keras from keras.preprocessing import image from keras.applications.inception_v3 import preprocess_input, decode_predictions model = keras.applications.InceptionV3(weights='imagenet') img_path = 'alvaro.jpg' img = image.load_img(img_path, target_size=(299, 299)) x = image.img_to_array(img) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) # decode print('Predicted:', decode_predictions(preds, top=3)[0]) Jersey 51,26% Wig 2,58% Drumstick 2,12% Predicted: [('n03595614', 'jersey', 0.51262307), ('n04584207', 'wig', 0.025850503), ('n03250847', 'drumstick', 0.021243958)]
  • 25.
    25 O que édeep learning? • Aprendizagem de representação dos dados. • Utiliza algoritmos hierárquicos com varias camadas. • Se alimentado com muitos dados consegue generalizar o problema.
  • 26.
  • 27.
  • 28.
  • 29.
    29 Deep Learning Mais Processamento Mais dadosNovos Modelos MNIST YouTube-8M
  • 30.
    30 Deep Learning -Aplicações • Reconhecimento de voz • Visão computacional • Processamento de linguagem natural
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
    35 TensorFlow Playground -http://playground.tensorflow.org/
  • 36.
    36 TensorFlow •Biblioteca de machineLearning Open Source •Funções especificas para Deep Learning •O seu uso vai do desenvolvimento a produção
  • 37.
    37 TensorFlow • Portável eescalável Laptop Datacenters Android iOS Raspberry Pi
  • 38.
  • 39.
    39 • Vetor n-dimensional,onde n = [0, 1, 2, 3, ...] Escalar S = 42 Vetor V = [1, 2, 3, 4] Matriz M = [[1, 0],[0, 1]] Cubo ...
  • 40.
    40 • Grafo deoperações realizados nos tensores • Grafo acíclico dirigido • Grafo é definido em uma linguagem de nível mais alto (Python) • Grafo é compilado e otimizado • Grafo é executado nos dispositivos disponíveis (CPU, GPU) • Dados (tensores) fluem através do grafo
  • 41.
    41 Exemplo de criaçãodo grafo import tensorflow as tf
  • 42.
    42 Exemplo de criaçãodo grafo Constant (2.0) a = 2 import tensorflow as tf a = tf.constant(2.0)
  • 43.
    43 Exemplo de criaçãodo grafo Constant (2.0) a = 2 Constant (3.0) b = 3 import tensorflow as tf a = tf.constant(2.0) b = tf.constant(3.0)
  • 44.
    44 Exemplo de criaçãodo grafo Constant (2.0) a = 2 Constant (3.0) b = 3 Operação Multiplicação c = a * b import tensorflow as tf a = tf.constant(2.0) b = tf.constant(3.0) c = tf.multiply(a, b)
  • 45.
    45 Exemplo de criaçãodo grafo import tensorflow as tf a = tf.constant(2.0) b = tf.constant(3.0) c = tf.multiply(a, b) with tf.Session() as sess: print(sess.run(c)) Constant (2.0) a = 2 Constant (3.0) b = 3 Operação Multiplicação c = a * b Output Retorna 6
  • 46.
    46 Qual problema oTensorFlow resolve? • Usar varias CPU e GPUs para treinar os modelos • Problema: Escrever código otimizado e distribuído é difícil! • Como resolver?
  • 47.
    47 Arquitetura do TensorFlow TensorFlowCore Execution Engine (C++) CPU GPU Android iOS ... Python Frontend C++ Frontend Java Frontend ...
  • 48.
    48 Vamos ver umexemplo MNIST 28x28 pixels 784 neurônios na entrada Input Layer Hidden Layers Output Layer 3 camadas: 32 neurônios 128 neurônios 32 neurônios 10 neurônios na saída
  • 49.
    49 Low Level API importtensorflow as tf from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets mnist = read_data_sets("MNIST_data/", one_hot=True) def create_layer(name, x_tensor, num_outputs): shape = x_tensor.get_shape().as_list()[1:] with tf.name_scope(name): weights = tf.Variable(tf.random_normal([shape[0], num_outputs], stddev=0.1), name='Weights') bias = tf.Variable(tf.zeros(num_outputs), name='biases') fc = tf.add(tf.matmul(x_tensor, weights), bias) fc = tf.nn.relu(fc) tf.summary.histogram('histogram', fc) return fc sess = tf.InteractiveSession()
  • 50.
    50 Low Level API x= tf.placeholder(tf.float32, shape=[None,784]) y_ = tf.placeholder(tf.float32, shape=[None,10]) with tf.name_scope('dnn'): h0 = create_layer('hidden_0', x, 32) h1 = create_layer('hidden_1', h0, 128) h2 = create_layer('hidden_2', h1, 32) with tf.name_scope('logit'): W = tf.Variable(tf.zeros([32, 10]), name='weights') b = tf.Variable(tf.zeros([10]),name='biases') y = tf.matmul(h2,W) + b tf.summary.histogram('histogram', y) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_))
  • 51.
    51 Low Level API train_step= tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1), name='correct_prediciton') accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32), name='accuracy') tf.summary.scalar('accuracy',accuracy) merged = tf.summary.merge_all() train_writer = tf.summary.FileWriter('/tmp/test/train',sess.graph) test_writer = tf.summary.FileWriter('/tmp/test/test') sess.run(tf.global_variables_initializer())
  • 52.
    52 Low Level API fori in range(2000): if i%10 ==0: summary, acc = sess.run([merged, accuracy],feed_dict={x: mnist.test.images, y_: mnist.test.labels}) test_writer.add_summary(summary,i) print('Step: {}, Accuracy: {}'.format(i,acc)) else: batch = mnist.train.next_batch(100) summary, _ = sess.run([merged, train_step], feed_dict={x: batch[0], y_: batch[1]}) train_writer.add_summary(summary, i) print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels})) Acurácia final: 0.9645
  • 53.
    53 High Level API defgenerate_input_fn(dataset, batch_size=BATCH_SIZE): def _input_fn(): X = tf.constant(dataset.images) Y = tf.constant(dataset.labels.astype(numpy.int64)) image_batch, label_batch = tf.train.shuffle_batch([X,Y], batch_size=batch_size, capacity=8*batch_size, min_after_dequeue=4*batch_size, enqueue_many=True) return {'pixels': image_batch} , label_batch return _input_fn mnist = read_data_sets("MNIST_data/", one_hot=False) feature_columns = [tf.contrib.layers.real_valued_column("pixels", dimension=784)] classifier = tf.contrib.learn.DNNClassifier(feature_columns=feature_columns, hidden_units=[32, 128, 32], n_classes=10, model_dir="/tmp/mnist_model_2") classifier.fit(input_fn=generate_input_fn(mnist.train, batch_size=100), steps=2000) accuracy_score = classifier.evaluate(input_fn=generate_input_fn(mnist.test, batch_size=100), steps=2000)['accuracy'] print('DNN Classifier Accuracy: {0:f}'.format(accuracy_score)) DNN Classifier Accuracy: 0.9635
  • 54.
    54 Keras from keras.models importSequential from keras.layers import Dense from keras.optimizers import RMSprop from tensorflow.contrib.learn.python.learn.datasets .mnist import read_data_sets mnist = read_data_sets("MNIST_data/", one_hot=True) batch_size = 100 epochs = 20 x_train, y_train = mnist.train.next_batch(50000) x_test, y_test = mnist.test.next_batch(10000) model = Sequential() model.add(Dense(32, activation='relu', input_shape=(784,))) model.add(Dense(128, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(10, activation='softmax')) model.summary() model.compile(loss='categorical_crossentropy', optimizer=RMSprop(), metrics=['accuracy']) history = model.fit(x_train, y_train, batch_size=batch_size, verbose=1, validation_data=(x_test, y_test)) score = model.evaluate(x_test, y_test, verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) Test accuracy: 0.9685
  • 55.
  • 56.
  • 57.
    57 Referências e links •http://playground.tensorflow.org/ • https://www.tensorflow.org/ • https://br.udacity.com/ • Machine Learning and TensorFlow: • https://pt.slideshare.net/jpapo/machine-learning-tensor-flow • Hands-on Tensorboard: • https://www.youtube.com/watch?v=eBbEDRsCmv4&t=5s • Intro to TensorFlow @ GDG global summit 2016: • https://www.youtube.com/watch?v=SMltx_mHFsY&t=2s • Adam Geitgey: Machine Learning is Fun! • https://medium.com/@ageitgey/machine-learning-is-fun-80ea3ec3c471#.khzmtikoz