构建CNN列车模块时出错

问题描述 投票:0回答:1

用我自己的4个类的自定义数据训练CNN(ShallowNet)但是在model.fit函数上遇到这个错误:

回溯(最近一次调用最后一次):文件“train_network.py”,第98行,在epochs = args [“epochs”],verbose = args [“verbose”]).... ValueError:检查目标时出错:预期激活_2有形状(无,1)但有阵形(373,4)

在这里我想问题是火车标签阵列的形状,

但在此之前,让我告诉你我是如何加载数据并标记arrya的

for imagePath in imagePaths:
    # load the image, pre-process it, and store it in the data list
    image = cv2.imread(imagePath)
    image = cv2.resize(image, (32, 32))
    image = img_to_array(image)
    data.append(image)

    # extract the class label from the image path and update the
    label = imagePath.split(os.path.sep)[-2]
    labels.append(int(label))

之后形成阵列并拆分列车和测试数据:

trainData = np.array(data, dtype="float") / 255.0
labels = np.array(labels)

(_, testData, _, testLabels) = train_test_split(trainData,
                                            labels, test_size=0.25, random_state=42)

testLabels = to_categorical(testLabels, num_classes=len(np.unique(testLabels)))

trainLabels = to_categorical(labels, num_classes=len(np.unique(labels)))

之后开始编译模型并传递适当的参数,根据帖子:

model = ConvNetFactory.build(args["network"], 3, 32, 32,
len(np.unique(trainLabels)),**kargs)

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)

model.compile(loss="sparse_categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])

然后开始训练,提供trainX和trainY以适应功能:

model.fit(trainData, trainLabels, batch_size=args["batch_size"],
      epochs=args["epochs"], verbose=args["verbose"])

但是在这一行它抛出错误,如前所述,以下是来自convnetfactory类的代码块:

    def ShallowNet(numChannels, imgRows, imgCols, numClasses, **kwargs):
        # initialzie the model
        model = Sequential()

        # define the first (and only) CONV => RELU layer
        model.add(Convolution2D(32, 3, 3, border_mode="same",
                            input_shape=(imgRows, imgCols, numChannels)))
        model.add(Activation("relu"))

        # add a FC layer followed by the soft-max classifier
        model.add(Flatten())
        model.add(Dense(numClasses))
        model.add(Activation("softmax"))

        # return the network architecture
        return model

在这个函数中,我刚刚将input_shape设置为通道,也是我尝试通过交换

loss = sparse_categorical_crossentropy

代替

loss = categorical_crossentropy

但这也没有用,这些也是我的traindata和标签数据的形状:

trainLabels.shape ==>(373,4)和trainData.shape ==>(373,32,32,3)

我使用的keras版本是2.0.6

任何帮助,将不胜感激。

python numpy opencv tensorflow keras
1个回答
3
投票

你的代码可以正常使用

model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])

我不确定“sparse_categorical_cross_entropy”的用法,但我认为你需要有一个输出,即输出层中的类ID,因此需要使用[None,1]数组。

以下是我用于测试的完整代码,包括使用随机值初始化训练数据:

import numpy as np
import keras
import random

from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D, Activation
from keras.optimizers import SGD
from keras import backend as K

imgRows = 32
imgCols = 32
numChannels = 3
numClasses = 4

# create random training data
trainData = np.zeros((373,32,32,3), np.float)
trainLabels = np.zeros((373,4), np.uint)

# initialize data randomly
for i in range(0,373):
    # set training data
    for p in range(0, 32):
        for q in range(0,32):
            for r in range(0,3):
                trainData[p,q,r] = np.random.ranf()
    # set a class label
    randLabel = random.randint(0,3)
    trainLabels[i,randLabel] = 1

# initialzie the model
model = Sequential()
# define the first (and only) CONV => RELU layer
model.add(Conv2D(32, kernel_size=(3, 3), border_mode="same", activation = 'relu',
                            input_shape=(imgRows, imgCols, numChannels)))
model.add(Activation("relu"))
# add a FC layer followed by the soft-max classifier
model.add(Flatten())
model.add(Dense(numClasses))
model.add(Activation("softmax"))

model.summary() 
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)    
model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])   
print K.image_data_format()  
model.fit(trainData, trainLabels, batch_size=8, epochs=100)
© www.soinside.com 2019 - 2024. All rights reserved.