Python math.tanh() Examples

The following are code examples for showing how to use math.tanh(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: Programming-Collective-Intelligence   Author: clyyuanzi   File: nn.py    (license) View Source Project 6 votes vote down vote up
def feedforward(self):
        #??????????
        for i in range(len(self.wordids)):
            self.ai[i]=1.0
        
        #??????????
        for j in range(len(self.hiddenids)):
            sumi = 0.0
            for i in range(len(self.wordids)):
                sumi=sumi+self.ai[i]*self.wi[i][j]
            self.ah[j]=tanh(sumi)
        
        #??????????
        for k in range(len(self.urlids)):
            sumj = 0.0 
            for j in range(len(self.hiddenids)):
                sumj = sumj + self.ah[j]*self.wo[j][k]
            self.ao[k]=tanh(sumj)
            
        return self.ao[:] 
Example 2
Project: lightML   Author: jfzhang95   File: NeuralNetwork.py    (license) View Source Project 6 votes vote down vote up
def update(self, inputs):
        # input activations
        for i in range(self.input_size - 1):
            self.ai[i] = inputs[i]

        # hidden activations
        for j in range(self.hidden_size):
            sum = 0.0
            for i in range(self.input_size):
                sum = sum + self.ai[i] * self.Wi[i][j]
            self.ah[j] = math.tanh(sum)

        # output activations
        for k in range(self.output_size):
            sum = 0.0
            for j in range(self.hidden_size):
                sum = sum + self.ah[j] * self.Wo[j][k]
            self.ao[k] = sigmoid(sum)

        return self.ao[:] 
Example 3
Project: ML_algorithm   Author: luoshao23   File: nn.py    (license) View Source Project 6 votes vote down vote up
def feedforward(self):
        for i in xrange(len(self.wordids)):
            self.ai[i] = 1.0

        for j in xrange(len(self.hiddenids)):
            sumit = 0.0
            for i in xrange(len(self.wordids)):
                sumit += self.ai[i] * self.wi[i][j]
            self.ah[j] = tanh(sumit)

        for k in xrange(len(self.urlids)):
            sumit = 0.0
            for j in xrange(len(self.hiddenids)):
                sumit += self.ah[j] * self.wo[j][k]
            self.ao[k] = tanh(sumit)

        return self.ao[:] 
Example 4
Project: keras-recommendation   Author: sonyisme   File: test_activations.py    (license) View Source Project 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 5
Project: aiw-second-edition   Author: dougmcilwraith   File: ch3.py    (license) View Source Project 6 votes vote down vote up
def similarity(user_id_a,user_id_b,sim_type=0):
    user_a_tuple_list = userdict[user_id_a].get_items()
    user_b_tuple_list = userdict[user_id_b].get_items()
    common_items=0
    sim = 0.0
    for t1 in user_a_tuple_list:
        for t2 in user_b_tuple_list:
            if (t1[0] == t2[0]):
                common_items += 1
                sim += math.pow(t1[1]-t2[1],2)
    if common_items>0:
        sim = math.sqrt(sim/common_items)
        sim = 1.0 - math.tanh(sim)
        if sim_type==1:
            max_common = min(len(user_a_tuple_list),len(user_b_tuple_list))
            sim = sim * common_items / max_common
    print "User Similarity between",names[user_id_a],"and",names[user_id_b],"is", sim
    return sim #If no common items, returns zero

#3.1
# load movielens data 
Example 6
Project: PCInotes   Author: ahangchen   File: nn.py    (license) View Source Project 6 votes vote down vote up
def feedforward(self):
        # the only inputs are the query words
        for i in range(len(self.wordids)):
            self.ai[i] = 1.0

        # hidden activations
        for j in range(len(self.hiddenids)):
            sum = 0.0
            for i in range(len(self.wordids)):
                sum = sum + self.ai[i] * self.wi[i][j]
            self.ah[j] = tanh(sum)

        # output activations
        for k in range(len(self.urlids)):
            sum = 0.0
            for j in range(len(self.hiddenids)):
                sum = sum + self.ah[j] * self.wo[j][k]
            self.ao[k] = tanh(sum)

        return self.ao[:] 
Example 7
Project: My_MachineLeaning_way   Author: salamer   File: nn.py    (license) View Source Project 6 votes vote down vote up
def feed_forward(self):
        for i in range(len(self.word_ids)):
            self.ai[i]=1.0

        for j in range(len(self.hidden_ids)):
            sum=0.0
            for i in range(len(self.word_ids)):
                sum=sum+self.ai[i]*self.wi[i][j]

            self.ah[j]=tanh(sum)

        for k in range(len(self.url_ids)):
            sum=0.0
            for j in range(len(self.hidden_ids)):
                sum=sum+self.ah[j]*self.wo[j][k]

            self.ao[k]=tanh(sum)

        return self.ao[:] 
Example 8
Project: duct   Author: ducted   File: generator.py    (license) View Source Project 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 9
Project: python   Author: hienha   File: nn.py    (license) View Source Project 6 votes vote down vote up
def feedforward(self):
        # the only inputs are the query words
        for i in range(len(self.wordids)):
            self.ai[i] = 1.0

        # hidden activations
        for j in range(len(self.hiddenids)):
            sum = 0.0
            for i in range(len(self.wordids)):
                sum = sum + self.ai[i] * self.wi[i][j]
            self.ah[j] = tanh(sum)

        # output activations
        for k in range(len(self.urlids)):
            sum = 0.0
            for j in range(len(self.hiddenids)):
                sum = sum + self.ah[j] * self.wo[j][k]
            self.ao[k] = tanh(sum)

        return self.ao[:] 
Example 10
Project: More-I-O   Author: koltafrickenfer   File: main.py    (license) View Source Project 6 votes vote down vote up
def obFixer(observation_space,observation): # fixes observation ranges, uses hyperbolic tangent for infinite values
  newObservation = []
  if observation_space.__class__ == gym.spaces.box.Box:
    for space in range(observation_space.shape[0]):
      high = observation_space.high[space]
      low = observation_space.low[space]
      if high == numpy.finfo(numpy.float32).max or high == float('Inf'):
        newObservation.append(math.tanh(observation[space]))
      else:
        dif = high - low 
        percent = (observation[space]+abs(low))/dif
        newObservation.append(((percent * 2)-1).tolist())
  if observation_space.__class__ == gym.spaces.discrete.Discrete:
    c = 0
    for neuron in range(observation_space.n):
      if observation == neuron:
        newObservation.append(1)
      else:
        newObservation.append(0)
  return newObservation 
Example 11
Project: dac   Author: jlonij   File: dac.py    (license) View Source Project 6 votes vote down vote up
def set_candidate_inlinks(self):
        '''
        Determine inlinks feature values.
        '''
        if not [f for f in self.features if f.startswith('candidate_inlinks')]:
            return

        for link_type in ['inlinks', 'inlinks_newspapers']:
            link_count = self.document.get(link_type)
            if link_count:
                setattr(self, 'candidate_' + link_type,
                    math.tanh(link_count * 0.001))
                if not hasattr(self.cand_list, 'sum_' + link_type):
                    self.cand_list.set_sum_inlinks()
                link_sum = getattr(self.cand_list, 'sum_' + link_type)
                if link_sum:
                    link_count_rel = link_count / float(link_sum)
                    setattr(self, 'candidate_' + link_type + '_rel',
                        link_count_rel) 
Example 12
Project: dac   Author: jlonij   File: dac.py    (license) View Source Project 6 votes vote down vote up
def set_solr_properties(self):
        '''
        Determine Solr iteration, position and score.
        '''
        if not [f for f in self.features if f.startswith('match_str_solr')]:
            return

        # Solr iteration
        self.match_str_solr_query_0 = 1 if self.query_id == 0 else 0
        self.match_str_solr_query_1 = 1 if self.query_id == 1 else 0
        self.match_str_solr_query_2 = 1 if self.query_id == 2 else 0
        self.match_str_solr_query_3 = 1 if self.query_id == 3 else 0
        self.match_str_solr_substitution = 1 if self.query_iteration == 1 else 0

        # Solr position (relative to other remaining candidates)
        pos = self.cand_list.filtered_candidates.index(self)
        self.match_str_solr_position = 1.0 - math.tanh(pos * 0.25)

        # Solr score (relative to other remaining candidates)
        if not hasattr(self.cand_list, 'max_score'):
            self.cand_list.set_max_score()
        if self.cand_list.max_score:
            self.match_str_solr_score = (self.document.get('score') /
                float(self.cand_list.max_score)) 
Example 13
Project: dac   Author: jlonij   File: dac.py    (license) View Source Project 6 votes vote down vote up
def set_entity_match(self):
        '''
        Match other entities appearing in the article with DBpedia abstract.
        '''
        if not 'match_txt_entities' in self.features:
            return

        if not hasattr(self.cluster, 'entity_parts'):
            self.cluster.get_entity_parts()
        if not hasattr(self.cluster, 'context_entity_parts'):
            self.cluster.get_context_entity_parts()
        if not self.cluster.context_entity_parts:
            return

        if not hasattr(self, 'abstract_bow'):
            self.tokenize_abstract()
        bow = [t for t in self.abstract_bow if len(t) > 4]

        entity_match = len(set(self.cluster.context_entity_parts) & set(bow))
        self.match_txt_entities = math.tanh(entity_match * 0.25) 
Example 14
Project: RecommendationSystem   Author: TURuibo   File: test_activations.py    (license) View Source Project 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 15
Project: ngraph   Author: NervanaSystems   File: test_activations.py    (license) View Source Project 5 votes vote down vote up
def reference_value(self, x):
        return np.vectorize(true_tanh)(x) 
Example 16
Project: Outfall-Rock-Protection-Design-Tool   Author: FranciscoChaves90   File: outfall_rockdesign.py    (license) View Source Project 5 votes vote down vote up
def __init__(self,tp,d):
		self.L0 = g*pow(tp,2)/(2*pi)
		while True:
			self.L = self.L0 #inititate self.L
			self.LIteration = 0 #inititate self.LIteration
			while abs(self.L-self.LIteration)>0.0001:
				self.LIteration = self.L
				self.L = self.L0 * math.tanh(2*math.pi*d/self.LIteration)
			break 
Example 17
Project: zippy   Author: securesystemslab   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_trig_hyperb_basic():
    for x in (list(range(100)) + list(range(-100,0))):
        t = x / 4.1
        assert cos(mpf(t)).ae(math.cos(t))
        assert sin(mpf(t)).ae(math.sin(t))
        assert tan(mpf(t)).ae(math.tan(t))
        assert cosh(mpf(t)).ae(math.cosh(t))
        assert sinh(mpf(t)).ae(math.sinh(t))
        assert tanh(mpf(t)).ae(math.tanh(t))
    assert sin(1+1j).ae(cmath.sin(1+1j))
    assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j))
    assert cos(1+1j).ae(cmath.cos(1+1j))
    assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j)) 
