Python numpy.log() Examples

The following are code examples for showing how to use numpy.log(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 6 votes vote down vote up
def test_log_results():
	# value defined at positive real numbers x > 0
	# derivative defined at real numbers x ≠ 0
	X = AutoDiff(0.5, 2)
	f = ef.log(X)
	assert f.val == np.log(0.5)
	assert f.der == np.array([[2/0.5]])
	assert f.jacobian == np.array([[1/0.5]])
	# derivative not defined at x = 0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(0, 2)
		f = ef.log(Y)
		assert np.isneginf(f.val)
		assert np.isinf(f.der)
		assert np.isinf(f.jacobian)
	# value not defined at x < 0, derivative defined
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(-0.5, 2)
		f = ef.log(Y)
		assert np.isnan(f.val)
		assert f.der == np.array([[2/-0.5]])
		assert f.jacobian == np.array([[1/-0.5]]) 
Example 2
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 6 votes vote down vote up
def test_log10_results():
	# value defined at positive real numbers x > 0
	# derivative defined at positive real numbers x > 0
	X = AutoDiff(0.5, 2)
	f = ef.log10(X)
	assert f.val == np.log10(0.5)
	assert f.der == np.array([[(1/((0.5)*np.log(10)))*2]])
	assert f.jacobian == np.array([[(1/((0.5)*np.log(10)))*1]])
	# neither value nor derivative defined at x = 0
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(0, 2)
		f = ef.log10(Y)
		assert np.isinf(f.val)
		assert np.isinf(f.der)
		assert np.isinf(f.jacobian)
	# value not defined at x < 0, derivative defined
	with pytest.warns(RuntimeWarning):
		Y = AutoDiff(-0.5, 2)
		f = ef.log10(Y)
		assert np.isnan(f.val)
		assert f.der == np.array([[(2/(-0.5*np.log(10)))]])
		assert f.jacobian == np.array([[1/(-0.5*np.log(10))]]) 
Example 3
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_log_results():
	# Realue defined at positive real numbers x > 0
	# Dualivative defined at real numbers x ≠ 0
	X = Dual(0.5, 2)
	f = ef.log(X)
	assert f.Real == np.log(0.5)
	assert f.Dual == np.array([[2/0.5]])

	# Dualivative not defined at x = 0
	Y = Dual(0, 2)
	f = ef.log(Y)
	assert np.isneginf(f.Real)
	assert np.isinf(f.Dual)

	# Realue not defined at x < 0, Dualivative defined
	with pytest.warns(RuntimeWarning):
		Y = Dual(-0.5, 2)
		f = ef.log(Y)
		assert np.isnan(f.Real)
		assert f.Dual == np.array([[2/-0.5]]) 
Example 4
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 6 votes vote down vote up
def test_log10_results():
	# Realue defined at positive real numbers x > 0
	# Dualivative defined at positive real numbers x > 0
	X = Dual(0.5, 2)
	f = ef.log10(X)
	assert f.Real == np.log10(0.5)
	assert f.Dual == np.array([[(1/((0.5)*np.log(10)))*2]])

	# neither Realue nor Dualivative defined at x = 0
	with pytest.warns(RuntimeWarning):
		Y = Dual(0, 2)
		f = ef.log10(Y)
		assert np.isinf(f.Real)
		assert np.isinf(f.Dual)

	# Realue not defined at x < 0, Dualivative defined
	with pytest.warns(RuntimeWarning):
		Y = Dual(-0.5, 2)
		f = ef.log10(Y)
		assert np.isnan(f.Real)
		assert f.Dual == np.array([[(2/(-0.5*np.log(10)))]]) 
Example 5
Project: FasterRCNN_TF_Py3   Author: upojzsb   File: bbox_transform.py    MIT License 6 votes vote down vote up
def bbox_transform(ex_rois, gt_rois):
    ex_widths = ex_rois[:, 2] - ex_rois[:, 0] + 1.0
    ex_heights = ex_rois[:, 3] - ex_rois[:, 1] + 1.0
    ex_ctr_x = ex_rois[:, 0] + 0.5 * ex_widths
    ex_ctr_y = ex_rois[:, 1] + 0.5 * ex_heights

    gt_widths = gt_rois[:, 2] - gt_rois[:, 0] + 1.0
    gt_heights = gt_rois[:, 3] - gt_rois[:, 1] + 1.0
    gt_ctr_x = gt_rois[:, 0] + 0.5 * gt_widths
    gt_ctr_y = gt_rois[:, 1] + 0.5 * gt_heights

    targets_dx = (gt_ctr_x - ex_ctr_x) / ex_widths
    targets_dy = (gt_ctr_y - ex_ctr_y) / ex_heights
    targets_dw = np.log(gt_widths / ex_widths)
    targets_dh = np.log(gt_heights / ex_heights)

    targets = np.vstack(
        (targets_dx, targets_dy, targets_dw, targets_dh)).transpose()
    return targets 
Example 6
Project: Deep_VoiceChanger   Author: pstuvwx   File: dataset.py    MIT License 6 votes vote down vote up
def wave2input_image(wave, window, pos=0, pad=0):
    wave_image = np.hstack([wave[pos+i*sride:pos+(i+pad*2)*sride+dif].reshape(height+pad*2, sride) for i in range(256//sride)])[:,:254]
    wave_image *= window
    spectrum_image = np.fft.fft(wave_image, axis=1)
    input_image = np.abs(spectrum_image[:,:128].reshape(1, height+pad*2, 128), dtype=np.float32)

    np.clip(input_image, 1000, None, out=input_image)
    np.log(input_image, out=input_image)
    input_image += bias
    input_image /= scale

    if np.max(input_image) > 0.95:
        print('input image max bigger than 0.95', np.max(input_image))
    if np.min(input_image) < 0.05:
        print('input image min smaller than 0.05', np.min(input_image))

    return input_image 
Example 7
Project: skylab   Author: coenders   File: utils.py    GNU General Public License v3.0 6 votes vote down vote up
def isf(self, x):
        r"""Inverse survival function

        """
        @np.vectorize
        def get_root(x):
            if x > self.eta:
                return 0.

            coeff = np.copy(self.coeff)
            coeff[-1] -= np.log(x)

            roots = np.roots(coeff)
            roots = np.real(roots[np.isreal(roots)])

            return np.amax(roots[roots > 0])

        ts = get_root(x)

        if ts.ndim == 0:
            ts = np.asscalar(ts)

        return ts 
Example 8
Project: skylab   Author: coenders   File: basellh.py    GNU General Public License v3.0 6 votes vote down vote up
def _select_events(self, src_ra, src_dec, scramble=False, inject=None):
        r"""Select events for log-likelihood evaluation.

        This method must set the private attributes number of total
        events `_nevents` and number of selected events `_nselected`.

        Parameters
        ----------
        src_ra : float
            Right ascension of source position
        src_dec : float
            Declination of source position
        scramble : bool, optional
            Scramble select events in right ascension.
        inject : ndarray, optional
            Structured array containing additional events to append to
            selection

        """
        pass 
Example 9
Project: skylab   Author: coenders   File: basellh.py    GNU General Public License v3.0 6 votes vote down vote up
def llh(self, nsources, **others):
        r"""Evaluate log-likelihood function given the source strength
        `nsources` and the parameter values specified in `others`.

        Parameters
        ----------
        nsources : float
            Source strength
        \*\*others
            Other parameters log-likelihood function depends on

        Returns
        -------
        ts : float
            Log-likelihood for the given parameter values
        grad : ndarray
            Gradient for each parameter

        """
        pass 
Example 10
Project: skylab   Author: coenders   File: ps_model.py    GNU General Public License v3.0 6 votes vote down vote up
def _effA(self, mc, livetime, **kwargs):
        r"""Build splines for effective Area given a fixed spectral
        index *gamma*.

        """

        # powerlaw weights
        w = mc["ow"] * mc["trueE"]**(-self.gamma) * livetime * 86400.

        # get pdf of event distribution
        h, bins = np.histogram(np.sin(mc["trueDec"]), weights=w,
                               bins=self.sinDec_bins, density=True)

        # normalize by solid angle
        h /= np.diff(self.sinDec_bins)

        # multiply histogram by event sum for event densitiy
        h *= w.sum()

        self._spl_effA = scipy.interpolate.InterpolatedUnivariateSpline(
                (bins[1:] + bins[:-1]) / 2., np.log(h), k=self.order)

        return 
Example 11
Project: skylab   Author: coenders   File: data.py    GNU General Public License v3.0 6 votes vote down vote up
def exp(N=100):
    r"""Create uniformly distributed data on sphere. """
    g = 3.7

    arr = np.empty((N, ), dtype=[("ra", np.float), ("sinDec", np.float),
                                 ("sigma", np.float), ("logE", np.float)])

    arr["ra"] = np.random.uniform(0., 2.*np.pi, N)
    arr["sinDec"] = np.random.uniform(-1., 1., N)

    E = np.log10(np.random.pareto(g, size=N) + 1)
    arr["sigma"] = np.random.lognormal(mean=np.log((mrs - mrs_min) * np.exp(-np.log(10)*E) + mrs_min),
                                       sigma=log_sig)
    arr["logE"] = E + logE_res * np.random.normal(size=N)

    return arr 
Example 12
Project: deep-learning-note   Author: wdxtub   File: 5_nueral_network.py    MIT License 6 votes vote down vote up
def cost0(params, input_size, hidden_size, num_labels, X, y, learning_rate):
    m = X.shape[0]
    X = np.matrix(X)
    y = np.matrix(y)
    
    # reshape the parameter array into parameter matrices for each layer
    theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))
    theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))
    
    # run the feed-forward pass
    a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
    
    # compute the cost
    J = 0
    for i in range(m):
        first_term = np.multiply(-y[i,:], np.log(h[i,:]))
        second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))
        J += np.sum(first_term - second_term)
    
    J = J / m
    
    return J 
