Python numpy.array_equal() Examples

The following are 30 code examples of numpy.array_equal(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module numpy , or try the search function .
Example #1
Source File: per_image_evaluation_test.py    From object_detector_app with MIT License 6 votes vote down vote up
def test_compute_corloc_with_very_large_iou_threshold(self):
    num_groundtruth_classes = 3
    matching_iou_threshold = 0.9
    nms_iou_threshold = 1.0
    nms_max_output_boxes = 10000
    eval1 = per_image_evaluation.PerImageEvaluation(num_groundtruth_classes,
                                                    matching_iou_threshold,
                                                    nms_iou_threshold,
                                                    nms_max_output_boxes)
    detected_boxes = np.array([[0, 0, 1, 1], [0, 0, 2, 2], [0, 0, 3, 3],
                               [0, 0, 5, 5]], dtype=float)
    detected_scores = np.array([0.9, 0.9, 0.1, 0.9], dtype=float)
    detected_class_labels = np.array([0, 1, 0, 2], dtype=int)
    groundtruth_boxes = np.array([[0, 0, 1, 1], [0, 0, 3, 3], [0, 0, 6, 6]],
                                 dtype=float)
    groundtruth_class_labels = np.array([0, 0, 2], dtype=int)

    is_class_correctly_detected_in_image = eval1._compute_cor_loc(
        detected_boxes, detected_scores, detected_class_labels,
        groundtruth_boxes, groundtruth_class_labels)
    expected_result = np.array([1, 0, 0], dtype=int)
    self.assertTrue(np.array_equal(expected_result,
                                   is_class_correctly_detected_in_image)) 
Example #2
Source File: object_detection_evaluation_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def test_add_single_ground_truth_image_info(self):
    expected_num_gt_instances_per_class = np.array([3, 1, 2], dtype=int)
    expected_num_gt_imgs_per_class = np.array([2, 1, 2], dtype=int)
    self.assertTrue(np.array_equal(expected_num_gt_instances_per_class,
                                   self.od_eval.num_gt_instances_per_class))
    self.assertTrue(np.array_equal(expected_num_gt_imgs_per_class,
                                   self.od_eval.num_gt_imgs_per_class))
    groundtruth_boxes2 = np.array([[10, 10, 11, 11], [500, 500, 510, 510],
                                   [10, 10, 12, 12]], dtype=float)
    self.assertTrue(np.allclose(self.od_eval.groundtruth_boxes["img2"],
                                groundtruth_boxes2))
    groundtruth_is_difficult_list2 = np.array([False, True, False], dtype=bool)
    self.assertTrue(np.allclose(
        self.od_eval.groundtruth_is_difficult_list["img2"],
        groundtruth_is_difficult_list2))
    groundtruth_class_labels1 = np.array([0, 2, 0], dtype=int)
    self.assertTrue(np.array_equal(self.od_eval.groundtruth_class_labels[
        "img1"], groundtruth_class_labels1)) 
Example #3
Source File: per_image_evaluation_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def test_compute_corloc_with_very_large_iou_threshold(self):
    num_groundtruth_classes = 3
    matching_iou_threshold = 0.9
    nms_iou_threshold = 1.0
    nms_max_output_boxes = 10000
    eval1 = per_image_evaluation.PerImageEvaluation(num_groundtruth_classes,
                                                    matching_iou_threshold,
                                                    nms_iou_threshold,
                                                    nms_max_output_boxes)
    detected_boxes = np.array([[0, 0, 1, 1], [0, 0, 2, 2], [0, 0, 3, 3],
                               [0, 0, 5, 5]], dtype=float)
    detected_scores = np.array([0.9, 0.9, 0.1, 0.9], dtype=float)
    detected_class_labels = np.array([0, 1, 0, 2], dtype=int)
    groundtruth_boxes = np.array([[0, 0, 1, 1], [0, 0, 3, 3], [0, 0, 6, 6]],
                                 dtype=float)
    groundtruth_class_labels = np.array([0, 0, 2], dtype=int)

    is_class_correctly_detected_in_image = eval1._compute_cor_loc(
        detected_boxes, detected_scores, detected_class_labels,
        groundtruth_boxes, groundtruth_class_labels)
    expected_result = np.array([1, 0, 0], dtype=int)
    self.assertTrue(np.array_equal(expected_result,
                                   is_class_correctly_detected_in_image)) 
Example #4
Source File: per_image_evaluation_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def test_compute_corloc_with_normal_iou_threshold(self):
    num_groundtruth_classes = 3
    matching_iou_threshold = 0.5
    nms_iou_threshold = 1.0
    nms_max_output_boxes = 10000
    eval1 = per_image_evaluation.PerImageEvaluation(num_groundtruth_classes,
                                                    matching_iou_threshold,
                                                    nms_iou_threshold,
                                                    nms_max_output_boxes)
    detected_boxes = np.array([[0, 0, 1, 1], [0, 0, 2, 2], [0, 0, 3, 3],
                               [0, 0, 5, 5]], dtype=float)
    detected_scores = np.array([0.9, 0.9, 0.1, 0.9], dtype=float)
    detected_class_labels = np.array([0, 1, 0, 2], dtype=int)
    groundtruth_boxes = np.array([[0, 0, 1, 1], [0, 0, 3, 3], [0, 0, 6, 6]],
                                 dtype=float)
    groundtruth_class_labels = np.array([0, 0, 2], dtype=int)

    is_class_correctly_detected_in_image = eval1._compute_cor_loc(
        detected_boxes, detected_scores, detected_class_labels,
        groundtruth_boxes, groundtruth_class_labels)
    expected_result = np.array([1, 0, 1], dtype=int)
    self.assertTrue(np.array_equal(expected_result,
                                   is_class_correctly_detected_in_image)) 
Example #5
Source File: test_shci.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def test_D2htoDinfh(self):
        SHCI = lambda: None
        SHCI.groupname = 'Dooh'
        #SHCI.orbsym = numpy.array([15,14,0,6,7,2,3,10,11,15,14,17,16,5,13,12,16,17,12,13])
        SHCI.orbsym = numpy.array([
            15, 14, 0, 7, 6, 2, 3, 10, 11, 15, 14, 17, 16, 5, 12, 13, 17, 16,
            12, 13
        ])

        coeffs, nRows, rowIndex, rowCoeffs, orbsym = D2htoDinfh(SHCI, 20, 20)
        coeffs1, nRows1, rowIndex1, rowCoeffs1, orbsym1 = shci.D2htoDinfh(
            SHCI, 20, 20)
        self.assertTrue(numpy.array_equal(coeffs1, coeffs))
        self.assertTrue(numpy.array_equal(nRows1, nRows))
        self.assertTrue(numpy.array_equal(rowIndex1, rowIndex))
        self.assertTrue(numpy.array_equal(rowCoeffs1, rowCoeffs))
        self.assertTrue(numpy.array_equal(orbsym1, orbsym)) 
Example #6
Source File: prunable_nn_test.py    From prunnable-layers-pytorch with GNU General Public License v3.0 6 votes vote down vote up
def test_PLinearDropInputs_ShouldDropRightParams(self):
        dropped_index = 0

        # assume input is 2x2x2, 2 layers of 2x2
        input_shape = (2, 2, 2)
        module = pnn.PLinear(8, 10)

        old_num_features = module.in_features
        old_weight = module.weight.data.cpu().numpy()
        resized_old_weight = np.resize(old_weight, (module.out_features, *input_shape))

        module.drop_inputs(input_shape, dropped_index)
        new_shape = module.weight.size()

        # ensure that the chosen index is dropped
        expected_weight = np.resize(np.delete(resized_old_weight, dropped_index, 1), new_shape)
        output = module.weight.data.cpu().numpy()
        self.assertTrue(np.array_equal(output, expected_weight))

        # ensure num features is reduced
        self.assertTrue(module.in_features, old_num_features-1) 
Example #7
Source File: test_operator_gpu.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_residual_fused():
    cell = mx.rnn.ResidualCell(
            mx.rnn.FusedRNNCell(50, num_layers=3, mode='lstm',
                               prefix='rnn_', dropout=0.5))

    inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(2)]
    outputs, _ = cell.unroll(2, inputs, merge_outputs=None)
    assert sorted(cell.params._params.keys()) == \
           ['rnn_parameters']

    args, outs, auxs = outputs.infer_shape(rnn_t0_data=(10, 50), rnn_t1_data=(10, 50))
    assert outs == [(10, 2, 50)]
    outputs = outputs.eval(ctx=mx.gpu(0),
                           rnn_t0_data=mx.nd.ones((10, 50), ctx=mx.gpu(0))+5,
                           rnn_t1_data=mx.nd.ones((10, 50), ctx=mx.gpu(0))+5,
                           rnn_parameters=mx.nd.zeros((61200,), ctx=mx.gpu(0)))
    expected_outputs = np.ones((10, 2, 50))+5
    assert np.array_equal(outputs[0].asnumpy(), expected_outputs) 
