为什么我的CNN二元分类模型没有学习?

2024-10-04 07:36:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到了10000张代表粒子检测的形状图像(100100),然后我创建了10000张形状的空图像(100100),并将它们混合在一起。我分别给出了0和1的类型标签,如代码所示:

Labels = np.append(np.ones(10000),np.zeros(empty_sheets.shape[0]))

images_scale1 = np.zeros(s)   #scaling each image so that it has a maximum number of 1
#scaling each image so that it has a maximum number of 1
l = s[0]
for i in range(l):
    images_scale1[i] = images[i]/np.amax(images[i])

empty_sheets_noise1 = add_noise(empty_sheets,0)

scale1noise1 = np.concatenate((images_scale1,empty_sheets_noise1),axis=0)
y11 = Labels

scale1noise1s, y11s = shuffle(scale1noise1, y11)

scale1noise1s_train, scale1noise1s_test, y11s_train, y11s_test = train_test_split(
                                                    scale1noise1s, y11,     test_size=0.25)

#reshaping image arrays so that they can be passed through CNN
scale1noise1s_train = scale1noise1s_train.reshape(scale1noise1s_train.shape[0],100,100,1)
scale1noise1s_test  = scale1noise1s_test.reshape(scale1noise1s_test.shape[0],100,100,1)
y11s_train = y11s_train.reshape(y11s_train.shape[0],1)
y11s_test = y11s_test.reshape(y11s_test.shape[0],1)

然后,为了设置模型,我创建了一个新函数:

def create_model():
    #initiates new model
    model = keras.models.Sequential()
    model.add(keras.layers.Conv2D(64, (3,3),activation='relu',input_shape=(100,100,1)))
    model.add(keras.layers.MaxPooling2D((2, 2)))
    model.add(keras.layers.Dropout(0.2))
    model.add(keras.layers.Flatten())
    model.add(keras.layers.Dense(32))
    model.add(keras.layers.Dense(64))
    model.add(keras.layers.Dense(1,activation='sigmoid'))
    return model

estimators1m1 = create_model()
estimators1m1.compile(optimizer='adam', metrics=['accuracy', tf.keras.metrics.Precision(),
                                  tf.keras.metrics.Recall()], loss='binary_crossentropy')

history = estimators1m1.fit(scale1noise1s_train, y11s_train, epochs=3, 
                    validation_data=(scale1noise1s_test, y11s_test))

这将产生以下结果:

Epoch 1/3 469/469 [==============================] - 62s 131ms/step - loss: 0.6939 - accuracy: 0.4917 - precision_2: 0.4905 - recall_2: 0.4456 - val_loss: 0.6933 - val_accuracy: 0.5012 - val_precision_2: 0.5012 - val_recall_2: 1.0000 Epoch 2/3 469/469 [==============================] - 63s 134ms/step - loss: 0.6889 - accuracy: 0.5227 - precision_2: 0.5209 - recall_2: 0.5564 - val_loss: 0.6976 - val_accuracy: 0.4994 - val_precision_2: 0.5014 - val_recall_2: 0.2191 Epoch 3/3 469/469 [==============================] - 59s 127ms/step - loss: 0.6527 - accuracy: 0.5783 - precision_2: 0.5764 - recall_2: 0.5887 - val_loss: 0.7298 - val_accuracy: 0.5000 - val_precision_2: 0.5028 - val_recall_2: 0.2131

我尝试了更多的纪元,但我仍然只能获得50%的准确率,这是无用的,因为它只是不断地预测相同的事情


Tags: testaddmodellayersnptrainvalprecision
1条回答
网友
1楼 · 发布于 2024-10-04 07:36:49

模型不起作用的原因可能有很多。更有可能的是,模型拟合不足,因为训练集和验证集的精度都较低,这意味着神经网络无法捕获数据中的模式。因此,你应该考虑通过添加更多的层来建立更复杂的模型,同时避免像辍学之类的技术过度拟合。您还应该通过超参数调优来获得最佳参数

相关问题 更多 >