Example 18
Project: zippy   Author: securesystemslab   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_invhyperb_inaccuracy():
    mp.dps = 15
    assert (asinh(1e-5)*10**5).ae(0.99999999998333333)
    assert (asinh(1e-10)*10**10).ae(1)
    assert (asinh(1e-50)*10**50).ae(1)
    assert (asinh(-1e-5)*10**5).ae(-0.99999999998333333)
    assert (asinh(-1e-10)*10**10).ae(-1)
    assert (asinh(-1e-50)*10**50).ae(-1)
    assert asinh(10**20).ae(46.744849040440862)
    assert asinh(-10**20).ae(-46.744849040440862)
    assert (tanh(1e-10)*10**10).ae(1)
    assert (tanh(-1e-10)*10**10).ae(-1)
    assert (atanh(1e-10)*10**10).ae(1)
    assert (atanh(-1e-10)*10**10).ae(-1) 
Example 19
Project: zippy   Author: securesystemslab   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_complex_functions():
    for x in (list(range(10)) + list(range(-10,0))):
        for y in (list(range(10)) + list(range(-10,0))):
            z = complex(x, y)/4.3 + 0.01j
            assert exp(mpc(z)).ae(cmath.exp(z))
            assert log(mpc(z)).ae(cmath.log(z))
            assert cos(mpc(z)).ae(cmath.cos(z))
            assert sin(mpc(z)).ae(cmath.sin(z))
            assert tan(mpc(z)).ae(cmath.tan(z))
            assert sinh(mpc(z)).ae(cmath.sinh(z))
            assert cosh(mpc(z)).ae(cmath.cosh(z))
            assert tanh(mpc(z)).ae(cmath.tanh(z)) 
