def RunPCAShogun(q): totalTimer = Timer() # Load input dataset. Log.Info("Loading dataset", self.verbose) try: feat = RealFeatures(self.data.T) with totalTimer: # Get the options for running PCA. if "new_dimensionality" in options: k = int(options.pop("new_dimensionality")) if (k > self.data.shape[1]): Log.Fatal("New dimensionality (" + str(k) + ") cannot be greater than" + "existing dimensionality (" + str(self.data.shape[1]) + ")!") q.put(-1) return -1 else: k = self.data.shape[1] if "whiten" in options: s = True options.pop("whiten") else: s = False if len(options) > 0: Log.Fatal("Unknown parameters: " + str(options)) raise Exception("unknown parameters") # Perform PCA. prep = ShogunPCA(s) prep.set_target_dim(k) prep.init(feat) prep.apply_to_feature_matrix(feat) except Exception as e: q.put(-1) return -1 time = totalTimer.ElapsedTime() q.put(time) return time
def RunPCAShogun(q): totalTimer = Timer() # Load input dataset. Log.Info("Loading dataset", self.verbose) try: feat = RealFeatures(self.data.T) with totalTimer: # Find out what dimension we want. match = re.search('-d (\d+)', options) if not match: k = self.data.shape[1] else: k = int(match.group(1)) if (k > self.data.shape[1]): Log.Fatal("New dimensionality (" + str(k) + ") cannot be greater than" + "existing dimensionality (" + str(self.data.shape[1]) + ")!") q.put(-1) return -1 # Get the options for running PCA. s = True if options.find("-s") > -1 else False # Perform PCA. prep = ShogunPCA(s) prep.set_target_dim(k) prep.init(feat) prep.apply_to_feature_matrix(feat) except Exception as e: q.put(-1) return -1 time = totalTimer.ElapsedTime() q.put(time) return time
def RunPCAShogun(): totalTimer = Timer() # Load input dataset. Log.Info("Loading dataset", self.verbose) try: feat = RealFeatures(self.data.T) with totalTimer: # Get the options for running PCA. if "new_dimensionality" in options: k = int(options.pop("new_dimensionality")) if (k > self.data.shape[1]): Log.Fatal("New dimensionality (" + str(k) + ") cannot be greater than" + "existing dimensionality (" + str(self.data.shape[1]) + ")!") return -1 else: k = self.data.shape[1] if "whiten" in options: s = True options.pop("whiten") else: s = False if len(options) > 0: Log.Fatal("Unknown parameters: " + str(options)) raise Exception("unknown parameters") # Perform PCA. prep = ShogunPCA(s) prep.set_target_dim(k) prep.init(feat) prep.apply_to_feature_matrix(feat) except Exception as e: return -1 return totalTimer.ElapsedTime()
class EigenFaces(): def __init__(self, num_components): """ Constructor """ self._num_components = num_components self._projections = [] def train(self, images, labels): """ Train eigenfaces """ print "Train..." #copy labels self._labels = labels #transform the numpe vector to shogun structure features = RealFeatures(images) #PCA self.pca = PCA() #set dimension self.pca.set_target_dim(self._num_components) #compute PCA self.pca.init(features) for sampleIdx in range(features.get_num_vectors()): v = features.get_feature_vector(sampleIdx) p = self.pca.apply_to_feature_vector(v) self._projections.insert(sampleIdx, p) print "Train ok!" def predict(self, image): """ Predict the face """ #image as row imageAsRow = np.asarray( image.reshape(image.shape[0] * image.shape[1], 1), np.float64) #project inthe subspace p = self.pca.apply_to_feature_vector( RealFeatures(imageAsRow).get_feature_vector(0)) #min value to find the face minDist = 1e100 #class minClass = -1 #search which face is the best match for sampleIdx in range(len(self._projections)): test = RealFeatures(np.asmatrix(p, np.float64).T) projection = RealFeatures( np.asmatrix(self._projections[sampleIdx], np.float64).T) dist = EuclideanDistance(test, projection).distance(0, 0) if (dist < minDist): minDist = dist minClass = self._labels[sampleIdx] return minClass def getMean(self): """ Return the mean vector """ return self.pca.get_mean() def getEigenValues(self): """ Return the eigenvalues vector """ return self.pca.get_eigenvalues()
#Read the last image of the file to test Eigenfaces image = cv2.resize(cv2.imread(list_filenames[0], cv2.IMREAD_GRAYSCALE), (IMAGE_HEIGHT, IMAGE_WIDHT)) #image as row imageAsRow = np.asarray(image.reshape(image.shape[0] * image.shape[1], 1), np.float64) #Reconstruct 10 eigen vectors to 300, step 15 for i in range(10, 300, 50): print "Reconstruct with " + str(i) + " eigenvectors" pca = PCA() #set dimension pca.set_target_dim(i) #compute PCA pca.init(RealFeatures(images)) pca.apply_to_feature_vector( RealFeatures(imageAsRow).get_feature_vector(0)) #reconstruct projection = pca.apply_to_feature_vector( RealFeatures(imageAsRow).get_feature_vector(0)) reconstruction = np.asmatrix( np.asarray(projection, np.float64))* \ np.asmatrix( pca.get_transformation_matrix()).T reconstruction = reconstruction + pca.get_mean() #normlize image
class EigenFaces(): def __init__(self, num_components): """ Constructor """ self._num_components = num_components; self._projections = [] def train(self, images, labels): """ Train eigenfaces """ print "Train...", #copy labels self._labels = labels; #transform the numpe vector to shogun structure features = RealFeatures(images) #PCA self.pca = PCA() #set dimension self.pca.set_target_dim(self._num_components); #compute PCA self.pca.init(features) for sampleIdx in range(features.get_num_vectors()): v = features.get_feature_vector(sampleIdx); p = self.pca.apply_to_feature_vector(v); self._projections.insert(sampleIdx, p); print "ok!" def predict(self, image): """ Predict the face """ #image as row imageAsRow = np.asarray(image.reshape(image.shape[0]*image.shape[1],1), np.float64); #project inthe subspace p = self.pca.apply_to_feature_vector(RealFeatures(imageAsRow).get_feature_vector(0)); #min value to find the face minDist =1e100; #class minClass = -1; #search which face is the best match for sampleIdx in range(len(self._projections)): test = RealFeatures(np.asmatrix(p,np.float64).T) projection = RealFeatures(np.asmatrix(self._projections[sampleIdx], np.float64).T) dist = EuclideanDistance( test, projection).distance(0,0) if(dist < minDist ): minDist = dist; minClass = self._labels[sampleIdx]; return minClass def getMean(self): """ Return the mean vector """ return self.pca.get_mean() def getEigenValues(self): """ Return the eigenvalues vector """ return self.pca.get_eigenvalues();
#image as row imageAsRow = np.asarray(image.reshape(image.shape[0]*image.shape[1],1), np.float64); reconstructions = range(10, 250, 50) reconstructions_images = np.empty( (IMAGE_HEIGHT, IMAGE_WIDHT*len(reconstructions) ), np.uint8) #Reconstruct 10 eigen vectors to 300, step 15 for i in reconstructions: print "Reconstruct with " + str(i) + " eigenvectors" pca = PCA() #set dimension pca.set_target_dim(i); #compute PCA pca.init(RealFeatures(images)) pca.apply_to_feature_vector(RealFeatures(imageAsRow) .get_feature_vector(0)); #reconstruct projection = pca.apply_to_feature_vector(RealFeatures(imageAsRow) .get_feature_vector(0)); reconstruction = np.asmatrix( np.asarray(projection, np.float64))* \ np.asmatrix( pca.get_transformation_matrix()).T reconstruction = reconstruction + pca.get_mean() #prepare the data to visualize in one window