ValueError:检查输入时出错:预期density_1_input的形状为(9,),但数组的形状为(1,)

时间:2019-12-19 07:32:00

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

嗨,所以我建立了一个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)

但是那也不起作用。我仍然是这个领域的新手

1 个答案:

答案 0 :(得分:2)

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

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的数组。

相关问题