Python math.tanh() Examples

The following are 30 code examples of math.tanh(). 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 math , or try the search function .
Example #1
Source Project: soccer-matlab   Author: utra-robosoccer   File: minitaur_ball_gym_env_example.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def FollowBallManualPolicy():
  """An example of a minitaur following a ball."""
  env = minitaur_ball_gym_env.MinitaurBallGymEnv(render=True,
                                                 pd_control_enabled=True,
                                                 on_rack=False)
  observation = env.reset()
  sum_reward = 0
  steps = 100000
  for _ in range(steps):
    action = [math.tanh(observation[0] * 4)]
    observation, reward, done, _ = env.step(action)
    sum_reward += reward
    if done:
      tf.logging.info("Return is {}".format(sum_reward))
      observation = env.reset()
      sum_reward = 0 
Example #2
Source Project: neat-python   Author: CodeReclaimers   File: activations.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        self.functions = {}
        self.add('sigmoid', sigmoid_activation)
        self.add('tanh', tanh_activation)
        self.add('sin', sin_activation)
        self.add('gauss', gauss_activation)
        self.add('relu', relu_activation)
        self.add('elu', elu_activation)
        self.add('lelu', lelu_activation)
        self.add('selu', selu_activation)
        self.add('softplus', softplus_activation)
        self.add('identity', identity_activation)
        self.add('clamped', clamped_activation)
        self.add('inv', inv_activation)
        self.add('log', log_activation)
        self.add('exp', exp_activation)
        self.add('abs', abs_activation)
        self.add('hat', hat_activation)
        self.add('square', square_activation)
        self.add('cube', cube_activation) 
Example #3
Source Project: CAPTCHA-breaking   Author: lllcho   File: test_activations.py    License: MIT License 6 votes vote down vote up
def test_tanh():

    from keras.activations import tanh as t
    test_values = get_standard_values()

    x = T.vector()
    exp = t(x)
    f = theano.function([x], exp)

    result = f(test_values)
    expected = [math.tanh(v) for v in test_values]

    print(result)
    print(expected)

    list_assert_equal(result, expected) 
Example #4
Source Project: pyth   Author: isaacg1   File: macros.py    License: MIT License 6 votes vote down vote up
def trig(a, b=' '):
    if is_num(a) and isinstance(b, int):

        funcs = [math.sin, math.cos, math.tan,
                 math.asin, math.acos, math.atan,
                 math.degrees, math.radians,
                 math.sinh, math.cosh, math.tanh,
                 math.asinh, math.acosh, math.atanh]

        return funcs[b](a)

    if is_lst(a):
        width = max(len(row) for row in a)
        padded_matrix = [list(row) + (width - len(row)) * [b] for row in a]
        transpose = list(zip(*padded_matrix))
        if all(isinstance(row, str) for row in a) and isinstance(b, str):
            normalizer = ''.join
        else:
            normalizer = list
        norm_trans = [normalizer(padded_row) for padded_row in transpose]
        return norm_trans
    return unknown_types(trig, ".t", a, b) 
Example #5
Source Project: FitML   Author: FitMachineLearning   File: BipedalWalker_Selective_Memory.py    License: MIT License 6 votes vote down vote up
def addToMemory(reward,averageReward):

    prob = 0.1
    if( reward > averageReward):
        prob = prob + 0.9 * math.tanh(reward - averageReward)
    else:
        prob = prob + 0.1 * math.tanh(reward - averageReward)
    print("average reward", averageReward, " reward ", reward, " prob", prob)
    #prob = prob / (rangeH - rangeL)
    #prob = reward / (1 + math.fabs(reward))
    #prob = (prob+1)/2
    if np.random.rand(1)<=prob :
        print("Adding reward",reward," based on prob ", prob)
        return True
    else:
        return False 
