使用预训练模型时如何在R中应用keras图像预处理

使用预训练模型时如何在R中应用keras图像预处理,r,keras,R,Keras,我试图训练一个模型来识别图片中有什么水果。它们可以是多标签的(例如,同一图像中的香蕉和苹果)。100行数据(水果)存储在csv文件中,前几行如下所示: Key Banana Apple Orange img_path 1 0 0 1 data/121.jpg 2 0 1 1 data/228.jpg 3 1 0 1 data/368.jpg ... 我要做的方法是在使用预先训练的模型(InceptionV3)训练我的keras模型之前,先提取特征。下面的代码工作得很好,我能够得到我想要的东西来

我试图训练一个模型来识别图片中有什么水果。它们可以是多标签的(例如,同一图像中的香蕉和苹果)。100行数据(水果)存储在csv文件中,前几行如下所示:

Key Banana Apple Orange img_path
1 0 0 1 data/121.jpg
2 0 1 1 data/228.jpg
3 1 0 1 data/368.jpg
...
我要做的方法是在使用预先训练的模型(InceptionV3)训练我的keras模型之前,先提取特征。下面的代码工作得很好,我能够得到我想要的东西来训练我的模型

fruit_model <- application_inception_v3(weights = 'imagenet', include_top = F,
                            input_shape = c(150, 150, 3))
freeze_weights(fruit_model)
extract_features <- function(img_path) {
   img <- image_load(img_path, target_size = c(150,150))
   x <- image_to_array(img)
   x <- array_reshape(x, c(1, dim(x)))
   x <- inception_v3_preprocess_input(x)

   output <- predict(fruit_model, x)
   output

 }

all_fruit_features <- array(data = 0.1, dim = c(nrow(fruit), 3, 3, 2048))

for (i in 1:nrow(fruit)) {
 all_fruit_features[i, , , ] <- extract_features(fruit$img_path[i])
}
# The all_fruit_features is an array with dim = (100,3,3,2048) which is the numpy array (x) that i use when fitting my model later on 

fruit\u模型问题解决。predict_generator的参数在上述代码中工作不正常。附加的是更新后的代码

extract_features <- function(img_path) {
  img <- image_load(img_path, target_size = c(150,150))
  x <- image_to_array(img)
  x <- array_reshape(x, c(1, dim(x)))
  x <- inception_v3_preprocess_input(x)
  output <- predict_generator(fruit_model,flow_images_from_data(x,generator = 
datagen,save_to_dir = 'image_folder',save_format = 'png'),steps=10)
  output
}

extract\u特征您是否尝试过更改旋转范围?另外,不同的“假”图像也有助于缓解过度拟合,只需添加不同的随机变换,例如:
train\u datagen=image\u data\u generator(旋转范围=40,宽度\u shift\u range=0.2,高度\u shift\u range=0.2,剪切范围=0.2,缩放范围=0.2,水平翻转=TRUE,填充模式=“最近”)
Hi,谢谢你的回复。我担心代码是否正确运行,也就是说,它实际生成的图像具有不同的转换,这就是我的模型无法正常工作的原因。我是keras的新手,不确定我是否正确编写了代码。处理转换可能会改进我的模型,但这不是我现在关心的问题。
extract_features <- function(img_path) {
  img <- image_load(img_path, target_size = c(150,150))
  x <- image_to_array(img)
  x <- array_reshape(x, c(1, dim(x)))
  x <- inception_v3_preprocess_input(x)
  output <- predict_generator(fruit_model,flow_images_from_data(x,generator = 
datagen,save_to_dir = 'image_folder',save_format = 'png'),steps=10)
  output
}