Example 20
Project: zippy   Author: securesystemslab   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_tanh():
    mp.dps = 15
    assert tanh(0) == 0
    assert tanh(inf) == 1
    assert tanh(-inf) == -1
    assert isnan(tanh(nan))
    assert tanh(mpc('inf', '0')) == 1 
Example 21
Project: zippy   Author: securesystemslab   File: test_math.py    (license) View Source Project 5 votes vote down vote up
def testTanhSign(self):
        # check that tanh(-0.) == -0. on IEEE 754 systems
        self.assertEqual(math.tanh(-0.), -0.)
        self.assertEqual(math.copysign(1., math.tanh(-0.)),
                         math.copysign(1., -0.)) 
Example 22
Project: twic_close_reading   Author: jarmoza   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_trig_hyperb_basic():
    for x in (list(range(100)) + list(range(-100,0))):
        t = x / 4.1
        assert cos(mpf(t)).ae(math.cos(t))
        assert sin(mpf(t)).ae(math.sin(t))
        assert tan(mpf(t)).ae(math.tan(t))
        assert cosh(mpf(t)).ae(math.cosh(t))
        assert sinh(mpf(t)).ae(math.sinh(t))
        assert tanh(mpf(t)).ae(math.tanh(t))
    assert sin(1+1j).ae(cmath.sin(1+1j))
    assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j))
    assert cos(1+1j).ae(cmath.cos(1+1j))
    assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j)) 
