TensorFlow 不兼容形状二进制分类

TensorFlow incompatible shapes binary classification

我有一个 pandas 特征和样本数据框,以及一个具有二进制类别(0 或 1)值的系列。因此,我正在尝试训练神经网络,但出现错误:

TensorFlow incompatible shapes binary classification

代码摘要如下:

X_train, X_test, y_train, y_test = train_test_split(df_x, series_y, random_state=1, test_size=0.25)

best_weight_path = 'best_weights.hdf5'

x = df_x.to_numpy()
y = series_y.to_numpy()

numpy_x_train = X_train.to_numpy()
numpy_y_train = y_train.to_numpy()
numpy_x_test = X_test.to_numpy()
numpy_y_test = y_test.to_numpy()
model = Sequential()
model.add(Dense(20, input_dim=x.shape[1], activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(2, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam')
monitor = EarlyStopping(monitor='val_loss', min_delta=1e-3, patience=5, verbose=1, mode='auto')
checkpointer = ModelCheckpoint(filepath=best_weight_path, verbose=0, save_best_only=True)
model.fit(x, y, validation_data=(numpy_x_test, numpy_y_test), callbacks=[monitor, checkpointer], verbose=0, epochs=1000)

ValueError: Shapes (None, 1) and (None, 2) are incompatible

最后一个密集层不应该有 2 个单元,因为有两种可能的结果,那么形状 (None, 1) 来自哪里?

问题与根据标签格式正确选择合适的损失函数有关。在分类任务中使用 softmax 时有两种可能性:

1 种可能性:如果你有 1D 整数编码目标,你可以使用 sparse_categorical_crossentropy 作为损失函数(这似乎是你的情况

n_class = 2
n_features = 100
n_sample = 1000

X = np.random.randint(0,10, (n_sample,n_features))
y = np.random.randint(0,n_class, n_sample)

inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)

model = Model(inp, out)
model.compile(loss='sparse_categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)

2 种可能性:如果您对目标进行单热编码以获得 2D 形状(n_samples、n_class),则可以使用 categorical_crossentropy

n_class = 2
n_features = 100
n_sample = 1000

X = np.random.randint(0,10, (n_sample,n_features))
y = pd.get_dummies(np.random.randint(0,n_class, n_sample)).values

inp = Input((n_features,))
x = Dense(128, activation='relu')(inp)
out = Dense(n_class, activation='softmax')(x)

model = Model(inp, out)
model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])
history = model.fit(X, y, epochs=3)