<s> import cPickle <EOL> import caffe <EOL> import cv2 <EOL> import glob <EOL> import logging <EOL> import numpy <EOL> import os <EOL> class ImageClassifier ( object ) : <EOL> def __init__ ( self , model , gpu_mode = False ) : <EOL> self . model = model <EOL> kwargs = { } <EOL> if self . model . get ( "<STR_LIT>" ) : <EOL> kwargs [ '<STR_LIT>' ] = tuple ( self . model . get ( "<STR_LIT>" ) ) <EOL> if self . model . get ( "<STR_LIT>" ) : <EOL> kwargs [ '<STR_LIT>' ] = tuple ( self . model . get ( "<STR_LIT>" ) ) <EOL> if self . model . get ( "<STR_LIT>" ) : <EOL> kwargs [ '<STR_LIT>' ] = float ( self . model . get ( "<STR_LIT>" ) ) <EOL> if self . model . get ( "<STR_LIT>" ) : <EOL> kwargs [ '<STR_LIT>' ] = numpy . array ( self . model . get ( "<STR_LIT>" ) ) <EOL> self . net = caffe . Classifier ( <EOL> model . deploy_path ( ) , <EOL> model . model_path ( ) , <EOL> ** kwargs <EOL> ) <EOL> self . confidence_threshold = <NUM_LIT:0.1> <EOL> if gpu_mode : <EOL> caffe . set_mode_gpu ( ) <EOL> else : <EOL> caffe . set_mode_cpu ( ) <EOL> self . labels = numpy . array ( model . labels ( ) ) <EOL> if self . model . bet_path ( ) : <EOL> self . bet = cPickle . load ( open ( self . model . bet_path ( ) ) ) <EOL> self . bet [ '<STR_LIT>' ] = map ( lambda w : w . replace ( '<STR_LIT:U+0020>' , '<STR_LIT:_>' ) , self . bet [ '<STR_LIT>' ] ) <EOL> else : <EOL> self . bet = None <EOL> self . net . forward ( ) <EOL> def classify_image ( self , filename ) : <EOL> image = caffe . io . load_image ( open ( filename ) ) <EOL> scores = self . net . predict ( [ image ] , oversample = True ) . flatten ( ) <EOL> if self . bet : <EOL> expected_infogain = numpy . dot ( self . bet [ '<STR_LIT>' ] , scores [ self . bet [ '<STR_LIT>' ] ] ) <EOL> expected_infogain *= self . bet [ '<STR_LIT>' ] <EOL> infogain_sort = expected_infogain . argsort ( ) [ : : - <NUM_LIT:1> ] <EOL> results = [ <EOL> ( self . bet [ '<STR_LIT>' ] [ v ] , float ( expected_infogain [ v ] ) ) <EOL> for v in infogain_sort <EOL> if expected_infogain [ v ] > self . confidence_threshold <EOL> ] <EOL> else : <EOL> indices = ( - scores ) . argsort ( ) <EOL> predictions = self . labels [ indices ] <EOL> results = [ <EOL> ( p , float ( scores [ i ] ) ) <EOL> for i , p in zip ( indices , predictions ) <EOL> if scores [ i ] > self . confidence_threshold <EOL> ] <EOL> return results </s>
