Best Python code snippet using lisa_python
test_feedforward.py
Source:test_feedforward.py  
1import numpy as np2from BCPNN.feedforward import BCPNN3from BCPNN.encoder import BinvecOneHotEncoder as encoder4class TestUnitTests:5    def setup(self):6        self.clf = BCPNN()7        self.test_pattern = np.array([8            [1, 0, 1, 1, 0],9            [1, 1, 0, 1, 0]10            ])11        self.transformed_pattern = encoder.transform(self.test_pattern)12        self.y = np.array([0,1])13        self.clf.fit(self.test_pattern, self.y)14    def test_encoder_encode(self):15        transformed = np.array([1, 0, 0, 1, 1, 0, 1, 0, 0, 1])16        assert (self.transformed_pattern[0] == transformed).all()17    def test_encoder_decode(self):18        inverse = encoder.inverse_transform(self.transformed_pattern)19        assert (inverse == self.test_pattern).all()20    def test_get_prob(self):21        f = self.clf._get_prob22        assert f(0) == 123        assert f(1) == 0.524        assert f(2) == 0.525        assert f(3) == 126        assert f(4) == 027    def test_get_joint_prob(self):28        f = self.clf._get_joint_prob29        assert f(0, 0) == 130        assert f(0, 1) == 0.531        assert f(1, 4) == 032    def test_get_prob_for_y(self):33        f = self.clf._get_prob34        assert f(self.clf.y_pad + 0) == 0.535        assert f(self.clf.y_pad + 1) == 0.536    def test_get_joint_prob_for_y(self):37        f = self.clf._get_joint_prob38        assert f(0, self.clf.y_pad + 0) == 0.539        assert f(0, self.clf.y_pad + 1) == 0.540        assert f(1, self.clf.y_pad + 1) == 0.541        assert f(1, self.clf.y_pad + 0) == 042        assert f(4, self.clf.y_pad + 1) == 043    def test_unique_label(self):44        y = [3,4,1,5,6,7,2,2,3]45        assert (BCPNN._unique_labels(y) == [1,2,3,4,5,6,7]).all()46    def test_class_idx_to_prob(self):47        y = np.arange(3)48        prediction = np.eye(3)49        assert (BCPNN._class_idx_to_prob(y) == prediction).all()50        y = np.array([1, 2, 0])51        prediction = np.array([[0, 1, 0], [0, 0, 1], [1, 0, 0]])52        assert (BCPNN._class_idx_to_prob(y) == prediction).all()53        y = np.array([1, 1, 0])54        prediction = np.array([[0, 1], [0,1], [1, 0]])55        assert (BCPNN._class_idx_to_prob(y) == prediction).all()56    def test_transfer_fn(self):57        g = self.clf._transfer_fn58        f = lambda s: g(np.array(s))59        support = [0, 0]60        assert (f(support) == [1, 1]).all()61        support = np.log([1, 2, 4, 1])62        assert (f(support) == [1, 1, 1, 1]).all()63        # test 2d arrays64        support = [[0, 0], [0, 0]]65        assert (f(support) == [[1,1], [1,1]]).all()66        support = np.log([[2, 6], [4, 1]]).tolist()67        assert (f(support) == [[1,1], [1,1]]).all()68class TestProba:69    test_pattern = np.array([70        [1, 0, 1, 0, 0, 1],71        [1, 0, 0, 1, 0, 1]72        ])73    targets = np.array([0, 1])74    def clf_factory(self, test_pattern=test_pattern, targets=targets):75        clf = BCPNN()76        clf.fit(test_pattern, targets)77        return clf78    def predict_runner(self, train_pattern, targets, predictions,79                test_pattern=None, mode='proba', atol=0.2):80        clf = self.clf_factory(train_pattern, targets)81        if mode == 'proba':82            f = clf.predict_proba83        elif mode == 'log':84            f = clf.predict_log_proba85        elif mode == 'predict':86            f = clf.predict87        if test_pattern is None:88            test_pattern = train_pattern89        output = f(test_pattern)90        assert output.shape == predictions.shape91        # NOTE: below form easier to debug92        # assert (output == predictions).all()93        assert np.allclose(output, predictions, atol=atol)94    def test_basic1(self):95        test_pattern = np.array([96            [1, 0, 1, 0],97            [0, 1, 0, 1]98            ])99        targets = np.array([0, 1])100        # predict_log_proba101        predictions = np.array([[ 0.69314718, -2.07944154],102                                [-2.07944154,  0.69314718]])103        self.predict_runner(test_pattern, targets, predictions,104                                mode='log', atol=0)105        # predict_proba106        predictions = np.array([[1, 0], [0, 1]])107        self.predict_runner(test_pattern, targets, predictions, mode='proba')108        # predict109        predictions = np.array([0, 1])110        self.predict_runner(test_pattern, targets, predictions, mode='predict')111    def test_basic2(self):112        train_pattern = np.array([113            [1, 0, 1, 0],114            [0, 1, 0, 1]115            ])116        targets = np.array([0, 1])117        test_pattern = np.append(train_pattern, [[1, 1, 1, 1]], axis=0)118        # predict_proba119        predictions = np.array([[1, 0], [0, 1], [0.5, 0.5]])120        self.predict_runner(train_pattern, targets, predictions,121                    test_pattern=test_pattern, mode='proba')122        # predict123        predictions = np.array([0, 1, 0])124        self.predict_runner(train_pattern, targets, predictions,125                    test_pattern=test_pattern, mode='predict')126    def test_basic3(self):127        train_pattern = np.array([128            [1, 0, 0],129            [0, 1, 0],130            ])131        targets = np.array([0, 1])132        test_pattern = np.append(train_pattern, [[1, 1, 1], [1, 1, 0]], axis=0)133        # predict_proba134        predictions = np.array([[1, 0.25], [0.25, 1], [0.5, 0.5], [0.5, 0.5]])135        self.predict_runner(train_pattern, targets, predictions,136                    test_pattern=test_pattern, mode='proba')137        # predict138        predictions = np.array([0, 1, 0, 0])139        self.predict_runner(train_pattern, targets, predictions,140                    test_pattern=test_pattern, mode='predict')141    def test_basic3_2(self):142        train_pattern = np.array([143            [1, 0, 1],144            [0, 1, 0],145            # we add one more sample of cls 1, as for both classes to146            # have equal amount of active features147            [0, 1, 0]148            ])149        targets = np.array([0, 1, 1])150        test_pattern = np.append(train_pattern, [[1, 1, 1], [1, 1, 0]], axis=0)151        # predict_proba152        predictions = np.array([[1, 0], [0, 1], [0, 1], [0.8, 0.2], [0.5, 0.5]])153        self.predict_runner(train_pattern, targets, predictions,154                    test_pattern=test_pattern, mode='proba')155        # predict156        predictions = np.array([0, 1, 1, 0, 0])157        self.predict_runner(train_pattern, targets, predictions,158                    test_pattern=test_pattern, mode='predict')159    def test_basic4(self):160        train_pattern = np.array([161            [1, 0, 0],162            [0, 1, 0]163            ])164        targets = np.array([0, 1])165        # TEST CASE166        test_pattern = np.append(train_pattern, [[0, 0, 1]], axis=0)167        # predict_proba168        predictions = np.array([[1, 0], [0, 1], [0.5, 0.5]])169        self.predict_runner(train_pattern, targets, predictions,170                    test_pattern=test_pattern, mode='proba', atol=0.25)171        # predict172        predictions = np.array([0, 1, 0])173        self.predict_runner(train_pattern, targets, predictions,174                    test_pattern=test_pattern, mode='predict')175        # TEST CASE176        test_pattern = np.append(train_pattern, [[0, 0, 0]], axis=0)177        # predict_proba178        predictions = np.array([[1, 0], [0, 1], [0.5, 0.5]])179        self.predict_runner(train_pattern, targets, predictions,180                    test_pattern=test_pattern, mode='proba', atol=0.25)181        # predict182        predictions = np.array([0, 1, 0])183        self.predict_runner(train_pattern, targets, predictions,184                    test_pattern=test_pattern, mode='predict')185    def test_basic5(self):186        train_pattern = np.array([187            [1, 0, 0],188            [0, 1, 0],189            [0, 0, 1]190            ])191        targets = np.array([0, 1, 2])192        # TEST CASE193        test_pattern = np.append(train_pattern, [[0, 0, 0]], axis=0)194        # predict_proba195        predictions = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0.5, 0.5, 0.5]])196        self.predict_runner(train_pattern, targets, predictions,197                    test_pattern=test_pattern, mode='proba', atol=0.2)198        # predict199        predictions = np.array([0, 1, 2, 0])200        self.predict_runner(train_pattern, targets, predictions,201                    test_pattern=test_pattern, mode='predict')202        # TEST CASE203        test_pattern = np.append(train_pattern, [[1, 1, 1]], axis=0)204        # predict_proba205        predictions = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0.3, 0.3, 0.3]])206        self.predict_runner(train_pattern, targets, predictions,207                    test_pattern=test_pattern, mode='proba', atol=0.2)208        # TEST CASE209        test_pattern = np.append(train_pattern, [[1, 0, 1]], axis=0)210        # predict_proba211        predictions = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1], [0.3, 0, 0.3]])212        self.predict_runner(train_pattern, targets, predictions,213                    test_pattern=test_pattern, mode='proba', atol=0.2)214    def test_different_sizes1(self):215        # Test different size of n_features and n_classes216        # n_features = 5, n_classes = 2217        test_pattern = np.array([218            [1, 0, 1, 0, 1],219            [1, 0, 1, 0, 1],220            [0, 1, 0, 1, 0]221            ])222        targets = np.array([0, 0, 1])223        # predict_proba224        predictions = np.array([[1, 0], [1, 0], [0, 1]])225        self.predict_runner(test_pattern, targets, predictions, mode='proba')226        # predict227        predictions = np.array([0, 0, 1])228        self.predict_runner(test_pattern, targets, predictions, mode='predict')229    def test_different_sizes2(self):230        # Test different size of n_features and n_classes231        # n_features = 4, n_classes = 3232        test_pattern = np.array([233            [1, 0, 0],234            [0, 1, 0],235            [0, 0, 1]236            ])237        targets = np.array([0, 1, 2])238        # predict_proba239        predictions = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])240        self.predict_runner(test_pattern, targets, predictions, mode='proba')241        # predict242        predictions = np.array([0, 1, 2])243        self.predict_runner(test_pattern, targets, predictions, mode='predict')244    def test_different_sizes3(self):245        # Test different size of n_features and n_classes246        # n_features = 3, n_classes = 3247        test_pattern = np.array([248            [1, 0, 1],249            [1, 0, 1],250            [0, 1, 0]251            ])252        targets = np.array([0, 2, 1])253        # predict_proba254        predictions = np.array([[0.75      , 0.03703704, 0.75      ],255           [0.75      , 0.03703704, 0.75      ],256           [0.11111111, 1.        , 0.11111111]])257        self.predict_runner(test_pattern, targets, predictions, mode='proba')258        # predict259        predictions = np.array([0, 0, 1])260        self.predict_runner(test_pattern, targets, predictions, mode='predict')261    def test_different_sizes4(self):262        # Test different size of n_features and n_classes263        # n_features = 4, n_classes = 3264        test_pattern = np.array([265            [1, 0, 1, 0, 0, 0, 0],266            [0, 0, 0, 0, 1, 1, 1],267            [0, 1, 0, 1, 0, 0, 0]268            ])269        targets = np.array([0, 1, 2])270        # predict_proba271        predictions = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])272        self.predict_runner(test_pattern, targets, predictions, mode='proba')273        # predict274        predictions = np.array([0, 1, 2])275        self.predict_runner(test_pattern, targets, predictions, mode='predict')276    # Encoder tests277    def test_encoder_effect_1(self):278        # extension of basic_3279        train_pattern = np.array([280            [1, 0, 1],281            [0, 1, 0]282            ])283        targets = np.array([0, 1])284        test_pattern = np.append(train_pattern, [[1, 1, 1], [1, 1, 0]], axis=0)285        train_pattern = encoder.transform(train_pattern)286        test_pattern = encoder.transform(test_pattern)287        # predict_proba288        predictions = np.array([289        [1.    , 0.0625],290        [0.0625, 1.    ],291        [1.    , 0.25  ],292        [0.25  , 1.    ]])293        self.predict_runner(train_pattern, targets, predictions,294                    test_pattern=test_pattern, mode='proba')295        # predict296        predictions = np.array([0, 1, 0, 1])297        self.predict_runner(train_pattern, targets, predictions,298                    test_pattern=test_pattern, mode='predict')299    def test_encoder_effect_2(self):300        # extension of  test_different_sizes3301        test_pattern = np.array([302            [1, 0, 1],303            [1, 0, 1],304            [0, 1, 0]305            ])306        targets = np.array([0, 2, 1])307        # train_pattern = encoder.transform(train_pattern)308        test_pattern = encoder.transform(test_pattern)309        # predict_proba310        predictions = np.array([311        [1.        , 0.01234568, 1.        ],312        [1.        , 0.01234568, 1.        ],313        [0.01234568, 1.        , 0.01234568]])314        self.predict_runner(test_pattern, targets, predictions, mode='proba')315        # predict316        predictions = np.array([0, 0, 1])317        self.predict_runner(test_pattern, targets, predictions, mode='predict')318    def test_encoder_effect_3(self):319        train_pattern = np.array([320            [1, 0, 0],321            [0, 1, 0],322            [0, 0, 1]323            ])324        targets = np.array([0, 1, 2])325        test_pattern = np.append(train_pattern, [[1, 1, 1], [1, 1, 0]], axis=0)326        train_pattern = encoder.transform(train_pattern)327        test_pattern = encoder.transform(test_pattern)328        # predict_proba329        predictions = np.array([[1.        , 0.05555556, 0.05555556],330                               [0.05555556, 1.        , 0.05555556],331                               [0.05555556, 0.05555556, 1.        ],332                               [0.11111111, 0.11111111, 0.11111111],333                               [0.5       , 0.5       , 0.01234568]])334        self.predict_runner(train_pattern, targets, predictions,335                    test_pattern=test_pattern, mode='proba')336        # predict337        predictions = np.array([0, 1, 2, 0, 0])338        self.predict_runner(train_pattern, targets, predictions,...test_modular_ff.py
Source:test_modular_ff.py  
1import pytest2import numpy as np3from BCPNN.feedforward_modular import mBCPNN as BCPNN4from BCPNN.encoder import ComplementEncoder5## TEST UTILS6def clf_factory(test_pattern, targets, module_sizes, normalize=True):7    clf = BCPNN(normalize=normalize)8    clf.fit(test_pattern, targets, module_sizes)9    return clf10def predict_runner(train_pattern, targets, predictions, module_sizes,11            test_pattern=None, mode='proba', atol=0.001, normalize=True):12    clf = clf_factory(train_pattern, targets, module_sizes, normalize)13    if mode == 'proba':14        f = clf.predict_proba15    elif mode == 'log':16        f = clf.predict_log_proba17    elif mode == 'predict':18        f = clf.predict19    if test_pattern is None:20        test_pattern = train_pattern21    output = f(test_pattern)22    assert output.shape == predictions.shape23    # NOTE: below form easier to debug24    # assert (output == predictions).all()25    assert np.allclose(output, predictions, atol=atol)26    assert (clf.weights != 0).all()27class TestUnitTests:28    def testComplementEncoder(self):29        X = np.array([[0.5, 0.2], [1, 0]])30        Xt = ComplementEncoder().fit_transform(X)31        assert np.array_equal(Xt, np.array([[0.5, 0.5, 0.2, 0.8], [1, 0, 0, 1]]))32        assert np.array_equal(ComplementEncoder.inverse_transform(Xt), X)33    @pytest.fixture(scope="function")34    def clf(self):35        return BCPNN()36    def testIndexTransform(self, clf):37        clf.module_sizes = np.array([1])38        modular = (0, 0)39        flat = 040        assert clf._modular_idx_to_flat(*modular) == flat41        assert clf._flat_to_modular_idx(flat) == modular42        clf.module_sizes = np.array([1, 1])43        modular = (1, 0)44        flat = 145        assert clf._modular_idx_to_flat(*modular) == flat46        assert clf._flat_to_modular_idx(flat) == modular47        clf.module_sizes = np.array([2, 2])48        modular = (0, 1)49        flat = 150        assert clf._modular_idx_to_flat(*modular) == flat51        assert clf._flat_to_modular_idx(flat) == modular52        modular = (1, 0)53        flat = 254        assert clf._modular_idx_to_flat(*modular) == flat55        assert clf._flat_to_modular_idx(flat) == modular56        clf.module_sizes = np.array([1, 3, 2])57        modular = (2, 1)58        flat = 559        assert clf._modular_idx_to_flat(*modular) == flat60        assert clf._flat_to_modular_idx(flat) == modular61    def testEmptyModuleSize(self, clf):62        X = np.array([[0, 1]])63        y = np.array([0])64        clf.fit(X, y)65        assert np.array_equal(clf.X_, X)66        assert np.array_equal(clf.module_sizes, [2, 1])67    class TestNormalization:68        def testCheckNormalization1(self, clf):69            X = np.array([[0, 1]])70            module_sizes = np.array([2, 2])71            clf.fit(X, X, module_sizes)72            X = np.array([[1, 1]])73            with pytest.raises(BCPNN.NormalizationError):74                clf.fit(X, X, module_sizes)75        def testCheckNormalization2(self, clf):76            X = np.array([[0, 1], [1/2, 1/2]])77            module_sizes = np.array([2, 2])78            clf.fit(X, X, module_sizes)79            clf._assert_module_normalization(X)80            X = np.array([[1, 1], [1/2, 1/2]])81            module_sizes = np.array([2, 2])82            with pytest.raises(BCPNN.NormalizationError):83                clf.fit(X, X, module_sizes)84        def testCheckNormalization3(self, clf):85            X = np.array([[0, 1/2, 1/2, 1/2, 1/2]])86            module_sizes = np.array([3, 2, 2])87            clf.fit(X, X[:, :2], module_sizes)88            X = np.array([[1, 1, 1, 1, 1]])89            module_sizes = np.array([3, 2, 2])90            with pytest.raises(BCPNN.NormalizationError):91                clf.fit(X, X[:, :2], module_sizes)92        def testCheckNormalization4(self, clf):93            # No module sizes given94            X = np.array([[0, 1]])95            clf.fit(X, X)96            X = np.array([[1, 1]])97            with pytest.raises(BCPNN.NormalizationError):98                clf.fit(X, X)99class TestModule:100    class TestBinary:101        def testModuleSize2_2_log(self):102            train_pattern = np.array([[0, 1], [1, 0]])103            targets       = np.array([[0, 1], [1, 0]])104            predictions   = np.array([[np.log(1/4), 0], [0, np.log(1/4)]])105            module_sizes  = np.array([2, 2])106            predict_runner(train_pattern, targets, predictions, module_sizes, mode='log')107        def testModuleSize2_2_predict(self):108            train_pattern = np.array([[0, 1], [1, 0]])109            targets       = np.array([[0, 1], [1, 0]])110            predictions   = np.array([1, 0])111            module_sizes  = np.array([2, 2])112            predict_runner(train_pattern, targets, predictions, module_sizes, mode='predict')113        def testModuleSize2_2_proba_no_norm(self):114            train_pattern = np.array([[0, 1], [1, 0]])115            targets       = np.array([[0, 1], [1, 0]])116            predictions   = np.array([[0.25, 1], [1, 0.25]])117            module_sizes  = np.array([2, 2])118            predict_runner(train_pattern, targets, predictions, module_sizes, mode='proba', normalize=False)119        def testModuleSize2_2_proba(self):120            train_pattern = np.array([[0, 1], [1, 0]])121            targets       = np.array([[0, 1], [1, 0]])122            predictions   = np.array([[0.2, 0.8], [0.8, 0.2]])123            module_sizes  = np.array([2, 2])124            predict_runner(train_pattern, targets, predictions, module_sizes, mode='proba')125        def testModuleSize3_2_proba(self):126            train_pattern = np.array([[0, 1, 0], [1, 0, 0]])127            targets       = np.array([[0, 1], [1, 0]])128            predictions   = np.array([[0.2, 0.8], [0.8, 0.2]])129            module_sizes  = np.array([3, 2])130            predict_runner(train_pattern, targets, predictions, module_sizes, mode='proba')131        def testModuleSize3_3_log(self):132            train_pattern = np.array([[0, 1, 0], [1, 0, 0]])133            targets       = np.array([[0, 1, 0], [1, 0, 0]])134            predictions   = np.array([[np.log(1/4), 0, np.log(1/4)], [0, np.log(1/4), np.log(1/4)]])135            module_sizes  = np.array([3, 3])136            predict_runner(train_pattern, targets, predictions, module_sizes, mode='log')137        def testModuleSize3_3_proba(self):138            train_pattern = np.array([[0, 1, 0], [1, 0, 0]])139            targets       = np.array([[0, 1, 0], [1, 0, 0]])140            predictions   = np.array([[1/6, 2/3, 1/6], [2/3, 1/6, 1/6]])141            module_sizes  = np.array([3, 3])142            predict_runner(train_pattern, targets, predictions, module_sizes, mode='proba')143        def testModuleSize2_2_2_log(self):144            train_pattern = np.array([[0, 1, 0, 1], [1, 0, 1, 0]])145            targets       = np.array([[0, 1], [1, 0]])146            predictions   = np.array([[np.log(1/8), np.log(2)], [np.log(2), np.log(1/8)]])147            module_sizes  = np.array([2, 2, 2])148            predict_runner(train_pattern, targets, predictions, module_sizes, mode='log')149        def testModuleSize2_2_2_proba(self):150            train_pattern = np.array([[0, 1, 0, 1], [1, 0, 1, 0]])151            targets       = np.array([[0, 1], [1, 0]])152            predictions   = np.array([[1/17, 16/17], [16/17, 1/17]])153            module_sizes  = np.array([2, 2, 2])154            predict_runner(train_pattern, targets, predictions, module_sizes, mode='proba')155        def testModuleSize2_3_2_log(self):156            train_pattern = np.array([[0, 1, 1, 0, 0], [1, 0, 0, 1, 0]])157            targets       = np.array([[0, 1], [1, 0]])158            predictions   = np.array([[np.log(1/8), np.log(2)], [np.log(2), np.log(1/8)]])159            module_sizes  = np.array([2, 3, 2])160            predict_runner(train_pattern, targets, predictions, module_sizes, mode='log')161        def testModuleNormalizationAssertion1_train(self):162            train_pattern = np.array([[1, 1]])163            targets       = np.array([[1, 0]])164            test_pattern  = np.array([[0, 0]])165            predictions   = np.array([[1, 0]])166            module_sizes  = np.array([2, 2])167            with pytest.raises(BCPNN.NormalizationError):168                predict_runner(train_pattern, targets, predictions, module_sizes, test_pattern=test_pattern,169                 mode='proba')170        def testModuleNormalizationAssertion1_test(self):171            train_pattern = np.array([[1, 0]])172            targets       = np.array([[1, 0]])173            test_pattern  = np.array([[1, 1]])174            predictions   = np.array([[1, 0]])175            module_sizes  = np.array([2, 2])176            with pytest.raises(BCPNN.NormalizationError):177                predict_runner(train_pattern, targets, predictions, module_sizes, test_pattern=test_pattern,178                 mode='proba')179    class TestFractional:180        def testModuleSize2_2_log(self):181            train_pattern = np.array([[1/3, 2/3], [2/3, 1/3]])182            targets       = np.array([[0, 1], [1, 0]])183            predictions   = np.array([[np.log(4/9), np.log(5/9)], [np.log(5/9), np.log(4/9)]])184            module_sizes  = np.array([2, 2])185            predict_runner(train_pattern, targets, predictions, module_sizes, mode='log')186        def testModuleSize2_3_2_log(self):187            train_pattern = np.array([[1/3, 2/3, 1/4, 1/4, 2/4], [1, 0, 0, 1, 0]])188            targets       = np.array([[0, 1], [1, 0]])189            predictions   = np.array([[np.log(155/480), np.log(288/240)], [np.log(6/5), np.log(1/10)]])190            module_sizes  = np.array([2, 3, 2])191            predict_runner(train_pattern, targets, predictions, module_sizes, mode='log')192    class TestDifferentTestPattern:193        def testModuleSize2_2_log(self):194            train_pattern = np.array([[1, 0], [0, 1]])195            targets       = np.array([[1, 0], [0, 1]])196            test_pattern  = np.array([[1/2, 1/2], [2/3, 1/3]])197            predictions   = np.array([[np.log(5/8), np.log(5/8)], [np.log(3/4), np.log(1/2)]])198            module_sizes  = np.array([2, 2])199            predict_runner(train_pattern, targets, predictions, module_sizes, test_pattern=test_pattern, mode='log')200        def testModuleSize2_2_predict(self):201            train_pattern = np.array([[1, 0], [0, 1]])202            targets       = np.array([[1, 0], [0, 1]])203            test_pattern  = np.array([[1/2, 1/2], [2/3, 1/3]])204            predictions   = np.array([[np.log(5/8), np.log(5/8)], [np.log(3/4), np.log(1/2)]])205            predictions   = np.array([0, 0])206            module_sizes  = np.array([2, 2])207            predict_runner(train_pattern, targets, predictions, module_sizes, test_pattern=test_pattern, mode='predict')208        def testModuleSize2_2_single_log(self):209            train_pattern = np.array([[1, 0]])210            targets       = np.array([[1, 0]])211            test_pattern  = np.array([[1, 0], [2/3, 1/3]])212            predictions   = np.array([[0, 0], [0, 0]])213            module_sizes  = np.array([2, 2])214            predict_runner(train_pattern, targets, predictions, module_sizes, test_pattern=test_pattern, mode='log')215        def testModuleSize3_2_log(self):216            train_pattern = np.array([[1, 0, 0], [0, 1, 0]])217            targets       = np.array([[1, 0], [0, 1]])218            test_pattern  = np.array([[0, 0, 1], [0, 1/2, 1/2]])219            predictions   = np.array([[np.log(1/2), np.log(1/2)], [np.log(3/8), np.log(3/4)]])220            module_sizes  = np.array([3, 2])221            predict_runner(train_pattern, targets, predictions, module_sizes, test_pattern=test_pattern, mode='log')222        def testModuleSize3_2_predict(self):223            train_pattern = np.array([[1, 0, 0], [0, 1, 0]])224            targets       = np.array([[1, 0], [0, 1]])225            test_pattern  = np.array([[0, 0, 1], [0, 1/2, 1/2]])226            predictions   = np.array([[np.log(1/2), np.log(1/2)], [np.log(3/8), np.log(3/4)]])227            predictions   = np.array([0, 1])228            module_sizes  = np.array([3, 2])...regular_re.py
Source:regular_re.py  
1import re2# pattern to search for3patterns = ['term1', 'term2', 'term3', 'term']4# string to search pattern in5text = 'This is a string with term1, and not the other term'6# for pattern in patterns:7#     print('I am searching for: {}'.format(pattern)) # code to execute each time a match is found8# Using re module functionality to perform the search 9for pattern in patterns:10    print('I am searching for: {}'.format(pattern))11    if re.search(pattern, text):12        print('MATCH FOUND')13    else:14        print('NO MATCH!')15# re.search() returns special regular expressions object <class '_sre.SRE_Match'> which contains more than the booleanes of the search, it contains other details e.g where in the text the match was found e.g: at what index withn the string, using the start() method16match_info = re.search(pattern, text).start()17print(match_info)18# You can also split the text, returns a list of the split part of the string19split_term = '@'20email = 'user@email.com'21print(re.split(split_term, email))22# Using re to find all instance of a pattern, returning a list of of all non-overlapping matches23print(re.findall('match', 'This text has two match strings that need to find match for'))24# Using metacharacters to find repetition within25def multi_re_find(patterns, phrase):26    for pat in patterns:27        print('Searching for pattern: %s') %pattern28        print(re.findall(pat, phrase))29        print('\n') # print a new line after every search pass30# Finding patterns31test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd'32test_pattern = ['sd*'] # returns a list with all patterns featuring 's' and 'd' repeated zero or more times33multi_re_find(test_pattern, test_phrase)34test_pattern = ['sd+'] # returns a list with all patterns featuring 's' and 'd' repeated one or more times35multi_re_find(test_pattern, test_phrase)36test_pattern = ['sd?'] # returns a list with all patterns featuring 's' and 'd' repeated zero or once37multi_re_find(test_pattern, test_phrase)38test_pattern = ['sd{3}'] # returns a list with all patterns featuring 's' and 'd' a specific number of times39multi_re_find(test_pattern, test_phrase)40test_pattern = ['sd{1,3}'] # returns a list with all patterns featuring 's' and 'd' a specific number of times or another specific number of times41multi_re_find(test_pattern, test_phrase)42test_pattern = ['s[sd]+'] # returns a list with all patterns featuring 's' and followed by either 1 or more 's' or 'd'.43multi_re_find(test_pattern, test_phrase)44# Exclusions using the 'carrot' ^ symbol45test_phrase = 'This is a string! But it has punctuation. How can we remove it?'46test_pattern = ['[^!.?]+'] # Splits the string where the punctuations appear one or more times47multi_re_find(test_pattern, test_phrase)48# Sequences of lower case letters: ['[a-z]+'], uppercase ['[A-Z]+'], both upper and lower case ['[a-zA-Z]+'], one upper followed by one or more lower case ['[A-Z][a-z]+'] etc49# Finding escape characters, which in python are prefixed by '\'. However the '\' must itself be escaped in a normal string, which is done by making a literal value using 'r'. 50test_phrase = 'This is a string890! But it has numbers 22. How can we #remove 12them?'51test_pattern = [r'\d+'] # returns sequences of one or more digits52multi_re_find(test_pattern, test_phrase)53test_phrase = 'This is a string890! But it has numbers 22. How can we #remove 12them?'54test_pattern = [r'\s+'] # returns sequences of one or more spaces55multi_re_find(test_pattern, test_phrase)56test_phrase = 'This is a string890! But it has numbers 22. How can we #remove 12them?'57test_pattern = [r'\D+'] # returns sequences of one or more non-digits58multi_re_find(test_pattern, test_phrase)59test_phrase = 'This is a string890! But it has numbers 22. How can we #remove 12them?'60test_pattern = [r'\S+'] # returns sequences of one or more non-spaces61multi_re_find(test_pattern, test_phrase)62test_phrase = 'This is a string890! But it has numbers 22. How can we #remove 12them?'63test_pattern = [r'\w+'] # returns sequences of one or more alphanumerics64multi_re_find(test_pattern, test_phrase)65test_phrase = 'This is a string890! But it has numbers 22. How can we #remove 12them?'66test_pattern = [r'\W+'] # returns sequences of one or more non-alphanumeric...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
