【问题标题】:How to use a pre-trained TensorFlow net in Keras loss function如何在 Keras 损失函数中使用预训练的 TensorFlow 网络
【发布时间】:2018-10-22 19:47:31
【问题描述】:

我有一个预训练的网络,我想使用它来评估我的 Keras 网络中的损失。 预训练网络是使用 TensorFlow 训练的,我只想将其用作损失计算的一部分。

我的自定义损失函数的代码目前是:

def custom_loss_func(y_true, y_pred):
   # Get saliency of both true and pred
   sal_true = deep_gaze.get_saliency_map(y_true)
   sal_pred = deep_gaze.get_saliency_map(y_pred)

   return K.mean(K.square(sal_true-sal_pred))

其中 deep_gaze 是一个对象,用于管理对我正在使用的外部预训练网络的访问。

是这样定义的:

class DeepGaze(object):
  CHECK_POINT = os.path.join(os.path.dirname(__file__), 'DeepGazeII.ckpt')  # DeepGaze II

def __init__(self):
    print('Loading Deep Gaze II...')

    with tf.Graph().as_default() as deep_gaze_graph:
        saver = tf.train.import_meta_graph('{}.meta'.format(self.CHECK_POINT))

        self.input_tensor = tf.get_collection('input_tensor')[0]
        self.log_density_wo_centerbias = tf.get_collection('log_density_wo_centerbias')[0]

    self.tf_session = tf.Session(graph=deep_gaze_graph)
    saver.restore(self.tf_session, self.CHECK_POINT)

    print('Deep Gaze II Loaded')

'''
Returns the saliency map of the input data. 
input format is a 4d array [batch_num, height, width, channel]
'''
def get_saliency_map(self, input_data):
    log_density_prediction = self.tf_session.run(self.log_density_wo_centerbias,
                                                 {self.input_tensor: input_data})

    return log_density_prediction

当我运行它时,我得到了错误:

TypeError:提要的值不能是 tf.Tensor 对象。可接受的提要值包括 Python 标量、字符串、列表、numpy ndarray 或 TensorHandles。

我做错了什么?有没有办法评估来自不同网络(由 Keras 使用 TensorFlow 后端制作)的 TensorFlow 对象上的网络。

提前致谢。

【问题讨论】:

    标签: python tensorflow keras deep-learning loss-function


    【解决方案1】:

    主要有两个问题:

    • 当你用input_data=y_true 调用get_saliency_map 时,你将一个张量input_data 提供给另一个张量self.input_tensor,这是无效的。此外,这些张量在图创建时不保存值,而是定义了最终将产生值的计算。

    • 1234563 .每个张量都必须根据图中的其他可用张量进行计算。

    此问题的解决方案是在您定义损失函数的图表中定义产生self.log_density_wo_centerbias 的模型,直接使用张量y_truey_pred 作为输入而不断开图表。

    【讨论】:

    • 嗨,首先,非常感谢您的快速回答。我有两个问题。首先是这将训练 log_density_wo_centerbias 中定义的模型,这是我不想要的。第二个是 log_density_wo_centerbias 被定义为 TensorFlow ckpt 文件,从我在网上找到的内容来看,没有方便的方法将其导入 Keras,还是有?
    • 您可以冻结模型的权重以避免更改它们。对于第二个问题,您需要在具有损失函数的图中重新定义 TensorFlow 模型,然后从该文件中加载权重。我认为没有其他可行的方法可以做到这一点。祝你好运!
    猜你喜欢
    • 1970-01-01
    • 2021-12-17
    • 2016-05-01
    • 2017-05-23
    • 2020-12-07
    • 1970-01-01
    • 2017-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多