Example 13
Project: deep-learning-note   Author: wdxtub   File: 5_nueral_network.py    MIT License 6 votes vote down vote up
def cost(params, input_size, hidden_size, num_labels, X, y, learning_rate):
    m = X.shape[0]
    X = np.matrix(X)
    y = np.matrix(y)
    
    # reshape the parameter array into parameter matrices for each layer
    theta1 = np.matrix(np.reshape(params[:hidden_size * (input_size + 1)], (hidden_size, (input_size + 1))))
    theta2 = np.matrix(np.reshape(params[hidden_size * (input_size + 1):], (num_labels, (hidden_size + 1))))
    
    # run the feed-forward pass
    a1, z2, a2, z3, h = forward_propagate(X, theta1, theta2)
    
    # compute the cost
    J = 0
    for i in range(m):
        first_term = np.multiply(-y[i,:], np.log(h[i,:]))
        second_term = np.multiply((1 - y[i,:]), np.log(1 - h[i,:]))
        J += np.sum(first_term - second_term)
    
    J = J / m
    
    # add the cost regularization term
    J += (float(learning_rate) / (2 * m)) * (np.sum(np.power(theta1[:,1:], 2)) + np.sum(np.power(theta2[:,1:], 2)))
    
    return J 
Example 14
Project: SyNEThesia   Author: RunOrVeith   File: feature_creators.py    MIT License 5 votes vote down vote up
def logfbank_features(signal, samplerate=44100, fps=24, num_filt=40, num_cepstra=40, nfft=8192, **kwargs):
    winstep = 2 / fps
    winlen = winstep * 2
    feat, energy = psf.fbank(signal=signal, samplerate=samplerate,
                             winlen=winlen, winstep=winstep, nfilt=num_filt,
                             nfft=nfft)
    feat = np.log(feat)
    feat = psf.dct(feat, type=2, axis=1, norm='ortho')[:, :num_cepstra]
    feat = psf.lifter(feat, L=22)
    feat = np.asarray(feat)

    energy = np.log(energy)
    energy = energy.reshape([energy.shape[0],1])

    if feat.shape[0] > 1:
        std = 0.5 * np.std(feat, axis=0)
        mat = (feat - np.mean(feat, axis=0)) / std
    else:
        mat = feat

    mat = np.concatenate((mat, energy), axis=1)

    duration = signal.shape[0] / samplerate
    expected_frames = fps * duration
    assert mat.shape[0] - expected_frames <= 1, "Producted feature number does not match framerate"
    return mat 
