训练深度学习模型时出现错误

我设计了一个CNN并使用以下参数进行编译,

training_file_loc = "8-SignLanguageMNIST/sign_mnist_train.csv"testing_file_loc = "8-SignLanguageMNIST/sign_mnist_test.csv"def getData(filename):    images = []    labels = []    with open(filename) as csv_file:        file = csv.reader(csv_file, delimiter = ",")        next(file, None)                for row in file:            label = row[0]            data = row[1:]            img = np.array(data).reshape(28,28)                        images.append(img)            labels.append(label)                images = np.array(images).astype("float64")        labels = np.array(labels).astype("float64")            return images, labelstraining_images, training_labels = getData(training_file_loc)testing_images, testing_labels = getData(testing_file_loc)print(training_images.shape, training_labels.shape)print(testing_images.shape, testing_labels.shape)training_images = np.expand_dims(training_images, axis = 3)testing_images = np.expand_dims(testing_images, axis = 3)training_datagen = ImageDataGenerator(    rescale = 1/255,    rotation_range = 45,    width_shift_range = 0.2,    height_shift_range = 0.2,    shear_range = 0.2,    zoom_range = 0.2,    horizontal_flip = True,    fill_mode = "nearest")training_generator = training_datagen.flow(    training_images,    training_labels,    batch_size = 64,)validation_datagen = ImageDataGenerator(    rescale = 1/255,    rotation_range = 45,    width_shift_range = 0.2,    height_shift_range = 0.2,    shear_range = 0.2,    zoom_range = 0.2,    horizontal_flip = True,    fill_mode = "nearest")validation_generator = training_datagen.flow(    testing_images,    testing_labels,    batch_size = 64,)model = tf.keras.Sequential([    keras.layers.Conv2D(16, (3, 3), input_shape = (28, 28, 1), activation = "relu"),    keras.layers.MaxPooling2D(2, 2),    keras.layers.Conv2D(32, (3, 3), activation = "relu"),    keras.layers.MaxPooling2D(2, 2),    keras.layers.Flatten(),    keras.layers.Dense(256, activation = "relu"),    keras.layers.Dropout(0.25),    keras.layers.Dense(512, activation = "relu"),    keras.layers.Dropout(0.25),    keras.layers.Dense(26, activation = "softmax")])model.compile(    loss = "categorical_crossentropy",    optimizer = RMSprop(lr = 0.001),    metrics = ["accuracy"])

但是,当我运行model.fit()时,出现了以下错误,

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

在将损失函数更改为sparse_categorical_crossentropy后,程序正常运行。

我不明白这是为什么。

谁能解释一下这是怎么回事,以及这两种损失函数的区别?


回答:

问题在于,categorical_crossentropy期望标签是一热编码的,这意味着,对于每个样本,它期望一个长度为num_classes的张量,其中label位置的元素被设置为1,其余为0。

另一方面,sparse_categorical_crossentropy直接使用整数标签(因为这里的用例是类别数目很大,所以一热编码标签会浪费大量内存)。我认为,但不能确定,categorical_crossentropy的运行速度比其稀疏版本更快。

对于你的情况,有26个类别,我建议使用非稀疏版本,并将你的标签转换为一热编码,如下所示:

def getData(filename):    images = []    labels = []    with open(filename) as csv_file:        file = csv.reader(csv_file, delimiter = ",")        next(file, None)                for row in file:            label = row[0]            data = row[1:]            img = np.array(data).reshape(28,28)                        images.append(img)            labels.append(label)                images = np.array(images).astype("float64")        labels = np.array(labels).astype("float64")            return images, tf.keras.utils.to_categorical(labels, num_classes=26) # 你可以省略num_classes,让它从数据中计算

补充说明:除非你有理由使用float64来处理图像,否则我建议改用float32(这样可以将数据集所需的内存减半,而且模型很可能在第一步操作中就将它们转换为float32

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

发表回复

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