Example #6
Source Project: tensor   Author: calston   File: generator.py    License: MIT License 6 votes vote down vote up
def get(self):
        self.x += self.config.get('dx', 0.1)

        val = eval(self.config.get('function', 'sin(x)'), {
            'sin': math.sin,
            'sinh': math.sinh,
            'cos': math.cos,
            'cosh': math.cosh,
            'tan': math.tan,
            'tanh': math.tanh,
            'asin': math.asin,
            'acos': math.acos,
            'atan': math.atan,
            'asinh': math.asinh,
            'acosh': math.acosh,
            'atanh': math.atanh,
            'log': math.log,
            'abs': abs,
            'e': math.e,
            'pi': math.pi,
            'x': self.x
        })

        return self.createEvent('ok', 'Sine wave', val) 
Example #7
Source Project: Structural-Engineering   Author: buddyd16   File: torsion.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def thetappp(self,z_in):
        T = self.T_k_in
        G = self.G_ksi
        J = self.J_in4
        l = self.l_in
        a = self.a
        z = z_in
        theta_tripleprime = (-(T*m.cosh(z/a)) + T*m.sinh(z/a)*m.tanh(l/(2*a)))/(G*J*a**2)

        return theta_tripleprime  

#Case 3 - Concentrated Torque at alpha*l with Pinned Ends
#T = Applied Concentrated Torsional Moment, Kip-in
#G = Shear Modulus of Elasticity, Ksi, 11200 for steel
#J = Torsinal Constant of Cross Section, in^4
#l = Span Lenght, in
#a = Torsional Constant
#alpa = load application point/l 
Example #8
Source Project: Structural-Engineering   Author: buddyd16   File: torsion.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def thetappp(self,z_in):
        T = self.T_k_in
        G = self.G_ksi
        J = self.J_in4
        l = self.l_in
        a = self.a
        alpha = self.alpha
        z = z_in
        if 0 <= z_in <= (alpha*l):
            theta_tripleprime = -((T*m.cosh(z/a)*(m.cosh((l*alpha)/a) - m.sinh((l*alpha)/a)/m.tanh(l/a)))/(G*J*a**2))
        else:
            theta_tripleprime = (T*(m.cosh(z/a)/m.tanh(l/a) - m.sinh(z/a))*m.sinh((l*alpha)/a))/(G*J*a**2)
        return theta_tripleprime       

#Case 4 - Uniformly Distributed Torque with Pinned Ends
#t = Distributed torque, Kip-in / in
#G = Shear Modulus of Elasticity, Ksi, 11200 for steel
#J = Torsinal Constant of Cross Section, in^4
#l = Span Lenght, in
#a = Torsional Constant 
Example #9
Source Project: Structural-Engineering   Author: buddyd16   File: torsion.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def thetappp(self,z_in):
        T = self.T_k_in
        G = self.G_ksi
        J = self.J_in4
        l = self.l_in
        a = self.a
        alpha = self.alpha
        H = self.H
        z = z_in
        
        if 0 <= z_in <= (alpha*l):
            theta_tripleprime = -((T*(m.cosh(z/a)/a**2 + ((-1.0 + (1.0 + H)*(m.cosh((l*alpha)/a))/m.tanh(l/a))*m.sinh(z/a))/a**2 - (H*(m.sinh(z/a)/m.sinh(l/a)))/a**2 - (m.sinh(z/a)*m.sinh((l*alpha)/a))/a**2 - (H*m.sinh(z/a)*m.sinh((l*alpha)/a))/a**2))/(G*(1.0 + H)*J))
        else:
            theta_tripleprime = 0
        return theta_tripleprime  
#Test Area 
Example #10
Source Project: vidaug   Author: okankop   File: temporal.py    License: MIT License 6 votes vote down vote up
def _get_distorted_indices(self, nb_images):
        inverse = random.randint(0, 1)

        if inverse:
            scale = random.random()
            scale *= 0.21
            scale += 0.6
        else:
            scale = random.random()
            scale *= 0.6
            scale += 0.8

        frames_per_clip = nb_images

        indices = np.linspace(-scale, scale, frames_per_clip).tolist()
        if inverse:
            values = [math.atanh(x) for x in indices]
        else:
            values = [math.tanh(x) for x in indices]

        values = [x / values[-1] for x in values]
        values = [int(round(((x + 1) / 2) * (frames_per_clip - 1), 0)) for x in values]
        return values 
