【问题标题】:Shape error in image classification model in Keras RKeras R中图像分类模型中的形状错误
【发布时间】:2019-05-15 23:56:53
【问题描述】:

我在某个代码领域遇到问题,这使我无法完成研究论文。我是机器学习和 R 的新手,但到目前为止我学到了很多东西。这是我的代码:

    # Install packages and libraries 
    install.packages("keras")
    source("http://bioconductor.org/biocLite.R")
    library(keras)
    library(EBImage)

    # Read images 
    setwd('C:/Users/ebarn/Desktop/DataSet')
    pics <- c('p1.jpg', 'p2.jpg', 'p3.jpg', 'p4.jpg', 'p5.jpg',   
    'p6.jpg','c1.jpg', 'c2.jpg', 'c3.jpg', 'c4.jpg', 'c5.jpg',  
    'c6.jpg')

    mypic <- list()
    for (i in 1:12) {mypic[[i]] <- readImage(pics[i])}

    # Explore 
    print(mypic[[1]])
    display(mypic[[1]])
    display(mypic[[8]])
    summary(mypic[[1]])
    hist(mypic[[12]])
    str(mypic)

    # Resize 
    for (i in 1:12) {mypic[[i]] <- resize(mypic[[i]], 28, 28)}
    str(mypic)

    # Reshape
    28*28*3
    for (i in 1:12) {mypic[[i]] <- array_reshape(mypic[[i]], c(28,   
    28, 3))} 
    str(mypic)

    # Row Bind 
    trainx <- NULL 
    for(i in 1:5) {trainx <- rbind(trainx, mypic[[i]])}
    str(trainx)

    for(i in 7:11) {trainx <- rbind(trainx, mypic[[i]])}
    str(trainx)

    testx <- rbind(mypic[[6]], mypic[[12]])
    trainy <- c(0,0,0,0,0,1,1,1,1,1)
    testy <- c(0, 1)

    # One Hot Encoding 
    trainLabels <- to_categorical(trainy)
    testLabels <- to_categorical(testy)
    trainLabels

    # Model 
    model <- keras_model_sequential()
    model %>%
    layer_dense(units = 256, activation = 'relu', input_shape = 
    c(2352))
    %>%
    layer_dense(units = 128, activation = 'relu') 
    %>% 
    layer_dense(units = 2, activation = 'softmax')

    summary(model)

    # Compile 
    model %>% 
    compile(loss = 'sparse_categorical_crossentropy',
          optimizer = optimizer_rmsprop(),
          metrics = c('accuracy'))

   # model.add(Dense(10, activation = 'softmax'))

   # Fit Model 
   history <- model %>% 
   fit(trainx, trainLabels, epochs = 30, batch_size = 32,    
   validation_split = 0.2)

    plot(history)

    # Evaluation & Prediction - train data
    model %>% evaluate(trainx, trainLabels)

拟合模型方法不会打印出我的图表。这是它给我的错误:

ValueError: Error when checking target: expected dense _1 to have shape (1,) but got array with shape (2,)

【问题讨论】:

标签: r tensorflow machine-learning keras neural-network


【解决方案1】:

您正在对标签进行一次性编码:

# One Hot Encoding 
trainLabels <- to_categorical(trainy)
testLabels <- to_categorical(testy)

因此,它们不再是稀疏标签,您需要使用categorical_crossentropy 作为损失函数而不是sparse_categorical_crossentropy。或者,您可以注释 one-hot 编码行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-26
    • 1970-01-01
    • 2018-07-24
    • 2020-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多