def main():
    """
    Script to export results for Kaggle, Images are read one by one
    """
    args = doParsing()
    print(args)

    # Load model with custom object for mobilenet
    model = load_model(args.modelPath,
                       custom_objects={
                           'relu6': mobilenet.relu6,
                           'DepthwiseConv2D': mobilenet.DepthwiseConv2D
                       })

    print("Loaded model from " + args.modelPath)

    print(model.summary())

    # Dogs and cats test dataset has 12500 samples

    results = []

    for file in sorted(glob.glob(args.datasetTestDir + "/*.jpg")):

        # One by one image prediction

        # Image processing (resize and inception like preprocessing to have [-1.0, 1.0] input range)
        image = imread(file)
        image = imresize(image, size=model.input_shape[1:3])
        image = image.astype(np.float32)
        processedImage = mobilenet.preprocess_input(image)

        # Add 1st dimension for image index in batch
        processedImage = np.expand_dims(processedImage, axis=0)

        # Get and print TOP1 class
        result = model.predict_classes(x=processedImage,
                                       batch_size=1,
                                       verbose=False)
        print(os.path.basename(file) + " -> " + classes[result[0]])

        # Get and save dog probability
        resultProba = model.predict_proba(x=processedImage,
                                          batch_size=1,
                                          verbose=False)
        results.append(
            (os.path.basename(file)[:os.path.basename(file).rfind('.')],
             resultProba[0][classes.index("dog")]))

    print("Test finished")

    if args.kaggleExportFile is not None:
        exportResults(results, args.kaggleExportFile)
Exemple #2
0
def main():
    """
    Predictions for images without labels, images are read one by one and you can export results.
    It works only with mobilenet.
    """

    # TODO: Add a generic load model

    args = doParsing()
    print(args)

    model = load_model(args.modelPath,
                       custom_objects={
                           'relu6': mobilenet.relu6,
                           'DepthwiseConv2D': mobilenet.DepthwiseConv2D
                       })

    print("Loaded model from " + args.modelPath)

    print(model.summary())

    results = []

    for file in tqdm(sorted(glob.glob(args.datasetTestDir + "/*.jpg"))):

        # One by one image prediction

        # Image processing (resize and inception like preprocessing to have [-1.0, 1.0] input range)
        image = imread(file)
        image = imresize(image, size=model.input_shape[1:3])
        image = image.astype(np.float32)
        processedImage = mobilenet.preprocess_input(image)

        # Add 1st dimension for image index in batch
        processedImage = np.expand_dims(processedImage, axis=0)

        # Get and save dog probability
        resultProba = model.predict_proba(x=processedImage,
                                          batch_size=1,
                                          verbose=False)
        results.append(
            (os.path.basename(file)[:os.path.basename(file).rfind('.')],
             resultProba[0]))

    print("Test finished")

    if args.kaggleExportFile is not None:
        exportResults(results, args.labelsFile, args.kaggleExportFile)
        print("Results for kaggle saved in " + args.kaggleExportFile)
Exemple #3
0
def main():
    """
    Script to export results for Kaggle, Images are read one by one
    """
    args = doParsing()
    print(args)

    # Load model
    model = tc.load_model(args.modelPath)

    print("Loaded model from " + args.modelPath)

    # Dogs and cats test dataset has 12500 samples

    results = []

    # One by one image prediction
    for imageFile in sorted(glob.glob(args.datasetTestDir + "/*.jpg")):

        # Load image as tc Image, no explicit resize to model input size
        image = tc.Image(imageFile)

        # Single image SFrame compatible with model utility functions
        sframe = tc.SFrame(data={"features": [image]})

        # Get and print TOP1
        probabilities = model.predict(sframe, output_type="probability_vector")
        print(
            os.path.basename(imageFile) + " -> " +
            model.classes[int(np.argmax(probabilities.to_numpy()[0]))])

        # Get and save dog probability
        results.append((os.path.basename(
            imageFile)[:os.path.basename(imageFile).rfind('.')],
                        probabilities[0][model.classes.index("dog")]))

    print("Test finished")

    if args.kaggleExportFile is not None:
        exportResults(results, args.kaggleExportFile)
Exemple #4
0
def main():
    """
    Example of predict_generator usage for images without labels, images are read one by one and you can export results
    """

    # TODO: Add a generic load model

    args = doParsing()
    print(args)

    model = joblib.load(args.modelPath)

    print("Loaded model from " + args.modelPath)

    results = []

    for file in tqdm(sorted(glob.glob(args.datasetTestDirs[0] + "/*.npy"))):

        # One by one image prediction
        features = []
        features.append(np.load(file))

        if len(args.datasetTestDirs) > 1:
            for datasetTestDir in args.datasetTestDirs[1:]:
                features.append(
                    np.load(
                        os.path.join(datasetTestDir, os.path.basename(file))))

        # Get probabilities
        resultProba = model.predict_proba(
            np.concatenate(features).reshape(1, -1))
        results.append(
            (os.path.basename(file)[:os.path.basename(file).rfind('.')],
             resultProba[0]))

    print("Test finished")

    if args.kaggleExportFile is not None:
        exportResults(results, args.labelsFile, args.kaggleExportFile)
        print("Results for kaggle saved in " + args.kaggleExportFile)
def main():
    """
    Script to export results for Kaggle, Images are read one by one
    """
    args = doParsing()
    print(args)

    # Load config (it includes preprocessing type)
    config = ConfigParams(args.configFile)

    # Load model
    model = TensorflowModel(args.modelPath)

    print("Loaded model from " + args.modelPath)

    # Dogs and cats test dataset has 12500 samples

    results = []

    inputPlaceholder = model.getGraph().get_tensor_by_name(config.inputName +
                                                           ":0")
    outputTensor = model.getGraph().get_tensor_by_name(config.outputName +
                                                       ":0")

    # One by one image prediction forcing CPU usage
    with model.getSession() as sess:

        with tf.device("/cpu:0"):

            for file in sorted(glob.glob(args.datasetTestDir + "/*.jpg")):

                image = ImageUtils.loadImage(file)
                # Resize image and preprocess (inception or vgg preprocessing based on config)
                processedImage = ImageUtils.preprocessing(
                    image=image,
                    width=config.inputSize,
                    height=config.inputSize,
                    preprocessingType=config.preprocessType,
                    meanRGB=config.meanRGB)

                # Convert colorspace
                processedImage = ImageUtils.convertImageFormat(
                    processedImage, format=config.inputFormat)

                # Add 1st dimension for image index in batch
                processedImage = np.expand_dims(processedImage, axis=0)

                # Get and print TOP1 class
                result = sess.run(outputTensor,
                                  feed_dict={inputPlaceholder: processedImage})
                print(
                    os.path.basename(file) + " -> " +
                    classes[int(np.argmax(result[0]))])

                # Get and save dog probability
                results.append((
                    os.path.basename(file)[:os.path.basename(file).rfind('.')],
                    result[0][classes.index("dog")]))

    print("Test finished")

    if args.kaggleExportFile is not None:
        exportResults(results, args.kaggleExportFile)