我使用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
答案 0 :(得分:0)
有两种解决方法,具体取决于各种环境:
使用clear_session()
功能:
from keras import backend as K
然后,在预测所有数据之后,在函数的开头或结尾执行以下操作:
K.clear_session()
呼叫_make_predict_function()
:
加载经过训练的模型调用后:
model._make_predict_function()
请参见explanation