def _normal_function(x, mean, variance):
"""
Find a value in the cumulative distribution function of a normal curve.
See https://en.wikipedia.org/wiki/Normal_distribution
Args:
x (float): Value to feed into the normal function
mean (float): Mean of the normal function
variance (float): Variance of the normal function
Returns: float
Example:
>>> round(_normal_function(0, 0, 5), 4)
0.1784
"""
e_power = -1 * (((x - mean) ** 2) / (2 * variance))
return (1 / math.sqrt(2 * variance * math.pi)) * (math.e ** e_power)
python类e()的实例源码
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
def evaluate(self):
self._set_ready()
condition = self.get_parameter_value(self.condition)
if not condition: return
input_value = self.get_parameter_value(self.input_value)
if isinstance(input_value, numbers.Number):
for e in range(0, input_value):
self._set_value(e)
for cell in self.output_cells: cell.evaluate()
else:
for e in input_value:
self._set_value(e)
for cell in self.output_cells: cell.evaluate()
pass
pass
for cell in self.output_cells:
cell.reset()
pass
pass
def train(self):
m = self.m
for k in range(self.itern):
cls = self.estimator(max_depth = 3, presort = True)
cls.fit(self.X, self.y, sample_weight = self.w)
self.estimators.append(cls)
y_predict = cls.predict(self.X)
error = 0 # number of wrong prediction
for i in range(m):
if y_predict[i] != self.y[i]:
error += self.w[i]
if error == 0:
error += 0.01 # smoothness
alpha = 0.5*log((1-error)/error) # estimator weight
self.alphas = np.append(self.alphas, alpha)
for i in range(m): # update sample weights
if y_predict[i] != self.y[i]:
self.w[i] *= e**alpha
else:
self.w[i] /= e**alpha
self.w /= sum(self.w)
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
def ok(f):
global PASS, FAIL
if THE.tests:
try:
print("\n-----| %s |-----------------------" % f.__name__)
if f.__doc__:
print("# "+ re.sub(r'\n[ \t]*',"\n# ",f.__doc__))
f()
print("# pass")
PASS += 1
except Exception,e:
FAIL += 1
print(traceback.format_exc())
return f
### LIB.tiles ##################################################
def mutate(old, abouts, pop=[], better= lambda x,y,z: cdom(x,y,z),
fiddles= None, # e.g. de. maxWalkSat
fiddle = any1thing, # e.g. around1 or any1thing
after = wrap, # e.g. wrap or cap
retries= THE.retries):
assert retries > 0, 'too hard to satisfy model'
new = abouts.copyDecs(old)
if fiddle:
for col in abouts._decs:
if r() < THE.cf:
new[col.pos] = fiddle(old[col.pos], col) # eg around1, any1thing
if fiddles:
new = fiddles(old,new,abouts,pop, better) # eg deFiddles maxWalkSatFiddles
if after: # e.g. wrap cap
for col in abouts._decs:
new[col.pos] = after(new[col.pos], col)
return new if abouts.ok(new) else mutate(old, abouts, pop,better,
fiddles,fiddle, after,
retries=retries-1)
### Tables #####################################################################
def cdom(x, y, abouts):
"many objective"
x= abouts.objs(x)
y= abouts.objs(y)
def w(better):
return -1 if better == less else 1
def expLoss(w,x1,y1,n):
return -1*math.e**( w*(x1 - y1) / n )
def loss(x, y):
losses= []
n = min(len(x),len(y))
for obj in abouts._objs:
x1, y1 = x[obj.pos] , y[obj.pos]
x1, y1 = obj.norm(x1), obj.norm(y1)
losses += [expLoss( w(obj.want),x1,y1,n)]
return sum(losses) / n
l1= loss(x,y)
l2= loss(y,x)
return l1 < l2
def gaussian_blur(cls, self, radius, n=3):
if self.mode == 'RGBA':
return cls.gaussian_blur(self.convert('RGBa'),
radius, n).convert('RGBA')
if self.mode == 'LA':
return cls.gaussian_blur(self.convert('La'),
radius, n).convert('LA')
# http://www.mia.uni-saarland.de/Publications/gwosdek-ssvm11.pdf
# [7] Box length.
L = math.sqrt(12.0 * float(radius) * radius / n + 1.0)
# [11] Box radius.
l = (L - 1.0) / 2.0
# Integer part.
li = math.floor(l)
# Reduce the fractional part in accordance with tests.
a = math.e ** (2.5 * (l - li) / (li + 1)) - 1
a /= math.e ** (2.5 / (li + 1)) - 1
box_radius = li + a
self.load()
return self._new(self.im.box_blur(box_radius, n))
def evaluateStack(self, s):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack(s)
if op in "+-*/^":
op2 = self.evaluateStack(s)
op1 = self.evaluateStack(s)
return self.opn[op](op1, op2)
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op](self.evaluateStack(s))
elif op[0].isalpha():
return 0
else:
return float(op)
def emp_cdf(samples,x):
''' Indicator Function for Empirical Distribution:
1: if X_i <= x
0: otherwise
sample = X_i
'''
def indicator(sample):
# Note: This function will grab the value of "x" from the scope of the parent function.
if sample <= x: return 1
else: return 0
sigma = 0
n = len(samples)
for X_i in samples:
sigma += indicator(X_i)
return (1/n) * sigma
# Function is a string with a matematical expression, e.g. function='x+5'
# Input: function is a f: R --> R
def __init__(self):
"""
'code_word' ????key???list?value?dict??????????
'word_code' ????key????value?dict????????????
'vocab' ?????
'N' N????????????
"""
self.a = 0.65
self.b = 0.8
self.c = 0.9
self.d = 0.96
self.e = 0.5
self.f = 0.1
self.degree = 180
self.PI = math.pi
self.code_word = {}
self.word_code = {}
self.vocab = set()
self.N = 0
self.read_cilin()
def test_callback_register_double(self):
# Issue #8275: buggy handling of callback args under Win64
# NOTE: should be run on release builds as well
dll = CDLL(_ctypes_test.__file__)
CALLBACK = CFUNCTYPE(c_double, c_double, c_double, c_double,
c_double, c_double)
# All this function does is call the callback with its args squared
func = dll._testfunc_cbk_reg_double
func.argtypes = (c_double, c_double, c_double,
c_double, c_double, CALLBACK)
func.restype = c_double
def callback(a, b, c, d, e):
return a + b + c + d + e
result = func(1.1, 2.2, 3.3, 4.4, 5.5, CALLBACK(callback))
self.assertEqual(result,
callback(1.1*1.1, 2.2*2.2, 3.3*3.3, 4.4*4.4, 5.5*5.5))
################################################################
tree_kernels.py 文件源码
项目:Semantic-Texual-Similarity-Toolkits
作者: rgtjf
项目源码
文件源码
阅读 18
收藏 0
点赞 0
评论 0
def ntk(self, ra, da, rb, db, hra, hrb):
if hra < hrb:
tmpkey = str(hra) + "#" + str(hrb)
else:
tmpkey = str(hrb) + "#" + str(hra)
if self.cache.exists(tmpkey):
return float(self.cache.read(tmpkey))
lena,lenb = len(ra), len(rb)
c, p, minlen = 0, 0, min(lena,lenb)
while c < minlen and ra[c] == rb[c]:
if ra[c] == "#": p += 1
c += 1
#print "p = ", p, "da, db", da, db, ra, rb
if self.gamma == 1:
r = (p+1)*(math.e**(-self.beta*(da + db - 2*p)))
else:
r = (1-self.gamma**(p+1))/(1-self.gamma)*(math.e**(-self.beta*(da + db - 2*p)))
if len(self.cache) > self.cachesize:
self.cache.removeAll()
self.cache.insert(tmpkey,r)
return r
# if self.gamma == 1:
# return (p+1)*(math.e**(-self.beta*(da + db - 2*p)))
# else:
# return (1-self.gamma**(p+1))/(1-self.gamma)*(math.e**(-self.beta*(da + db - 2*p)))
def test_import(self):
self.assert_ok("""\
import math
print(math.pi, math.e)
from math import sqrt
print(sqrt(2))
""")
def evaluateStack(self, s ):
op = s.pop()
if op == 'unary -':
return -self.evaluateStack( s )
if op in "+-x/^":
op2 = self.evaluateStack( s )
op1 = self.evaluateStack( s )
return self.opn[op]( op1, op2 )
elif op == "PI":
return math.pi # 3.1415926535
elif op == "E":
return math.e # 2.718281828
elif op in self.fn:
return self.fn[op]( self.evaluateStack( s ) )
elif op[0].isalpha():
return 0
else:
return float( op )
def Incap(self):
df1 = self.sharedf
incap=[]
for x in df1['market_value']:
incap.append(math.log(x,math.e))
df1['incap'] = incap
return df1[['date','incap']]
def expmin(values, num):
"""
Return a list of `num` exponentially distributed numbers from the
list `values`, starting at the lowest one. The base is the constant `e`.
"""
l = len(values)
v = []
for i in range(num):
index = int((exp(i / num) - 1.0) / (e - 1.0) * l)
index = clipint(index, l)
v.append(values[index])
return v
def expmax(values, num):
"""
Return a list of `num` exponentially distributed numbers from the
list `values`, starting at the highest one. The base is the constant `e`.
"""
l = len(values)
last = l - 1
v = []
for i in range(num):
index = last - int((exp(i / num) - 1.0) / (e - 1.0) * l)
index = clipint(index, l)
v.append(values[index])
return v