Я пытаюсь построить сверточную нейронную сеть в R, используя изображения, которые я скачал на свой компьютер из inte rnet! Эти изображения находятся в разных папках, но не помечены (помечены только папки). Я пометил изображения на своем поезде другим сценарием! Я создал свою модель, но когда я пытаюсь запустить историю заказов и график:
history <- model %>%
fit(
x= trainData$X, y= as.numeric(trainData$y),
epochs = 100,
batch_size = 32,
validation_split = 0.2,
)
plot(history)
У меня появляются следующие ошибки:
1) Ошибка в py_call_impl (вызываемый, точки $ args, точки $ ключевые слова):
ValueError: Нет данных для "conv2d_4_input". Нужны данные для каждого ключа: ['conv2d_4_input']
2) Ошибка в кривой (expr = x, from = from, to = to, xlim = xlim, ylab = ylab,: 'expr' не сделал оценить объект длины 'n'
Что я могу сделать, чтобы исправить их?
Мой код:
setwd("C:/Users/User/Desktop/R files mine/yes")
library(keras)
library(EBImage)
library(stringr)
library(pbapply)
library(tensorflow)
secondaccordion <- readImage("train/accordion/accordion_0002.jpg")
display(secondaccordion)
width <- 100
height <- 100
dir_path <- "train/"
extract_feature <- function(dir_path, width, height, labelsExist = T) {
img_size <- width * height
images_names <- list.files(dir_path, pattern="*.jpg",recursive = TRUE)
if(labelsExist){
## Select only cats or dogs images
accairanchant <- str_extract(images_names, "^(accordion|airplanes|anchor|ant)")
# Set accordion == 0, airplanes == 1, anchor == 2, ant == 3
key <- c("accordion" = 0, "airplanes" = 1, "anchor" = 2, "ant" = 3)
y <- key[accairanchant]
}
print(paste("Start processing", length(images_names), "images"))
## This function will resize an image, turn it into greyscale
feature_list <- pblapply(images_names, function(imgname) {
## Read image
img <- readImage(file.path(dir_path, imgname))
## Resize image
img_resized <- resize(img, w = width, h = height)
## Set to grayscale (normalized to max)
grayimg <- channel(img_resized, "gray")
## Get the image as a matrix
img_matrix <- grayimg@.Data
## Coerce to a vector (row-wise)
img_vector <- as.vector(t(img_matrix))
return(img_vector)
})
## bind the list of vector into matrix
feature_matrix <- do.call(rbind, feature_list)
feature_matrix <- as.data.frame(feature_matrix)
## Set names
names(feature_matrix) <- paste0("pixel", c(1:img_size))
if(labelsExist){
return(list(X = feature_matrix, y = y))
}else{
return(feature_matrix)
}
}
trainData <- extract_feature(dir_path = "train/", width = width, height = height)
testData <- extract_feature("test/", width, height, labelsExist = F)
par(mar = rep(0, 4))
testaccordion <- t(matrix(as.numeric(trainData$X[2,]),
nrow = width, ncol = height, T))
image(t(apply(testaccordion, 2, rev)), col = gray.colors(12),
axes = F)
str(testaccordion,2)
save(trainData, testData, file = "accairanchant.Rdata")
model <- keras_model_sequential() %>%
layer_conv_2d(filters = 32, kernel_size = c(3,3), activation = "relu",
input_shape = c(100,100,1),data_format='channels_last') %>%
layer_max_pooling_2d(pool_size = c(2,2)) %>%
layer_conv_2d(filters = 64, kernel_size = c(3,3), activation = "relu") %>%
layer_max_pooling_2d(pool_size = c(2,2)) %>%
layer_conv_2d(filters = 64, kernel_size = c(3,3), activation = "relu")
summary(model)
model %>%
layer_dropout(rate = 0.25) %>%
layer_flatten() %>%
layer_dense(units = 64, activation = "relu") %>%
layer_dropout(rate = 0.25) %>%
layer_dense(units = 4, activation = "softmax")
summary(model)
model %>% compile(
optimizer = "adam",
loss = "sparse_categorical_crossentropy",
metrics = "accuracy"
)
history <- model %>%
fit(
x= trainData$X, y= as.numeric(trainData$y),
epochs = 100,
batch_size = 32,
validation_split = 0.2,
)
plot(history)
evaluate(model, testData[1], testData[2], verbose = 0)