Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
tensorflow
GitHub Repository: tensorflow/docs-l10n
Path: blob/master/site/pt-br/addons/tutorials/optimizers_conditionalgradient.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.

Otimizadores do TensorFlow Addons: ConditionalGradient

Visão geral

Este notebook demonstra como usar o Otimizador Conditional Gradient do pacote do Addons.

ConditionalGradient

A restrição dos parâmetros de uma rede neural mostrou ser vantajosa no treinamento devido a efeitos de regularização subjacentes. Com frequência, os parâmetros são restringidos por uma penalidade soft (que nunca garante a satisfação da restrição) ou por uma operação de projeção (que é computacionalmente cara). O otimizador Conditional gradient (GC), pelo contrário, aplica as restrições estritamente sem a necessidade de um passo caro de projeção. Ele minimiza uma aproximação linear do objetivo no conjunto de restrições. Neste notebook, você demonstra a aplicação da restrição da norma de Frobenius pelo otimizador CG no dataset MNIST. O CG já está disponível como uma API do TensorFlow. Confira mais detalhes sobre o otimizador em https://arxiv.org/pdf/1803.06453.pdf

Configuração

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

Crie o modelo

model_1 = 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

Defina uma função de callback personalizada

def frobenius_norm(m): """This function is to calculate the frobenius norm of the matrix of all layer's weight. Args: m: is a list of weights param for each layers. """ total_reduce_sum = 0 for i in range(len(m)): total_reduce_sum = total_reduce_sum + tf.math.reduce_sum(m[i]**2) norm = total_reduce_sum**0.5 return norm
CG_frobenius_norm_of_weight = [] CG_get_weight_norm = tf.keras.callbacks.LambdaCallback( on_epoch_end=lambda batch, logs: CG_frobenius_norm_of_weight.append( frobenius_norm(model_1.trainable_weights).numpy()))

Treine e avalie: usando CG como otimizador

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

# Compile the model model_1.compile( optimizer=tfa.optimizers.ConditionalGradient( learning_rate=0.99949, lambda_=203), # Utilize TFA optimizer loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) history_cg = model_1.fit( x_train, y_train, batch_size=batch_size, validation_data=(x_test, y_test), epochs=epochs, callbacks=[CG_get_weight_norm])

Treine e avalie: usando SGD como otimizador

model_2 = 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'), ])
SGD_frobenius_norm_of_weight = [] SGD_get_weight_norm = tf.keras.callbacks.LambdaCallback( on_epoch_end=lambda batch, logs: SGD_frobenius_norm_of_weight.append( frobenius_norm(model_2.trainable_weights).numpy()))
# Compile the model model_2.compile( optimizer=tf.keras.optimizers.SGD(0.01), # Utilize SGD optimizer loss=tf.keras.losses.SparseCategoricalCrossentropy(), metrics=['accuracy']) history_sgd = model_2.fit( x_train, y_train, batch_size=batch_size, validation_data=(x_test, y_test), epochs=epochs, callbacks=[SGD_get_weight_norm])

Norma de Frobenius de pesos: CG x SGD

A implementação atual do otimizador CG é baseada na Norma do Frobenius, considerando-a como regularizadora na função alvo. Portanto, você compara o efeito regularizado do CG com o otimizador SGD, que não aplicou o regularizador de Norma de Frobenius.

plt.plot( CG_frobenius_norm_of_weight, color='r', label='CG_frobenius_norm_of_weights') plt.plot( SGD_frobenius_norm_of_weight, color='b', label='SGD_frobenius_norm_of_weights') plt.xlabel('Epoch') plt.ylabel('Frobenius norm of weights') plt.legend(loc=1)

Exatidão do treinamento e da validação: CG x SGD

plt.plot(history_cg.history['accuracy'], color='r', label='CG_train') plt.plot(history_cg.history['val_accuracy'], color='g', label='CG_test') plt.plot(history_sgd.history['accuracy'], color='pink', label='SGD_train') plt.plot(history_sgd.history['val_accuracy'], color='b', label='SGD_test') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend(loc=4)