我有一个keras模型,我使用python 2.7训练过。当我尝试预测时,这个模型在python 2.7上正常工作。但是当我试图预测在python 3上使用这个模型时,它始终预测[[nan nan nan nan nan nan nan]]值。
以下是我用来从json
加载模型的代码def load_model_from_args(args):
with open(args.json) as json_file:
model = model_from_json(json_file.read())
model.load_weights(args.weights)
return model
这是我试图获得预测的地方
def get_emotion(features,model):
predictions = model.predict(features)
print(predictions)
# [[nan nan nan nan nan nan nan]]
# the reset of the code
产生这种类型差异的原因是什么?
答案 0 :(得分:0)
您可以尝试以下方法(不确定它是否可行,但看起来很干净):
获取模型的权重并使用numpy保存:
#in 2.7
weights = model.get_weights()
np.save('weights27.npy', weights)
通过Python 3中的代码再次创建模型:
#in python 3, do no load the saved model, create a new one:
#same layers, same sizes, everything
...model code...
model3 = Model(...)
将权重加载到模型中:
model3.set_weights(np.load('weights27.npy'))
尝试使用该模型。
weights = model.get_weights()
for i,w in enumerate(weights):
np.save('weights-' + str(i) + ".npy", w, allow_pickle=False)
在python 3中:
weights = []
for i in range(theTotalNumberOfSavedWeights):
weights.append(np.load("weights-" + str(i) + ".npy", allow_pickle=False))
model2.set_weights(weights)