我使用芹菜和redis的瓶服務器。調用.apply_async()時發生錯誤。 numpy數組是可視化keral神經網絡模型輸出的一部分。我知道有一種方法可以將keras模型轉換爲json。我的主要問題在於,我不知道芹菜何時或如何進行轉化,我無法控制它。芹菜錯誤:numpy數組不是JSON可序列化
這裏是我的代碼:
@celery.task(bind=True)
def celery_createDirectoryAndSaveNNOutput(self, pInput, ID, filename, layersToShow, model):
layer_outputs = [layer.output for layer in model.layers[1:]]
viz_model = Model(input=model.input, output=layer_outputs)
features = viz_model.predict(pInput)
layerOutputs = {}
folderName = "static/"+ID+"_"+filename
if not os.path.exists(folderName):
os.makedirs(folderName)
for layerIndex in layersToShow:
images = getFeatureMapImages(features[int(layerIndex)])
layerOutputs[layerIndex] = []
for i in range(0, len(images)):
path = folderName+"/layer"+str(int(layerIndex))+"_"+str(i)+".jpg"
cv2.imwrite(path, images[i])
layerOutputs[layerIndex].append(path)
self.update_state(state='PROGRESS', meta={'current': 0, 'total': 10,"status":filename})
return {'current': i, 'total': len(layersToShow),'status': "temp"}
@app.route("/nnvisualisation_uploadMultipleImages", methods=["POST"])
def nnvisualisation_uploadMultipleImages():
uploaded_files = request.files.getlist("file[]")
weight = request.form.get("weight")
ID = request.form.get("ID")
layersToShow = [5]
modelName = "VGG16"
preds = {}
path = os.path.join(STATIC_PATH, uploaded_files[0].filename)
uploaded_files[0].save(os.path.join(STATIC_PATH, uploaded_files[0].filename))
pInput, result = preTrainedModel[modelName](path)
#ERROR HERE:
task = celery_createDirectoryAndSaveNNOutput.s(pInput=pInput, ID=ID, filename=uploaded_files[0].filename, layersToShow=layersToShow, model=getModel(modelName)).apply_async(serializer='json')
...
return jsonify({}), 202, {'Location': url_for('taskstatus',task_id=task.id)}
我已經嘗試了所有可用的序列 YAML:
EncodeError: cannot represent an object: keras.engine.training.Model object at 0x10fdf26d0>
泡菜:
EncodeError: Can't pickle type 'module': attribute lookup builtin.module failed
msgpack:
EncodeError: can't serialize array([[[[-103.93900299, -107.77899933, -123.68000031],... , dtype=float32) (numpy array)
JSON:
EncodeError: array([[[[-103.93900299, -107.77899933, -123.68000031],... , dtype=float32) (numpy array) is not JSON serializable
任何意見或建議是極大的讚賞。謝謝。
'json'是一個與'javascript'兼容的字符串格式。它編碼字典,列表和字符串。其他的'python'類必須將它們自己「序列化」成其中一個結構。 'numpy'陣列不會自動做到這一點,儘管有些工具可以提供幫助。做一些關於'keras'和'json'的搜索。 – hpaulj
感謝您的評論。我知道有一種方法可以將keras模型轉換爲json。我的主要問題在於,我不知道芹菜何時或如何進行轉化,我無法控制它。 – matchifang