Example #11
Source Project: sample-factory   Author: alex-petrenko   File: reward_shaping.py    License: MIT License 6 votes vote down vote up
def step(self, action):
        obs, rew, done, info = self.env.step(action)
        self.raw_episode_return += rew
        self.episode_length += info.get('num_frames', 1)

        # optimistic asymmetric clipping from IMPALA paper
        squeezed = tanh(rew / 5.0)
        clipped = 0.3 * squeezed if rew < 0.0 else squeezed
        rew = clipped * 5.0

        if done:
            score = self.raw_episode_return

            info['episode_extra_stats'] = dict()
            level_name = self.unwrapped.level_name

            # add extra 'z_' to the summary key to put them towards the end on tensorboard (just convenience)
            level_name_key = f'z_{self.unwrapped.task_id:02d}_{level_name}'
            info['episode_extra_stats'][f'{level_name_key}_{RAW_SCORE_SUMMARY_KEY_SUFFIX}'] = score
            info['episode_extra_stats'][f'{level_name_key}_len'] = self.episode_length

        return obs, rew, done, info 
Example #12
Source Project: CIFAR-ZOO   Author: BIGBALLON   File: utils.py    License: MIT License 6 votes vote down vote up
def adjust_learning_rate(optimizer, epoch, config):
    lr = get_current_lr(optimizer)
    if config.lr_scheduler.type == 'STEP':
        if epoch in config.lr_scheduler.lr_epochs:
            lr *= config.lr_scheduler.lr_mults
    elif config.lr_scheduler.type == 'COSINE':
        ratio = epoch / config.epochs
        lr = config.lr_scheduler.min_lr + \
            (config.lr_scheduler.base_lr - config.lr_scheduler.min_lr) * \
            (1.0 + math.cos(math.pi * ratio)) / 2.0
    elif config.lr_scheduler.type == 'HTD':
        ratio = epoch / config.epochs
        lr = config.lr_scheduler.min_lr + \
            (config.lr_scheduler.base_lr - config.lr_scheduler.min_lr) * \
            (1.0 - math.tanh(
                config.lr_scheduler.lower_bound
                + (config.lr_scheduler.upper_bound
                   - config.lr_scheduler.lower_bound)
                * ratio)
             ) / 2.0
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
    return lr 
Example #13
Source Project: pytorch-sentiment-neuron   Author: guillitte   File: visualize.py    License: MIT License 6 votes vote down vote up
def color(p):
	p = math.tanh(3*p)*.5+.5
	q = 1.-p*1.3
	r = 1.-abs(0.5-p)*1.3+.3*q
	p=1.3*p-.3
	i = int(p*255)	
	j = int(q*255)
	k = int(r*255)
	if j<0:
		j=0	
	if k<0:
		k=0
	if k >255:
		k=255
	if i<0:
		i = 0
	return ('\033[38;2;%d;%d;%dm' % (j, k, i)).encode() 
Example #14
Source Project: neat-python   Author: CodeReclaimers   File: activations.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def tanh_activation(z):
    z = max(-60.0, min(60.0, 2.5 * z))
    return math.tanh(z) 
Example #15
Source Project: hadrian   Author: modelop   File: link.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        return unwrapForNorm(x, lambda y: math.tanh(y)) 
Example #16
Source Project: hadrian   Author: modelop   File: kernel.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x, y, gamma, intercept):
	return math.tanh(gamma * dot(x, y, self.errcodeBase + 0, self.name, pos) + intercept) 
Example #17
Source Project: hadrian   Author: modelop   File: pfamath.py    License: Apache License 2.0 5 votes vote down vote up
def genpy(self, paramTypes, args, pos):
        return "math.tanh({0})".format(*args) 
Example #18
Source Project: hadrian   Author: modelop   File: pfamath.py    License: Apache License 2.0 5 votes vote down vote up
def __call__(self, state, scope, pos, paramTypes, x):
        return math.tanh(x) 
Example #19
def kl_weight(it):
    """
    Credit to: https://github.com/kefirski/pytorch_RVAE/
    0 -> 1
    """
    return (math.tanh((it - 3500)/1000) + 1)/2 
