Beispiel #1
0
 def test_ground_truth_test(self):
     d = Dataset(test_config, 'test_pascal_val')
     d.load_from_pascal('val')
     gt = d.get_det_gt(with_diff=False, with_trun=False)
     correct = np.matrix(
         [[139., 200., 69., 102., 18., 0., 0., 0.],
          [123., 155., 93., 41., 17., 0., 0., 1.],
          [239., 156., 69., 50., 8., 0., 0., 1.]])
     print(gt)
     assert np.all(gt.arr == correct)
Beispiel #2
0
class TestDatasetPolicy:
    def __init__(self):
        self.dataset = Dataset('test_pascal_val')
        self.train_dataset = Dataset('test_pascal_train')
        self.weights_dataset_name = 'test_pascal_val'
        self.config = {
            'suffix': 'default',
            'detectors':
            ['perfect'],  # perfect,perfect_with_noise,dpm,csc_default,csc_half
            'policy_mode': 'random',
            'bounds': None,
            'weights_mode':
            'manual_1'  # manual_1, manual_2, manual_3, greedy, rl
        }
        self.dp = DatasetPolicy(self.dataset, self.train_dataset,
                                self.weights_dataset_name, **self.config)

    def test_run_on_dataset(self):
        # run on test dataset
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        assert (len(samples) == clses.shape[0])
        assert (len(samples) == self.dp.dataset.num_images() *
                len(self.dp.actions))
        train_dets, train_clses, train_samples = self.dp.run_on_dataset(
            train=True, force=True)
        assert (len(train_samples) == train_clses.shape[0])
        assert (len(train_samples) == self.dp.train_dataset.num_images() *
                len(self.dp.actions))

    def test_unique_samples(self):
        "Test the correctness of making a list of samples unique."
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        new_sample = copy.deepcopy(samples[11])
        new_sample2 = copy.deepcopy(samples[11])
        new_sample2.dt = -40  # an unreasonable value
        assert (new_sample in samples)
        assert (new_sample2 not in samples)

    def test_output_det_statistics(self):
        self.dp.output_det_statistics()

    def test_learn_weights(self):
        dataset = Dataset('full_pascal_val')
        train_dataset = Dataset('full_pascal_train')
        dataset.images = dataset.images[:20]
        train_dataset.images = train_dataset.images[:20]
        dp = DatasetPolicy(dataset, train_dataset, self.weights_dataset_name,
                           **self.config)
        weights = dp.learn_weights()

    def test_regress(self):
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        weights, error = self.dp.regress(samples, 'greedy')
        print "Weights after %d samples:\n %s" % (len(samples), weights)
        print "Error after %d samples: %s" % (len(samples), error)
        samples += samples
        weights, error = self.dp.regress(samples, 'greedy')
        print "Weights after %d samples:\n %s" % (len(samples), weights)
        print "Error after %d samples: %s" % (len(samples), error)
        samples += samples
        weights, error = self.dp.regress(samples, 'greedy')
        print "Weights after %d samples:\n %s" % (len(samples), weights)
        print "Error after %d samples: %s" % (len(samples), error)

    def test_load_weights(self):
        modes = ['manual_1', 'manual_2', 'manual_3']
        for mode in modes:
            print "%s weights:" % mode
            self.dp.weights_mode = mode
            self.dp.load_weights()
            print self.dp.get_reshaped_weights()
            assert (self.dp.weights.shape[0] == len(self.dp.actions) *
                    BeliefState.num_features)
            self.dp.write_weights_image('temp_weights_%s.png' % mode)

    def test_perfect_detector(self):
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        #embed()
        dets = dets.subset(['x', 'y', 'w', 'h', 'cls_ind', 'img_ind'])
        gt = self.dataset.get_det_gt()
        gt = gt.subset(['x', 'y', 'w', 'h', 'cls_ind', 'img_ind'])

        # TODO: does this make sense?
        dets.sort_by_column('x')
        gt.sort_by_column('x')
        print dets
        print gt
        assert (dets == gt)

    def test_load_dpm_detections(self):
        conf = dict(self.config)
        conf['detectors'] = ['dpm']
        policy = DatasetPolicy(self.dataset, self.train_dataset, **conf)
        assert (policy.detectors == ['dpm'])
        dets = policy.load_ext_detections(self.dataset,
                                          'dpm_may25',
                                          force=True)
        dets = dets.with_column_omitted('time')

        # load the ground truth dets, processed in Matlab
        # (timely/data/test_support/concat_dets.m)
        filename = os.path.join(config.test_support_dir, 'val_dets.mat')
        dets_correct = Table(
            scipy.io.loadmat(filename)['dets'], [
                'x1', 'y1', 'x2', 'y2', 'dummy', 'dummy', 'dummy', 'dummy',
                'score', 'cls_ind', 'img_ind'
            ], 'dets_correct')
        dets_correct = dets_correct.subset(
            ['x1', 'y1', 'x2', 'y2', 'score', 'cls_ind', 'img_ind'])
        dets_correct.arr[:, :4] -= 1
        dets_correct.arr[:, :4] = BoundingBox.convert_arr_from_corners(
            dets_correct.arr[:, :4])
        dets_correct.cols = ['x', 'y', 'w', 'h', 'score', 'cls_ind', 'img_ind']

        print('----mine:')
        print(dets)
        print('----correct:')
        print(dets_correct)
        assert (dets_correct == dets)
