Keras CNN模型准确率保持相对稳定且验证准确率未提高

我正在尝试使用Keras训练一个模型来识别良性和恶性图像,但我没有达到预期的结果。数据集分类得很好,来自ISIC – Archive (https://www.isic-archive.com/)。我多次尝试更改学习率,但都没有效果…训练间隔之一的结果

以下是我使用Adam优化器训练模型的代码:

# In[1]:from keras.callbacks import ModelCheckpointfrom keras.models import Sequentialfrom keras.layers import Dropout, Flatten, Densefrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2Dfrom PIL import ImageFilefrom tqdm import tqdmfrom keras.preprocessing import imagefrom sklearn.datasets import load_filesfrom keras.utils import np_utilsimport numpy as npfrom glob import globimport keras# define function to load train, test, and validation datasetsdef load_dataset(path):    data = load_files(path)    condition_files = np.array(data['filenames'])    condition_targets = np_utils.to_categorical(np.array(data['target']), 2)    print(condition_targets)    return condition_files, condition_targets# load train, test, and validation datasetstrain_files, train_targets = load_dataset(    '/Users/Grampun/Desktop/ISIC-Archive-Downloader-master/data_set/training_data')valid_files, valid_targets = load_dataset(    '/Users/Grampun/Desktop/ISIC-Archive-Downloader-master/data_set/valid_data')test_files, test_targets = load_dataset(    '/Users/Grampun/Desktop/ISIC-Archive-Downloader-master/data_set/test_data')# load list of labelscondition_names = [item[58:-1] for item in sorted(    glob("/Users/Grampun/Desktop/ISIC-Archive-Downloader-master/data_set/training_data/*/"))]print(condition_names)# print statistics about the datasetprint('There are %d total categories.' % len(condition_names))print('There are %s total images.\n' %      len(np.hstack([train_files, valid_files, test_files])))print('There are %d training images.' % len(train_files))print('There are %d validation images.' % len(valid_files))print('There are %d test images.' % len(test_files))# In[2]:def path_to_tensor(img_path):    # loads RGB image as PIL.Image.Image type    img = image.load_img(img_path, target_size=(224, 224))    # convert PIL.Image.Image type to 3D tensor with shape (224, 224, 3)    x = image.img_to_array(img)    # convert 3D tensor to 4D tensor with shape (1, 224, 224, 3) and return 4D tensor    return np.expand_dims(x, axis=0)def paths_to_tensor(img_paths):    list_of_tensors = [path_to_tensor(img_path)                       for img_path in tqdm(img_paths)]    return np.vstack(list_of_tensors)ImageFile.LOAD_TRUNCATED_IMAGES = True# pre-process the data for Kerastrain_tensors = paths_to_tensor(train_files).astype('float32')/255valid_tensors = paths_to_tensor(valid_files).astype('float32')/255test_tensors = paths_to_tensor(test_files).astype('float32')/255# (IMPLEMENTATION) Model Architecture## In[4]:model = Sequential()model.add(Conv2D(32, kernel_size=(3, 3),                 activation='relu',                 input_shape=(224, 224, 3)))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(128, activation='relu'))model.add(Dropout(0.5))model.add(Dense(2, activation='sigmoid'))model.summary()#  Compile the Model# In[ ]:# opt = keras.optimizers.Adadelta()opt = keras.optimizers.Adam(lr=0.00003, beta_1=0.9,                            beta_2=0.999, epsilon=1e-08, decay=0.0)model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])# ### Train the Model## In[ ]:# TODO: specify the number of epochs that you would like to use to train the model.epochs = 20checkpointer = ModelCheckpoint(filepath='weights.best.from_scratch.6.hdf5',                               verbose=1, save_best_only=True)model.fit(train_tensors, train_targets,          validation_data=(valid_tensors, valid_targets),          epochs=epochs, batch_size=10, callbacks=[checkpointer], verbose=1)# ### Load the Model with the Best Validation Loss# In[5]:model.load_weights('weights.best.from_scratch.6.hdf5')# ### Test the Model## In[6]:# get index of predicted label for each image in test setcondition_predictions = [np.argmax(model.predict(    np.expand_dims(tensor, axis=0))) for tensor in test_tensors]# report test accuracytest_accuracy = 100*np.sum(np.array(condition_predictions) ==                           np.argmax(test_targets, axis=1))/len(condition_predictions)print('Test accuracy: %.4f%%' % test_accuracy)  # confusion matrix

任何帮助都将不胜感激(这是我的第一个机器学习项目,我还在学习中)。谢谢!


回答:

这行代码是您问题的根源: model.add(Dense(2, activation='sigmoid'))

请使用以下之一:

  1. model.add(Dense(2, activation='softmax'))
  2. model.add(Dense(1, activation='sigmoid'))

请注意,在情况(1)中,您需要使用’categorical_crossentropy’而不是’binary_crossentropy’。因此,您还需要更改

model.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])

model.compile(optimizer=opt, loss='categorical_crossentropy', metrics=['accuracy'])

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

发表回复

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