ValueError:形状(None,1)和(None,2)不兼容(使用keras和opencv的卷积神经网络)

时间:2020-10-05 15:05:32

标签: python opencv keras conv-neural-network cnn

我正在使用Google colab上的卷积神经网络训练遮罩检测模型(遮罩与非遮罩)。编译时,出现此错误:

enter image description here

enter image description here

相关代码为:

train_data,test_data,train_target,test_target = train_test_split(data , target , test_size =0.1)

model = Sequential()

model.add(Conv2D(200 , (3,3), input_shape = data.shape[1:])) 
#imageshape=100*100
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
#first cnn layer followed by relu and maxpooling layers

model.add(Conv2D(100,(3,3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size = (2,2)))
#2nd cnn layer follwed by relu and maxpooling layers

model.add(Flatten())
model.add(Dropout(0.5))
#flatten layer

model.add(Dense(50 , activation='relu')) 
model.add(Dropout(0.5))
#dense layer of 50 neurons

model.add(Dense(2,activation= 'softmax'))
#the final layer with 2 outputs for two categories

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

#fit the model
checkpoint = ModelCheckpoint('model-{epoch:03d}.model',monitor='val_loss',verbose=0,save_best_only=True,mode='auto')
 history=model.fit(train_data,train_target,epochs=20,callbacks=[checkpoint],validation_split=0.2)

,模型摘要为:

enter image description here

1 个答案:

答案 0 :(得分:1)

模型的输出形状为(1238,)

train_target

您的Y数据(标签数据)的形状如您在评论0 or 1中提到的那样(我指的是(None, 1)

模型输出形状的设计必须与Y数据的形状匹配。

在这种情况下,您会遇到二进制分类问题,并且您的数据可能具有值(None, 2),即shape = model.add(Dense(1, activation='sigmoid')) #the final layer with 2 outputs for two categories 。但是模型的最后一层会输出形状为#model compile model.compile(loss='binary_crossentropy' , optimizer = 'adam' , metrics['accuracy']) 的数组。

我的建议是将模型更改为仅输出1值而不是2。

模型的代码更改:

    public ActionResult Reports(string ReportType)
    {
        LocalReport localreport = new LocalReport();
        localreport.ReportPath = Server.MapPath("~/Reports/EmployeeReport.rdlc");

        ReportDataSource reportDataSource = new ReportDataSource();
        reportDataSource.Name = "EmployeeReportDataSet";
        reportDataSource.Value = db.Employees.ToList();
        localreport.DataSources.Add(reportDataSource);       
        string mimeType;
        string encoding;
        string fileNameExtension = "XLSX";
     
        string[] streams;
        Warning[] warnings;
        byte[] renderedByte;
        renderedByte = localreport.Render("EXCELOPENXML", null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
        Response.AddHeader("content-disposition", "attachment; filename=employee_report." + fileNameExtension);
        return File(renderedByte, fileNameExtension);

    }

用于编译的代码更改:

select p.*,
       (select count(*)
        from comments c
        where c.fk_commented_post = p.id_post and c.status = 1
       ) as num_comments,
       (select sum(vp.type)
        from votes_posts vp
        where c.fk_voted_post = p.id_post
       ) as num_score       
from posts p
where p.status = 1;