Example 15
Project: PEAKachu   Author: tbischler   File: gtest.py    ISC License 5 votes vote down vote up
def _olnf(self, obs, exp):
        return obs * np.log(obs/exp) if obs > 0.1 else 0 
Example 16
Project: osqf2015   Author: mvaz   File: model.py    MIT License 5 votes vote down vote up
def likelihood_statistic(self, n_outliers, n_obs):
        p_obs = n_outliers * 1.0 / n_obs
        p_expected = 1. - self.level
        stat_expected = p_expected ** n_outliers * (1-p_expected) ** (n_obs-n_outliers)
        stat_obs = p_obs ** n_outliers * (1-p_obs) ** (n_obs - n_outliers)
        return -2 * np.log(stat_expected / stat_obs) 
Example 17
Project: osqf2015   Author: mvaz   File: model.py    MIT License 5 votes vote down vote up
def logreturns(self, n_days=1):
        self.ts['LogReturns'] = np.log( self.ts.Value.pct_change(periods=n_days) + 1) 
Example 18
Project: osqf2015   Author: mvaz   File: model.py    MIT License 5 votes vote down vote up
def devol(self, _lambda=0.06, n_days=1):
        _com = (1 - _lambda) / _lambda
        self.df['LogReturns'] = np.log(self.df.Close.pct_change(periods=n_days) + 1)
        self.df['Vola'] = pd.ewmstd( self.df.LogReturns, com=_com, ignore_na=True)[2:]
        self.df['DevolLogReturns'] = self.df.LogReturns / self.df.Vola
        self.df.set_index('Date', inplace=True) 