Example 23
Project: twic_close_reading   Author: jarmoza   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_invhyperb_inaccuracy():
    mp.dps = 15
    assert (asinh(1e-5)*10**5).ae(0.99999999998333333)
    assert (asinh(1e-10)*10**10).ae(1)
    assert (asinh(1e-50)*10**50).ae(1)
    assert (asinh(-1e-5)*10**5).ae(-0.99999999998333333)
    assert (asinh(-1e-10)*10**10).ae(-1)
    assert (asinh(-1e-50)*10**50).ae(-1)
    assert asinh(10**20).ae(46.744849040440862)
    assert asinh(-10**20).ae(-46.744849040440862)
    assert (tanh(1e-10)*10**10).ae(1)
    assert (tanh(-1e-10)*10**10).ae(-1)
    assert (atanh(1e-10)*10**10).ae(1)
    assert (atanh(-1e-10)*10**10).ae(-1) 
Example 24
Project: twic_close_reading   Author: jarmoza   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_complex_functions():
    for x in (list(range(10)) + list(range(-10,0))):
        for y in (list(range(10)) + list(range(-10,0))):
            z = complex(x, y)/4.3 + 0.01j
            assert exp(mpc(z)).ae(cmath.exp(z))
            assert log(mpc(z)).ae(cmath.log(z))
            assert cos(mpc(z)).ae(cmath.cos(z))
            assert sin(mpc(z)).ae(cmath.sin(z))
            assert tan(mpc(z)).ae(cmath.tan(z))
            assert sinh(mpc(z)).ae(cmath.sinh(z))
            assert cosh(mpc(z)).ae(cmath.cosh(z))
            assert tanh(mpc(z)).ae(cmath.tanh(z)) 
