Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/pt-br/addons/tutorials/optimizers_lazyadam.ipynb
25118 views
Kernel: Python 3
#@title Licensed under the Apache License, Version 2.0 # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.

Visão geral

Este notebook demonstra como usar o otimizador lazy adam do pacote do Addons.

LazyAdam

LazyAdam é uma variante do otimizador Adam que lida com atualizações esparsas com mais eficiência. O algoritmo Adam original mantém dois acumuladores de média móvel para cada variável que pode ser treinada. Os acumuladores são atualizados a cada passo. Essa classe fornece tratamento mais lazy de atualizações de gradientes para variáveis esparsas. Ela só atualiza acumuladores de média móvel para índices de variáveis esparsas que aparecem no lote atual, em vez de atualizar os acumuladores para todos os índices. Em comparação com o otimizador Adam original, ela pode fornecer grandes melhorias no rendimento do treinamento do modelo para algumas aplicações. No entanto, ela fornece uma semântica levemente diferente do algoritmo Adam original, e pode levar a diferentes resultados empíricos.

Configuração

!pip install -U tensorflow-addons
import tensorflow as tf import tensorflow_addons as tfa
# Hyperparameters batch_size=64 epochs=10

Crie o modelo

model = tf.keras.Sequential([ tf.keras.layers.Dense(64, input_shape=(784,), activation='relu', name='dense_1'), tf.keras.layers.Dense(64, activation='relu', name='dense_2'), tf.keras.layers.Dense(10, activation='softmax', name='predictions'), ])

Prepare os dados

# Load MNIST dataset as NumPy arrays dataset = {} num_validation = 10000 (x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data() # Preprocess the data x_train = x_train.reshape(-1, 784).astype('float32') / 255 x_test = x_test.reshape(-1, 784).astype('float32') / 255

Treine e avalie

Basta substituir os otimizadores típicos do Keras pelo novo otimizador do tfa

# Compile the model model.compile( optimizer=tfa.optimizers.LazyAdam(0.001), # Utilize TFA optimizer loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) # Train the network history = model.fit( x_train, y_train, batch_size=batch_size, epochs=epochs)
# Evaluate the network print('Evaluate on test data:') results = model.evaluate(x_test, y_test, batch_size=128, verbose = 2) print('Test loss = {0}, Test acc: {1}'.format(results[0], results[1]))