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

时间:2018-03-01 13:02:44

标签: python json numpy keras

我想编写一个简单的函数来从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

1 个答案:

答案 0 :(得分: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)