def test_get_gradient(self): model = keras.applications.MobileNetV2() gradient_model = keras.models.Sequential() gradient_model.add(model) gradient_model.add(Categorical(7)) gradient_model.get_config() get_gradient(gradient_model, np.random.random((1, 224, 224, 3))) get_gradient(gradient_model, np.random.random((1, 224, 224, 3)), targets=model.get_layer('bn_Conv1').trainable_weights[0])
def test_cut_model(self): model = keras.applications.MobileNetV2() head, tail = split_model_by_layer(model, 'block_5_add') gradient_model = keras.models.Sequential() gradient_model.add(tail) gradient_model.add(Categorical(7)) gradients = get_gradient([head, gradient_model], np.random.random((1, 224, 224, 3))) self.assertEqual(2, len(gradients))
def process(relu_type, target_class): # Build model and get gradients model = keras.applications.MobileNetV2() if relu_type is not None: model = replace_relu(model, relu_type=relu_type) gradient_model = keras.models.Sequential() gradient_model.add(model) gradient_model.add(Categorical(target_class)) gradients = get_gradient(gradient_model, inputs) # Visualize gradients gradient = gradients.numpy()[0] gradient = (gradient - np.min(gradient)) / (np.max(gradient) - np.min(gradient) + 1e-4) gradient = (gradient * 255.0).astype(np.uint8) return Image.fromarray(gradient)