class TestDatasetPolicy:
    def __init__(self):
        self.dataset = Dataset("test_pascal_val")
        self.train_dataset = Dataset("test_pascal_train")
        self.weights_dataset_name = "test_pascal_val"
        self.config = {
            "suffix": "default",
            "detectors": ["perfect"],  # perfect,perfect_with_noise,dpm,csc_default,csc_half
            "policy_mode": "random",
            "bounds": None,
            "weights_mode": "manual_1",  # manual_1, manual_2, manual_3, greedy, rl
        }
        self.dp = DatasetPolicy(self.dataset, self.train_dataset, self.weights_dataset_name, **self.config)

    def test_run_on_dataset(self):
        # run on test dataset
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        assert len(samples) == clses.shape[0]
        assert len(samples) == self.dp.dataset.num_images() * len(self.dp.actions)
        train_dets, train_clses, train_samples = self.dp.run_on_dataset(train=True, force=True)
        assert len(train_samples) == train_clses.shape[0]
        assert len(train_samples) == self.dp.train_dataset.num_images() * len(self.dp.actions)

    def test_unique_samples(self):
        "Test the correctness of making a list of samples unique."
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        new_sample = copy.deepcopy(samples[11])
        new_sample2 = copy.deepcopy(samples[11])
        new_sample2.dt = -40  # an unreasonable value
        assert new_sample in samples
        assert new_sample2 not in samples

    def test_output_det_statistics(self):
        self.dp.output_det_statistics()

    def test_learn_weights(self):
        dataset = Dataset("full_pascal_val")
        train_dataset = Dataset("full_pascal_train")
        dataset.images = dataset.images[:20]
        train_dataset.images = train_dataset.images[:20]
        dp = DatasetPolicy(dataset, train_dataset, self.weights_dataset_name, **self.config)
        weights = dp.learn_weights()

    def test_regress(self):
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        weights, error = self.dp.regress(samples, "greedy")
        print "Weights after %d samples:\n %s" % (len(samples), weights)
        print "Error after %d samples: %s" % (len(samples), error)
        samples += samples
        weights, error = self.dp.regress(samples, "greedy")
        print "Weights after %d samples:\n %s" % (len(samples), weights)
        print "Error after %d samples: %s" % (len(samples), error)
        samples += samples
        weights, error = self.dp.regress(samples, "greedy")
        print "Weights after %d samples:\n %s" % (len(samples), weights)
        print "Error after %d samples: %s" % (len(samples), error)

    def test_load_weights(self):
        modes = ["manual_1", "manual_2", "manual_3"]
        for mode in modes:
            print "%s weights:" % mode
            self.dp.weights_mode = mode
            self.dp.load_weights()
            print self.dp.get_reshaped_weights()
            assert self.dp.weights.shape[0] == len(self.dp.actions) * BeliefState.num_features
            self.dp.write_weights_image("temp_weights_%s.png" % mode)

    def test_perfect_detector(self):
        dets, clses, samples = self.dp.run_on_dataset(force=True)
        # embed()
        dets = dets.subset(["x", "y", "w", "h", "cls_ind", "img_ind"])
        gt = self.dataset.get_det_gt()
        gt = gt.subset(["x", "y", "w", "h", "cls_ind", "img_ind"])

        # TODO: does this make sense?
        dets.sort_by_column("x")
        gt.sort_by_column("x")
        print dets
        print gt
        assert dets == gt

    def test_load_dpm_detections(self):
        conf = dict(self.config)
        conf["detectors"] = ["dpm"]
        policy = DatasetPolicy(self.dataset, self.train_dataset, **conf)
        assert policy.detectors == ["dpm"]
        dets = policy.load_ext_detections(self.dataset, "dpm_may25", force=True)
        dets = dets.with_column_omitted("time")

        # load the ground truth dets, processed in Matlab
        # (timely/data/test_support/concat_dets.m)
        filename = os.path.join(config.test_support_dir, "val_dets.mat")
        dets_correct = Table(
            scipy.io.loadmat(filename)["dets"],
            ["x1", "y1", "x2", "y2", "dummy", "dummy", "dummy", "dummy", "score", "cls_ind", "img_ind"],
            "dets_correct",
        )
        dets_correct = dets_correct.subset(["x1", "y1", "x2", "y2", "score", "cls_ind", "img_ind"])
        dets_correct.arr[:, :4] -= 1
        dets_correct.arr[:, :4] = BoundingBox.convert_arr_from_corners(dets_correct.arr[:, :4])
        dets_correct.cols = ["x", "y", "w", "h", "score", "cls_ind", "img_ind"]

        print ("----mine:")
        print (dets)
        print ("----correct:")
        print (dets_correct)
        assert dets_correct == dets
