Keras形状错误 - 我输入它要求的形状

问题描述 投票:0回答:1

我想编写一个简单的函数来从json加载keras模型并运行预测。但是每次运行它都会出现以下错误:

ValueError: Error when checking : expected input_2 to have shape (28,) but got array with shape (1,)

下面的代码显示我已经打印出numpy数组的形状并返回(28,),如果我把它留作python列表,这仍然会发生。

def doit():
    # load json and create model
    json_file = open('model.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = model_from_json(loaded_model_json)
    # load weights into new model
    loaded_model.load_weights("model.h5")
    x = [1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
    z = np.array(x)
    print(z.shape)
    prediction = loaded_model.predict(z)
    return prediction
python json numpy keras
1个回答
1
投票

您的模型已经初始化(和训练),以接收来自形状(N,28)矩阵的输入。它预计有28列。

解决此问题的方法是重塑您的单个输入行以匹配:

z = z[:, np.newaxis].T #(1,28) shape

要么:

z = z.reshape(1,-1) #reshapes to (1,whatever is in there)
z = z.reshape(-1,28) #probably better, reshapes to (amount of samples, input_dim)
© www.soinside.com 2019 - 2024. All rights reserved.