【问题标题】:Getting error in implementing Keras in R for image classification在 R 中实现 Keras 进行图像分类时出错
【发布时间】:2020-07-15 10:11:20
【问题描述】:

我正在尝试创建一个深度学习模型,用于基于 5 个变量(R、G、B、NIR、NDVI)对图像进行分类。训练样本位于一个点 shapefile 中,其中包含所有 6 个变量,包括类列。我在 R 中使用 Keras 库来创建模型。

library(keras)
install_keras()
library(tensorflow)
install_tensorflow(gpu=T)
library(magrittr)
library("tidyverse")
library(reticulate)

#Training samples 
trainingSamples <- readOGR("Q:/2.0.Projects/Fiber/Satellite/Field Validation/Cerato training samples/Training samples/AllSamples.shp")
data.df <- as.data.frame(trainingSamples)
train.df <- data.df[c(3:7,12)] #3-7 variables are R,G,B,NIR and NDVI and 12th variable is corresponding class.

#converting class variable into numeric (Classes are in characters)
train.df$Class <- as.numeric(train.df$Class)

规范化数据

for (i in 1:5) {
  train.df[,i] <- (train.df[,i]-min(train.df[,i]))/(max(train.df[,i])-min(train.df[,i]))
}

拆分数据 - 确定样本大小

  ind <- sample(2, nrow(train.df), replace=TRUE, prob=c(0.80, 0.20))
    training <- train.df[ind==1, 1:5]
    test <- train.df[ind==2, 1:5]

# Split the class attribute
    traintarget <- train.df[ind==1, 6]
    testtarget <- train.df[ind==2, 6]

一种热编码

trainlabels <- to_categorical(traintarget)
testlabels <- to_categorical(testtarget)

创建模型

model <- keras_model_sequential()
model %>%
  layer_dense(units=5, activation = 'relu', input_shape = c(5)) %>%
  layer_dense(units=1, activation = 'softmax')

summary(model)

#Compiling the model to configure the learning process
model %>%
  compile(loss = 'categorical_crossentropy',
          optimizer = 'adam',
          metrics = 'accuracy')

#Fit model
mymodel <- model %>%
  fit(training, 
      trainlabels,
      epoch=100,
      batch_size=32,
      validation_split=0.2)

错误

Error in (function (classes, fdef, mtable)  : 
  unable to find an inherited method for function ‘fit’ for signature ‘"keras.engine.sequential.Sequential", "matrix"’

我尝试将数据帧转换为矩阵,然后将暗名称应用为 NULL,但仍然出现相同的错误。任何帮助将不胜感激。

【问题讨论】:

    标签: r keras deep-learning neural-network


    【解决方案1】:

    在我意识到我在同一个 R 会话中使用了两个脚本之前,我遇到了完全相同的问题。因此,我加载了一大堆(30 多个)其他库。因此,我重新启动了 R 会话,只加载了 keras 库——问题消失了。所以看起来其他库之一导致了与 fit 函数的冲突。

    【讨论】:

    • 感谢您的建议。我确实删除了除 keras 之外的所有其他库。不幸的是仍然显示相同的错误。
    【解决方案2】:

    通过以下步骤解决该问题: 1. 为这个练习删除一大堆未使用的库(由 @hopethishelps 建议)

    1. 将数据帧转换为矩阵
    2. 如下调整模型 input_shape 和输出层

      模型

    模型 %>%

    输入层

    layer_dense(units = 5, activation = "relu", input_shape = ncol(training)) %>%

    隐藏层

    layer_dense(units = 10, activation = "relu") %>%

    输出层

    layer_dense(units = ncol(trainlabels), activation = "softmax")

    【讨论】:

      猜你喜欢
      • 2018-08-05
      • 1970-01-01
      • 2021-05-08
      • 2019-05-27
      • 2019-08-08
      • 2018-02-19
      • 2019-05-15
      • 2023-04-04
      • 2021-10-12
      相关资源
      最近更新 更多