├── README.md └── caffe_features_classify.py /README.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/jacobgil/CaffeFeaturesExample/0635c0db786ba770c0ebc37c29858f651377e0b4/README.md -------------------------------------------------------------------------------- /caffe_features_classify.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import sys, time, glob 3 | #caffe_root = "/home/vagrant/caffe/" 4 | #sys.path.insert(0, caffe_root + 'python') 5 | 6 | import caffe 7 | from sklearn.metrics import accuracy_score 8 | from random import shuffle 9 | from sklearn import svm 10 | 11 | def init_net(): 12 | net = caffe.Classifier(caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt', 13 | caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel') 14 | net.set_phase_test() 15 | net.set_mode_cpu() 16 | # input preprocessing: 'data' is the name of the input blob == net.inputs[0] 17 | net.set_mean('data', np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')) # ImageNet mean 18 | net.set_raw_scale('data', 255) # the reference model operates on images in [0,255] range instead of [0,1] 19 | net.set_channel_swap('data', (2,1,0)) # the reference model has channels in BGR order instead of RGB 20 | return net 21 | 22 | def get_features(file, net): 23 | #print "getting features for", file 24 | scores = net.predict([caffe.io.load_image(file)]) 25 | feat = net.blobs['fc8'].data[4][:,0, 0] 26 | return feat 27 | 28 | def shuffle_data(features, labels): 29 | new_features, new_labels = [], [] 30 | index_shuf = range(len(features)) 31 | shuffle(index_shuf) 32 | for i in index_shuf: 33 | new_features.append(features[i]) 34 | new_labels.append(labels[i]) 35 | 36 | return new_features, new_labels 37 | 38 | def get_dataset(net, A_DIR, B_DIR): 39 | CLASS_A_IMAGES = glob.glob(A_DIR + "/*.jpg") 40 | CLASS_B_IMAGES = glob.glob(B_DIR + "/*.jpg") 41 | CLASS_A_FEATURES = map(lambda f: get_features(f, net), CLASS_A_IMAGES) 42 | CLASS_B_FEATURES = map(lambda f: get_features(f, net), CLASS_B_IMAGES) 43 | features = CLASS_A_FEATURES + CLASS_B_FEATURES 44 | labels = [0] * len(CLASS_A_FEATURES) + [1] * len(CLASS_B_FEATURES) 45 | 46 | return shuffle_data(features, labels) 47 | 48 | net = init_net() 49 | x, y = get_dataset(net, sys.argv[1], sys.argv[2]) 50 | l = int(len(y) * 0.4) 51 | 52 | x_train, y_train = x[: l], y[: l] 53 | x_test, y_test = x[l : ], y[l : ] 54 | 55 | clf = svm.SVC() 56 | clf.fit(x_train, y_train) 57 | 58 | y_pred = clf.predict(x_test) 59 | print "Accuracy: %.3f" % accuracy_score(y_test, y_pred) 60 | --------------------------------------------------------------------------------