如何使用CNN python代码解决以下错误?

时间:2019-03-02 06:37:00

标签: python pycharm

图像数据描述:尺寸为200x200的2D二进制图像 存在123个标签(类),每个类(标签)包含10个图像帧,其中我认为剩下的前4个图像将是训练数据集。

据我所知,我更改了CNN代码以对图像数据进行分类,但是出现以下错误:

警告:tensorflow:来自C:\ Users \ hp \ PycharmProjects \ FirstProject3 \ venv \ lib \ site-packages \ tensorflow \ python \ framework \ op_def_library.py:263:colocate_with(来自tensorflow.python.framework.ops)已弃用,并将在以后的版本中删除。

更新说明:

托管服务器自动处理的托管。

警告:tensorflow:从C:\ Users \ hp \ PycharmProjects \ FirstProject3 \ venv \ lib \ site-packages \ keras \ backend \ tensorflow_backend.py:3445:使用以下命令调用dropout(来自tensorflow.python.ops.nn_ops) keep_prob已过时,将在以后的版本中删除。

更新说明:

请使用rate代替keep_prob。费率应设置为rate = 1 - keep_prob

回溯(最近通话最近一次):

文件“ C:/Users/hp/PycharmProjects/FirstProject3/test.py”,第79行,在     model.fit(x_train,y_train,batch_size = batch_size,epochs = epochs,verbose = 1,validation_data =(x_test,y_test))

文件“ C:\ Users \ hp \ PycharmProjects \ FirstProject3 \ venv \ lib \ site-packages \ keras \ engine \ training.py”,第952行,适合     batch_size =批量大小)

文件_standardize_user_data中的第789行“ C:\ Users \ hp \ PycharmProjects \ FirstProject3 \ venv \ lib \ site-packages \ keras \ engine \ training.py”     exception_prefix ='target')

standardize_input_data中的行138中的文件“ C:\ Users \ hp \ PycharmProjects \ FirstProject3 \ venv \ lib \ site-packages \ keras \ engine \ training_utils.py”     str(data_shape))

ValueError:检查目标时出错:预期density_2具有形状(123,)但形状为(124,)的数组

如何解决该错误?

我的代码:

    import keras
    from keras.models import Sequential
    from keras.layers import Dense, Dropout, Flatten
    from keras.layers import Conv2D, MaxPooling2D
    import numpy as np
    import cv2
    import os

    path1='C:\\Data\\For new Paper3\Old\\GaitDatasetB-silh_PerfectlyAlingedImages_EnergyImage\\';
    all_images = []
    all_labels = []
    subjects = os.listdir(path1)
    numberOfSubject = len(subjects)
    print('Number of Subjects: ', numberOfSubject)
    for number1 in range(0, numberOfSubject):  # numberOfSubject
        path2 = (path1 + subjects[number1] + '/')
        sequences = os.listdir(path2);
        numberOfsequences = len(sequences)
        for number2 in range(4, numberOfsequences):
            path3 = path2 + sequences[number2]
            img = cv2.imread(path3 , 0)
            img = img.reshape(200, 200, 1)
            all_images.append(img)
            all_labels.append(number1+1)
    x_train = np.array(all_images)
    y_train = np.array(all_labels)
    y_train = keras.utils.to_categorical(y_train)
    print(y_train)

    print(x_train)


    all_images = []
    all_labels = []

    for number1 in range(0, numberOfSubject):  # numberOfSubject
        path2 = (path1 + subjects[number1] + '/')
        sequences = os.listdir(path2);
        numberOfsequences = len(sequences)
        for number2 in range(0, 4):
            path3 = path2 + sequences[number2]
            img = cv2.imread(path3 , 0)
            img = img.reshape(200, 200, 1)
            all_images.append(img)
            all_labels.append(number1+1)
    x_test = np.array(all_images)
    y_test = np.array(all_labels)
    y_test = keras.utils.to_categorical(y_test)
    print(y_test)

    print(x_test)

    batch_size = 738
    num_classes = 123
    epochs = 12

    model = Sequential()
    model.add(Conv2D(32, kernel_size=(5, 5), activation='relu', input_shape=(200,200,1)))
    model.add(Conv2D(64, (5, 5), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.25))
    model.add(Flatten())
    model.add(Dense(738, activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(num_classes, activation='softmax'))

    model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy'])

    model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test))

    score = model.evaluate(x_test, y_test, verbose=0)
    print('Test loss:', score[0])
    print('Test accuracy:', score[1])

代码参考:https://towardsdatascience.com/build-your-own-convolution-neural-network-in-5-mins-4217c2cf964f

1 个答案:

答案 0 :(得分:1)

在分配124时,您的数据具有num_classes=123类。

这些警告是由于您拥有最新的tensorflow版本,而keras尚未更新以完全支持它。