我在尝试使用深度神经网络进行预测时遇到了以下错误:
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)