【问题标题】:what is the corresponding function of K.gradients for tensorflow 2.0?tensorflow 2.0的K.gradients对应的功能是什么?
【发布时间】:2019-06-27 05:20:12
【问题描述】:

我想用tensorflow2.0可视化分类结果。对于keras,cam需要如下代码:

import tensorflow as tf
import keras.backend as K
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input, decodpredictions
import numpy as np
import cv2

img_path = 'image/test.jpg'

model = VGG16(weights='imagenet')
img = image.load_img('image/test.jpg', target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Predicted:', decode_predictions(preds, top=3)[0])
print np.argmax(preds[0])
african_elephant_output = model.output[:, 386]
last_conv_layer = model.get_layer('block5_conv3')
grads = K.gradients(african_elephant_output, last_conv_layer.output)[0]

但是我用tensorflow2.0的时候,好像没有这个渐变功能。那么tensorflow2.0的K.gradients对应的函数是什么?

【问题讨论】:

  • 您遇到了什么实际错误?
  • TypeError: gradients_v2() 得到了一个意外的关键字参数“colocate_gradients_with_ops”。 @Matias Valdenegro
  • 你用的是keras还是tf.keras?因为普通的 Keras 与 Tensorflow 2.0 alpha/beta 不兼容。
  • 我正在使用 keras。但 tf.keras 也会出错。我已经更新了我的问题并添加了更多代码。

标签: tensorflow keras tf.keras


【解决方案1】:

这里:

import keras.backend as K
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.preprocessing import image
from tensorflow.keras.applications.vgg16 import preprocess_input, decodpredictions

您正在混合使用彼此不兼容的 keras 和 tf.keras 软件包。您应该从tf.keras 导入后端:

import tensorflow.keras.backend as K

【讨论】:

  • 好像不行:RuntimeError: tf.gradients is not supported when eager execution is enabled. Use tf.GradientTape instead.
  • @tidy 我建议不要使用 TensorFlow 2.0,因为它仍然是测试版,还有很多 bug。
  • 好的,感谢您的帮助@Matias Valdenegro。我会试试TensorFlow1.x。
猜你喜欢
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 2018-06-08
相关资源
最近更新 更多