from keras.models import * from keras.layers import * from keras.applications import * from keras.preprocessing.image import * import h5py import warnings warnings.filterwarnings('ignore')
def get_features(MODEL, width, height, lambda_func=None): input_tensor = Input((height, width, 3)) x = input_tensor if lambda_func:
x = Lambda(lambda_func)(x) base_model = MODEL(input_tensor=x, weights='imagenet', include_top=False) model = Model(base_model.input, GlobalAveragePooling2D()(base_model.output)) gen = ImageDataGenerator()
# 注意 train 和 test 是图片存储路径 train_generator = gen.flow_from_directory("train", (width, height), shuffle=False, batch_size=16) test_generator = gen.flow_from_directory("test", (width, height), shuffle=False, batch_size=16, class_mode=None) train = model.predict_generator(train_generator, train_generator.nb_sample) test = model.predict_generator(test_generator, test_generator.nb_sample) with h5py.File("data_%s.h5"%MODEL.func_name) as h: h.create_dataset("train", data=train) h.create_dataset("test", data=test) h.create_dataset("label", data=train_generator.classes)
import h5py import numpy as np from sklearn.utils import shuffle from keras.models import * from keras.layers import *
np.random.seed(12345678) X_train = [] X_test = []
for filename in ["data_ResNet50.h5", "data_Xception.h5", "data_InceptionV3.h5"]: with h5py.File(filename, 'r') as h: X_train.append(np.array(h['train'])) X_test.append(np.array(h['test'])) y_train = np.array(h['label'])
X_train = np.concatenate(X_train, axis=1) X_test = np.concatenate(X_test, axis=1) X_train, y_train = shuffle(X_train, y_train) input_tensor = Input(X_train.shape[1:]) x = Dropout(0.5)(input_tensor) x = Dense(1, activation='sigmoid')(x) model = Model(input_tensor, x) model.compile(optimizer='adadelta', loss='binary_crossentropy', metrics=['accuracy'])