0
$\begingroup$

Keras 2.1.2 with Tensorflow backend.
The train.py looks like below:

if args.model is not None:
    model = load_model(args.model)
else:
    base_model = inception_v3.InceptionV3(weights='imagenet', include_top=False)
    for layer in base_model.layers[:5]:
       layer.trainable = False
    x = base_model.output
    x = GlobalAveragePooling2D()(x)
    x = Dense(1024, activation='relu')(x)
    predictions = Dense(len(classes), activation='sigmoid')(x)
    model = Model(inputs=base_model.input, outputs=predictions)
    from keras.optimizers import SGD
    model.compile(optimizer=SGD(lr=0.0001, momentum=0.9), loss='binary_crossentropy', metrics=["accuracy"])

datagen = ImageDataGenerator(rotation_range=rotate,
                             horizontal_flip=horizontal_flip,
                             vertical_flip=vertical_flip,
                             width_shift_range=width_shift,
                             height_shift_range=height_shift,
                             rescale=1./255.,
                             fill_mode='nearest')

test_datagen = ImageDataGenerator(rescale=1./255)

img_rows, img_cols = 299, 299
shape = (img_rows, img_cols)

train_generator = datagen.flow_from_directory(
        directory=path,
        target_size=shape,
        color_mode='rgb',
        classes=classes,
        batch_size=batch_size,
        shuffle=True)


validation_generator = test_datagen.flow_from_directory(
        directory=valpath,
        target_size=shape,
        batch_size=batch_size)


#Add checkpoint to save best model
filepath = os.path.join(target, "V3")
for _class in classes:
    filepath += "_" + _class
filepath += "_" + datetime.datetime.now().strftime('%I-%M%p_%d-%b-%Y') + "_{epoch:02d}-{loss:.3f}-{acc:.4f}"  + ".hdf5"

checkpoint = ModelCheckpoint(filepath, verbose=1)
callbacks_list = [checkpoint]

total = 0
for _class in classes:
    total += len(os.listdir(os.path.join(path, _class)))

print("Training on " + str(total) + " images.")

hist = model.fit_generator(generator=train_generator,
                           steps_per_epoch=total/batch_size,
                           epochs=epochs,
                           verbose=1,
                           callbacks=callbacks_list,
               validation_data=validation_generator,
               validation_steps=total/batch_size)

test.py:

from keras.applications.inception_v3 import InceptionV3
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input, decode_predictions

from keras.preprocessing.image import ImageDataGenerator
from keras.models import Model
from keras.models import Sequential
from keras.models import load_model
from keras.layers import Dense, Dropout, Activation, Flatten, BatchNormalization
from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
from keras.regularizers import l2
from keras.utils import np_utils
from keras import backend as K
from keras.callbacks import ModelCheckpoint


model = load_model(args.model)

img_path = '3sep_final_piece_42999170137806862.jpg'
img = image.load_img(img_path, target_size=(299, 299))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

x = preprocess_input(x)

preds = model.predict(x)
print('Predicted:', preds)

Training on 1 class, I want to check if an image belongs to this class or not. Would this method work or I should switch to categorical_cse.

Note:- I had a previously trained 8 class model with softmax activation function instead of sigmoid and categorical_crossentropy, with rest of the train script same. For that, the test.py gives pred like [[0,0,1,0,0,0,0,0]] which makes sense.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.