我的目标是采用一个没有最后两个完全连接层的预训练模型来为 CIFAR-10 构建新的我自己的分类器。我遇到的第一个问题是 VGG 需要至少 48*48*3
张量,而 CIFAR-10 数据集带有 32*32*3
图像。我知道 ImageDataGenerator.flow_from_directory
带有内置 target_size
参数,但我不能在这里使用它,因为图像已经在内存中:
from keras.applications import VGG16
from keras.datasets import cifar10
from keras.preprocessing.image import ImageDataGenerator
import numpy as np
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
vgg_conv = VGG16(weights='imagenet', include_top=False, input_shape=(48, 48, 3)) # 48 its a minimum width
>> type(x_train) #we have numpy here
numpy.ndarray
为了转换图像,我使用skimage
(不知道为什么,但它似乎有效):
from skimage import transform
new_shape = (48,88,3)
x_train = np.asarray([transform.resize(image, new_shape) for image in x_train])
接下来我们将其传递给生成器,以便能够批量向 NN 提供数据。不幸的是它没有 target_size
参数,所以我之前使用过 resize
:
train_generator = datagen.flow(
x_train,
batch_size=batch_size,
shuffle=True)
然后我迭代 train_generator
但没有运气:
for inputs_batch in train_generator:
features_batch = vgg_conv.predict(inputs_batch)
train_features[i * batch_size : (i + 1) * batch_size] = features_batch
i += 1
if i * batch_size >= nImages:
break
这是我收到的错误:
ValueError Traceback (most recent call last) ----> 2 features_batch = vgg_conv.predict(inputs_batch) ValueError: Error when checking input: expected input_4 to have shape (48, 48, 3) but got array with shape (48, 88, 3)
该问题可能与流生成器
有关,其中:
# Returns
An `Iterator` yielding tuples of `(x, y)`
where `x` is a numpy array of image data
(in the case of a single image input) or a list
of numpy arrays (in the case with
additional inputs) and `y` is a numpy array
of corresponding labels. If 'sample_weight' is not None,
the yielded tuples are of the form `(x, y, sample_weight)`.
If `y` is None, only the numpy array `x` is returned.
所以我有两个问题:这里出了什么问题,有没有更好的方法来调整图像大小,也许有一些内置于 Keras 函数中?
最佳答案
(注意: as per requested by OP,我已将我的评论合并到这个答案中。)
这里有一个拼写错误:
new_shape = (48,88,3)
;它应该是new_shape = (48,48,3)
,即48
而不是88
,如错误所示。不要忘记通过将
rescale=1./255
传递给ImageDataGenerator
来标准化图像。至于调整图像大小,您当前的方法很好。但您也可以尝试 this SO answer 中提供的解决方案。上述解决方案的优点是它将成为模型的一部分,您可以向模型提供任意大小的图像。
关于python - 使用skimage调整到更大的分辨率会导致keras中的形状类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51126531/