2017-08-26 4 views
1

J'utilise des applications KERAS pour le transfert d'apprentissage avec ResNet 50 et création v3 mais pour prédire toujours obtenir [[ 0.]]Keras model.predict toujours 0

Le code ci-dessous est un problème de classification binaire. J'ai également essayé vgg19 et vgg16 mais ils fonctionnent bien, c'est juste resnet et inception. L'ensemble de données est un partage 50/50. Et je change seulement la ligne de code model = applications.resnet50.ResNet50 pour chaque modèle.

ci-dessous est le code:

from keras.callbacks import EarlyStopping 
early_stopping = EarlyStopping(monitor='val_loss', patience=2) 

img_width, img_height = 256, 256 
train_data_dir = xxx 
validation_data_dir = xxx 
nb_train_samples = 14000 
nb_validation_samples = 6000 
batch_size = 16 
epochs = 50 

if K.image_data_format() == 'channels_first': 
    input_shape = (3, img_width, img_height) 
else: 
    input_shape = (img_width, img_height, 3) 

model = applications.resnet50.ResNet50(weights = "imagenet", include_top=False, input_shape = (img_width, img_height, 3)) 


    from keras.callbacks import EarlyStopping 
early_stopping = EarlyStopping(monitor='val_loss', patience=2) 

img_width, img_height = 256, 256 
train_data_dir = xxx 
validation_data_dir = xxx 
nb_train_samples = 14000 
nb_validation_samples = 6000 
batch_size = 16 
epochs = 50 

if K.image_data_format() == 'channels_first': 
    input_shape = (3, img_width, img_height) 
else: 
    input_shape = (img_width, img_height, 3) 

model = applications.resnet50.ResNet50(weights = "imagenet", include_top=False, input_shape = (img_width, img_height, 3)) 


#Freeze the layers which you don't want to train. Here I am freezing the first 5 layers. 
for layer in model.layers[:5]: 
    layer.trainable = False 

#Adding custom Layers 
x = model.output 
x = Flatten()(x) 
x = Dense(1024, activation="relu")(x) 
x = Dropout(0.5)(x) 
#x = Dense(1024, activation="relu")(x) 
predictions = Dense(1, activation="sigmoid")(x) 

# creating the final model 
model_final = Model(input = model.input, output = predictions) 

# compile the model 
model_final.compile(loss = "binary_crossentropy", optimizer = optimizers.SGD(lr=0.0001, momentum=0.9), metrics=["accuracy"]) 


# Initiate the train and test generators with data Augumentation 
train_datagen = ImageDataGenerator(
    rescale=1./255, 
    shear_range=0.2, 
    zoom_range=0.2, 
    horizontal_flip=True) 

test_datagen = ImageDataGenerator(
    rescale=1./255, 
    shear_range=0.2, 
    zoom_range=0.2, 
    horizontal_flip=True) 

train_generator = train_datagen.flow_from_directory(
    train_data_dir, 
    target_size=(img_width, img_height), 
    batch_size=batch_size, 
    class_mode='binary') 

validation_generator = test_datagen.flow_from_directory(
    validation_data_dir, 
    target_size=(img_width, img_height), 
    batch_size=batch_size, 
    class_mode='binary') 

# Save the model according to the conditions 
#checkpoint = ModelCheckpoint("vgg16_1.h5", monitor='val_acc', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', period=1) 
#early = EarlyStopping(monitor='val_acc', min_delta=0, patience=10, verbose=1, mode='auto') 



model_final.fit_generator(
    train_generator, 
    steps_per_epoch=nb_train_samples // batch_size, 
    epochs=epochs, 
    validation_data=validation_generator, 
    validation_steps=nb_validation_samples // batch_size, 
    callbacks=[early_stopping]) 



from keras.models import load_model 
import numpy as np 
from keras.preprocessing.image import img_to_array, load_img 

#test_model = load_model('vgg16_1.h5') 
img = load_img('testn7.jpg',False,target_size=(img_width,img_height)) 
x = img_to_array(img) 
x = np.expand_dims(x, axis=0) 
#preds = model_final.predict_classes(x) 
prob = model_final.predict(x, verbose=0) 
#print(preds) 
print(prob) 

Notez que model_final.evaluate_generator(validation_generator, nb_validation_samples) fournit une précision attendue comme 80% sa juste prédire qui est toujours 0.

trouve juste étrange que vgg19 et vgg16 fonctionnent bien, mais pas resnet50 et début. Est-ce que ces modèles nécessitent autre chose pour fonctionner?

Toute idée serait géniale.

Merci d'avance.

+0

Comment faites-vous votre prétraitement? Je ne le vois pas dans votre code et c'est peut-être la raison pour laquelle vous obtenez ces résultats. Vous devez importer la fonction de prétraitement appropriée depuis Inception3 ou ResNet et l'utiliser pour préparer vos images (c'est-à-dire 'from fromception_v3 import InceptionV3, preprocess_input'). – petezurich

+0

Aussi, vous devez supprimer 'rescale = 1./255' des générateurs. Sinon, les tableaux d'images seront redimensionnés deux fois. ('inception_v3.preprocess_input()' déjà fait cela pour vous) –

+0

Merci, je vais essayer cela, quoi d'autre preprocessing_input faire? Je ne peux pas trouver des documents pour cela. – Stig

Répondre

0

Merci! preprocessing_input() fonctionne :)

+0

Pouvez-vous [modifier] votre réponse pour expliquer * comment * 'preprocessing_input()' fonctionne? Qu'est ce que ça fait? Comment l'avez-vous appelé? –

0

Je courais dans le même problème. Vous mettez à l'échelle toutes les valeurs RVB de 0-255 à 0-1 pendant l'entraînement.

La même chose devrait être faite au moment de la prédiction. Essayez x = img_to_array(img) x = x/255