Example 25
Project: twic_close_reading   Author: jarmoza   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_tanh():
    mp.dps = 15
    assert tanh(0) == 0
    assert tanh(inf) == 1
    assert tanh(-inf) == -1
    assert isnan(tanh(nan))
    assert tanh(mpc('inf', '0')) == 1 
Example 26
Project: krpcScripts   Author: jwvanderbeck   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_trig_hyperb_basic():
    for x in (list(range(100)) + list(range(-100,0))):
        t = x / 4.1
        assert cos(mpf(t)).ae(math.cos(t))
        assert sin(mpf(t)).ae(math.sin(t))
        assert tan(mpf(t)).ae(math.tan(t))
        assert cosh(mpf(t)).ae(math.cosh(t))
        assert sinh(mpf(t)).ae(math.sinh(t))
        assert tanh(mpf(t)).ae(math.tanh(t))
    assert sin(1+1j).ae(cmath.sin(1+1j))
    assert sin(-4-3.6j).ae(cmath.sin(-4-3.6j))
    assert cos(1+1j).ae(cmath.cos(1+1j))
    assert cos(-4-3.6j).ae(cmath.cos(-4-3.6j)) 
Example 27
Project: krpcScripts   Author: jwvanderbeck   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_invhyperb_inaccuracy():
    mp.dps = 15
    assert (asinh(1e-5)*10**5).ae(0.99999999998333333)
    assert (asinh(1e-10)*10**10).ae(1)
    assert (asinh(1e-50)*10**50).ae(1)
    assert (asinh(-1e-5)*10**5).ae(-0.99999999998333333)
    assert (asinh(-1e-10)*10**10).ae(-1)
    assert (asinh(-1e-50)*10**50).ae(-1)
    assert asinh(10**20).ae(46.744849040440862)
    assert asinh(-10**20).ae(-46.744849040440862)
    assert (tanh(1e-10)*10**10).ae(1)
    assert (tanh(-1e-10)*10**10).ae(-1)
    assert (atanh(1e-10)*10**10).ae(1)
    assert (atanh(-1e-10)*10**10).ae(-1) 
Example 28
Project: krpcScripts   Author: jwvanderbeck   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_complex_functions():
    for x in (list(range(10)) + list(range(-10,0))):
        for y in (list(range(10)) + list(range(-10,0))):
            z = complex(x, y)/4.3 + 0.01j
            assert exp(mpc(z)).ae(cmath.exp(z))
            assert log(mpc(z)).ae(cmath.log(z))
            assert cos(mpc(z)).ae(cmath.cos(z))
            assert sin(mpc(z)).ae(cmath.sin(z))
            assert tan(mpc(z)).ae(cmath.tan(z))
            assert sinh(mpc(z)).ae(cmath.sinh(z))
            assert cosh(mpc(z)).ae(cmath.cosh(z))
            assert tanh(mpc(z)).ae(cmath.tanh(z)) 
Example 29
Project: krpcScripts   Author: jwvanderbeck   File: test_functions.py    (license) View Source Project 5 votes vote down vote up
def test_tanh():
    mp.dps = 15
    assert tanh(0) == 0
    assert tanh(inf) == 1
    assert tanh(-inf) == -1
    assert isnan(tanh(nan))
    assert tanh(mpc('inf', '0')) == 1 
Example 30
Project: mit_ocw_6034_ai_patrick_winston   Author: yenicelik   File: bpnn.py    (license) View Source Project 5 votes vote down vote up
def makeMatrix(I, J, fill=0.0):
    m = []
    for i in range(I):
        m.append([fill]*J)
    return m