Example 19
Project: autodmri   Author: samuelstjean   File: gamma.py    MIT License 5 votes vote down vote up
def maxlk_sigma(m, xold=None, eps=1e-8, max_iter=100):
    '''Maximum likelihood equation to estimate sigma from gamma distributed values'''

    sum_m2 = np.sum(m**2)
    K = m.size
    sum_log_m2 = np.sum(np.log(m**2))

    def f(sigma):
        return digamma(sum_m2/(2*K*sigma**2)) - sum_log_m2/K + np.log(2*sigma**2)

    def fprime(sigma):
        return -sum_m2 * polygamma(1, sum_m2/(2*K*sigma**2)) / (K*sigma**3) + 2/sigma

    if xold is None:
        xold = m.std()

    for _ in range(max_iter):

        xnew = xold - f(xold) / fprime(xold)

        if np.abs(xold - xnew) < eps:
            break

        xold = xnew

    return xnew 
Example 20
Project: cs207-FinalProject   Author: PYNE-AD   File: AutoDiff.py    MIT License 5 votes vote down vote up
def __pow__(self, other):
		# Convert to float so that negative integers will work
		other = float(other) if type(other)==int else other
		try:
			return AutoDiff(self.val**other.val, other.val * (self.val ** (other.val-1)) * self.der + (self.val**other.val) *np.log(np.abs(self.val)) * other.der, self.n, 0, other.val * (self.val**(other.val-1)) * self.jacobian + (self.val**other.val * np.log(np.abs(self.val)) * other.jacobian))
		except AttributeError:
			return AutoDiff(self.val**other, other * (self.der) * self.val**(other-1), self.n, 0, other * (self.jacobian) * self.val**(other-1)) 
Example 21
Project: cs207-FinalProject   Author: PYNE-AD   File: AutoDiff.py    MIT License 5 votes vote down vote up
def __rpow__(self, other):
		try:
			return AutoDiff(other.val**self.val, other.val * (self.val ** (other.val-1)) * self.der + (self.val**other.val) *np.log(np.abs(self.val)) * other.der, self.n, 0, other.val * (self.val**(other.val-1)) * self.jacobian + (self.val**other.val * np.log(np.abs(self.val)) * other.jacobian))
		except AttributeError:
			return AutoDiff(other**self.val, np.log(other) * other**self.val * self.der, self.n, 0, np.log(other) * other**self.val * self.jacobian)

	# Unary operations
	# Unary addition: identity 
