Exemple #1
0
def _liblinear_classify(vecs, model):
    from linearutil import predict as liblinear_predict
    import sys
    orig_stdout = sys.stdout
    try:
        with open('/dev/null', 'w') as dev_null:
            sys.stdout = dev_null
            # We don't really need -b 1 here
            predictions, _, _ = liblinear_predict(
                    [], vecs, model, '') #'-b 1')
            return predictions
    finally:
        sys.stdout = orig_stdout
Exemple #2
0
    def _liblinear_classify(self, vec, ranked=False):
        import sys
        orig_stdout = sys.stdout
        try:
            with open('/dev/null', 'w') as dev_null:
                sys.stdout = dev_null

                # Ask for probs. when it is necessary
                if not ranked:
                    args = ''
                else:
                    args = '-b 1'

                from linearutil import predict as liblinear_predict
                predictions, _, probabilities = liblinear_predict(
                        [], [vec], self.model, args)
        finally:
            sys.stdout = orig_stdout

        try:
            if not ranked:
                return self.name_by_lbl_id[predictions[0]]
            else:
                # We need a bit of magic to get this list right since LibLinear
                # only returns a single label we will played with the indexes
                # NOTE: Labels are stored in self.model.label, never assume otherwise
                probs_and_lbl = [(prob, self.name_by_lbl_id[lbl_id])
                        for lbl_id, prob in izip(self.model.label, probabilities[0])]
                probs_and_lbl.sort()
                probs_and_lbl.reverse()
                # Now flip the tuples and we have the ranked labels
                return [(lbl, prob) for prob, lbl in probs_and_lbl]
        except KeyError:
            print predictions
            print self.name_by_lbl_id
            raise