我已经使用预训练的imagenet分类器建立了一个模型,用于对包含30种动物的图片的数据进行特征提取。当我尝试对图像进行分类时,它会引发以下错误。
py_call_impl(可调用,dots $ args,dots $ keywords)错误: ValueError:检查输入时出错:预期density_33_input具有2维,但数组的形状为(1,150,150,3)
代码如下:
extract_features <- function(directory, sample_count){
features <- array(0,dim = c(sample_count,4,4,512))
labels <- array(0,dim = c(sample_count,30))
generator <- flow_images_from_directory(directory = directory,generator = datagen,target_size = c(150,150),
batch_size = batch_size,class_mode = "categorical")
i <- 0
while(TRUE){
batch <- generator_next(generator) #generator_next retrieves the next item
inputs_batch <- batch[[1]]
labels_batch <- batch[[2]]
features_batch <- conv_base %>% predict(inputs_batch)
index_range <- ((i*batch_size)+1):((i+1)*batch_size)
features[index_range, , , ] <- features_batch
labels[index_range,] <- labels_batch
i<-i+1
if(i*batch_size >= sample_count)
break #Because generators yield data indefinitely in a loop, you must break after every image has been seen once.
}
list(features=features,labels=labels)
}
train <- extract_features(train_dir,9400)
validation <- extract_features(validation_dir,2300)
#The extracted features are currently of shape (samples,4,4,512). We will feed them to a densely connected classifier,
#so first we must flatten them to (samples,8192):
reshape_features <- function(features){
array_reshape(features,dim = c(nrow(features),4*4*512))
}
train$features <- reshape_features(train$features)
validation$features <- reshape_features(validation$features)
######Defining and training a densely connected classifier######
model_pretrained <- keras_model_sequential() %>%
layer_dense(units = 512, activation = "relu",input_shape = 4*4*512) %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 512, activation = "relu") %>%
layer_dropout(rate = 0.5) %>%
layer_dense(units = 512, activation = "relu") %>%layer_dropout(rate = 0.5) %>%
layer_dense(units = 30,activation = "sigmoid")
model_pretrained %>% compile(optimizer = "rmsprop",loss = "binary_crossentropy",metrics = c("accuracy"))
history <- model_pretrained %>% fit(train$features,train$labels,epochs = 30, batch_size = 20,
validation_data = list(validation$features,validation$labels))
model_pretrained%>%save_model_hdf5("model_pretrained.h5")
img_path <- "~/Downloads/DL_Beginner/test/Img-10.jpg"
img <- image_load(img_path,target_size =c(150,150))%>%
image_to_array()%>%array_reshape(dim = c(1,150,150,3))%>%imagenet_preprocess_input()
preds <- model_pretrained%>%predict_classes(img)
有人可以帮助我解决这个问题吗?