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

你好,我构建了一个深度神经网络(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)

但这也没有奏效。我在这个领域还是新手


回答:

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

import numpy as npimport tensorflow as tfdef 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的单一数组。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注