代码之家  ›  专栏  ›  技术社区  ›  Mitiku

当使用python 3调用预测函数时,用python 2训练的keras模型给出了NaN值。

  •  0
  • Mitiku  · 技术社区  · 7 年前

    我有一个用python 2.7训练过的keras模型。当我试图预测时,这个模型在python 2.7上工作正常。但当我尝试在python 3上使用这个模型进行预测时,它总是预测[[南南南南南]]的值。

    下面是我用来从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
    

    产生这种类型差异的原因是什么?

    1 回复  |  直到 7 年前
        1
  •  0
  •   Daniel Möller    7 年前

    您可以尝试以下方法(不确定是否有效,但看起来很干净):

    获取模型的权重并用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)