Example #8
Source File: prunable_nn_test.py    From prunnable-layers-pytorch with GNU General Public License v3.0 6 votes vote down vote up
def test_PBatchNorm2dDropInputChannel_ShouldDropRightParams(self):
        dropped_index = 0
        module = pnn.PBatchNorm2d(2)

        old_num_features = module.num_features
        old_bias = module.bias.data.cpu().numpy()
        old_weight = module.weight.data.cpu().numpy()

        module.drop_input_channel(dropped_index)

        # ensure that the chosen index is dropped
        expected_weight = np.delete(old_weight, dropped_index, 0)
        self.assertTrue(np.array_equal(module.weight.data.cpu().numpy(), expected_weight))
        expected_bias = np.delete(old_bias, dropped_index, 0)
        self.assertTrue(np.array_equal(module.bias.data.cpu().numpy(), expected_bias))
        # ensure num features is reduced
        self.assertTrue(module.num_features, old_num_features-1) 
Example #9
Source File: df_jk.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def _ewald_exxdiv_for_G0(cell, kpts, dms, vk, kpts_band=None):
    s = cell.pbc_intor('int1e_ovlp', hermi=1, kpts=kpts)
    madelung = tools.pbc.madelung(cell, kpts)
    if kpts is None:
        for i,dm in enumerate(dms):
            vk[i] += madelung * reduce(numpy.dot, (s, dm, s))
    elif numpy.shape(kpts) == (3,):
        if kpts_band is None or is_zero(kpts_band-kpts):
            for i,dm in enumerate(dms):
                vk[i] += madelung * reduce(numpy.dot, (s, dm, s))

    elif kpts_band is None or numpy.array_equal(kpts, kpts_band):
        for k in range(len(kpts)):
            for i,dm in enumerate(dms):
                vk[i,k] += madelung * reduce(numpy.dot, (s[k], dm[k], s[k]))
    else:
        for k, kpt in enumerate(kpts):
            for kp in member(kpt, kpts_band.reshape(-1,3)):
                for i,dm in enumerate(dms):
                    vk[i,kp] += madelung * reduce(numpy.dot, (s[k], dm[k], s[k])) 