Example #20
Source Project: ironpython2   Author: IronLanguages   File: test_math.py    License: Apache License 2.0 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN)))
        # check that tanh(-0.) == -0. on IEEE 754 systems
        if float.__getformat__("double").startswith("IEEE"):
            self.assertEqual(math.tanh(-0.), -0.)
            self.assertEqual(math.copysign(1., math.tanh(-0.)),
                             math.copysign(1., -0.)) 
Example #21
Source Project: nevergrad   Author: facebookresearch   File: corefuncs.py    License: MIT License 5 votes vote down vote up
def genzcornerpeak(y: np.ndarray) -> float:
    """One of the Genz functions, originally used in integration,

    tested in optim because why not."""
    value = float(1 + np.mean(np.tanh(y)))
    if value == 0:
        return float("inf")
    return value ** (-len(y) - 1) 
Example #22
Source Project: nevergrad   Author: facebookresearch   File: corefuncs.py    License: MIT License 5 votes vote down vote up
def linear(x: np.ndarray) -> float:
    return tanh(x[0]) 
Example #23
Source Project: visma   Author: aerospaceresearch   File: hyperbolic.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self.value = 'tanh' 
Example #24
Source Project: visma   Author: aerospaceresearch   File: hyperbolic.py    License: GNU General Public License v3.0 5 votes vote down vote up
def calculate(self, val):
        return self.coefficient * ((math.tanh(val)) ** self.power)

################################
# Inverse Hyperbolic Functions #
################################ 
Example #25
Source Project: ngraph-python   Author: NervanaSystems   File: test_activations.py    License: Apache License 2.0 5 votes vote down vote up
def reference_value(self, x):
        return np.vectorize(true_tanh)(x) 
Example #26
Source Project: BinderFilter   Author: dxwu   File: test_math.py    License: MIT License 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN)))
        # check that tanh(-0.) == -0. on IEEE 754 systems
        if float.__getformat__("double").startswith("IEEE"):
            self.assertEqual(math.tanh(-0.), -0.)
            self.assertEqual(math.copysign(1., math.tanh(-0.)),
                             math.copysign(1., -0.)) 
Example #27
Source Project: oss-ftp   Author: aliyun   File: test_math.py    License: MIT License 5 votes vote down vote up
def testTanh(self):
        self.assertRaises(TypeError, math.tanh)
        self.ftest('tanh(0)', math.tanh(0), 0)
        self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
        self.ftest('tanh(inf)', math.tanh(INF), 1)
        self.ftest('tanh(-inf)', math.tanh(NINF), -1)
        self.assertTrue(math.isnan(math.tanh(NAN)))
        # check that tanh(-0.) == -0. on IEEE 754 systems
        if float.__getformat__("double").startswith("IEEE"):
            self.assertEqual(math.tanh(-0.), -0.)
            self.assertEqual(math.copysign(1., math.tanh(-0.)),
                             math.copysign(1., -0.)) 
Example #28
Source Project: hybrid_rvae   Author: kefirski   File: functions.py    License: MIT License 5 votes vote down vote up
def kld_coef(i):
    import math
    return (math.tanh((i - 13000) / 5000) + 1) / 2 
Example #29
Source Project: m2cgen   Author: BayesWitnesses   File: test_python.py    License: MIT License 5 votes vote down vote up
def test_tanh_expr():
    expr = ast.TanhExpr(ast.NumVal(2.0))

    interpreter = interpreters.PythonInterpreter()

    expected_code = """
import math
def score(input):
    return math.tanh(2.0)
    """

    utils.assert_code_equal(interpreter.interpret(expr), expected_code) 
Example #30
Source Project: fastats   Author: fastats   File: test_convert_to_jit.py    License: MIT License 5 votes vote down vote up
def test_does_not_convert_math_builtins():
    for func in (math.atan2, math.atanh, math.degrees, math.exp, math.floor, math.log,
                 math.sin, math.sinh, math.tan, math.tanh):
        assert convert_to_jit(func) is func