Alan Barzilay

TensorFlow 2.0

Tensores

Um tensor é um array retangular n-dimensional e é o objeto mais basico do TensorFlow.

>>> tf.zeros([2,3,4])

<tf.Tensor: shape=(2, 3, 4), dtype=float32, numpy=
array([[[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]],

       [[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]]], dtype=float32)>

Tensores

Um tensor é um array retangular n-dimensional e é o objeto mais basico do TensorFlow.

>>> tf.ones([2,3,4])

<tf.Tensor: shape=(2, 3, 4), dtype=float32, numpy=
array([[[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]],

       [[1., 1., 1., 1.],
        [1., 1., 1., 1.],
        [1., 1., 1., 1.]]], dtype=float32)>
4

Shape: []

Sha pe: [3]

Shape: [3,2]

Como criar um Tensor?

>>> tf.constant([1,2,3])
<tf.Tensor: shape=(3,), dtype=int32, numpy=array([1, 2, 3], dtype=int32)>
>>> 

Como criar um Tensor?

>>> tf.constant([1,2,3], dtype=np.uint )
<tf.Tensor: shape=(3,), dtype=uint64, numpy=array([1, 2, 3], dtype=uint64)>
>>> 

Slicing

Você pode acessar o conteúdo de um tensor da mesma maneira que qualquer lista

>>> tensor = tf.constant([1,24,73])
>>> tensor[2]
<tf.Tensor: shape=(), dtype=int32, numpy=73>
>>> tensor[2].numpy()
73
>>> 

Constant

Variable

>>> tensor = tf.constant([1,2,3,4,5])
>>> tensor[1].assign(19)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'
>>> 
>>> tensor_var = tf.Variable([1,2,3,4,5])
>>> tensor_var[1].assign(19)
<tf.Variable 'UnreadVariable' shape=(5,) dtype=int32, numpy=array([ 1, 19,  3,  4,  5], dtype=int32)>
>>> 

Operações Básicas

>>> a = tf.constant([1,2,3,4,5])
>>> b = tf.constant([5,4,3,2,1])
>>> c = a + b
>>> print(c.numpy())
[6 6 6 6 6]
>>> 

Ragged

Sparce

Keras API

A biblioteca Keras foi absorvida pelo TensorFlow e se tornou sua API high-level oficial.

>>> from tensorflow import keras
>>> from tensorflow.keras import layers

Sequencial

Para modelos simples podemos usar a API sequencial para "empilhar" camadas.

>>> model = keras.Sequential(
...     [   keras.Input(shape=(7,)),
...         layers.Dense(6, activation="relu"),
...         layers.Dense(10, activation="sigmoid"),
...     ]
... )
>>> 

Como ficaria a declaração dessa rede?

>>> model = keras.Sequential(
...     [   keras.Input(shape=(4,)),
...         layers.Dense(5, activation="relu"),
...         layers.Dense(3, activation="relu"),
...         layers.Dense(1, activation="sigmoid"),
...     ]
... )
>>> 
>>> model.summary()
Model: "sequential_1"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_3 (Dense)              (None, 5)                 25        
_________________________________________________________________
dense_4 (Dense)              (None, 3)                 18        
_________________________________________________________________
dense_5 (Dense)              (None, 1)                 4         
=================================================================
Total params: 47
Trainable params: 47
Non-trainable params: 0
_________________________________________________________________
>>> 

Compilar

>>> model.compile(optimizer= 'rmsprop', loss='binary_crossentropy', metrics = None)

Treinar

>>> model.fit(x= dados_treino, y= labels_treino, batch_size=None, epochs=None)

Avaliar & Prever

>>> model.evaluate(dados_teste,labels_teste)
>>> model.predict(dados)
>>> model = keras.Sequential(
...     [   keras.Input(shape=(4,)),
...         layers.Dense(5, activation="relu"),
...         layers.Dense(3, activation="relu"),
...         layers.Dense(1, activation="sigmoid"),
...     ]
... )
>>> model.compile(optimizer= 'rmsprop', loss='binary_crossentropy' , metrics = None)
>>> model.fit(x= dados_treino, y= labels_treino, batch_size=None, epochs=None)
>>> model.evaluate(dados_teste,labels_teste)
>>> model.predict(dados)

TF 1.X  Vs. TF 2.0

  • Keras API
  • tf.contrib
  • Eager Execution