# our sigmoid function, tanh is a little nicer than the standard 1/(1+e^-x) 
Example 31
Project: mit_ocw_6034_ai_patrick_winston   Author: yenicelik   File: bpnn.py    (license) View Source Project 5 votes vote down vote up
def sigmoid(x):
    return math.tanh(x)

# derivative of our sigmoid function 
Example 32
Project: oil   Author: oilshell   File: test_math.py    (license) View Source Project 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 33
Project: python2-tracer   Author: extremecoders-re   File: test_math.py    (license) View Source Project 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 34
Project: PyTrafficCar   Author: liyuming1978   File: nonlinearities.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, opt={}):
        self.out_sx = opt['in_sx']
        self.out_sy = opt['in_sy']
        self.out_depth = opt['in_depth']
        self.layer_type = 'tanh' 
Example 35
Project: PyTrafficCar   Author: liyuming1978   File: nonlinearities.py    (license) View Source Project 5 votes vote down vote up
def forward(self, V, is_training):
        self.in_act = V
        V2 = V.cloneAndZero()
        V2.w = map(tanh, V.w)
        self.out_act = V2
        return self.out_act 
Example 36
Project: Clustering   Author: Ram81   File: NN.py    (license) View Source Project 5 votes vote down vote up
def dsigmoid(y):
	return y * (1.0 - y)

#using tanh instead of logistic sigmoid 
Example 37
Project: Clustering   Author: Ram81   File: NN.py    (license) View Source Project 5 votes vote down vote up
def tanh(x):
	return math.tanh(x)

#derivative of tanh 
Example 38
Project: Clustering   Author: Ram81   File: NN.py    (license) View Source Project 5 votes vote down vote up
def feedForward(self, inputs):
		'''
			Feed Forward Propagation
		'''	
		
		if len(inputs) != self.input - 1:
			raise ValueError("Wrong Number of Inputs!")
		
		#input activations
		for i in range(self.input - 1): #-1 because of bias term
			self.ai[i] = inputs[i]
		
		#hidden layer activations
		for i in range(self.hidden):
			sum_ = 0.0
			for j in range(self.input):
				sum_ += self.ai[j] * self.wi[j][i]
			self.ah[i] = tanh(sum_)			#assigning the activation
		
		#output activations
		for k in range(self.output):		
			sum_ = 0.0
			for i in range(self.hidden):
				sum_ += self.ah[i] * self.wi[i][k]
			self.ao[k] = sigmoid(sum_)			#assigning the activation
		
		return self.ao[:] 
Example 39
Project: NLP.py   Author: PythonOptimizers   File: sparse_vector_class.py    (license) View Source Project 5 votes vote down vote up
def tanh(a):
    """Elementwise hyperbolic tangent."""
    if not isSparseVector(a):
        raise TypeError("Argument must be a SparseVector")
    rv = SparseVector(a.n, {})
    for k in a.values.keys():
        rv.values[k] = math.tanh(a.values[k])
    return rv 
Example 40
Project: web_ctp   Author: molebot   File: test_math.py    (license) View Source Project 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))) 
Example 41
Project: web_ctp   Author: molebot   File: test_math.py    (license) View Source Project 5 votes vote down vote up
def testTanhSign(self):
        # check that tanh(-0.) == -0. on IEEE 754 systems
        self.assertEqual(math.tanh(-0.), -0.)
        self.assertEqual(math.copysign(1., math.tanh(-0.)),
                         math.copysign(1., -0.)) 
Example 42
Project: huaat_ml_dl   Author: ieee820   File: bpnn.py    (license) View Source Project 5 votes vote down vote up
def sigmod(x):
    '''
    the sigmod function,tanh is a little better than the standard  1/(1+e^-x)
    :param x:    the self variable
    :return:     the value after tanh
    '''
    return math.tanh(x) 