Example #10
Source File: test_gluon_rnn.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 6 votes vote down vote up
def test_residual():
    cell = gluon.rnn.ResidualCell(gluon.rnn.GRUCell(50, prefix='rnn_'))
    inputs = [mx.sym.Variable('rnn_t%d_data'%i) for i in range(2)]
    outputs, _ = cell.unroll(2, inputs)
    outputs = mx.sym.Group(outputs)
    assert sorted(cell.collect_params().keys()) == \
           ['rnn_h2h_bias', 'rnn_h2h_weight', 'rnn_i2h_bias', 'rnn_i2h_weight']
    # assert outputs.list_outputs() == \
    #        ['rnn_t0_out_plus_residual_output', 'rnn_t1_out_plus_residual_output']

    args, outs, auxs = outputs.infer_shape(rnn_t0_data=(10, 50), rnn_t1_data=(10, 50))
    assert outs == [(10, 50), (10, 50)]
    outputs = outputs.eval(rnn_t0_data=mx.nd.ones((10, 50)),
                           rnn_t1_data=mx.nd.ones((10, 50)),
                           rnn_i2h_weight=mx.nd.zeros((150, 50)),
                           rnn_i2h_bias=mx.nd.zeros((150,)),
                           rnn_h2h_weight=mx.nd.zeros((150, 50)),
                           rnn_h2h_bias=mx.nd.zeros((150,)))
    expected_outputs = np.ones((10, 50))
    assert np.array_equal(outputs[0].asnumpy(), expected_outputs)
    assert np.array_equal(outputs[1].asnumpy(), expected_outputs) 
