【问题标题】:Why does my saved Tensorflow model predict nonsense when I restore it?为什么我保存的 Tensorflow 模型在恢复时会预测废话?
【发布时间】:2020-01-19 11:57:25
【问题描述】:

我在 Tensorflow 中训练了一个卷积神经网络,它分析图像并计算其中的对象,并将其保存以备后用。现在我正在尝试恢复模型并预测切割成图块的图像的值。不过,我得到的是无意义的值,并且每个图块的数字几乎相同。每个加载的模型给出一个特定值的数字,每个图像相同,但每个模型不同。 我在想,也许我使用了恢复模型中的错误张量? 这是我的代码的摘录:

x = tf.placeholder(tf.float32, [None, 98, 98, 3], name='x')
y = tf.placeholder(tf.float32, [None, ], name='y') 

# create two convolutional layers: layer1 and layer2

s3 = create_conv_layer_for_sum(layer2, f2, f3, [5, 5], 2, outf_sum, name='s_layer3')
y_pred = s3

error = tf.pow((y - y_pred), 2)
# other error measures also present
optimiser = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(error)
init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    # train the model here
    saver = tf.train.Saver()
        save_path = saver.save(sess, "models/model"+str(num)+"/model.ckpt")


def create_conv_layer_for_sum(input_data, num_input_channels, num_filters, filter_shape, stride, out_fction, name):
    # ...
    sum = tf.reduce_sum(transformed, axis=[1, 2, 3], name=name+'_output')
    return sum 

这部分是训练和保存。 然后我恢复模型:

    sess = tf.Session()

    saver = tf.train.import_meta_graph('models/' + model + '/model.ckpt.meta')
    saver.restore(sess, 'models/' + model + '/model.ckpt')

    inputData = CNNutils.load_photo(photo, 98)  # cuts photo into squares and stacks those as a numpy array

    graph = tf.get_default_graph()

    x = graph.get_tensor_by_name('x:0')

    s3 = graph.get_tensor_by_name('s_layer3_output:0')

    y_pred = tf.reduce_sum(s3)

    pred, sum3 = sess.run([y_pred, s3], feed_dict={x: inputData})
    print(pred)
    print(sum3) 

s3 应该是最后一层的输出,然后y_pred 将来自各个图块的整个图像的预测相加。

如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: python tensorflow machine-learning model conv-neural-network


    【解决方案1】:

    您可以使用model.save 保存模型并使用load_model 恢复模型吗?

    Keras 支持更简单的界面,可将模型权重和模型架构一起保存到单个 H5 文件中。

    model.save方式保存模型包含了我们需要知道的关于模型的所有信息,包括:

    1. 模型权重。
    2. 模型架构。
    3. 模型编译详细信息(损失和指标)。
    4. 模型优化器状态。

    然后可以通过调用load_model() 函数并传递文件名来加载保存的模型。该函数返回具有相同架构和权重的模型。

    您可以找到模型here的保存和加载示例。

    【讨论】:

      猜你喜欢
      • 2016-04-02
      • 2017-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多