Example 22
Project: cs207-FinalProject   Author: PYNE-AD   File: Dual.py    MIT License 5 votes vote down vote up
def __rpow__(self, other):
		try: # need to do
			return Dual(other.Real ** self.Real, other.Dual ** self.Dual)
		except AttributeError:
			return Dual(other ** self.Real, self.Dual * np.log(other) * (other ** self.Real))

	# Unary functions 
Example 23
Project: cs207-FinalProject   Author: PYNE-AD   File: Dual_test.py    MIT License 5 votes vote down vote up
def test_rpow_constant_results():
	x = Dual(5, 2)
	f = 3**x
	assert f.Real == 243
	assert f.Dual == 486 * np.log(3) 
Example 24
Project: cs207-FinalProject   Author: PYNE-AD   File: Dual_test.py    MIT License 5 votes vote down vote up
def test_rpow_constant_vector_results():
	x = Dual(np.array([[4, 3]]), np.array([[2, 1]]))
	f = 3**x
	assert np.all(f.Real == np.array([[81, 27]]))
	assert np.all(f.Dual == np.array([[162*np.log(3), 27*np.log(3)]])) 
Example 25
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_log_constant_results():
	a = ef.log(0.5)
	assert a == np.log(0.5)
	with pytest.warns(RuntimeWarning):
		b = ef.log(0)
		assert np.isneginf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.log(-0.5)
		assert np.isnan(b) 
Example 26
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_test.py    MIT License 5 votes vote down vote up
def test_logbase_constant_results():
	a = ef.logbase(0.5,2)
	assert a == np.log(0.5)/np.log(2)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(0,2)
		assert np.isneginf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(-0.5,2)
		assert np.isnan(b) 
Example 27
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_log_constant_results():
	a = ef.log(0.5)
	assert a == np.log(0.5)
	with pytest.warns(RuntimeWarning):
		b = ef.log(0)
		assert np.isneginf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.log(-0.5)
		assert np.isnan(b) 
Example 28
Project: cs207-FinalProject   Author: PYNE-AD   File: elemFunctions_Dual_test.py    MIT License 5 votes vote down vote up
def test_logbase_constant_results():
	a = ef.logbase(0.5,2)
	assert a == np.log(0.5)/np.log(2)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(0,2)
		assert np.isneginf(b)
	with pytest.warns(RuntimeWarning):
		b = ef.logbase(-0.5,2)
		assert np.isnan(b) 
Example 29
Project: cs207-FinalProject   Author: PYNE-AD   File: AutoDiff_test.py    MIT License 5 votes vote down vote up
def test_pow_ad_results():
	x = AutoDiff(2, 1)
	f = x**x
	assert f.val == 4
	assert f.der == 4 + np.log(16)
	assert f.jacobian == 4 + np.log(16) 
Example 30
Project: cs207-FinalProject   Author: PYNE-AD   File: AutoDiff_test.py    MIT License 5 votes vote down vote up
def test_rpow_vector_results():
	x = AutoDiff([4, 3], [2, 1], 2, 1)
	y = AutoDiff([2, 1], [1, 3], 2, 2)
	f = x**y
	assert np.all(f.val == np.array([[4**2, 3**1]]).T)
	assert np.all(f.der == np.array([[2*(4**(2-1))*2, (4**2) * np.log(4) * 1], [1*(3**(1-1))*1, (3**1) * np.log(3)*3]]))
	assert np.all(f.jacobian == np.array([[2*(4**(2-1))*1, (4**2) * np.log(4) * 1], [1*(3**(1-1))*1, (3**1) * np.log(3)*1]])) 
Example 31
Project: cs207-FinalProject   Author: PYNE-AD   File: AutoDiff_test.py    MIT License 5 votes vote down vote up
def test_rpow_constant_vector_results():
	x = AutoDiff([4, 3], [2, 1], 1, 1)
	f = 3**x
	assert np.all(f.val == np.array([[3**(4), 3**3]]).T)
	assert np.all(f.der == np.array([[(3**(4))*2 * np.log(3)], [(3**(3))*1 * np.log(3)]]))
	assert np.all(f.jacobian == np.array([[(3**(4))*1 * np.log(3)], [(3**(3))*1 * np.log(3)]]))