Beispiel #4
0
class TestEvaluationSynthetic(unittest.TestCase):
    def setUp(self):
        self.d = Dataset(test_config, 'test_data2')
        self.d.load_from_json(test_data2)
        self.classes = self.d.classes

        det_gt = self.d.get_det_gt()

        # perfect detections
        scores = np.ones(det_gt.shape[0])
        self.full_dets = det_gt.append_column('score', scores)

        # perfect detections, but only for class 'A'
        dets_just_A = self.d.get_det_gt_for_class('A')
        scores = np.ones(dets_just_A.shape[0])
        self.partial_dets = dets_just_A.append_column('score', scores)

    def test_values(self):
        det_gt = self.d.get_det_gt()

        self.d.set_class_values('uniform')
        assert(np.all(self.d.values == 1. / 3 * np.ones(len(self.classes))))

        ap = evaluation.compute_det_map(self.full_dets, det_gt, self.d.values)
        assert(ap == 1)
        ap = evaluation.compute_det_map(
            self.partial_dets, det_gt, self.d.values)
        assert_almost_equal(ap, 1 / 3.)

        self.d.set_class_values('inverse_prior')
        assert(np.all(self.d.values == np.array([0.25, 0.25, 0.5])))

        ap = evaluation.compute_det_map(self.full_dets, det_gt, self.d.values)
        assert(ap == 1)
        ap = evaluation.compute_det_map(
            self.partial_dets, det_gt, self.d.values)
        assert_almost_equal(ap, 0.25)

    def test_compute_pr_multiclass(self):
        cols = ['x', 'y', 'w', 'h', 'cls_ind', 'img_ind', 'diff']
        dets_cols = ['x', 'y', 'w', 'h', 'score', 'time', 'cls_ind', 'img_ind']

        # two objects of different classes in the image, perfect detection
        arr = np.array(
            [[0, 0, 10, 10, 0, 0, 0],
             [10, 10, 10, 10, 1, 0, 0]])
        gt = Table(arr, cols)

        dets_arr = np.array(
            [[0, 0, 10, 10, -1, -1, 0, 0],
             [10, 10, 10, 10, -1, -1, 1, 0]])
        dets = Table(dets_arr, dets_cols)

        # make sure gt and gt_cols aren't modified
        gt_arr_copy = gt.arr.copy()
        gt_cols_copy = list(gt.cols)
        ap, rec, prec = evaluation.compute_det_pr(dets, gt)
        assert(np.all(gt.arr == gt_arr_copy))
        assert(gt_cols_copy == gt.cols)

        correct_ap = 1
        correct_rec = np.array([0.5, 1])
        correct_prec = np.array([1, 1])
        print((ap, rec, prec))
        assert(correct_ap == ap)
        assert(np.all(correct_rec == rec))
        assert(np.all(correct_prec == prec))

        # some extra detections to generate false positives
        dets_arr = np.array(
            [[0, 0, 10, 10, -1, -1, 0, 0],
             [0, 0, 10, 10, 0, -1, 0, 0],
             [10, 10, 10, 10, 0, -1, 1, 0],
             [10, 10, 10, 10, -1, -1, 1, 0]])
        dets = Table(dets_arr, dets_cols)

        ap, rec, prec = evaluation.compute_det_pr(dets, gt)
        correct_rec = np.array([0.5, 1, 1, 1])
        correct_prec = np.array([1, 1, 2. / 3, 0.5])
        print((ap, rec, prec))
        assert(np.all(correct_rec == rec))
        assert(np.all(correct_prec == prec))

        # confirm that running on the same dets gives the same answer
        ap, rec, prec = evaluation.compute_det_pr(dets, gt)
        correct_rec = np.array([0.5, 1, 1, 1])
        correct_prec = np.array([1, 1, 2. / 3, 0.5])
        print((ap, rec, prec))
        assert(np.all(correct_rec == rec))
        assert(np.all(correct_prec == prec))

        # now let's add two objects of a different class to gt to lower recall
        arr = np.array(
            [[0, 0, 10, 10, 0, 0, 0],
             [10, 10, 10, 10, 1, 0, 0],
             [20, 20, 10, 10, 2, 0, 0],
             [30, 30, 10, 10, 2, 0, 0]])
        gt = Table(arr, cols)
        ap, rec, prec = evaluation.compute_det_pr(dets, gt)
        correct_rec = np.array([0.25, 0.5, 0.5, 0.5])
        correct_prec = np.array([1, 1, 2. / 3, 0.5])
        print((ap, rec, prec))
        assert(np.all(correct_rec == rec))
        assert(np.all(correct_prec == prec))

        # now call it with empty detections
        dets_arr = np.array([])
        dets = Table(dets_arr, dets_cols)
        ap, rec, prec = evaluation.compute_det_pr(dets, gt)
        correct_ap = 0
        correct_rec = np.array([0])
        correct_prec = np.array([0])
        print((ap, rec, prec))
        assert(np.all(correct_ap == ap))
        assert(np.all(correct_rec == rec))
        assert(np.all(correct_prec == prec))

    def test_plots(self):
        full_results_dirname = os.path.join(res_dir, 'full_dets_eval')
        partial_results_dirname = os.path.join(res_dir, 'partial_dets_eval')

        evaluation.evaluate_detections_whole(
            self.d, self.partial_dets, partial_results_dirname, force=True)
        assert(os.path.exists(
            os.path.join(partial_results_dirname, 'whole_dashboard.html')))
        pngs = glob.glob(os.path.join(partial_results_dirname, '*.png'))
        assert(len(pngs) == 4)  # 3 classes + 1 multiclass

        evaluation.evaluate_detections_whole(
            self.d, self.full_dets, full_results_dirname, force=True)