Example #11
Source File: per_image_evaluation_test.py    From object_detector_app with MIT License 6 votes vote down vote up
def test_compute_corloc_with_normal_iou_threshold(self):
    num_groundtruth_classes = 3
    matching_iou_threshold = 0.5
    nms_iou_threshold = 1.0
    nms_max_output_boxes = 10000
    eval1 = per_image_evaluation.PerImageEvaluation(num_groundtruth_classes,
                                                    matching_iou_threshold,
                                                    nms_iou_threshold,
                                                    nms_max_output_boxes)
    detected_boxes = np.array([[0, 0, 1, 1], [0, 0, 2, 2], [0, 0, 3, 3],
                               [0, 0, 5, 5]], dtype=float)
    detected_scores = np.array([0.9, 0.9, 0.1, 0.9], dtype=float)
    detected_class_labels = np.array([0, 1, 0, 2], dtype=int)
    groundtruth_boxes = np.array([[0, 0, 1, 1], [0, 0, 3, 3], [0, 0, 6, 6]],
                                 dtype=float)
    groundtruth_class_labels = np.array([0, 0, 2], dtype=int)

    is_class_correctly_detected_in_image = eval1._compute_cor_loc(
        detected_boxes, detected_scores, detected_class_labels,
        groundtruth_boxes, groundtruth_class_labels)
    expected_result = np.array([1, 0, 1], dtype=int)
    self.assertTrue(np.array_equal(expected_result,
                                   is_class_correctly_detected_in_image)) 
Example #12
Source File: test_numpy_helper.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def test_takebak_2d(self):
        b = numpy.arange(9.).reshape((3,3))
        a = numpy.arange(49.).reshape(7,7)
        idx = numpy.array([3,0,5])
        idy = numpy.array([5,4,1])
        ref = a.copy()
        ref[idx[:,None],idy] += b
        lib.takebak_2d(a, b, idx, idy)
        self.assertTrue(numpy.array_equal(ref, a))

        b = numpy.arange(9, dtype=numpy.int32).reshape((3,3))
        a = numpy.arange(49, dtype=numpy.int32).reshape(7,7)
        ref = a.copy()
        ref[idx[:,None],idy] += b
        lib.takebak_2d(a, b, idx, idy)
        self.assertTrue(numpy.array_equal(ref, a)) 
Example #13
Source File: object_detection_evaluation_test.py    From object_detector_app with MIT License 6 votes vote down vote up
def test_add_single_ground_truth_image_info(self):
    expected_num_gt_instances_per_class = np.array([3, 1, 2], dtype=int)
    expected_num_gt_imgs_per_class = np.array([2, 1, 2], dtype=int)
    self.assertTrue(np.array_equal(expected_num_gt_instances_per_class,
                                   self.od_eval.num_gt_instances_per_class))
    self.assertTrue(np.array_equal(expected_num_gt_imgs_per_class,
                                   self.od_eval.num_gt_imgs_per_class))
    groundtruth_boxes2 = np.array([[10, 10, 11, 11], [500, 500, 510, 510],
                                   [10, 10, 12, 12]], dtype=float)
    self.assertTrue(np.allclose(self.od_eval.groundtruth_boxes["img2"],
                                groundtruth_boxes2))
    groundtruth_is_difficult_list2 = np.array([False, True, False], dtype=bool)
    self.assertTrue(np.allclose(
        self.od_eval.groundtruth_is_difficult_list["img2"],
        groundtruth_is_difficult_list2))
    groundtruth_class_labels1 = np.array([0, 2, 0], dtype=int)
    self.assertTrue(np.array_equal(self.od_eval.groundtruth_class_labels[
        "img1"], groundtruth_class_labels1)) 
Example #14
Source File: object_detection_evaluation_test.py    From object_detector_app with MIT License 6 votes vote down vote up
def test_add_single_detected_image_info(self):
    expected_scores_per_class = [[np.array([0.8, 0.7], dtype=float)], [],
                                 [np.array([0.9], dtype=float)]]
    expected_tp_fp_labels_per_class = [[np.array([0, 1], dtype=bool)], [],
                                       [np.array([0], dtype=bool)]]
    expected_num_images_correctly_detected_per_class = np.array([0, 0, 0],
                                                                dtype=int)
    for i in range(self.od_eval.num_class):
      for j in range(len(expected_scores_per_class[i])):
        self.assertTrue(np.allclose(expected_scores_per_class[i][j],
                                    self.od_eval.scores_per_class[i][j]))
        self.assertTrue(np.array_equal(expected_tp_fp_labels_per_class[i][
            j], self.od_eval.tp_fp_labels_per_class[i][j]))
    self.assertTrue(np.array_equal(
        expected_num_images_correctly_detected_per_class,
        self.od_eval.num_images_correctly_detected_per_class)) 
