【问题标题】:ValueError: Error when checking input: expected dense_1_input to have shape (9,) but got array with shape (1,)ValueError:检查输入时出错:预期dense_1_input的形状为(9,)但得到的数组形状为(1,)
【发布时间】:2020-04-11 18:40:59
【问题描述】:

嗨,所以我建立了一个 DNN 网络,使用对象的特征对图像中的一些对象进行分类,如下所示:

contours, _ = cv2.findContours(imgthresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

for contour in contours:
    features = np.array([])
    (x_start, y_start, character_width, character_height) = cv2.boundingRect(contour)
    x_end = x_start + character_width
    y_end = y_start + character_height
    character_area = character_width * character_height
    features = np.append(features, [character_width, character_height, character_area, x_start,
                                    y_start, x_end, y_end, image_width, image_height])

    print(features)
    print(features.shape)
    cv2.rectangle(image, (x_start, y_start), (x_end, y_end), (0, 255, 0), thickness=1)

print(features) 输出为:

[  5.   1.   5. 105.  99. 110. 100. 100. 117.]

print(features.shape) 是:

(9,)

我使用以下代码构建和训练了一个 DNN:

model = Sequential()

model.add(Dense(50, input_dim=9, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(40, activation='relu'))

model.add(Dropout(0.5))

model.add(Dense(30,activation='relu'))

model.add(Dense(2, activation='softmax'))

输入层有 9 个输入特征。所以我尝试使用以下方法获得模型的预测:

model.predict_classes(features)

训练数据,CSV 文件,包含 10 列(9 个特征和 1 个用于输出)

我收到以下错误:

ValueError: Error when checking input: expected dense_1_input to have shape (9,) but got array with shape (1,)

我尝试使用以下方法重塑特征数组:

np.reshape(features,(1,9)

但这也没有用。我还是这个领域的新手

【问题讨论】:

  • print(features) 行输出什么?当你用np.array([]) 初始化你的数组然后附加一些东西时,我想你的数组的第一个元素是一个形状列表 (1,)
  • @AlexisBRENON 抱歉忘了把它的输出放在我现在将更新它的问题中
  • @AlexisBRENON 我用输出值更新了问题

标签: python machine-learning keras deep-learning valueerror


【解决方案1】:

这是一个最小的工作示例。

import numpy as np
import tensorflow as tf

def main():
    features = np.array([5, 1, 5, 105, 99, 110, 100, 100, 117])
    model = tf.keras.Sequential()
    model.add(tf.keras.layers.Dense(50, input_dim=9, activation="relu"))

    print(tf.expand_dims(features, 0))
    print(np.reshape(features, (1, 9)))

    print(model.predict_classes(np.reshape(features, (1, 9))))


if __name__ == '__main__':
    main()

如您所见,np.reshape 调用使其正常工作。大致相当于tf.expand_dims

您当前的错误来自您的模型需要批量维度这一事实。 因此,如果您向它传递一个形状为 (9,) 的数组,它会推断它是一批标量,而不是大小为 9 的单个数组。

【讨论】:

    猜你喜欢
    • 2018-09-30
    • 2020-11-22
    • 1970-01-01
    • 2018-10-24
    • 2020-05-30
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多