Gradcam带制导的反向传播器,用于Tensorflow 2.0中的转移学习

阿韦武

在TF 2.0中将梯度可视化与转移学习结合使用时出现错误。梯度可视化可在不使用转移学习的模型上运行。

当我运行代码时,出现错误:

    assert str(id(x)) in tensor_dict, 'Could not compute output ' + str(x)
AssertionError: Could not compute output Tensor("block5_conv3/Identity:0", shape=(None, 14, 14, 512), dtype=float32)

当我运行下面的代码时出错。我认为命名约定或将基本模型vgg16的输入和输出连接到我要添加的层时存在问题。非常感谢您的帮助!

"""
Broken example when grad_model is created. 
"""
!pip uninstall tensorflow
!pip install tensorflow==2.0.0
import cv2
import numpy as np
import tensorflow as tf
from tensorflow.keras import layers
import matplotlib.pyplot as plt

IMAGE_PATH = '/content/cat.3.jpg'
LAYER_NAME = 'block5_conv3'
model_layer = 'vgg16'
CAT_CLASS_INDEX = 281

imsize = (224,224,3)

img = tf.keras.preprocessing.image.load_img(IMAGE_PATH, target_size=(224, 224))
plt.figure()
plt.imshow(img)
img = tf.io.read_file(IMAGE_PATH)
img = tf.image.decode_jpeg(img)
img = tf.cast(img, dtype=tf.float32)
# img = tf.keras.preprocessing.image.img_to_array(img)
img = tf.image.resize(img, (224,224))
img = tf.reshape(img, (1, 224,224,3))

input = layers.Input(shape=(imsize[0], imsize[1], imsize[2]))
base_model = tf.keras.applications.VGG16(include_top=False, weights='imagenet',
                                          input_shape=(imsize[0], imsize[1], imsize[2]))
# base_model.trainable = False
flat = layers.Flatten()
dropped = layers.Dropout(0.5)
global_average_layer = tf.keras.layers.GlobalAveragePooling2D()

fc1 = layers.Dense(16, activation='relu', name='dense_1')
fc2 = layers.Dense(16, activation='relu', name='dense_2')
fc3 = layers.Dense(128, activation='relu', name='dense_3')
prediction = layers.Dense(2, activation='softmax', name='output')
for layr in base_model.layers:
    if ('block5' in layr.name):

        layr.trainable = True
    else:
        layr.trainable = False

x = base_model(input)
x = global_average_layer(x)
x = fc1(x)
x = fc2(x)
x = prediction(x)

model = tf.keras.models.Model(inputs = input, outputs = x)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),
                  loss='binary_crossentropy',
                  metrics=['accuracy'])

这部分代码就是错误所在。我不确定标记输入和输出的正确方法是什么。

# Create a graph that outputs target convolution and output
grad_model = tf.keras.models.Model(inputs = [model.input, model.get_layer(model_layer).input], 
                                   outputs=[model.get_layer(model_layer).get_layer(LAYER_NAME).output,
                                            model.output])

print(model.get_layer(model_layer).get_layer(LAYER_NAME).output)
# Get the score for target class

# Get the score for target class
with tf.GradientTape() as tape:
    conv_outputs, predictions = grad_model(img)
    loss = predictions[:, 1]

以下部分用于绘制gradcam的热图。

print('Prediction shape:', predictions.get_shape())
# Extract filters and gradients
output = conv_outputs[0]
grads = tape.gradient(loss, conv_outputs)[0]

# Apply guided backpropagation
gate_f = tf.cast(output > 0, 'float32')
gate_r = tf.cast(grads > 0, 'float32')
guided_grads = gate_f * gate_r * grads

# Average gradients spatially
weights = tf.reduce_mean(guided_grads, axis=(0, 1))

# Build a ponderated map of filters according to gradients importance
cam = np.ones(output.shape[0:2], dtype=np.float32)

for index, w in enumerate(weights):
    cam += w * output[:, :, index]

# Heatmap visualization
cam = cv2.resize(cam.numpy(), (224, 224))
cam = np.maximum(cam, 0)
heatmap = (cam - cam.min()) / (cam.max() - cam.min())

cam = cv2.applyColorMap(np.uint8(255 * heatmap), cv2.COLORMAP_JET)

output_image = cv2.addWeighted(cv2.cvtColor(img.astype('uint8'), cv2.COLOR_RGB2BGR), 0.5, cam, 1, 0)

plt.figure()
plt.imshow(output_image)
plt.show()

我也在https://github.com/tensorflow/tensorflow/issues/37680上的github上向tensorflow团队询问了这个问题

阿韦武

我想到了。如果您设置模型以使用自己的图层扩展vgg16基本模型,而不是将基本模型插入到像图层这样的新模型中,那么它将起作用。首先建立模型,并确保声明input_tensor。

inp = layers.Input(shape=(imsize[0], imsize[1], imsize[2]))
base_model = tf.keras.applications.VGG16(include_top=False, weights='imagenet', input_tensor=inp,
                                          input_shape=(imsize[0], imsize[1], imsize[2]))

这样,我们就不必包括x=base_model(inp)要显示要输入的内容的行。该行已包含在中tf.keras.applications.VGG16(...)

与其将vgg16基本模型放入另一个模型中,还不如通过在基本模型本身上添加层来进行gradcam。我抓取了VGG16的最后一层(除去顶部)的输出,即池化层。

block5_pool = base_model.get_layer('block5_pool')
x = global_average_layer(block5_pool.output)
x = fc1(x)
x = prediction(x)

model = tf.keras.models.Model(inputs = inp, outputs = x)
model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=1e-4),
                  loss='binary_crossentropy',
                  metrics=['accuracy'])