Example #15
Source File: object_detection_evaluation_test.py    From DOTA_models with Apache License 2.0 6 votes vote down vote up
def test_add_single_detected_image_info(self):
    expected_scores_per_class = [[np.array([0.8, 0.7], dtype=float)], [],
                                 [np.array([0.9], dtype=float)]]
    expected_tp_fp_labels_per_class = [[np.array([0, 1], dtype=bool)], [],
                                       [np.array([0], dtype=bool)]]
    expected_num_images_correctly_detected_per_class = np.array([0, 0, 0],
                                                                dtype=int)
    for i in range(self.od_eval.num_class):
      for j in range(len(expected_scores_per_class[i])):
        self.assertTrue(np.allclose(expected_scores_per_class[i][j],
                                    self.od_eval.scores_per_class[i][j]))
        self.assertTrue(np.array_equal(expected_tp_fp_labels_per_class[i][
            j], self.od_eval.tp_fp_labels_per_class[i][j]))
    self.assertTrue(np.array_equal(
        expected_num_images_correctly_detected_per_class,
        self.od_eval.num_images_correctly_detected_per_class)) 
Example #16
Source File: data_processor_test.py    From neural-pipeline with MIT License 6 votes vote down vote up
def test_train(self):
        model = SimpleModel().train()
        train_config = TrainConfig(model, [], torch.nn.Module(), torch.optim.SGD(model.parameters(), lr=0.1))
        dp = TrainDataProcessor(train_config=train_config)

        self.assertFalse(model.fc.weight.is_cuda)
        self.assertTrue(model.training)
        res = dp.predict({'data': torch.rand(1, 3)}, is_train=True)
        self.assertTrue(model.training)
        self.assertTrue(res.requires_grad)
        self.assertIsNone(res.grad)

        with self.assertRaises(NotImplementedError):
            dp.process_batch({'data': torch.rand(1, 3), 'target': torch.rand(1)}, is_train=True)

        loss = SimpleLoss()
        train_config = TrainConfig(model, [], loss, torch.optim.SGD(model.parameters(), lr=0.1))
        dp = TrainDataProcessor(train_config=train_config)
        res = dp.process_batch({'data': torch.rand(1, 3), 'target': torch.rand(1)}, is_train=True)
        self.assertTrue(model.training)
        self.assertTrue(loss.module.requires_grad)
        self.assertIsNotNone(loss.module.grad)
        self.assertTrue(np.array_equal(res, loss.res.data.numpy())) 
Example #17
Source File: chunkUtil.py    From hsds with Apache License 2.0 6 votes vote down vote up
def chunkWriteSelection(chunk_arr=None, slices=None, data=None):
    log.info("chunkWriteSelection")
    dims = chunk_arr.shape

    rank = len(dims)

    if rank == 0:
        msg = "No dimension passed to chunkReadSelection"
        raise ValueError(msg)
    if len(slices) != rank:
        msg = "Selection rank does not match dataset rank"
        raise ValueError(msg)
    if len(data.shape) != rank:
        msg = "Input arr does not match dataset rank"
        raise ValueError(msg)

    updated = False
    # check if the new data modifies the array or not
    if not np.array_equal(chunk_arr[slices], data):
        # update chunk array
        chunk_arr[slices] = data
        updated = True
    return updated 
Example #18
Source File: test_exp_replay.py    From reinforcement_learning with MIT License 6 votes vote down vote up
def test3(self):
    exprep = exp_replay.ExpReplay(mem_size=100, state_size=[2,2], kth=4)
    for i in xrange(120):
      exprep.add_step(Step(cur_step=[[i,i],[i,i]], action=0, next_step=[[i+1,i+1],[i+1,i+1]], reward=0, done=False))
    self.assertEqual(len(exprep.mem), 100)
    self.assertEqual(exprep.mem[-1:][0].cur_step, [[119,119],[119,119]])
    last_state = exprep.get_last_state()

    self.assertEqual(np.shape(last_state),(2,2,4))
    self.assertTrue(np.array_equal(last_state[:,:,0], [[116,116],[116,116]]))
    self.assertTrue(np.array_equal(last_state[:,:,1], [[117,117],[117,117]]))
    self.assertTrue(np.array_equal(last_state[:,:,2], [[118,118],[118,118]]))
    self.assertTrue(np.array_equal(last_state[:,:,3], [[119,119],[119,119]]))

    sample = exprep.sample(5)
    self.assertEqual(len(sample), 5)
    self.assertEqual(np.shape(sample[0].cur_step), (2,2,4))
    self.assertEqual(np.shape(sample[0].next_step), (2,2,4)) 
