/* compute the face descriptors for all faces of the given class, which are used for prediction /* this function is used to "train" the recognizer and has to be performed for all persons faces, /* which you want to recognize before running prediction
969212
function addFaces(faces, className, numJitters = 0) {
      if (!faces || !faces.length) {
        throw new Error('train - expected an array containing atleast one face image')
      }

      if (!className) {
        throw new Error('train - expected a class name')
      }

      const faceDescriptors = flatten(
        faces.map(f => getJitteredFaces(f, numJitters).map(jf => getNet().computeFaceDescriptor(jf)))
      )

      addFaceDescriptors(faceDescriptors, className)
    }
902628
function loadPresetDescriptor(descriptor) {
  return {
    type: "preset",
    options: loadDescriptor(descriptor).value,
    alias: descriptor.alias,
    loc: descriptor.loc,
    dirname: descriptor.dirname
  };
}
280639
function isStage1ClassDescriptor(possibleDesc) {
  let [target] = possibleDesc;

  return (
    possibleDesc.length === 1 &&
    typeof target === 'function' &&
    'prototype' in target &&
    !target.__isComputedDecorator
  );
}
949415
def computePreRec(cm, class_names):
    '''
    
    '''
    n_classes = cm.shape[0]
    if len(class_names) != n_classes:
        print("Error in computePreRec! Confusion matrix and class_names "
              "list must be of the same size!")
        return
    precision = []
    recall = []
    f1 = []    
    for i, c in enumerate(class_names):
        precision.append(cm[i,i] / numpy.sum(cm[:,i]))
        recall.append(cm[i,i] / numpy.sum(cm[i,:]))
        f1.append( 2 * precision[-1] * recall[-1] / (precision[-1] + recall[-1]))
    return recall, precision, f1
174652
def with_descriptor(self, descriptor):
        '''
        
        '''
        res = {}
        desc = "%s_descriptor" % descriptor
        for eid, ent in self.items():
            if desc in ent:
                res[eid] = ent
        return res
774783
def polynet(num_classes=1000, pretrained='imagenet'):
    
    if pretrained:
        settings = pretrained_settings['polynet'][pretrained]
        assert num_classes == settings['num_classes'], \
            'num_classes should be {}, but is {}'.format(
                settings['num_classes'], num_classes)
        model = PolyNet(num_classes=num_classes)
        model.load_state_dict(model_zoo.load_url(settings['url']))
        model.input_space = settings['input_space']
        model.input_size = settings['input_size']
        model.input_range = settings['input_range']
        model.mean = settings['mean']
        model.std = settings['std']
    else:
        model = PolyNet(num_classes=num_classes)
    return model
231299
function detectFaces(img, faceSize = 150) {
      return locateFaces(img)
        .then(rects => getFacesFromLocations(img, rects.map(mmodRect => mmodRect.rect), faceSize))
    }
715251
private Set<ClassDescriptor> computeKnownSubtypes(ClassDescriptor classDescriptor) throws ClassNotFoundException {
        LinkedList<ClassVertex> workList = new LinkedList<>();

        ClassVertex startVertex = resolveClassVertex(classDescriptor);
        workList.addLast(startVertex);

        Set<ClassDescriptor> result = new HashSet<>();

        while (!workList.isEmpty()) {
            ClassVertex current = workList.removeFirst();

            if (result.contains(current.getClassDescriptor())) {
                // Already added this class
                continue;
            }

            // Add class to the result
            result.add(current.getClassDescriptor());

            // Add all known subtype vertices to the work list
            Iterator<InheritanceEdge> i = graph.incomingEdgeIterator(current);
            while (i.hasNext()) {
                InheritanceEdge edge = i.next();
                workList.addLast(edge.getSource());
            }
        }

        return new HashSet<>(result);
    }
820882
@Override
	public void trainOnInstance(Instance inst) {
		// Update class statistics with weights
		int classIndex = (int) inst.classValue();
		Double weight = this.classInstances.get(classIndex);
		if (weight == null)
			weight = 0.;
		this.classInstances.put(classIndex, weight + inst.weight());
		
		// Get the class prototype
		Double classPrototype = this.classPrototypes.get(classIndex);
		if (classPrototype == null)
			classPrototype = 1.;
		
		// Iterate over the attributes of the given instance
		for (int attributePosition = 0; attributePosition < inst
				.numAttributes(); attributePosition++) {
			// Get the attribute index - Dense -> 1:1, Sparse is remapped
			int attributeID = inst.index(attributePosition);
			// Skip class attribute
			if (attributeID == inst.classIndex())
				continue;
			// Get the attribute observer for the current attribute
			GaussianNumericAttributeClassObserver obs = this.attributeObservers
					.get(attributeID);
			// Lazy init of observers, if null, instantiate a new one
			if (obs == null) {
				// FIXME: At this point, we model everything as a numeric
				// attribute
				obs = new GaussianNumericAttributeClassObserver();
				this.attributeObservers.put(attributeID, obs);
			}
			
			// Get the probability density function under the current model
			GaussianEstimator obs_estimator = obs.getEstimator(classIndex);
			if (obs_estimator != null) {
				// Fetch the probability that the feature value is zero
				double probDens_zero_current = obs_estimator.probabilityDensity(0);
				classPrototype -= probDens_zero_current;
			}
			
			// FIXME: Sanity check on data values, for now just learn
			// Learn attribute value for given class
			obs.observeAttributeClass(inst.valueSparse(attributePosition),
					(int) inst.classValue(), inst.weight());
			
			// Update obs_estimator to fetch the pdf from the updated model
			obs_estimator = obs.getEstimator(classIndex);
			// Fetch the probability that the feature value is zero
			double probDens_zero_updated = obs_estimator.probabilityDensity(0);
			// Update the class prototype
			classPrototype += probDens_zero_updated;
		}
		// Store the class prototype
		this.classPrototypes.put(classIndex, classPrototype);
		// Count another training instance
		this.instancesSeen++;
	}
442044
public static int cudnnGetFilter4dDescriptor(
        cudnnFilterDescriptor filterDesc, 
        int[] dataType, /** image data type */
        int[] format, 
        int[] k, /** number of output feature maps */
        int[] c, /** number of input feature maps */
        int[] h, /** height of each input filter */
        int[] w)/**  */
    {
        return checkResult(cudnnGetFilter4dDescriptorNative(filterDesc, dataType, format, k, c, h, w));
    }
