記錄深度學習踩過的坑

一、使用keras在本地預測,沒有任何問題,但部署到伺服器上就報錯。

Traceback (most recent call last): File "/media/wave/D/workspace/LinuxPyCharm/actauto/classification/comments_class.py", line 38, in category_class result_vec = model_COC.predict(vecs)[0] File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 902, in predict return self.model.predict(x, batch_size=batch_size, verbose=verbose) File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1582, in predict self._make_predict_function() File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1049, in _make_predict_function **kwargs) File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 2251, in function return Function(inputs, outputs, updates=updates) File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 2205, in __init__ with tf.control_dependencies(self.outputs): File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3595, in control_dependencies return get_default_graph().control_dependencies(control_inputs) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 3324, in control_dependencies c = self.as_graph_element(c) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2414, in as_graph_element return self._as_graph_element_locked(obj, allow_tensor, allow_operation) File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2493, in _as_graph_element_locked raise ValueError("Tensor %s is not an element of this graph." % obj)ValueError: Tensor Tensor("dense_2/Softmax:0", shape=(?, 8), dtype=float32) is not an element of this graph.

很對人也遇到了這種問題,參考keras的github討論區,github.com/keras-team/k

也有人提出了解決辦法,但比較麻煩

知乎 @王岳王院長 也遇到此問題,他的解決辦法最好。在次引用:

就是說,當你引用模型後,隨後進行一次預測,後面再用到時,就不會報錯。

import numpy as npfrom keras.models import load_modelmodel = load_model(model_example.h5)print(testing model:, model.predict(np.zeros((1, 299, 299, 3))))...

二、使用keras載入多個模型做ensemble時,報錯

Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 167, in load_model model.optimizer.set_weights(optimizer_weight_values) File "/usr/local/lib/python2.7/dist-packages/keras/optimizers.py", line 97, in set_weights provided weight shape + str(w.shape))Exception: Optimizer weight shape (256, 32) not compatible with provided weight shape (4,)

很多人遇到了此問題,參考keras的github討論區,github.com/keras-team/k

解決辦法是:

引入模型時,將compile參數設置為False

model = load_model(my_model.hdf5, compile=False)model.compile(optimizer=adam, loss=categorical_crossentropy, metrics=[accuracy])

來自 oarriaga (Octavio Arriaga) 的解決辦法,很有效。


推薦閱讀:

TAG:Keras | 深度學習DeepLearning | TensorFlow |