【问题标题】:Keras shape error - im inputting the shape its asking forKeras 形状错误 - 输入它要求的形状
【发布时间】:2018-03-01 13:02:43
【问题描述】:

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

【问题讨论】:

  • z = z[:, np.newaxis].T
  • 多么奇特的修复!转置如何解决问题?确定它会将输入转换为 (1,28) 吗?

标签: python json numpy keras


【解决方案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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-15
    • 2018-08-15
    • 1970-01-01
    • 2023-03-28
    • 2019-01-26
    • 2023-03-22
    • 2017-03-01
    • 2018-02-16
    相关资源
    最近更新 更多