1374236
function LDA(...classes) {
	// Compute pairwise LDA classes (needed for multiclass LDA)
	if(classes.length < 2) {
		throw new Error('Please pass at least 2 classes');
	}

	let numberOfPairs = classes.length * (classes.length - 1) / 2;
	let pair1 = 0;
	let pair2 = 1;

	let pairs = new Array(numberOfPairs);

	for(let i = 0; i < numberOfPairs; i++){
		pairs[i] = computeLdaParams(classes[pair1], classes[pair2], pair1, pair2);

		pair2++;
		if(pair2 == classes.length) {
			pair1++;
			pair2 = pair1 + 1;
		}
	} 

	this.pairs = pairs;
	this.numberOfClasses = classes.length;
}
198338
def _predict(self, features):
        

        from sklearn.exceptions import NotFittedError

        try:
            prediction = self.kernel.predict_classes(features)[:, 0]
        except NotFittedError:
            raise NotFittedError(
                "{} is not fitted yet. Call 'fit' with appropriate "
                "arguments before using this method.".format(
                    type(self).__name__
                )
            )

        return prediction
866581
def _prob_match(self, features):
        

        # compute the probabilities
        probs = self.kernel.predict_proba(features)

        # get the position of match probabilities
        classes = list(self.kernel.classes_)
        match_class_position = classes.index(1)

        return probs[:, match_class_position]
110075
function getFacesFromLocations(img, rects, faceSize = 150) {
      const shapes = rects.map(rect => faceLandmarkPredictor.predict(img, rect))
      return fr.extractImageChips(img, fr.getFaceChipDetails(shapes, faceSize))
    }
313447
@Override
    public ISeqClassifier train(List<SequenceTuple> trainingData) {
        if (trainingData == null || trainingData.size() == 0) {
            LOG.warn("Training data is empty.");
            return this;
        }

        if (modelPath == null) {
            try {
                modelPath = Files.createTempDirectory("crfsuite").toAbsolutePath().toString();
            } catch (IOException e) {
                LOG.error("Create temp directory failed.", e);
                e.printStackTrace();
            }
        }

        Pair<List<ItemSequence>, List<StringList>> crfCompatibleTrainingData = loadTrainingData(trainingData);
        Trainer trainer = new Trainer();

        String algorithm = (String) props.getOrDefault("algorithm", DEFAULT_ALGORITHM);
        props.remove("algorithm");
        String graphicalModelType = (String) props.getOrDefault("graphicalModelType", DEFAULT_GRAPHICAL_MODEL_TYPE);
        props.remove("graphicalModelType");

        trainer.select(algorithm, graphicalModelType);

        // Set parameters
        props.entrySet().forEach(pair -> trainer.set((String) pair.getKey(), (String) pair.getValue()));

        // Add training data into the trainer
        for (int i = 0; i < trainingData.size(); i++) {
            // Use group id = 0 but the API doesn't say what it is used for :(
            trainer.append(crfCompatibleTrainingData.getLeft().get(i), crfCompatibleTrainingData.getRight().get(i), 0);
        }

        // Start training without hold-outs. trainer.message()
        // will be called to report the training process
        trainer.train(modelPath, -1);
        return this;
    }
900850
function (Class, descriptors) {
    ClassFactory.prototype.updateDynamicFunctions.call(this, Class, descriptors);
    if (!Class.cast || Class.cast.isAutoGenerated) {
      Class.cast = this.createStaticCast(Class, descriptors);
    }
    if (!Class.validate || Class.validate.isAutoGenerated) {
      Class.validate = this.createStaticValidate(Class, descriptors);
    }
    if (!Class.input || Class.input.isAutoGenerated) {
      Class.input = this.createStaticInput(Class, descriptors);
    }
    if (!Class.toJSON || Class.toJSON.isAutoGenerated) {
      Class.toJSON = this.createStaticToJSON(Class, descriptors);
    }
  }
265478
function addFaces(faces, className, numJitters = 0) {
      if (!faces || !faces.length) {
        throw new Error('train - expected an array containing atleast one face image')
      }

      if (!className) {
        throw new Error('train - expected a class name')
      }

      const promises = flatten(
        faces.map(
          f => getJitteredFaces(f, numJitters).map(
            () => getNet().computeFaceDescriptorAsync(f)
          )
        )
      )

      return Promise.all(promises)
        .then(descriptors => addFaceDescriptors(descriptors, className))
    }