【发布时间】:2018-07-03 08:00:11
【问题描述】:
我正在尝试训练一个模型来识别图片中的水果种类。它们可以是多标签的(例如,同一图像中的香蕉和苹果)。 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
但是,由于我只有 100 行数据(这对于训练深度学习模型来说太少了),我希望通过使用 keras 图像处理来获得更多数据。我希望通过应用方向更改来生成更多具有相同图像的图像(1 张图像变为 5 张图像)。我在下面尝试了类似的方法,但是当我用新的 numpy 数组拟合我的模型时,我的准确性较低,所以我认为我的代码在下面做错了。我不确定它是什么。
datagen = image_data_generator(
rotation_range=20,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=T)
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) ,steps = 10)
output
}
all_fruit_features <- array(data = 0.1, dim = c(nrow(fruit)*10, 3, 3, 2048))
for (i in 1:nrow(fruit)) {
for (j in 1:10){
lol <- extract_features(fruit$img_path[i])
all_fruit_features[j+(i-1)*10, , , ] <- array_reshape(lol[j], c(1,
dim(lol[j])))
}
}
这里的 all_fruit_features 是一个带有 dim = (1000,3,3,2048) 的数组,这是我想要的,但是当我稍后用我的模型运行它时,它看起来精度较低,我不确定是什么错误的。请帮忙谢谢。
【问题讨论】:
-
您是否尝试过更改旋转范围?还有不同的“假”图像,可以帮助缓解过度拟合,只需添加不同的随机变换,例如:
train_datagen = image_data_generator( rotation_range = 40, width_shift_range = 0.2, height_shift_range = 0.2, shear_range = 0.2, zoom_range = 0.2, horizontal_flip = TRUE, fill_mode = "nearest" ) -
您好,感谢您的回复。我担心代码是否正确运行,即它实际上是在生成具有不同转换的图像,这就是我的模型无法正常运行的原因。我是 keras 的新手,不确定我是否正确编写了代码。解决转换问题可能会在随后改进我的模型,但这不是我现在关心的问题。