Created
December 29, 2013 23:18
-
-
Save mthomure/8175902 to your computer and use it in GitHub Desktop.
This script illustrates the application of a trained image classifier to a new set of images in Glimpse.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This script illustrates how to apply a trained image classifier to a new set | |
# of images. | |
# Author: Mick Thomure | |
# Date: 12/29/2013 | |
from glimpse.experiment import * | |
from glimpse.pools import * | |
def PredictImageClasses(exp, images, pool): | |
"""Apply existing model to a new set of images. | |
The experiment object "exp" should have a model and a trained classifier. | |
""" | |
ev = exp.evaluation[0] | |
model = exp.extractor.model | |
# Compute model activity for each image. | |
images = map(model.MakeState, images) | |
builder = Callback(BuildLayer, model, ev.layers, save_all=False) | |
states = pool.map(builder, images) | |
# Create feature vectors from model activity. | |
ftrs = ExtractFeatures(ev.layers, states) | |
# Use the (existing) classifier to predict the class of each image. | |
lbls = ev.results.classifier.predict(ftrs) | |
# Convert the numeric label to a class name. | |
classes = exp.corpus.class_names[lbls] | |
return classes | |
def main(corpus, images): | |
# Number of imprinted prototypes. | |
num_prototypes = 10 | |
# Worker pool used for imprinting and for computing feature vectors. Make it | |
# a MulticorePool() if you want. | |
pool = MulticorePool() | |
# Create the experiment, and train the model. | |
print "Training on %s" % corpus | |
exp = ExperimentData() | |
SetModel(exp) | |
SetCorpus(exp, corpus) | |
MakePrototypes(exp, num_prototypes, 'imprint') | |
ComputeActivation(exp, Layer.C2, pool) | |
TrainAndTestClassifier(exp, Layer.C2) | |
# Apply the model to non-training images. | |
classes = PredictImageClasses(exp, images, pool) | |
print "Predicting class for previously unseen images:" | |
print "\n".join("%s %s" % x for x in zip(images,classes)) | |
# Labeled images for training/testing. | |
corpus = 'glimpse/corpora/data/easy' | |
# Another set of images to which the model is applied. | |
from glob import glob | |
images = glob('glimpse/corpora/data/moderate/circle/*') | |
main(corpus, images) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment