Python numpy.add() Examples

The following are 30 code examples for showing how to use numpy.add(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module numpy , or try the search function .

Example 1
Project: Keras-GAN   Author: eriklindernoren   File: sgan.py    License: MIT License 8 votes vote down vote up
def build_generator(self):

        model = Sequential()

        model.add(Dense(128 * 7 * 7, activation="relu", input_dim=self.latent_dim))
        model.add(Reshape((7, 7, 128)))
        model.add(BatchNormalization(momentum=0.8))
        model.add(UpSampling2D())
        model.add(Conv2D(128, kernel_size=3, padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(momentum=0.8))
        model.add(UpSampling2D())
        model.add(Conv2D(64, kernel_size=3, padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Conv2D(1, kernel_size=3, padding="same"))
        model.add(Activation("tanh"))

        model.summary()

        noise = Input(shape=(self.latent_dim,))
        img = model(noise)

        return Model(noise, img) 
Example 2
Project: Keras-GAN   Author: eriklindernoren   File: context_encoder.py    License: MIT License 7 votes vote down vote up
def build_discriminator(self):

        model = Sequential()

        model.add(Conv2D(64, kernel_size=3, strides=2, input_shape=self.missing_shape, padding="same"))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Conv2D(128, kernel_size=3, strides=2, padding="same"))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Conv2D(256, kernel_size=3, padding="same"))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Flatten())
        model.add(Dense(1, activation='sigmoid'))
        model.summary()

        img = Input(shape=self.missing_shape)
        validity = model(img)

        return Model(img, validity) 
Example 3
Project: sparse-subspace-clustering-python   Author: abhinav4192   File: BuildAdjacency.py    License: MIT License 6 votes vote down vote up
def BuildAdjacency(CMat, K):
    CMat = CMat.astype(float)
    CKSym = None
    N, _ = CMat.shape
    CAbs = np.absolute(CMat).astype(float)
    for i in range(0, N):
        c = CAbs[:, i]
        PInd = np.flip(np.argsort(c), 0)
        CAbs[:, i] = CAbs[:, i] / float(np.absolute(c[PInd[0]]))
    CSym = np.add(CAbs, CAbs.T).astype(float)
    if K != 0:
        Ind = np.flip(np.argsort(CSym, axis=0), 0)
        CK = np.zeros([N, N]).astype(float)
        for i in range(0, N):
            for j in range(0, K):
                CK[Ind[j, i], i] = CSym[Ind[j, i], i] / float(np.absolute(CSym[Ind[0, i], i]))
        CKSym = np.add(CK, CK.T)
    else:
        CKSym = CSym
    return CKSym 
Example 4
Project: tensortrade   Author: tensortrade-org   File: heston.py    License: Apache License 2.0 6 votes vote down vote up
def geometric_brownian_motion_jump_diffusion_log_returns(params: ModelParameters):
    """
    Constructs combines a geometric brownian motion process
    (log returns) with a jump diffusion process (log returns) to produce
    a sequence of gbm jump returns.

    Arguments:
        params : ModelParameters
            The parameters for the stochastic model.

    Returns:
        A GBM process with jumps in it
    """
    jump_diffusion = jump_diffusion_process(params)
    geometric_brownian_motion = geometric_brownian_motion_log_returns(params)
    return np.add(jump_diffusion, geometric_brownian_motion) 
Example 5
Project: tensortrade   Author: tensortrade-org   File: test_feed.py    License: Apache License 2.0 6 votes vote down vote up
def test_multi_step_adding():

    a1 = Stream([1, 2, 3]).rename("a1")
    a2 = Stream([4, 5, 6]).rename("a2")

    t1 = BinOp(np.add)(a1, a2).rename("t1")
    t2 = BinOp(np.add)(t1, a2).rename("t2")

    feed = DataFeed([a1, a2, t1, t2])

    output = feed.next()
    assert output == {'a1': 1, 'a2': 4, 't1': 5, 't2': 9}

    feed = DataFeed([a1, a2, t2])

    output = feed.next()
    assert output == {'a1': 1, 'a2': 4, 't2': 9} 
Example 6
Project: NeuroKit   Author: neuropsychology   File: rsp_findpeaks.py    License: MIT License 6 votes vote down vote up
def _rsp_findpeaks_outliers(rsp_cleaned, extrema, amplitude_min=0.3):

    # Only consider those extrema that have a minimum vertical distance to
    # their direct neighbor, i.e., define outliers in absolute amplitude
    # difference between neighboring extrema.
    vertical_diff = np.abs(np.diff(rsp_cleaned[extrema]))
    median_diff = np.median(vertical_diff)
    min_diff = np.where(vertical_diff > (median_diff * amplitude_min))[0]
    extrema = extrema[min_diff]

    # Make sure that the alternation of peaks and troughs is unbroken. If
    # alternation of sign in extdiffs is broken, remove the extrema that
    # cause the breaks.
    amplitudes = rsp_cleaned[extrema]
    extdiffs = np.sign(np.diff(amplitudes))
    extdiffs = np.add(extdiffs[0:-1], extdiffs[1:])
    removeext = np.where(extdiffs != 0)[0] + 1
    extrema = np.delete(extrema, removeext)
    amplitudes = np.delete(amplitudes, removeext)

    return extrema, amplitudes 
Example 7
Project: Keras-GAN   Author: eriklindernoren   File: ccgan.py    License: MIT License 6 votes vote down vote up
def build_discriminator(self):

        img = Input(shape=self.img_shape)

        model = Sequential()
        model.add(Conv2D(64, kernel_size=4, strides=2, padding='same', input_shape=self.img_shape))
        model.add(LeakyReLU(alpha=0.8))
        model.add(Conv2D(128, kernel_size=4, strides=2, padding='same'))
        model.add(LeakyReLU(alpha=0.2))
        model.add(InstanceNormalization())
        model.add(Conv2D(256, kernel_size=4, strides=2, padding='same'))
        model.add(LeakyReLU(alpha=0.2))
        model.add(InstanceNormalization())

        model.summary()

        img = Input(shape=self.img_shape)
        features = model(img)

        validity = Conv2D(1, kernel_size=4, strides=1, padding='same')(features)

        label = Flatten()(features)
        label = Dense(self.num_classes+1, activation="softmax")(label)

        return Model(img, [validity, label]) 
Example 8
Project: Keras-GAN   Author: eriklindernoren   File: bigan.py    License: MIT License 6 votes vote down vote up
def build_encoder(self):
        model = Sequential()

        model.add(Flatten(input_shape=self.img_shape))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(self.latent_dim))

        model.summary()

        img = Input(shape=self.img_shape)
        z = model(img)

        return Model(img, z) 
Example 9
Project: Keras-GAN   Author: eriklindernoren   File: infogan.py    License: MIT License 6 votes vote down vote up
def build_generator(self):

        model = Sequential()

        model.add(Dense(128 * 7 * 7, activation="relu", input_dim=self.latent_dim))
        model.add(Reshape((7, 7, 128)))
        model.add(BatchNormalization(momentum=0.8))
        model.add(UpSampling2D())
        model.add(Conv2D(128, kernel_size=3, padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(momentum=0.8))
        model.add(UpSampling2D())
        model.add(Conv2D(64, kernel_size=3, padding="same"))
        model.add(Activation("relu"))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Conv2D(self.channels, kernel_size=3, padding='same'))
        model.add(Activation("tanh"))

        gen_input = Input(shape=(self.latent_dim,))
        img = model(gen_input)

        model.summary()

        return Model(gen_input, img) 
Example 10
Project: Keras-GAN   Author: eriklindernoren   File: wgan.py    License: MIT License 6 votes vote down vote up
def build_generator(self):

        model = Sequential()

        model.add(Dense(128 * 7 * 7, activation="relu", input_dim=self.latent_dim))
        model.add(Reshape((7, 7, 128)))
        model.add(UpSampling2D())
        model.add(Conv2D(128, kernel_size=4, padding="same"))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Activation("relu"))
        model.add(UpSampling2D())
        model.add(Conv2D(64, kernel_size=4, padding="same"))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Activation("relu"))
        model.add(Conv2D(self.channels, kernel_size=4, padding="same"))
        model.add(Activation("tanh"))

        model.summary()

        noise = Input(shape=(self.latent_dim,))
        img = model(noise)

        return Model(noise, img) 
Example 11
Project: Keras-GAN   Author: eriklindernoren   File: lsgan.py    License: MIT License 6 votes vote down vote up
def build_generator(self):

        model = Sequential()

        model.add(Dense(256, input_dim=self.latent_dim))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(1024))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(np.prod(self.img_shape), activation='tanh'))
        model.add(Reshape(self.img_shape))

        model.summary()

        noise = Input(shape=(self.latent_dim,))
        img = model(noise)

        return Model(noise, img) 
Example 12
Project: Keras-GAN   Author: eriklindernoren   File: lsgan.py    License: MIT License 6 votes vote down vote up
def build_discriminator(self):

        model = Sequential()

        model.add(Flatten(input_shape=self.img_shape))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(Dense(256))
        model.add(LeakyReLU(alpha=0.2))
        # (!!!) No softmax
        model.add(Dense(1))
        model.summary()

        img = Input(shape=self.img_shape)
        validity = model(img)

        return Model(img, validity) 
Example 13
Project: Keras-GAN   Author: eriklindernoren   File: cogan.py    License: MIT License 6 votes vote down vote up
def build_discriminators(self):

        img1 = Input(shape=self.img_shape)
        img2 = Input(shape=self.img_shape)

        # Shared discriminator layers
        model = Sequential()
        model.add(Flatten(input_shape=self.img_shape))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(Dense(256))
        model.add(LeakyReLU(alpha=0.2))

        img1_embedding = model(img1)
        img2_embedding = model(img2)

        # Discriminator 1
        validity1 = Dense(1, activation='sigmoid')(img1_embedding)
        # Discriminator 2
        validity2 = Dense(1, activation='sigmoid')(img2_embedding)

        return Model(img1, validity1), Model(img2, validity2) 
Example 14
Project: Keras-GAN   Author: eriklindernoren   File: dualgan.py    License: MIT License 6 votes vote down vote up
def build_generator(self):

        X = Input(shape=(self.img_dim,))

        model = Sequential()
        model.add(Dense(256, input_dim=self.img_dim))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dropout(0.4))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dropout(0.4))
        model.add(Dense(1024))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dropout(0.4))
        model.add(Dense(self.img_dim, activation='tanh'))

        X_translated = model(X)

        return Model(X, X_translated) 
Example 15
Project: Keras-GAN   Author: eriklindernoren   File: gan.py    License: MIT License 6 votes vote down vote up
def build_generator(self):

        model = Sequential()

        model.add(Dense(256, input_dim=self.latent_dim))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(1024))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(np.prod(self.img_shape), activation='tanh'))
        model.add(Reshape(self.img_shape))

        model.summary()

        noise = Input(shape=(self.latent_dim,))
        img = model(noise)

        return Model(noise, img) 
Example 16
Project: Keras-GAN   Author: eriklindernoren   File: gan.py    License: MIT License 6 votes vote down vote up
def build_discriminator(self):

        model = Sequential()

        model.add(Flatten(input_shape=self.img_shape))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(Dense(256))
        model.add(LeakyReLU(alpha=0.2))
        model.add(Dense(1, activation='sigmoid'))
        model.summary()

        img = Input(shape=self.img_shape)
        validity = model(img)

        return Model(img, validity) 
Example 17
Project: Keras-GAN   Author: eriklindernoren   File: bgan.py    License: MIT License 6 votes vote down vote up
def build_generator(self):

        model = Sequential()

        model.add(Dense(256, input_dim=self.latent_dim))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(1024))
        model.add(LeakyReLU(alpha=0.2))
        model.add(BatchNormalization(momentum=0.8))
        model.add(Dense(np.prod(self.img_shape), activation='tanh'))
        model.add(Reshape(self.img_shape))

        model.summary()

        noise = Input(shape=(self.latent_dim,))
        img = model(noise)

        return Model(noise, img) 
Example 18
Project: Keras-GAN   Author: eriklindernoren   File: bgan.py    License: MIT License 6 votes vote down vote up
def build_discriminator(self):

        model = Sequential()

        model.add(Flatten(input_shape=self.img_shape))
        model.add(Dense(512))
        model.add(LeakyReLU(alpha=0.2))
        model.add(Dense(256))
        model.add(LeakyReLU(alpha=0.2))
        model.add(Dense(1, activation='sigmoid'))
        model.summary()

        img = Input(shape=self.img_shape)
        validity = model(img)

        return Model(img, validity) 
Example 19
Project: recruit   Author: Frank-qlu   File: test_old_ma.py    License: Apache License 2.0 6 votes vote down vote up
def test_testAddSumProd(self):
        # Test add, sum, product.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf, s) = self.d
        assert_(eq(np.add.reduce(x), add.reduce(x)))
        assert_(eq(np.add.accumulate(x), add.accumulate(x)))
        assert_(eq(4, sum(array(4), axis=0)))
        assert_(eq(4, sum(array(4), axis=0)))
        assert_(eq(np.sum(x, axis=0), sum(x, axis=0)))
        assert_(eq(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0)))
        assert_(eq(np.sum(x, 0), sum(x, 0)))
        assert_(eq(np.product(x, axis=0), product(x, axis=0)))
        assert_(eq(np.product(x, 0), product(x, 0)))
        assert_(eq(np.product(filled(xm, 1), axis=0),
                           product(xm, axis=0)))
        if len(s) > 1:
            assert_(eq(np.concatenate((x, y), 1),
                               concatenate((xm, ym), 1)))
            assert_(eq(np.add.reduce(x, 1), add.reduce(x, 1)))
            assert_(eq(np.sum(x, 1), sum(x, 1)))
            assert_(eq(np.product(x, 1), product(x, 1))) 
Example 20
Project: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 6 votes vote down vote up
def test_addsumprod(self):
        # Tests add, sum, product.
        (x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
        assert_equal(np.add.reduce(x), add.reduce(x))
        assert_equal(np.add.accumulate(x), add.accumulate(x))
        assert_equal(4, sum(array(4), axis=0))
        assert_equal(4, sum(array(4), axis=0))
        assert_equal(np.sum(x, axis=0), sum(x, axis=0))
        assert_equal(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0))
        assert_equal(np.sum(x, 0), sum(x, 0))
        assert_equal(np.product(x, axis=0), product(x, axis=0))
        assert_equal(np.product(x, 0), product(x, 0))
        assert_equal(np.product(filled(xm, 1), axis=0), product(xm, axis=0))
        s = (3, 4)
        x.shape = y.shape = xm.shape = ym.shape = s
        if len(s) > 1:
            assert_equal(np.concatenate((x, y), 1), concatenate((xm, ym), 1))
            assert_equal(np.add.reduce(x, 1), add.reduce(x, 1))
            assert_equal(np.sum(x, 1), sum(x, 1))
            assert_equal(np.product(x, 1), product(x, 1)) 
Example 21
Project: recruit   Author: Frank-qlu   File: test_core.py    License: Apache License 2.0 6 votes vote down vote up
def test_datafriendly_add(self):
        # Test keeping data w/ (inplace) addition
        x = array([1, 2, 3], mask=[0, 0, 1])
        # Test add w/ scalar
        xx = x + 1
        assert_equal(xx.data, [2, 3, 3])
        assert_equal(xx.mask, [0, 0, 1])
        # Test iadd w/ scalar
        x += 1
        assert_equal(x.data, [2, 3, 3])
        assert_equal(x.mask, [0, 0, 1])
        # Test add w/ array
        x = array([1, 2, 3], mask=[0, 0, 1])
        xx = x + array([1, 2, 3], mask=[1, 0, 0])
        assert_equal(xx.data, [1, 4, 3])
        assert_equal(xx.mask, [1, 0, 1])
        # Test iadd w/ array
        x = array([1, 2, 3], mask=[0, 0, 1])
        x += array([1, 2, 3], mask=[1, 0, 0])
        assert_equal(x.data, [1, 4, 3])
        assert_equal(x.mask, [1, 0, 1]) 
Example 22
Project: argus-freesound   Author: lRomul   File: tiles.py    License: MIT License 5 votes vote down vote up
def compute_pyramid_patch_weight_loss(width, height) -> np.ndarray:
    """Compute a weight matrix that assigns bigger weight on pixels in center and
    less weight to pixels on image boundary.
    This weight matrix then used for merging individual tile predictions and helps dealing
    with prediction artifacts on tile boundaries.

    :param width: Tile width
    :param height: Tile height
    :return: Since-channel image [Width x Height]
    """
    xc = width * 0.5
    yc = height * 0.5
    xl = 0
    xr = width
    yb = 0
    yt = height
    Dc = np.zeros((width, height))
    De = np.zeros((width, height))

    for i in range(width):
        for j in range(height):
            Dc[i, j] = np.sqrt(np.square(i - xc + 0.5) + np.square(j - yc + 0.5))
            De_l = np.sqrt(np.square(i - xl + 0.5) + np.square(j - j + 0.5))
            De_r = np.sqrt(np.square(i - xr + 0.5) + np.square(j - j + 0.5))
            De_b = np.sqrt(np.square(i - i + 0.5) + np.square(j - yb + 0.5))
            De_t = np.sqrt(np.square(i - i + 0.5) + np.square(j - yt + 0.5))
            De[i, j] = np.min([De_l, De_r, De_b, De_t])

    alpha = (width * height) / np.sum(np.divide(De, np.add(Dc, De)))
    W = alpha * np.divide(De, np.add(Dc, De))
    return W, Dc, De 
Example 23
Project: tensortrade   Author: tensortrade-org   File: node.py    License: Apache License 2.0 5 votes vote down vote up
def __add__(self, other):
        if np.isscalar(other):
            other = Constant(other, "Constant({})".format(other))
            name = "Add({},{})".format(self.name, other.name)
            return BinOp(np.add, name)(self, other)
        assert isinstance(other, Node)
        name = "Add({},{})".format(self.name, other.name)
        return BinOp(np.add, name)(self, other) 
Example 24
Project: tensortrade   Author: tensortrade-org   File: test_feed.py    License: Apache License 2.0 5 votes vote down vote up
def test_stream_adding():
    a1 = Stream([1, 2, 3]).rename("a1")
    a2 = Stream([4, 5, 6]).rename("a2")

    t1 = BinOp(np.add)(a1, a2).rename("a1+a2")

    feed = DataFeed([t1, a1, a2])

    output = feed.next()

    assert output == {'a1': 1, 'a2': 4, 'a1+a2': 5} 
Example 25
Project: tensortrade   Author: tensortrade-org   File: test_transform.py    License: Apache License 2.0 5 votes vote down vote up
def test_namespace():

    a = Stream([1, 2, 3]).rename("a")

    with Module("world") as world:
        a1 = Stream([4, 5, 6]).rename("a1")
        a2 = Stream([7, 8, 9]).rename("a2")

        with Module("sub-world") as sub_world:
            a3 = Stream([10, 11, 12]).rename("a3")
            a4 = Stream([13, 14, 15]).rename("a4")

            t3 = BinOp(np.add)(a2, a4).rename("t3")

    t1 = BinOp(np.multiply)(a, t3).rename("t1")

    feed = DataFeed([t1, world, sub_world])

    assert feed.next() == {
        "world:/a1": 4,
        "world:/a2": 7,
        "world:/sub-world:/a3": 10,
        "world:/sub-world:/a4": 13,
        "world:/sub-world:/t3": 20,
        "t1": 20
    }
    feed.reset()
    assert feed.next() == {
        "world:/a1": 4,
        "world:/a2": 7,
        "world:/sub-world:/a3": 10,
        "world:/sub-world:/a4": 13,
        "world:/sub-world:/t3": 20,
        "t1": 20
    } 
Example 26
Project: gnocchi   Author: gnocchixyz   File: utils.py    License: Apache License 2.0 5 votes vote down vote up
def to_timestamps(values):
    try:
        if len(values) == 0:
            return []
        if isinstance(values[0], (numpy.datetime64, datetime.datetime)):
            times = numpy.array(values)
        else:
            try:
                # Try to convert to float. If it works, then we consider
                # timestamps to be number of seconds since Epoch
                # e.g. 123456 or 129491.1293
                float(values[0])
            except ValueError:
                try:
                    # Try to parse the value as a string of ISO timestamp
                    # e.g. 2017-10-09T23:23:12.123
                    numpy.datetime64(values[0])
                except ValueError:
                    # Last chance: it can be relative timestamp, so convert
                    # to timedelta relative to now()
                    # e.g. "-10 seconds" or "5 minutes"
                    times = numpy.fromiter(
                        numpy.add(numpy.datetime64(utcnow()),
                                  [to_timespan(v, True) for v in values]),
                        dtype='datetime64[ns]', count=len(values))
                else:
                    times = numpy.array(values, dtype='datetime64[ns]')
            else:
                times = numpy.array(values, dtype='float') * 10e8
    except ValueError:
        raise ValueError("Unable to convert timestamps")

    times = times.astype('datetime64[ns]')

    if (times < unix_universal_start64).any():
        raise ValueError('Timestamp must be after Epoch')

    return times 
Example 27
Project: simpleflow   Author: PytLab   File: operations.py    License: MIT License 5 votes vote down vote up
def compute_output(self):
        ''' Compute and return the value of addition operation.
        '''
        x, y = self.input_nodes
        self.output_value = np.add(x.output_value, y.output_value)
        return self.output_value 
Example 28
Project: simpleflow   Author: PytLab   File: operations.py    License: MIT License 5 votes vote down vote up
def add(x, y, name=None):
    ''' Returns x + y element-wise.
    '''
    return Add(x, y, name)

# ------------------------------------------------------------------------------
# Multiplication operation
# ------------------------------------------------------------------------------ 
Example 29
Project: iAI   Author: aimuch   File: chptToBin.py    License: MIT License 5 votes vote down vote up
def convert_rnn_bias(weights, dimensions, forget_bias = 1.0):
    """
    TensorFlow bias parameters for BasicLSTMCell
    are formatted as:
    CellN: Bi, Bc, Bf, Bo

    TensorRT expects the format to be:
    CellN: Wf, Wi, Wc, Wo, Rf, Ri, Rc, Ro

    Since Tensorflow already combines U and W,
    we double the size and set all of U to zero.
    """
    num_units = dimensions["num_units"]
    layers = dimensions["layers"]
    temp_weights = np.zeros([layers, 2 * 4, num_units], dtype=np.float32)
    weights = np.reshape(weights, (layers, 4, num_units))

    # then we reorder gates from Tensorflow's 'icfo' into TensorRT's 'fico' order
    input_perm = [ 1, 2, 0, 3 ]
    for i in range(4):
        temp_weights[:, input_perm[i], :] = weights[:, i, :]
    #  Add a value to f bias to be consistent with the Tensorflow model.
    print("Adding {0} to forget bias".format(forget_bias))
    temp_weights[:, 0, :] = np.add(temp_weights[:, 0, :], forget_bias)
    weights = deepcopy(temp_weights)

    return weights 
Example 30
Project: iAI   Author: aimuch   File: chptToBin.py    License: MIT License 5 votes vote down vote up
def convert_rnn_bias(weights, dimensions, forget_bias = 1.0):
    """
    TensorFlow bias parameters for BasicLSTMCell
    are formatted as:
    CellN: Bi, Bc, Bf, Bo

    TensorRT expects the format to be:
    CellN: Wf, Wi, Wc, Wo, Rf, Ri, Rc, Ro

    Since Tensorflow already combines U and W,
    we double the size and set all of U to zero.
    """
    num_units = dimensions["num_units"]
    layers = dimensions["layers"]
    temp_weights = np.zeros([layers, 2 * 4, num_units], dtype=np.float32)
    weights = np.reshape(weights, (layers, 4, num_units))

    # then we reorder gates from Tensorflow's 'icfo' into TensorRT's 'fico' order
    input_perm = [ 1, 2, 0, 3 ]
    for i in range(4):
        temp_weights[:, input_perm[i], :] = weights[:, i, :]
    #  Add a value to f bias to be consistent with the Tensorflow model.
    print("Adding {0} to forget bias".format(forget_bias))
    temp_weights[:, 0, :] = np.add(temp_weights[:, 0, :], forget_bias)
    weights = deepcopy(temp_weights)

    return weights