现在,我将获取可视化层LAYER_NAME='block5_conv3'

# Create a graph that outputs target convolution and output
grad_model = tf.keras.models.Model(inputs = [model.input], 
                                   outputs=[model.output, model.get_layer(LAYER_NAME).output])

print(model.get_layer(LAYER_NAME).output)
# Get the score for target class

# Get the score for target class
with tf.GradientTape() as tape:
    predictions, conv_outputs = grad_model(img)
    loss = predictions[:, 1]
print('Prediction shape:', predictions.get_shape())
# Extract filters and gradients
output = conv_outputs[0]
grads = tape.gradient(loss, conv_outputs)[0]

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Tensorflow中的LSTM反向传播

来自分类Dev

Tensorflow-转移学习实施(语义分割)

来自分类Dev

使用Tensorflow(MobileNet)进行转移学习

来自分类Dev

反向传播在 Tensorflow 中不起作用

来自分类Dev

神经网络中2个隐藏层的反向传播和正向传播

来自分类Dev

在Tensorflow(Python)中使用初始模型进行转移学习

来自分类Dev

使用tensorflow进行InceptionV3和转移学习

来自分类Dev

转移学习Tensorflow.js大小/形状错误

来自分类Dev

Tensorflow中的反向传播(经过时间)代码

来自分类Dev

Tensorflow.js神经网络中的反向传播

来自分类Dev

TensorflowHub预训练的MobileNetV2更改输入形状并进行转移学习

来自分类Dev

从ADLS2转移到Compute Target速度非常慢的Azure机器学习

来自分类Dev

Neuroph:多层感知器反向传播学习不起作用

来自分类Dev

使用TensorFlow Hub进行学习转移:使用单个测试图像?

来自分类Dev

在张量流中馈送图像数据以进行转移学习

来自分类Dev

弹性反向传播中的错误?

来自分类Dev

反向传播中的梯度检查

来自分类Dev

在TF Summit 2020中实施``学习使用Tensorflow进行阅读''演讲-Tensorflow 2.1 / 2.2中的EncoderDecoder Seq2Seq模型-自定义火车步骤

来自分类Dev

用于Tensorflow 2中的自定义训练循环的Tensorboard

来自分类Dev

为什么我在tensorflow上进行转移学习的实现在几次迭代后就抛出一个错误?

来自分类Dev

在变分自动编码器中从解码器输入到编码器输出的反向传播

来自分类Dev

如何在 Elasticsearch 中添加用于故障转移的节点

来自分类Dev

Spring Boot 2 OIDC(OAuth2)客户端/资源服务器未在WebClient中传播访问令牌

来自分类Dev

为什么简单的2层神经网络无法学习0,0序列?

来自分类Dev

我如何使用tensorflow 2均衡学习率?

来自分类Dev

Tensorflow 2 LSTM模型无法使用序列学习

来自分类Dev

TensorFlow GradCAM-model.fit()-ValueError:形状(None,1)和(None,2)不兼容

来自分类Dev

Apache Flume 1.5在Hadoop 2 /自动故障转移群集配置中未提供预期的结果

来自分类Dev

Django中的机器学习(tensorflow / sklearn)?

Related 相关文章

  1. 1

    Tensorflow中的LSTM反向传播

  2. 2

    Tensorflow-转移学习实施(语义分割)

  3. 3

    使用Tensorflow(MobileNet)进行转移学习

  4. 4

    反向传播在 Tensorflow 中不起作用

  5. 5

    神经网络中2个隐藏层的反向传播和正向传播

  6. 6

    在Tensorflow(Python)中使用初始模型进行转移学习

  7. 7

    使用tensorflow进行InceptionV3和转移学习

  8. 8

    转移学习Tensorflow.js大小/形状错误

  9. 9

    Tensorflow中的反向传播(经过时间)代码

  10. 10

    Tensorflow.js神经网络中的反向传播

  11. 11

    TensorflowHub预训练的MobileNetV2更改输入形状并进行转移学习

  12. 12

    从ADLS2转移到Compute Target速度非常慢的Azure机器学习

  13. 13

    Neuroph:多层感知器反向传播学习不起作用

  14. 14

    使用TensorFlow Hub进行学习转移:使用单个测试图像?

  15. 15

    在张量流中馈送图像数据以进行转移学习

  16. 16

    弹性反向传播中的错误?

  17. 17

    反向传播中的梯度检查

  18. 18

    在TF Summit 2020中实施``学习使用Tensorflow进行阅读''演讲-Tensorflow 2.1 / 2.2中的EncoderDecoder Seq2Seq模型-自定义火车步骤

  19. 19

    用于Tensorflow 2中的自定义训练循环的Tensorboard

  20. 20

    为什么我在tensorflow上进行转移学习的实现在几次迭代后就抛出一个错误?

  21. 21

    在变分自动编码器中从解码器输入到编码器输出的反向传播

  22. 22

    如何在 Elasticsearch 中添加用于故障转移的节点

  23. 23

    Spring Boot 2 OIDC(OAuth2)客户端/资源服务器未在WebClient中传播访问令牌

  24. 24

    为什么简单的2层神经网络无法学习0,0序列?

  25. 25

    我如何使用tensorflow 2均衡学习率?

  26. 26

    Tensorflow 2 LSTM模型无法使用序列学习

  27. 27

    TensorFlow GradCAM-model.fit()-ValueError:形状(None,1)和(None,2)不兼容

  28. 28

    Apache Flume 1.5在Hadoop 2 /自动故障转移群集配置中未提供预期的结果

  29. 29

    Django中的机器学习(tensorflow / sklearn)?

热门标签

归档