Example 43
Project: othello-rl   Author: jpypi   File: nn.py    (license) View Source Project 5 votes vote down vote up
def activation(x):
    #return expit(x)
    ##return 1.7159 * math.tanh(2/3*x)
    #print(x)

    return np.tanh(x)#list(map(math.tanh, x))
    #return np.multiply(x > 0, x) 
Example 44
Project: othello-rl   Author: jpypi   File: nn.py    (license) View Source Project 5 votes vote down vote up
def dactivation(x):
    #v = expit(x)
    #return v*(1-v)
    #return 1 - math.tanh(x)**2

    return 1 - np.tanh(x)**2#list(map(lambda y: 1 - math.tanh(y)**2, x))
    #return np.float64(x > 0) 
Example 45
Project: Hanhan_NLP   Author: hanhanwu   File: short_context_search.py    (license) View Source Project 5 votes vote down vote up
def feedforward(self, words, urls):
        
        for j in range(len(self.hidden_nodes)):
            sum = 0.0
            for i in range(len(self.words)):
                sum += self.li[i]*self.w_ih[i][j]
            self.lh[j] = tanh(sum)
            
        for j in range(len(self.urls)):
            sum = 0.0
            for i in range(len(self.hidden_nodes)):
                sum += self.lh[i]*self.w_ho[i][j]
            self.lo[j] = tanh(sum)
            
        return self.lo 
Example 46
Project: hyper-engine   Author: maxim5   File: sugar.py    (license) View Source Project 5 votes vote down vote up
def tanh(node): return merge([node], math.tanh) 
Example 47
Project: pefile.pypy   Author: cloudtracer   File: test_math.py    (license) View Source Project 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 48
Project: ouroboros   Author: pybee   File: cmath.py    (license) View Source Project 5 votes vote down vote up
def tan(x):
    z = _make_complex(x)
    z = tanh(complex(-z.imag, z.real))
    return complex(z.imag, -z.real) 
Example 49
Project: ouroboros   Author: pybee   File: cmath.py    (license) View Source Project 5 votes vote down vote up
def tanh(x):

    _tanh_special = [
        [-1, None, complex(-1, -0.0), -1, None, -1, -1],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [nan+nanj, None, complex(-0.0, -0.0), complex(-0.0, 0.0), None, nan+nanj, nan+nanj],
        [nan+nanj, None, complex(0.0, -0.0), 0.0, None, nan+nanj, nan+nanj],
        [nan+nanj, None, None, None, None, nan+nanj, nan+nanj],
        [1, None, complex(1, -0.0), 1, None, 1, 1],
        [nan+nanj, nan+nanj, complex(float("nan"), -0.0), nan, nan+nanj, nan+nanj, nan+nanj]
    ]

    z = _make_complex(x)

    if not isfinite(z):
        if math.isinf(z.imag) and math.isfinite(z.real):
            raise ValueError
        if math.isinf(z.real) and math.isfinite(z.imag) and z.imag != 0:
            if z.real > 0:
                return complex(1, math.copysign(0.0, math.sin(z.imag)
                                                * math.cos(z.imag)))
            return complex(-1, math.copysign(0.0, math.sin(z.imag)
                                             * math.cos(z.imag)))
        return _tanh_special[_special_type(z.real)][_special_type(z.imag)]

    if abs(z.real) > _LOG_LARGE_DOUBLE:
        return complex(
            math.copysign(1, z.real),
            4*math.sin(z.imag)*math.cos(z.imag)*math.exp(-2*abs(z.real))
        )
    tanh_x = math.tanh(z.real)
    tan_y = math.tan(z.imag)
    cx = 1/math.cosh(z.real)
    denom = 1 + tanh_x * tanh_x * tan_y * tan_y
    return complex(tanh_x * (1 + tan_y*tan_y)/denom,
                   ((tan_y / denom) * cx) * cx) 
Example 50
Project: ouroboros   Author: pybee   File: test_math.py    (license) View Source Project 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)))