【问题标题】:Error Loading Keras Model Second Time. Feed_dict Error第二次加载 Keras 模型时出错。 Feed_dict 错误
【发布时间】:2019-12-26 19:21:55
【问题描述】:

我使用 Keras 的 model.save 将经过训练的模型保存为 h5py 格式。然后我在我的烧瓶应用程序中使用它。 在 'print(loading model' 下的 'model = tf.keras.models.load_model('soundmodel.k')' 行,整个操作在第一次运行时运行顺利,允许我将生成的音频播放到我的浏览器.

@app.route('/api/generate', methods=['POST'])
def generate():
    block_size = 2700
    seq_len = 215

    print(request.form['firstGen'], 'hi\n')
    upl_str = request.form['filePath']
    is_first_gen = request.form['firstGen']
    if is_first_gen == "1":
        print(is_first_gen, '\n')

    x_data, y_data = make_tensors(upl_str, seq_len, block_size)


    #if is_first_gen == "1":

    print('loading model')
    model = tf.keras.models.load_model('soundmodel.k')
    masterpiece = compose(model, x_data)
    masterpiece = convert_sample_blocks_to_np_audio(masterpiece[0])

    masterpiece = write_np_as_wav(masterpiece, sample_rate=44100, filename='new.wav')
    print('wrote np as wav')
    wpath = os.path.join(os.getcwd(), 'new.wav')

    response = {
        'wavPath': wpath
    }

    K.clear_session()

    return jsonify(response)

但是第二次之后,当我运行它时,我得到了这个错误:

loading model
[2019-12-26 13:30:30,274] ERROR in app: Exception on /api/generate [POST]
Traceback (most recent call last):
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\client\session.py", line 1040, in _run
    subfeed, allow_tensor=True, allow_operation=False)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\framework\ops.py", line 3339, in as_graph_element
    return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\framework\ops.py", line 3418, in _as_graph_element_locked
    raise ValueError("Tensor %s is not an element of this graph." % obj)
ValueError: Tensor Tensor("Placeholder:0", shape=(2700, 10800), dtype=float32) is not an element of this graph.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\flask\app.py", line 2446, in wsgi_app
    response = self.full_dispatch_request()
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\flask_cors\extension.py", line 161, in wrapped_function
    return cors_after_request(app.make_response(f(*args, **kwargs)))
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\flask\app.py", line 1820, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\flask\_compat.py", line 39, in reraise
    raise value
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request
    rv = self.dispatch_request()
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\flask\app.py", line 1935, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "C:\Users\Iman\code\music-generator\app.py", line 426, in generate
    model = tf.keras.models.load_model('soundmodel.k')
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\keras\engine\saving.py", line 232, in load_model
    load_weights_from_hdf5_group(f['model_weights'], model.layers)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\keras\engine\saving.py", line 802, in load_weights_from_hdf5_group
    K.batch_set_value(weight_value_tuples)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\keras\backend.py", line 2719, in batch_set_value
    get_session().run(assign_ops, feed_dict=feed_dict)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\client\session.py", line 877, in run
    run_metadata_ptr)
  File "C:\Users\Iman\.conda\envs\pyenv3\lib\site-packages\tensorflow\python\client\session.py", line 1043, in _run
    'Cannot interpret feed_dict key as Tensor: ' + e.args[0])
TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("Placeholder:0", shape=(2700, 10800), dtype=float32) is not an element of this graph.

我尝试在使用模型后删除它,并使用 K.clear_session() 清除会话以尝试像第一次运行时那样加载模型,但这似乎没有任何区别。我还尝试添加一个标志来阻止它第二次加载模型,但是模型将根本没有被定义,从而导致错误。所以我认为flask会在函数返回后清除这些变量。

当我调用加载模型函数时发生错误,因此它在失败之前没有尝试运行预测操作。 我正在使用 tensorflow 1.1 和 keras 2.0.6。我的 python 版本是 Python 3.5.4

【问题讨论】:

    标签: python tensorflow flask keras lstm


    【解决方案1】:

    有几种解决方法,具体取决于不同的上下文:

    1. 使用clear_session()函数

      from keras import backend as K
      

      然后在预测所有数据后,在函数的开头或结尾处执行以下操作:

      K.clear_session()
      
    2. 致电_make_predict_function()

      加载经过训练的模型调用后:

      model._make_predict_function()
      

      explanation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 2018-01-27
      • 2014-11-20
      相关资源
      最近更新 更多