【问题标题】:Tensorflow: Error while loading pre-trained ResNet modelTensorflow:加载预训练的 ResNet 模型时出错
【发布时间】:2019-03-01 22:13:16
【问题描述】:

我想使用来自 Tensorflow 的预训练 ResNet 模型。我下载了模型的code (resnet_v1.py) 和checkpoint (resnet_v1_50.ckpt) 文件here

我已经可以通过使用以下帖子解决错误ImportError: No module named 'nets':请参阅heretsveti_iko 的答案。

现在我收到以下错误,不知道该怎么办:

NotFoundError (see above for traceback): Restoring from checkpoint failed. 
This is most likely due to a Variable name or other graph key that is missing from the checkpoint. 
Please ensure that you have not altered the graph expected based on the checkpoint. Original error:

    Tensor name "resnet_v1_50/block1/unit_1/bottleneck_v1/conv1/biases" 
not found in checkpoint files /home/resnet_v1_50.ckpt
         [[node save/RestoreV2 (defined at my_resnet.py:34)  = 
RestoreV2[dtypes=[DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, ...,
DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT, DT_FLOAT], _device="/job:localhost
/replica:0/task:0/device:CPU:0"](_arg_save/Const_0_0, save/RestoreV2
/tensor_names, save/RestoreV2/shape_and_slices)]]

这是我尝试加载模型时使用的代码:

import numpy as np
import tensorflow as tf
import resnet_v1

# Restore variables of resnet model
slim = tf.contrib.slim

# Paths
network_dir = "home/resnet_v1_50.ckpt"

# Image dimensions
in_width, in_height, in_channels = 224, 224, 3

# Placeholder
X = tf.placeholder(tf.float32, [None, in_width, in_height, in_channels])

# Define network graph
logits, activations = resnet_v1.resnet_v1_50(X, is_training=False)
prediction = tf.argmax(logits, 1)

with tf.Session() as sess:
    variables_to_restore = slim.get_variables_to_restore()
    saver = tf.train.Saver(variables_to_restore)
    saver.restore(sess, network_dir) 

    # Restore variables
    variables = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)

    # Feed random image into resnet
    img = np.random.randn(1, in_width, in_height, in_channels)
    pred = sess.run(prediction, feed_dict={X:img})

谁能告诉我,为什么它不起作用?我必须如何更改我的代码才能使其运行?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    也许您可以使用来自tf.keras.applications 的 ResNet50?

    根据错误,如果您没有以任何方式更改图表,并且这是您的整个源代码,那么它可能真的非常难以调试。

    如果您选择理智的tf.keras.applications.resnet50 方式,您可以这样做:

    import tensorflow
    
    in_width, in_height, in_channels = 224, 224, 3
    
    pretrained_resnet = tensorflow.keras.applications.ResNet50(
        weights="imagenet",
        include_top=False,
        input_shape=(in_width, in_height, in_channels),
    )
    
    # You can freeze some layers if you want, depends on your task
    # Make "top" (last 3 layers below) whatever fits your task as well
    
    model = tensorflow.keras.models.Sequential(
        [
            pretrained_resnet,
            tensorflow.keras.layers.Flatten(),
            tensorflow.keras.layers.Dense(1024, activation="relu"),
            tensorflow.keras.layers.Dense(10, activation="softmax"),
        ]
    )
    
    print(model.summary())
    

    现在建议使用这种方法,尤其是考虑到即将推出的 Tensorflow 2.0、健全性和可读性。 顺便提一句。这个模型和Tensorflow提供的一样,都是从IIRC转过来的。

    您可以在链接文档和各种博客文章(如 this one 或其他网络资源)中阅读有关 tf.keras.applications 的更多信息。

    我如何在 Keras 中使用

    回答cmets的问题

    • How do I pass images to the network?:如果要进行预测,请使用model.predict(image),其中图像为np.array。就这么简单。

    • How do I access weights?: 好吧,这个更复杂...开玩笑,每一层都有.get_weights() 方法返回它的权重和偏差,你可以用for layer in model.layers() 遍历层。您也可以使用model.get_weights() 一次获取所有权重。

    总而言之,您将在比调试此问题更短的时间内学习 Keras,并在其中比在 Tensorflow 中更有效率。他们有30 seconds guide 是有原因的。

    顺便说一句。Tensorflow 默认提供 Keras,因此,Tensorflow 的 Keras 风格 TensorFlow 的一部分(不管这听起来多么令人困惑)。这就是我在示例中使用tensorflow 的原因。

    使用 Tensorflow 的 Hub 的解决方案

    您似乎可以使用集线器加载和微调 Resn​​et50,如 this link 中所述。

    【讨论】:

    • 我只是使用原始源代码加载了图表,没有对图表进行任何更改(我希望如此,至少)。我不熟悉 Keras,因此我只想使用 Tensorflow。如何将图像传递到网络?我还需要访问所有层的所有权重、偏差和激活。如何使用 Keras 做到这一点?
    • 更新了我的答案。 Keras 不是 Tensorflow,因此你可以学习、使用它,而且它不会以你的方式出现 + 有一个直观的 API。哦,如果这是你真正追求和需要的,你可以使用 tf.keras.estimator.model_to_estimator 将 Keras 的模型转换为 tf.Estimator
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-09
    相关资源
    最近更新 更多