本文整理汇总了Python中scipy.tanh函数的典型用法代码示例。如果您正苦于以下问题:Python tanh函数的具体用法?Python tanh怎么用?Python tanh使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了tanh函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: forward_pass
def forward_pass(self, xL, xR):
bs = sp.ones((1,xL.shape[1]), dtype=float)
# First Layer
xLb = sp.vstack([xL, bs])
xRb = sp.vstack([xR, bs])
a1L = sp.dot(self.w1l, xLb)
a1R = sp.dot(self.w1r, xRb)
z1L = sp.tanh(a1L)
z1R = sp.tanh(a1R)
# Second Layer
z1Lb = sp.vstack([z1L, bs])
z1LRb = sp.vstack([z1L, z1R, bs])
z1Rb = sp.vstack([z1R, bs])
a2L = sp.dot(self.w2l, z1Lb)
a2LR = sp.dot(self.w2lr, z1LRb)
a2R = sp.dot(self.w2r, z1Rb)
z2 = a2LR*self.sigmoid(a2L)*self.sigmoid(a2R)
# Third Layer
z2b = sp.vstack([z2, bs])
a3 = sp.dot(self.w3, z2b)
return a1L, a1R, a2L, a2LR, a2R, a3, z1Lb, z1LRb, z1Rb, z2b, xLb, xRb
示例2: fgrad_y
def fgrad_y(self, y, psi, return_precalc = False):
"""
gradient of f w.r.t to y ([N x 1])
returns: Nx1 vector of derivatives, unless return_precalc is true,
then it also returns the precomputed stuff
"""
mpsi = psi.copy()
mpsi[:,0:2] = SP.exp(mpsi[:,0:2])
s = SP.zeros((len(psi), y.shape[0], y.shape[1]))
r = SP.zeros((len(psi), y.shape[0], y.shape[1]))
d = SP.zeros((len(psi), y.shape[0], y.shape[1]))
grad = 1
for i in range(len(mpsi)):
a,b,c = mpsi[i]
s[i] = b*(y+c)
r[i] = SP.tanh(s[i])
d[i] = 1 - r[i]**2
grad += a*b*d[i]
#vectorized version
S = (mpsi[:,1]*(y + mpsi[:,2])).T
R = SP.tanh(S)
D = 1-R**2
GRAD = (1+(mpsi[:,0:1]*mpsi[:,1:2]*D).sum(axis=0))[:,SP.newaxis]
if return_precalc:
return GRAD,S,R,D
#return grad, s, r, d
return grad
示例3: DP_lib
def DP_lib(compuesto, T):
"""Dohrn, R.; Prausnitz, J.M. A simple perturbation term for the Carnahan-Starling equation of state. Fluid Phase Eq. 1990, 61, 53."""
Tr = T / compuesto.Tc
if Tr >= 1:
m = 1
else:
m = 0
a1 = 0.367845 + 0.055966 * compuesto.f_acent
a2 = -1 ** m * (0.604709 + 0.008477 * compuesto.f_acent)
ac = 0.550408 * R_atml ** 2 * compuesto.Tc ** 2 / compuesto.Pc.atm
a = ac * (a1 * tanh(a2 * abs(Tr - 1) ** 0.7) + 1)
b1 = 0.356983 - 0.190003 * compuesto.f_acent
b2 = -1 ** m * (1.37 - 1.898981 * compuesto.f_acent)
bc = 0.187276 * R_atml * compuesto.Tc / compuesto.Pc.atm
b = bc * (b1 * tanh(b2 * abs(log(Tr)) ** 0.8) + 1)
sigma = (3 * b / 2 / pi / Avogadro) ** (1.0 / 3)
return a, b, sigma
def DP_Z(self, T, P):
"""Factor de compresibilidad según la ecuación de estado de Dohrn-Prausnith"""
V = self.DP_V(T, P) * self.peso_molecular
return P * V / R_atml / T
def DP_V(self, T, P):
"""Volumen según el modelo de Dohrn-Prausnith"""
a, b, sigma = self.DP_lib(T, P)
D = sigma
E = sigma ** 2
F = sigma ** 3
if self.Fase(T, P) == "gas":
V = 25
else:
V = 0.5
def Vm(V):
nu = b / 4 / V
Zref = (
1
+ (3 * D * E / F - 2) * nu
+ (3 * E ** 3 / F ** 2 - 3 * D * E / F + 1) * nu ** 2
- E ** 3 / F ** 2 * nu ** 3
) / (1 - nu) ** 3
Zpert = a / R_atml / T / V * (1 - 1.41 * b / V / 4 + 5.07 * (b / V / 4) ** 2)
return V - (Zref + Zpert) * R_atml * T / P
v = fsolve(Vm, V)
return unidades.SpecificVolume(v / self.peso_molecular)
def DP_RhoG(self, T, P):
"""Método para el cálculo de la densidad de gases haciendo uso de la ecuación de estado de Dohrn-Prausnith"""
z = self.DP_Z(T, P)
return unidades.SpecificVolume(P / z / R_atml / T * self.peso_molecular)
示例4: double_tanh_warp
def double_tanh_warp(x, n, lcore, lmid, ledge, la, lb, xa, xb):
r"""Implements a sum-of-tanh warping function and its derivative.
.. math::
l = a\tanh\frac{x-x_a}{l_a} + b\tanh\frac{x-x_b}{l_b}
Parameters
----------
x : float or array of float
Locations to evaluate the function at.
n : int
Derivative order to take. Used for ALL of the points.
lcore : float
Core length scale.
lmid : float
Intermediate length scale.
ledge : float
Edge length scale.
la : positive float
Transition of first tanh.
lb : positive float
Transition of second tanh.
xa : float
Transition of first tanh.
xb : float
Transition of second tanh.
Returns
-------
l : float or array
Warped length scale at the given locations.
Raises
------
NotImplementedError
If `n` > 1.
"""
a, b, c = scipy.dot([[-0.5, 0, 0.5], [0, 0.5, -0.5], [0.5, 0.5, 0]],
[[lcore], [ledge], [lmid]])
a = a[0]
b = b[0]
c = c[0]
if n == 0:
return a * scipy.tanh((x - xa) / la) + b * scipy.tanh((x - xb) / lb) + c
elif n == 1:
return (a / la * (scipy.cosh((x - xa) / la))**(-2.0) +
b / lb * (scipy.cosh((x - xb) / lb))**(-2.0))
else:
raise NotImplementedError("Only derivatives up to order 1 are supported!")
示例5: plot_neural_net
def plot_neural_net(X, y, clf, segment=False):
values = X
pca_plot(X, y, save="00_conn.png", segment=segment)
counter = 1
for i, layer in enumerate(clf.nn.modulesSorted):
name = layer.__class__.__name__
if name == "BiasUnit":
continue
try:
conn = clf.nn.connections[layer][0]
except IndexError:
continue
if "Linear" not in name:
if "Sigmoid" in name:
add = "sigmoid"
values = sigmoid(values)
elif "Tanh" in name:
add = "tanh"
values = tanh(values)
pca_plot(values, y, save="%02d_conn_%s.png" % (counter, add), segment=segment)
counter += 1
shape = (conn.outdim, conn.indim)
temp = numpy.dot(numpy.reshape(conn.params, shape), values.T)
pca_plot(temp.T, y, save="%02d_conn.png" % counter, segment=segment)
counter += 1
values = temp.T
示例6: tanh_warp_arb
def tanh_warp_arb(X, l1, l2, lw, x0):
r"""Warps the `X` coordinate with the tanh model
.. math::
l = \frac{l_1 + l_2}{2} - \frac{l_1 - l_2}{2}\tanh\frac{x-x_0}{l_w}
Parameters
----------
X : :py:class:`Array`, (`M`,) or scalar float
`M` locations to evaluate length scale at.
l1 : positive float
Small-`X` saturation value of the length scale.
l2 : positive float
Large-`X` saturation value of the length scale.
lw : positive float
Length scale of the transition between the two length scales.
x0 : float
Location of the center of the transition between the two length scales.
Returns
-------
l : :py:class:`Array`, (`M`,) or scalar float
The value of the length scale at the specified point.
"""
if isinstance(X, scipy.ndarray):
if isinstance(X, scipy.matrix):
X = scipy.asarray(X, dtype=float)
return 0.5 * ((l1 + l2) - (l1 - l2) * scipy.tanh((X - x0) / lw))
else:
return 0.5 * ((l1 + l2) - (l1 - l2) * mpmath.tanh((X - x0) / lw))
示例7: draw_eccentricities
def draw_eccentricities(self, eccentricity='flat', emin=0., emax='tidal'):
"""Draw a new eccentricity distribution.
Either provide an array (with the same length as the number of binaries) or choose from:
- 'flat': Flat distribution between `emin` and `emax`.
- 'thermal`: f(e) ~ e^2 between `emin` and `emax`.
If `emax` is set to 'tidal' it will depend on the period of the binary to mimic tidal circulirization through:
emax = max(emin, 0.5 * (0.95 + tanh(0.6 * log_10(period in days) - 1.7)))
If this setting is chosen the eccentricities will have to be redrawn if the periods are redrawn.
Arguments:
- `eccentricity`: New eccentricity distribution (array or name of distriution).
- `emin`: Minimum eccentricity (default: 0.)
- `emax`: Maximum eccentricity (default: set by tidal circularization)
"""
nbinaries = self.size
if emax == 'tidal':
emax = .5 * (0.95 + sp.tanh(0.6 * sp.log10(self['period'] * 365.25) - 1.7))
emax[emax < emin] = emin
if eccentricity == 'flat':
self['eccentricity'] = sp.random.rand(nbinaries) * (emax - emin) + emin
elif eccentricity == 'thermal':
self['eccentricity'] = sp.sqrt(sp.random.rand(nbinaries) * (emax ** 2. - emin ** 2.) + emin ** 2.)
elif isinstance(eccentricity, basestring):
raise ValueError("Eccentricity distribution '%s' not found" % eccentricity)
else:
self['eccentricity'] = eccentricity
示例8: calculate_dwf
def calculate_dwf(self):
"""
Calculates Debye-Waller factor according to
Sears and Shelley Acta Cryst. A 47, 441 (1991)
"""
run = self.vanaws.getRun()
nhist = self.vanaws.getNumberHistograms()
thetasort = np.empty(nhist) # half of the scattering angle, in radians
for i in range(nhist):
det = self.vanaws.getDetector(i)
thetasort[i] = 0.5 * self.vanaws.detectorTwoTheta(det)
# T in K
temperature = self.get_temperature()
# Wavelength, Angstrom
wlength = float(run.getLogData('wavelength').value)
# Vanadium mass, kg
mass_vana = 0.001*self.Mvan/sp.constants.N_A
temp_ratio = temperature/self.DebyeT
if temp_ratio < 1.e-3:
integral = 0.5
else:
integral = \
integrate.quad(lambda x: x/sp.tanh(0.5*x/temp_ratio), 0, 1)[0]
msd = 3.*sp.constants.hbar**2 / \
(2.*mass_vana*sp.constants.k * self.DebyeT)*integral*1.e20
return np.exp(-msd*(4.*sp.pi*sp.sin(thetasort)/wlength)**2)
示例9: astroOut
def astroOut(self):
for astro in self.astros:
astro.act = tanh(astro.act)
for syn in astro.syns:
i, j = syn
self.astroOuts[i][j] = astro.act * self.syn_wi[i][j]
return self.astroOuts.copy()
示例10: calculateCPandRT
def calculateCPandRT(stim_strengths, k, A, t1_nondt, t2_nondt):
"""
Given a diffusion to bound model with flat bounds, compute the following
as a function of stimulus strength:
1) Probability of t1 choice (correct choice for positive strengths)
2) Mean reaction times for t1 and t2 choices
Parameters
----------
stim_strengths : array of unique stimulus strengths
k : float, proportionality constant between stim_strength and drift rate
A : float, bound
t1_nondt: float, non decision time for making t1 choice
t2_nondt: float, non decision time for making t2 choice
Returns
-------
out : dictionary with keys stim_strength, p_t1, t1_meanrt, t2_meanrt
"""
# compute probability of t1 response given k and A
p = 1 / (1 + np.exp(-2 * A * k * stim_strengths))
# compute mean response times for t1 and t2
t1_meanrt = np.zeros(len(stim_strengths))
t2_meanrt = np.zeros(len(stim_strengths))
for i in range(len(stim_strengths)):
if stim_strengths[i] == 0:
t1_meanrt[i] = A ** 2 + t1_nondt
t2_meanrt[i] = A ** 2 + t2_nondt
else:
t1_meanrt[i] = A / (k * stim_strengths[i]) * \
sp.tanh(A * k * stim_strengths[i]) + t1_nondt
t2_meanrt[i] = A / (k * stim_strengths[i]) * \
sp.tanh(A * k * stim_strengths[i]) + t2_nondt
out = {}
out['stim_strengths'] = stim_strengths
out['p_t1'] = p
out['t1_meanrt'] = t1_meanrt
out['t2_meanrt'] = t2_meanrt
return out
示例11: grate
def grate(k,L):
l2 = (np.pi**2)/(4*(L**2))
mu = np.sqrt(k**2 + l2)
th = sp.tanh(mu/2.)
cth = 1./th
sigma = (k/mu)*np.sqrt( (mu/2.-cth)*(th-mu/2.) )
sigma[np.isnan(sigma)] = 0.
return sigma
示例12: activateHid
def activateHid(self):
# self.ah[:] = tanh(sum(self.wi.T * self.ai, axis=1))
for j in range(self.hiddim):
s = 0
for i in range(self.indim):
s += sum(self.wi[i][j] * (self.ai + self.astroOuts[i][j]))
# print self.astroOuts
self.ah[j] = tanh(s)
示例13: TempProfile
def TempProfile(z,T0=1000.,z0=100.):
"""This function creates a tempreture profile for test purposes."""
zall = (z-z0)*2.*sp.exp(1)/400. -sp.exp(1)
atanshp = (sp.tanh(zall)+1.)/2
Te = 1700*atanshp+T0
Ti = 500*atanshp+T0
return (Te,Ti)
示例14: performAction
def performAction(self, action):
#Filtered mapping towards performAction of the underlying environment
#The standard Johnnie task uses a PID controller to controll directly angles instead of forces
#This makes most tasks much simpler to learn
isJoints=self.env.getSensorByName('JointSensor') #The joint angles
isSpeeds=self.env.getSensorByName('JointVelocitySensor') #The joint angular velocitys
act=(action+1.0)/2.0*(self.env.cHighList-self.env.cLowList)+self.env.cLowList #norm output to action intervall
action=tanh((act-isJoints-isSpeeds)*16.0)*self.maxPower*self.env.tourqueList #simple PID
EpisodicTask.performAction(self, action)
示例15: main
def main():
a = array([1, 1])
b = array([0, 0])
x = array([-0.5, 1])
y = tanh( a * x + b)
dbma = [-(-0.46 * 2.79), -(0.76*2.42)]
print("ma byt:", dbma[0], dbma[1])
print("je:", ipgauss(x, y, a, b)[0])
开发者ID:pe-ge,项目名称:Computational-analysis-of-memory-capacity-in-echo-state-networks,代码行数:11,代码来源:test_ipdebug.py