# positive tests 
Example 32
Project: disentangling_conditional_gans   Author: zalandoresearch   File: tfutil.py    MIT License 5 votes vote down vote up
def log2(x):
    with tf.name_scope('Log2'):
        return tf.log(x) * np.float32(1.0 / np.log(2.0)) 
Example 33
Project: disentangling_conditional_gans   Author: zalandoresearch   File: tfutil.py    MIT License 5 votes vote down vote up
def exp2(x):
    with tf.name_scope('Exp2'):
        return tf.exp(x * np.float32(np.log(2.0))) 
Example 34
Project: mmdetection   Author: open-mmlab   File: grid_head.py    Apache License 2.0 5 votes vote down vote up
def init_weights(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
                # TODO: compare mode = "fan_in" or "fan_out"
                kaiming_init(m)
        for m in self.modules():
            if isinstance(m, nn.ConvTranspose2d):
                normal_init(m, std=0.001)
        nn.init.constant_(self.deconv2.bias, -np.log(0.99 / 0.01)) 
Example 35
Project: mmdetection   Author: open-mmlab   File: weight_init.py    Apache License 2.0 5 votes vote down vote up
def bias_init_with_prob(prior_prob):
    """ initialize conv/fc bias value according to giving probablity"""
    bias_init = float(-np.log((1 - prior_prob) / prior_prob))
    return bias_init 
Example 36
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def print_log(print_string, log):
    print("{}".format(print_string))
    log.write('{}\n'.format(print_string))
    log.flush() 
Example 37
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def ensembleVer2(input_folder, output_path):
    print('Out:' + output_path)
    csv_files = [f for f in os.listdir(input_folder) if f.endswith('.csv')]
    model_scores = []
    for i, csv in enumerate(csv_files):
        df = pd.read_csv(os.path.join(input_folder, csv), index_col=0)
        if i == 0:
            index = df.index
        else:
            assert index.equals(df.index), "Indices of one or more files do not match!"
        model_scores.append(df)
    print("Read %d files. Averaging..." % len(model_scores))

    # print(model_scores)
    concat_scores = pd.concat(model_scores)
    print(concat_scores.head())
    concat_scores['is_iceberg'] = concat_scores['is_iceberg'].astype(np.float32)

    averaged_scores = concat_scores.groupby(level=0).mean()
    assert averaged_scores.shape[0] == len(list(index)), "Something went wrong when concatenating/averaging!"
    averaged_scores = averaged_scores.reindex(index)

    stacked_1 = pd.read_csv('statoil-submission-template.csv')  # for the header
    print(stacked_1.shape)
    sub = pd.DataFrame()
    sub['id'] = stacked_1['id']

    sub['is_iceberg'] = np.exp(np.mean(
        [
            averaged_scores['is_iceberg'].apply(lambda x: np.log(x))
        ], axis=0))

    print(sub.shape)
    sub.to_csv(output_path, index=False, float_format='%.9f')
    print("Averaged scores saved to %s" % output_path)


# Convert the np arrays into the correct dimention and type
# Note that BCEloss requires Float in X as well as in y 
Example 38
Project: subword-qac   Author: clovaai   File: generate.py    MIT License 5 votes vote down vote up
def log_sum_exp(a, b):
    return max(a, b) + np.log(1 + math.exp(-abs(a - b))) 
Example 39
Project: PIC   Author: ameroyer   File: nn.py    MIT License 5 votes vote down vote up
def log_sum_exp(x):
    """Numerically stable log_sum_exp implementation that prevents overflow."""
    axis = len(x.get_shape())-1
    m = tf.reduce_max(x, axis)
    m2 = tf.reduce_max(x, axis, keep_dims=True)
    return m + tf.log(tf.reduce_sum(tf.exp(x-m2), axis)) 
Example 40
Project: PIC   Author: ameroyer   File: nn.py    MIT License 5 votes vote down vote up
def log_prob_from_logits(x):
    """Numerically stable log_softmax implementation that prevents overflow."""
    axis = len(x.get_shape())-1
    m = tf.reduce_max(x, axis, keep_dims=True)
    return x - m - tf.log(tf.reduce_sum(tf.exp(x-m), axis, keep_dims=True)) 
Example 41
Project: PIC   Author: ameroyer   File: nn.py    MIT License 5 votes vote down vote up
def colorization_loss(x, l, nr_mix=10, colorspace="RGB", sum_all=True):
    """ Main loss function. Per pixel normalized (but not per batch yet)"""
    xs = int_shape(x)
    return discretized_mix_logistic_loss(x, l, nr_mix, colorspace, sum_all) / (np.log(2.) * xs[1] * xs[2] * (3. if colorspace == "RGB" else 2)) 
Example 42
Project: neural-fingerprinting   Author: StephanZheng   File: test_utils_tf.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def numpy_kl_with_logits(p_logits, q_logits):
    def numpy_softmax(logits):
        logits -= np.max(logits, axis=1, keepdims=True)
        exp_logits = np.exp(logits)
        return exp_logits / np.sum(exp_logits, axis=1, keepdims=True)

    p = numpy_softmax(p_logits)
    log_p = p_logits - np.log(np.sum(np.exp(p_logits), axis=1, keepdims=True))
    log_q = q_logits - np.log(np.sum(np.exp(q_logits), axis=1, keepdims=True))
    return (p * (log_p - log_q)).sum(axis=1).mean() 
Example 43
Project: ML_from_scratch   Author: jarfa   File: util.py    Apache License 2.0 5 votes vote down vote up
def logloss(observed, predicted, trim=1e-9):
    # keep loss from being infinite
    predicted = np.clip(predicted, trim, 1.0 - trim)
    return -np.mean(
        observed * np.log(predicted) + 
        (1. - observed) * np.log(1. - predicted)
    ) 
Example 44
Project: ML_from_scratch   Author: jarfa   File: util.py    Apache License 2.0 5 votes vote down vote up
def normLL(raw_logloss, baserate):
    # compute what logloss would be if you always predicted the baserate
    ll_br = -(baserate * np.log(baserate) + (1 - baserate) * np.log(1 - baserate))
    return 1. - (raw_logloss / ll_br) 
Example 45
Project: ML_from_scratch   Author: jarfa   File: util.py    Apache License 2.0 5 votes vote down vote up
def logit(prob):
    return np.log(prob / (1.0 - prob)) 
Example 46
Project: ML_from_scratch   Author: jarfa   File: test_util.py    Apache License 2.0 5 votes vote down vote up
def test_logit(self):
        probs = np.array([0.1, 0.5, 0.7])
        log_odds = np.log(np.array([1./9, 1., 7./3]))
        self.assertListEqual(
            rounded_list(logit(probs)),
            rounded_list(log_odds)
        ) 
Example 47
Project: ML_from_scratch   Author: jarfa   File: test_util.py    Apache License 2.0 5 votes vote down vote up
def test_ilogit(self):
        probs = np.array([0.1, 0.5, 0.7])
        log_odds = np.log(np.array([1./9, 1., 7./3]))
        self.assertListEqual(
            rounded_list(probs),
            rounded_list(ilogit(log_odds))
        ) 
Example 48
Project: programsynthesishunting   Author: flexgp   File: math_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def rlog(x):
    """
    Koza's protected log:
    if x == 0:
      return 1
    else:
      return log(abs(x))

    See pdiv above for explanation of this type of code.

    :param x: argument to log, np.array
    :return: np.array of log(x), or 1 where x is 0.
    """
    with np.errstate(divide='ignore'):
        return np.where(x == 0, np.ones_like(x), np.log(np.abs(x))) 
Example 49
Project: programsynthesishunting   Author: flexgp   File: math_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def plog(x):
    """
    Protected log operator. Protects against the log of 0.

    :param x: np.array, argument to log
    :return: np.array of log(x), but protected
    """
    return np.log(1.0 + np.abs(x)) 
Example 50
Project: programsynthesishunting   Author: flexgp   File: math_functions.py    GNU General Public License v3.0 5 votes vote down vote up
def ilog(n, base):
    """
    Find the integer log of n with respect to the base.

    >>> import math
    >>> for base in range(2, 16 + 1):
    ...     for n in range(1, 1000):
    ...         assert ilog(n, base) == int(math.log(n, base) + 1e-10), '%s %s' % (n, base)
    """
    count = 0
    while n >= base:
        count += 1
        n //= base
    return count