Beispiel #5
0
class TestDatasetJson(object):
    def setup(self):
        self.d = Dataset(test_config, 'test_data1')
        self.d.load_from_json(test_data1)
        self.classes = ["A", "B", "C"]

    def test_load(self):
        assert(self.d.num_images() == 4)
        assert(self.d.classes == self.classes)

    def test_get_det_gt(self):
        gt = self.d.get_det_gt(with_diff=True, with_trun=False)
        df = Table(
            np.array([[0., 0., 0., 0., 0., 0, 0, 0.],
                      [1., 1., 1., 1., 1., 0, 0, 0.],
                      [1., 1., 1., 0., 0., 0, 0, 1.],
                      [0., 0., 0., 0., 1., 0, 0, 2.],
                      [0., 0., 0., 0., 2., 0, 0, 3.],
                      [1., 1., 1., 1., 2., 0, 0, 3.]]),
            ['x', 'y', 'w', 'h', 'cls_ind', 'diff', 'trun', 'img_ind'])
        print(gt)
        print(df)
        assert(gt == df)

    def test_get_cls_counts(self):
        arr = np.array(
            [[1, 1, 0],
                [1, 0, 0],
                [0, 1, 0],
                [0, 0, 2]])
        print(self.d.get_cls_counts())
        assert(np.all(self.d.get_cls_counts() == arr))

    def test_get_cls_ground_truth(self):
        table = Table(
            np.array([[True, True, False],
                     [True, False, False],
                     [False, True, False],
                     [False, False, True]]), ["A", "B", "C"])
        assert(self.d.get_cls_ground_truth() == table)

    def test_det_ground_truth_for_class(self):
        gt = self.d.get_det_gt_for_class("A", with_diff=True, with_trun=True)
        arr = np.array(
            [[0., 0., 0., 0., 0., 0., 0, 0.],
             [1., 1., 1., 0., 0., 0., 0., 1.]])
        cols = ['x', 'y', 'w', 'h', 'cls_ind', 'diff', 'trun', 'img_ind']
        print(gt.arr)
        assert(np.all(gt.arr == arr))
        assert(gt.cols == cols)

        # no diff or trun
        gt = self.d.get_det_gt_for_class("A", with_diff=False, with_trun=False)
        arr = np.array(
            [[0., 0., 0., 0., 0., 0., 0, 0.],
             [1., 1., 1., 0., 0., 0., 0., 1.]])
        cols = ['x', 'y', 'w', 'h', 'cls_ind', 'diff', 'trun', 'img_ind']
        print(gt.arr)
        assert(np.all(gt.arr == arr))
        assert(gt.cols == cols)

    def test_set_class_values(self):
        assert(np.all(self.d.values == 1 / 3. * np.ones(len(self.classes))))
        self.d.set_class_values('uniform')
        assert(np.all(self.d.values == 1 / 3. * np.ones(len(self.classes))))
        self.d.set_class_values('inverse_prior')
        print(self.d.values)
        assert(np.all(self.d.values == np.array([0.25, 0.25, 0.5])))