Example #19
Source File: test_molecule.py    From QCElemental with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_water_minima_fragment():

    mol = water_dimer_minima.copy()
    frag_0 = mol.get_fragment(0, orient=True)
    frag_1 = mol.get_fragment(1, orient=True)
    assert frag_0.get_hash() == "5f31757232a9a594c46073082534ca8a6806d367"
    assert frag_1.get_hash() == "bdc1f75bd1b7b999ff24783d7c1673452b91beb9"

    frag_0_1 = mol.get_fragment(0, 1)
    frag_1_0 = mol.get_fragment(1, 0)

    assert np.array_equal(mol.symbols[:3], frag_0.symbols)
    assert np.allclose(mol.masses[:3], frag_0.masses)

    assert np.array_equal(mol.symbols, frag_0_1.symbols)
    assert np.allclose(mol.geometry, frag_0_1.geometry)

    assert np.array_equal(np.hstack((mol.symbols[3:], mol.symbols[:3])), frag_1_0.symbols)
    assert np.allclose(np.hstack((mol.masses[3:], mol.masses[:3])), frag_1_0.masses) 
Example #20
Source File: test_shci.py    From pyscf with Apache License 2.0 6 votes vote down vote up
def test_D2htoDinfh(self):
        SHCI = lambda: None
        SHCI.groupname = 'Dooh'
        #SHCI.orbsym = numpy.array([15,14,0,6,7,2,3,10,11,15,14,17,16,5,13,12,16,17,12,13])
        SHCI.orbsym = numpy.array([
            15, 14, 0, 7, 6, 2, 3, 10, 11, 15, 14, 17, 16, 5, 12, 13, 17, 16,
            12, 13
        ])

        coeffs, nRows, rowIndex, rowCoeffs, orbsym = D2htoDinfh(SHCI, 20, 20)
        coeffs1, nRows1, rowIndex1, rowCoeffs1, orbsym1 = shci.D2htoDinfh(
            SHCI, 20, 20)
        self.assertTrue(numpy.array_equal(coeffs1, coeffs))
        self.assertTrue(numpy.array_equal(nRows1, nRows))
        self.assertTrue(numpy.array_equal(rowIndex1, rowIndex))
        self.assertTrue(numpy.array_equal(rowCoeffs1, rowCoeffs))
        self.assertTrue(numpy.array_equal(orbsym1, orbsym)) 
Example #21
Source File: prunable_nn_test.py    From prunnable-layers-pytorch with GNU General Public License v3.0 6 votes vote down vote up
def test_pruneFeatureMap_ShouldPruneRightParams(self):
        dropped_index = 0
        output = self.module(self.input)
        torch.autograd.backward(output, self.upstream_gradient)

        old_weight_size = self.module.weight.size()
        old_bias_size = self.module.bias.size()
        old_out_channels = self.module.out_channels
        old_weight_values = self.module.weight.data.cpu().numpy()

        # ensure that the chosen index is dropped
        self.module.prune_feature_map(dropped_index)

        # check bias size
        self.assertEqual(self.module.bias.size()[0], (old_bias_size[0]-1))
        # check output channels
        self.assertEqual(self.module.out_channels, old_out_channels-1)

        _, *other_old_weight_sizes = old_weight_size
        # check weight size
        self.assertEqual(self.module.weight.size(), (old_weight_size[0]-1, *other_old_weight_sizes))
        # check weight value
        expected = np.delete(old_weight_values, dropped_index , 0)
        self.assertTrue(np.array_equal(self.module.weight.data.cpu().numpy(), expected)) 
Example #22
Source File: test_exp_replay.py    From reinforcement_learning with MIT License 5 votes vote down vote up
def test4(self):
    # -1 for sending raw state
    exprep = exp_replay.ExpReplay(mem_size=100, state_size=[4], kth=-1)
    for i in xrange(120):
      exprep.add_step(Step(cur_step=[i,i,i,i], action=0, next_step=[i+1,i+1,i+1,i+1], reward=0, done=False))
    last_state = exprep.get_last_state()
    self.assertEqual(np.shape(last_state),(4,))
    self.assertTrue(np.array_equal(last_state, [119,119,119,119]))

    sample = exprep.sample(5)
    self.assertEqual(len(sample), 5)
    self.assertEqual(np.shape(sample[0].cur_step), (4,)) 
