我正在尝试运行使用VGG16的代码https://github.com/fchollet/deep-learning-with-python-notebooks/blob/master/5.3-using-a-pretrained-convnet.ipynb。我的数据集来自https://www.kaggle.com/c/dogs-vs-cats/data。我在一个名为sample的文件夹中有三个文件夹测试,训练,验证。我使用train文件夹中未使用的图像并将其存储在validate中。
我查看了Solution 1,Solution 2或Solution 3错误 ZeroDivisionError:整数除法或模数为零,但我似乎无法解决我面临的问题。错误发生在features[i * batch_size : (i + 1) * batch_size] = features_batch
。
import keras
keras.__version__
from keras.applications import VGG16
conv_base = VGG16(weights='imagenet',
include_top=False,
input_shape=(150, 150, 3))
conv_base.summary()
import os
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
base_dir = 'C:\\Users\\K\\Documents\\Code\\sample'
test_dir = os.path.join(base_dir, 'test')
train_dir = os.path.join(base_dir, 'train')
validation_dir = os.path.join(base_dir, 'validation')
datagen = ImageDataGenerator(rescale=1./255)
batch_size = 20
def extract_features(directory, sample_count):
features = np.zeros(shape=(sample_count, 4, 4, 512))
labels = np.zeros(shape=(sample_count))
generator = datagen.flow_from_directory(directory,target_size=(150, 150),batch_size=batch_size,class_mode='binary')
i = 0
for inputs_batch, labels_batch in generator:
features_batch = conv_base.predict(inputs_batch)
features[i * batch_size : (i + 1) * batch_size] = features_batch
labels[i * batch_size : (i + 1) * batch_size] = labels_batch
i += 1
if i * batch_size >= sample_count:
# Note that since generators yield data indefinitely in a loop,
# we must `break` after every image has been seen once.
break
return features, labels
train_features, train_labels = extract_features(train_dir, 2000)
validation_features, validation_labels = extract_features(validation_dir, 1000)
test_features, test_labels = extract_features(test_dir, 1000)