Keras稀疏分类交叉熵损失函数中的错误

我在尝试使用深度神经网络进行预测时遇到了以下错误:

InvalidArgumentError: logits和labels的第一维必须相同,得到的logits形状为[32,4],labels形状为[128]

以下是特征的相关信息:

new_features.shape(19973, 8)new_features[0].shape(8,)

以下是标签/输出信息:

output.shape(19973, 4)output[0].shape(4,)

这是Keras的代码:

model = Sequential(  [    Dense(units=8, input_shape=new_features[0].shape, name="layer1"),    Dense(units=1024, activation="relu", name="layer2"),    Dense(units=1024, activation="relu", name="layer3"),    Dense(units=4,  name="layer4", activation="softmax"),  ])model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')model.fit(new_features, output, epochs=2)

特征和标签包含浮点值。


回答:

问题出在你的目标形状上。首先,在分类问题中,你的目标必须是整数类型。

如果你有一维整数编码的目标,你可以使用sparse_categorical_crossentropy作为损失函数

X = np.random.randint(0,10, (1000,100))y = np.random.randint(0,3, 1000)model = Sequential([    Dense(128, input_dim = 100),    Dense(3, activation='softmax'),])model.summary()model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])history = model.fit(X, y, epochs=3)

否则,如果你对目标进行了独热编码以获得二维形状(n_samples, n_class),你可以使用categorical_crossentropy

X = np.random.randint(0,10, (1000,100))y = pd.get_dummies(np.random.randint(0,3, 1000)).valuesmodel = Sequential([    Dense(128, input_dim = 100),    Dense(3, activation='softmax'),])model.summary()model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])history = model.fit(X, y, epochs=3)

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中创建了一个多类分类项目。该项目可以对…

发表回复

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