Example #23
Source File: kmeans.py    From hadrian with Apache License 2.0 5 votes vote down vote up
def newCluster(self):
        """Pick a random point from the dataset and ensure that it is different from all other cluster centers.

        :rtype: 1-d Numpy array
        :return: a *copy* of a random point, guaranteed to be different from all other clusters.
        """
        newCluster = self.randomPoint()
        while any(numpy.array_equal(x, newCluster) for x in self.clusters):
            newCluster = self.randomPoint()
        return newCluster 
Example #24
Source File: test_rounding.py    From Hexy with MIT License 5 votes vote down vote up
def test_cube_round():
    test_coords = np.array([
        [1.1, -1.4, 0.3],
        [3.3, 2.3, -5.4],
        ]);

    expected_coords = np.array([
        [1, -1, 0],
        [3, 2, -5],
        ]);

    assert(np.array_equal(hx.cube_round(test_coords), expected_coords)) 
Example #25
Source File: test_conversions.py    From Hexy with MIT License 5 votes vote down vote up
def test_the_converted_coords_and_dataset_coords_retrieve_the_same_data():
    axial_coords = hx.cube_to_axial(coords)
    cube_coords = hx.axial_to_cube(axial_coords)
    pixel_coords = hx.cube_to_pixel(cube_coords, radius)
    pixel_to_cube_coords = hx.pixel_to_cube(pixel_coords, radius)
    pixel_to_cube_to_axial_coords = hx.cube_to_axial(pixel_to_cube_coords)

    # check that we can correctly retrieve hexes after conversions
    hm[axial_coords] = coords
    retrieved = hm[pixel_to_cube_to_axial_coords]

    assert np.array_equal(retrieved, coords) 
Example #26
Source File: test_conversions.py    From Hexy with MIT License 5 votes vote down vote up
def test_cube_to_pixel_conversion():
    axial_coords = hx.cube_to_axial(coords)
    cube_coords = hx.axial_to_cube(axial_coords)
    pixel_coords = hx.cube_to_pixel(cube_coords, radius)
    pixel_to_cube_coords = hx.pixel_to_cube(pixel_coords, radius)
    pixel_to_cube_to_axial_coords = hx.cube_to_axial(pixel_to_cube_coords)

    assert np.array_equal(cube_coords, pixel_to_cube_coords) 
Example #27
Source File: test_conversions.py    From Hexy with MIT License 5 votes vote down vote up
def test_axial_to_pixel_conversion():
    axial_coords = hx.cube_to_axial(coords)
    pixel_coords = hx.axial_to_pixel(axial_coords, radius)
    pixel_to_axial_coords = hx.pixel_to_axial(pixel_coords, radius)

    assert np.array_equal(axial_coords, pixel_to_axial_coords) 
Example #28
Source File: test_hex_line.py    From Hexy with MIT License 5 votes vote down vote up
def test_get_hex_line():
    expected = [
            [-3, 3, 0],
            [-2, 2, 0],
            [-1, 2, -1],
            [0, 2, -2],
            [1, 1, -2],
            ]
    start = np.array([-3, 3, 0])
    end = np.array([1, 1, -2])
    print(hx.get_hex_line(start, end))
    print(expected);
    assert(np.array_equal(
        hx.get_hex_line(start, end),
        expected)); 
Example #29
Source File: test_rounding.py    From Hexy with MIT License 5 votes vote down vote up
def test_axial_round():
    test_coords = np.array([
        [1.1, -1.4],
        [3.3, 2.3],
        ]);

    expected_coords = np.array([
        [1, -1],
        [3, 2],
        ]);

    assert(np.array_equal(hx.axial_round(test_coords), expected_coords)) 
Example #30
Source File: test_quaternion.py    From quadcopter-simulation with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_as_v_thta(self):
        x = [1.0,0.0,0.0]
        q = Quaternion.from_v_theta(x, np.pi/2)
        expected_v = np.array(x)
        expected_theta = np.pi/2
        actual_v, actual_theta = q.as_v_theta()
        print actual_v, actual_theta, expected_v
        self.assertTrue(np.array_equal(expected_v, actual_v))
        self.assertEqual(expected_theta, actual_theta)