Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 构建CNN训练模块时出错_Python_Numpy_Opencv_Tensorflow_Keras - Fatal编程技术网

Python 构建CNN训练模块时出错

Python 构建CNN训练模块时出错,python,numpy,opencv,tensorflow,keras,Python,Numpy,Opencv,Tensorflow,Keras,在使用我自己的自定义数据对CNN(ShallowNet)进行4节课的培训时,我在model.fit函数中遇到了以下错误: model.fit(trainData, trainLabels, batch_size=args["batch_size"], epochs=args["epochs"], verbose=args["verbose"]) 回溯(最近一次呼叫最后一次): 文件“train_network.py”,第98行,在 epochs=args[“epochs”],ver

在使用我自己的自定义数据对CNN(ShallowNet)进行4节课的培训时,我在model.fit函数中遇到了以下错误:

model.fit(trainData, trainLabels, batch_size=args["batch_size"],
      epochs=args["epochs"], verbose=args["verbose"])
回溯(最近一次呼叫最后一次): 文件“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
在这个函数中,我刚刚在稍后的通道中输入了_形状,我还尝试通过交换

loss = sparse_categorical_crossentropy
而不是

loss = categorical_crossentropy
但这也不起作用,还有我的列车数据和标签数据的形状:

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

keras版本am使用的是2.0.6


任何帮助都将不胜感激。

您的代码与

model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])
我不确定“稀疏\分类\交叉\熵”的用法,但我认为您需要在输出层使用一个类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)

您的代码可以与

model.compile(loss="categorical_crossentropy", optimizer=sgd, metrics=["accuracy"])
我不确定“稀疏\分类\交叉\熵”的用法,但我认为您需要在输出层使用一个类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)

您好@U.Swap,您能告诉我作为ShallowNet函数的参数传递的NumClass的值是多少吗?它是4,因为数据集中的类数是4请包含model.summary()的输出,它会告诉我们模型是否正确构建以及参数是否正确。您好@U.Swap,您能告诉我作为ShallowNet函数的参数传递的NumClass的值是多少吗?它是4,因为dataset中的类数是4请包含model.summary()的输出,它将告诉我们模型是否正确构建以及参数是否正确。trainLabels[randLabel]=1这是一个字典集合,但是numpy数组是必需的。感谢您指出,编辑了代码使其trainLabels[i,randLabel]=1。幸运的是,这只会影响训练,因为您有实际的数据。我想您提到的是由to_分类函数本身完成的,但我尝试了用7个类预先定义标签数组形状,但现在它抛出:ValueError:输入数组应具有与目标数组相同的样本数。找到574个输入样本和4018个目标样本。4018是574*7。请检查目标标签阵列是否为4018x1而不是574x7。我避免使用to_Category,因为使用另一个库只会在解释事情时增加复杂性。trainLabels[randLabel]=1这是一个字典集合,但需要numpy数组。感谢您指出,编辑代码使其trainLabels[I,randLabel]=1。幸运的是,这只会影响训练,因为您有实际的数据。我想您提到的是由to_分类函数本身完成的,但我尝试了用7个类预先定义标签数组形状,但现在它抛出:ValueError:输入数组应具有与目标数组相同的样本数。找到574个输入样本和4018个目标样本。4018是574*7。请检查目标标签阵列是否为4018x1而不是574x7。我避免使用tou_category,因为使用另一个库只会在解释问题时增加复杂性。