In [1]:
from sys import path
path.append('/home/bingnan/ecworkspace/HFT1')

In [4]:
%matplotlib inline

In [5]:
from init import *

In [115]:
import itertools, sys

In [6]:
_xin_mean = xin.mean(axis=0)
_xin_std = xin.std(axis=0)
xin_stdzd = (xin - _xin_mean) / _xin_std
xout_stdzd = (xout - _xin_mean) / _xin_std
xtest_stdzd = (xtest - _xin_mean) / _xin_std

In [ ]:
distance.cdist

In [148]:
def my_kernel_eu(x, y, gamma=.1):
    print x.shape, y.shape
    f = pairwise.euclidean_distances
#     timer1.refresh('set f')
    dis = f(x, y, squared=True)
    timer1.refresh('calculate dis')
    dis *= 1./80
    timer1.refresh('/= 80')
    dis *= -gamma
    timer1.refresh(' *= -gamma ')
    np.exp(dis, dis)
    timer1.refresh(' exp ')
    print sys.getsizeof(dis)/1024./1024.
    return dis

In [107]:
def my_kernel_scipy(x, y, gamma=.1):
    print x.shape, y.shape
#     f = pairwise.euclidean_distances
#     timer1.refresh('set f')
    dis = distance.cdist(x, y, metric='euclidean')
    timer1.refresh('calculate dis')
    dis *= 1./80
    timer1.refresh('/= 80')
    dis *= -gamma
    timer1.refresh(' *= -gamma ')
    np.exp(dis, dis)
    timer1.refresh(' exp ')
    return dis

In [21]:
def MyTime(startpoint, s):
    time_length = tm.time() - startpoint
    print '{0:.3f}s consumed. '.format(time_length) + s + ' is done.'

In [33]:
def MyTime(startpoint, s, time_list, event_list):
    """
    startpoint is the start time
    s is event name(finished)
    time_list and event_list are python lists
    
    """
    time_length = tm.time() - startpoint
    time_list.append(time_length)
    event_list.append(s)
    #print '{0:.3f}s consumed. '.format(time_length) + s + ' is done.'

In [2]:
class MyTimeCLS(object):
    def __init__(self):
        self.start_time = tm.time()
        self._time_list = [0.]
        self.interval_list = []
        self.event_list = []
    def refresh(self, event):
        current_time = tm.time() - self.start_time
        self._time_list.append(current_time)
        self.event_list.append(event)
    """ len(self._time_list) is 1 longer than len(self.event_list)""" 
    def show(self):
        self._time_list = np.array(self._time_list)
        self.interval_list = self._time_list[1:] - self._time_list[:-1]
        for t, e in itertools.izip(self.interval_list, self.event_list):
            #print "{0:.3f} s till {1} is done.".format(t, e)
            print "{0:.4f} s for: {1}.".format(t, e)
        print "{0:.4f} s in total".format(self._time_list[-1])

In [35]:
timer1 = MyTimeCLS()

In [44]:
import timeit

In [43]:
timer1.refresh('r3')

In [ ]:


In [140]:
sys.getsizeof(np.random.rand(10000, 10000))/1024./1024.


Out[140]:
762.9395599365234

In [122]:
sys.getsizeof(x0)/1024/1024


Out[122]:
564177992

In [109]:
def MyRgrs(xi, xo, yi, yo, model=None, align=False):
    '''use yi and yout 's index to align. x is of full length.

    Parameters
    ----------
    model : sklearn clf

    Returns
    -------
    res : regression result

    '''
    if align:
        xi = xi.ix[yi.index]
        xo = xo.ix[yo.index]
    if not xi.ndim > 1:
        xi = xi.reshape(-1, 1)
        xo = xo.reshape(-1, 1)
    timer1.refresh('regression preparation')
    res = model.fit(xi, yi)
    timer1.refresh('fit')
    rsq_in = res.score(xi, yi)
    timer1.refresh('rsq_in calc')
#     res.predict(xi)
#     timer1.refresh('predict xin')
    rsq_out = res.score(xo, yo)
    timer1.refresh('rsq_out calc')
    timer1.refresh('All in regression func')
    return res, rsq_in, rsq_out

In [145]:
yin2 = yin.ix[::50]
print len(yin2)
yout2 = yout.ix[::15]
print len(yout2)


10448
11609

In [149]:
timer1 = MyTimeCLS()
for myepsilon in np.arange(.2, .3, .3):
    #MyTime(start_time, 'enter loop1')
    for myc in np.arange(10e-2, 100e-2, 100e-2):
        #MyTime(start_time, 'enter loop2')
        for mygamma in np.arange(.4341/5, 300e-2, 300e-2):
            #MyTime(start_time, 'enter loop3')
            mmy_kernel = functools.partial(my_kernel_eu, gamma=mygamma)
            #MyTime(start_time, 'Partial func.')
            mod = svm.SVR(kernel=mmy_kernel, epsilon=myepsilon, C=myc)
            #MyTime(start_time, 'SVR model')
            #print ('\n\n===========$\epsilon$: %f, $C$: %f, $\gamma$: %f===================' % (myepsilon, myc, mygamma))
            res_eu, rsqin, rsq_out = MyRgrs(xin_stdzd#.ix[:, temp1]
                                         , xout_stdzd#.ix[:, temp1]
                                         , yin2, yout2, mod, align=True)


(10448, 80) (10448, 80)
832.830184937
(10448, 80) (10448, 80)
832.830184937
(11609, 80) (10448, 80)
925.375717163

In [150]:
timer1.show()


0.0281 s for: regression preparation.
1.4876 s for: calculate dis.
0.1533 s for: /= 80.
0.1531 s for:  *= -gamma .
3.4451 s for:  exp .
2.0001 s for: fit.
1.3395 s for: calculate dis.
0.1527 s for: /= 80.
0.1528 s for:  *= -gamma .
3.4405 s for:  exp .
0.2925 s for: rsq_in calc.
1.4858 s for: calculate dis.
0.1699 s for: /= 80.
0.1699 s for:  *= -gamma .
3.8549 s for:  exp .
0.3446 s for: rsq_out calc.
0.0000 s for: All in regression func.
18.6707 s in total

In [146]:
timer1 = MyTimeCLS()
for myepsilon in np.arange(.2, .3, .3):
    #MyTime(start_time, 'enter loop1')
    for myc in np.arange(10e-2, 100e-2, 100e-2):
        #MyTime(start_time, 'enter loop2')
        for mygamma in np.arange(.4341/5, 300e-2, 300e-2):
            #MyTime(start_time, 'enter loop3')
            mmy_kernel = functools.partial(my_kernel_scipy, gamma=mygamma)
            #MyTime(start_time, 'Partial func.')
            mod = svm.SVR(kernel=mmy_kernel, epsilon=myepsilon, C=myc)
            #MyTime(start_time, 'SVR model')
            #print ('\n\n===========$\epsilon$: %f, $C$: %f, $\gamma$: %f===================' % (myepsilon, myc, mygamma))
            res_eu, rsqin, rsq_out = MyRgrs(xin_stdzd#.ix[:, temp1]
                                         , xout_stdzd#.ix[:, temp1]
                                         , yin2, yout2, mod, align=True)


(10448, 80) (10448, 80)
(10448, 80) (10448, 80)
(11609, 80) (10448, 80)

In [111]:
print timer1._time_list[-1]
timer1.show()


63.8748390675
0.027 s for: regression preparation.
8.163 s for: calculate dis.
0.156 s for: /= 80.
0.151 s for:  *= -gamma .
3.478 s for:  exp .
1.768 s for: fit.
8.248 s for: calculate dis.
0.150 s for: /= 80.
0.164 s for:  *= -gamma .
3.445 s for:  exp .
0.255 s for: rsq_in calc.
8.339 s for: calculate dis.
0.177 s for: /= 80.
0.197 s for:  *= -gamma .
3.512 s for:  exp .
0.276 s for: predict xin.
17.021 s for: calculate dis.
0.324 s for: /= 80.
0.314 s for:  *= -gamma .
7.177 s for:  exp .
0.532 s for: rsq_out calc.
0.000 s for: All in regression func.

In [110]:
print timer2._time_list[-1]
timer2.show()


29.3167819977
0.028 s for: regression preparation.
0.004 s for: set f.
1.502 s for: calculate dis.
0.154 s for: /= 80.
0.151 s for:  *= -gamma .
3.448 s for:  exp .
1.997 s for: fit.
0.005 s for: set f.
1.328 s for: calculate dis.
0.151 s for: /= 80.
0.151 s for:  *= -gamma .
3.446 s for:  exp .
0.293 s for: rsq_in calc.
0.004 s for: set f.
1.335 s for: calculate dis.
0.153 s for: /= 80.
0.153 s for:  *= -gamma .
3.457 s for:  exp .
0.294 s for: predict xin.
0.011 s for: set f.
2.792 s for: calculate dis.
0.316 s for: /= 80.
0.313 s for:  *= -gamma .
7.184 s for:  exp .
0.648 s for: rsq_out calc.
0.000 s for: All in regression func.

In [ ]:


In [ ]:

timeit playground


In [372]:
n_feature = 101
a, b = np.random.rand(1283, n_feature), np.random.rand(1687, n_feature)
myweight = np.random.rand(n_feature)

In [373]:


In [116]:
%timeit (pairwise.euclidean_distances(temp, temp))


100 loops, best of 3: 7.84 ms per loop

In [119]:
%timeit (pairwise.manhattan_distances(temp, temp))


10 loops, best of 3: 85.1 ms per loop

In [120]:
%timeit (distance.cdist(temp, temp, metric='euclidean'))


10 loops, best of 3: 87.4 ms per loop

In [131]:
myweight = np.random.rand(80)

In [134]:
%timeit temp1 = distance.cdist(temp, temp, metric='minkowski', p=1.5)


1 loops, best of 3: 12.4 s per loop

In [123]:
%timeit temp1 = distance.cdist(temp, temp, metric='wminkowski', p=1.5, w=myweight)


1 loops, best of 3: 26.1 s per loop

In [146]:
timer1 = MyTimeCLS()
timer1.refresh('start')
temp1 = distance.cdist(temp, temp, metric='minkowski', p=1.5)
timer1.refresh('dist')
timer1.show()


0.000 s for: start.
15.354 s for: dist.

In [149]:
timer1 = MyTimeCLS()
timer1.refresh('start')
temp2 = distance.cdist(temp, temp, metric='wminkowski', p=1.5, w=myweight)
timer1.refresh('dist')
timer1.show()


0.000 s for: start.
15.344 s for: dist.

another way


In [156]:
timer1 = MyTimeCLS()
timer1.refresh('start')
temp *= myweight
temp3 = distance.cdist(temp, temp, metric='minkowski', p=1.5)
timer1.refresh('dist')
timer1.show()


0.000 s for: start.
15.204 s for: dist.

In [159]:
temp2


Out[159]:
array([[ 0.        ,  4.23849875,  4.30244052, ...,  4.23943752,
         4.43685612,  3.96344131],
       [ 4.23849875,  0.        ,  4.6172182 , ...,  4.5436439 ,
         4.31411272,  4.29435462],
       [ 4.30244052,  4.6172182 ,  0.        , ...,  4.12493838,
         3.61471474,  3.84290533],
       ..., 
       [ 4.23943752,  4.5436439 ,  4.12493838, ...,  0.        ,
         3.43379686,  3.99392494],
       [ 4.43685612,  4.31411272,  3.61471474, ...,  3.43379686,
         0.        ,  3.99838261],
       [ 3.96344131,  4.29435462,  3.84290533, ...,  3.99392494,
         3.99838261,  0.        ]])

In [162]:
np.abs(temp2 - temp3).sum()


Out[162]:
2.9693136838204737e-10

In [ ]:

profile tools


In [164]:
import cProfile, pstats, StringIO

In [402]:
pr = cProfile.Profile()
pr.enable()
#---
temp2 = distance.cdist(a, b, metric='wminkowski', p=3, w=myweight)
#---
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()


         54 function calls in 31.220 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        2    0.000    0.000   31.220   15.610 /usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py:2791(run_code)
        1    0.000    0.000   31.219   31.219 <ipython-input-402-eaebc98915d6>:4(<module>)
        1    0.000    0.000   31.219   31.219 /usr/local/lib/python2.7/dist-packages/scipy/spatial/distance.py:1744(cdist)
        1   31.212   31.212   31.212   31.212 {scipy.spatial._distance_wrap.cdist_weighted_minkowski_wrap}
        1    0.007    0.007    0.007    0.007 {numpy.core.multiarray.zeros}
        2    0.000    0.000    0.000    0.000 /usr/lib/python2.7/codeop.py:132(__call__)
        2    0.000    0.000    0.000    0.000 {compile}
        2    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/scipy/spatial/distance.py:121(_copy_array_if_base_present)
        2    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/numpy/core/numerictypes.py:698(issubsctype)
        5    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/scipy/spatial/distance.py:141(_convert_to_double)
        4    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/numpy/core/numerictypes.py:603(obj2sctype)
        2    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/core/hooks.py:122(__call__)
        2    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py:414(asarray)
        1    0.000    0.000    0.000    0.000 <ipython-input-402-eaebc98915d6>:6(<module>)
        2    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/utils/ipstruct.py:125(__getattr__)
        2    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py:1008(user_global_ns)
        7    0.000    0.000    0.000    0.000 {isinstance}
        2    0.000    0.000    0.000    0.000 {numpy.core.multiarray.array}
        6    0.000    0.000    0.000    0.000 {issubclass}
        2    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/core/hooks.py:202(pre_run_code_hook)
        1    0.000    0.000    0.000    0.000 {callable}
        2    0.000    0.000    0.000    0.000 {len}
        1    0.000    0.000    0.000    0.000 {method 'lower' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}




In [174]:
pr = cProfile.Profile()
pr.enable()
#---
a *= myweight
b *= myweight
temp3 = distance.cdist(a, b, metric='minkowski', p=1.5)
#---
pr.disable()
s = StringIO.StringIO()
sortby = 'cumulative'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print s.getvalue()


         69 function calls in 76.827 seconds

   Ordered by: cumulative time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        4    0.000    0.000   76.827   19.207 /usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py:2791(run_code)
        1    0.000    0.000   76.824   76.824 <ipython-input-174-6d54f9679799>:6(<module>)
        1    0.000    0.000   76.824   76.824 /usr/local/lib/python2.7/dist-packages/scipy/spatial/distance.py:1744(cdist)
        1   76.824   76.824   76.824   76.824 {scipy.spatial._distance_wrap.cdist_minkowski_wrap}
        1    0.001    0.001    0.001    0.001 <ipython-input-174-6d54f9679799>:4(<module>)
        1    0.001    0.001    0.001    0.001 <ipython-input-174-6d54f9679799>:5(<module>)
        4    0.000    0.000    0.000    0.000 /usr/lib/python2.7/codeop.py:132(__call__)
        4    0.000    0.000    0.000    0.000 {compile}
        2    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/scipy/spatial/distance.py:121(_copy_array_if_base_present)
        2    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/numpy/core/numerictypes.py:698(issubsctype)
        4    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/numpy/core/numerictypes.py:603(obj2sctype)
        4    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/core/hooks.py:122(__call__)
        4    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/scipy/spatial/distance.py:141(_convert_to_double)
        1    0.000    0.000    0.000    0.000 {numpy.core.multiarray.zeros}
        2    0.000    0.000    0.000    0.000 /usr/local/lib/python2.7/dist-packages/numpy/core/numeric.py:414(asarray)
        4    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/utils/ipstruct.py:125(__getattr__)
        4    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.py:1008(user_global_ns)
        1    0.000    0.000    0.000    0.000 <ipython-input-174-6d54f9679799>:8(<module>)
        2    0.000    0.000    0.000    0.000 {numpy.core.multiarray.array}
        6    0.000    0.000    0.000    0.000 {issubclass}
        4    0.000    0.000    0.000    0.000 /usr/lib/python2.7/dist-packages/IPython/core/hooks.py:202(pre_run_code_hook)
        7    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'lower' of 'str' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
        1    0.000    0.000    0.000    0.000 {callable}
        2    0.000    0.000    0.000    0.000 {len}



mathematical perspective

1-D scenario


In [175]:
a, b = np.arange(4), np.arange(1, 5)

In [176]:
print a.shape, b.shape


(4,) (4,)

In [178]:
c, d = a.reshape(-1, 1), b.reshape(1, -1)
print c.shape, d.shape


(4, 1) (1, 4)

In [179]:
c - d


Out[179]:
array([[-1, -2, -3, -4],
       [ 0, -1, -2, -3],
       [ 1,  0, -1, -2],
       [ 2,  1,  0, -1]])

2-D scenario


In [360]:
n_feature = 77
a, b =np.random.rand(330, n_feature), np.random.rand(440, n_feature)
# a, b = np.round(a, 1), np.round(b, 1)
myweight = np.random.rand(n_feature, 1, 1)
print a.shape, b.shape, myweight.shape


(330, 77) (440, 77) (77, 1, 1)

In [361]:
c, d = (a.T)[:, :, np.newaxis], (b.T)[:, np.newaxis, :]
print c.shape, d.shape


(77, 330, 1) (77, 1, 440)

In [362]:
e = c - d
print e.shape


(77, 330, 440)

In [363]:
g = e * myweight
#print g

In [364]:
#h = np.sum(np.abs(g), axis=0)
h = np.sqrt(np.sum(g**2, axis=0))

In [365]:
mdzz = distance.cdist(a, b, metric='wminkowski', 
                      p=2, w=myweight
                      )

In [367]:
np.abs(h-mdzz).sum()


Out[367]:
2.8983482280864337e-11

In [226]:
mdzz.shape


Out[226]:
(5, 6)

In [ ]:


In [241]:
c[0, 4, :] - d[0, :, 1]


Out[241]:
array([ 0.27207679])

In [242]:
f[0,:,:]


Out[242]:
array([[ 0.60494899,  0.1632261 ,  0.11540897,  0.63460453,  0.02465587,
         0.26170082],
       [ 0.61445864,  0.15371646,  0.12491861,  0.64411417,  0.03416552,
         0.27121046],
       [ 0.5900235 ,  0.1781516 ,  0.10048348,  0.61967904,  0.00973038,
         0.24677533],
       [ 0.04670862,  0.72146648,  0.4428314 ,  0.07636416,  0.5335845 ,
         0.29653956],
       [ 0.4960983 ,  0.27207679,  0.00655828,  0.52575384,  0.08419482,
         0.15285013]])

test it!


In [95]:
def mycdist(a, b, p, w):
    w = w[np.newaxis, np.newaxis, :]
    timer2.refresh('w newaxis')
    c, d = a[:, np.newaxis, :], b[np.newaxis, :, :]
    timer2.refresh('a,b newaxis')
#     g = np.abs(c - d) * w
    e = c - d
    timer2.refresh('broad cast')
    e *= w
    timer2.refresh('mul weight')
    e = np.abs(e)
    timer2.refresh('ABS')
    if p == 1:
        h = np.sum(e, axis=2)
        timer2.refresh('just sum')
    elif p == 2:
        h = np.sqrt(np.sum(e**p, axis=2))
        timer2.refresh('shortcut')
    else:
        h = np.sqrt(np.sum(np.power(e, p), axis=2))
        timer2.refresh('power func')
    return h

In [471]:
4096*2


Out[471]:
8192

In [151]:
n_feature = 128
a, b = np.random.rand(512, n_feature), np.random.rand(512, n_feature)
myweight = np.random.rand(n_feature)

In [99]:
timer1 = MyTimeCLS()
timer1.refresh('start')
c, d = a * myweight, b * myweight
temp1 = pairwise.manhattan_distances(c, d)
timer1.refresh('dist')
timer1.show()


0.0001 s for: start.
1.6579 s for: dist.
1.6580 s in total

In [157]:
for i in np.arange(.2, 10, .2):
    print '\n========{0}=========='.format(i)
    timer3 = MyTimeCLS()
    timer3.refresh('start')
    temp3 = distance.cdist(a, b, metric='wminkowski', p=i, w=myweight)
    timer3.refresh('dist')
    timer3.show()


========0.2==========
0.0000 s for: start.
3.1877 s for: dist.
3.1877 s in total

========0.4==========
0.0000 s for: start.
3.1482 s for: dist.
3.1482 s in total

========0.6==========
0.0000 s for: start.
3.1428 s for: dist.
3.1428 s in total

========0.8==========
0.0000 s for: start.
3.1446 s for: dist.
3.1446 s in total

========1.0==========
0.0000 s for: start.
0.4080 s for: dist.
0.4080 s in total

========1.2==========
0.0000 s for: start.
3.1440 s for: dist.
3.1440 s in total

========1.4==========
0.0000 s for: start.
3.1433 s for: dist.
3.1433 s in total

========1.6==========
0.0000 s for: start.
3.1461 s for: dist.
3.1461 s in total

========1.8==========
0.0000 s for: start.
3.1593 s for: dist.
3.1593 s in total

========2.0==========
0.0000 s for: start.
0.5154 s for: dist.
0.5154 s in total

========2.2==========
0.0000 s for: start.
3.1486 s for: dist.
3.1486 s in total

========2.4==========
0.0000 s for: start.
3.1540 s for: dist.
3.1540 s in total

========2.6==========
0.0000 s for: start.
3.1559 s for: dist.
3.1559 s in total

========2.8==========
0.0000 s for: start.
3.1508 s for: dist.
3.1508 s in total

========3.0==========
0.0000 s for: start.
3.1679 s for: dist.
3.1679 s in total

========3.2==========
0.0000 s for: start.
3.1621 s for: dist.
3.1621 s in total

========3.4==========
0.0000 s for: start.
3.1587 s for: dist.
3.1587 s in total

========3.6==========
0.0000 s for: start.
3.1744 s for: dist.
3.1744 s in total

========3.8==========
0.0000 s for: start.
3.1732 s for: dist.
3.1732 s in total

========4.0==========
0.0000 s for: start.
3.3083 s for: dist.
3.3083 s in total

========4.2==========
0.0000 s for: start.
3.1748 s for: dist.
3.1748 s in total

========4.4==========
0.0000 s for: start.
3.1802 s for: dist.
3.1802 s in total

========4.6==========
0.0000 s for: start.
3.1805 s for: dist.
3.1805 s in total

========4.8==========
0.0000 s for: start.
3.1766 s for: dist.
3.1766 s in total

========5.0==========
0.0000 s for: start.
3.1920 s for: dist.
3.1920 s in total

========5.2==========
0.0000 s for: start.
3.1890 s for: dist.
3.1890 s in total

========5.4==========
0.0000 s for: start.
3.2122 s for: dist.
3.2122 s in total

========5.6==========
0.0000 s for: start.
3.2003 s for: dist.
3.2003 s in total

========5.8==========
0.0000 s for: start.
3.2060 s for: dist.
3.2060 s in total

========6.0==========
0.0000 s for: start.
3.2084 s for: dist.
3.2084 s in total

========6.2==========
0.0000 s for: start.
3.2122 s for: dist.
3.2122 s in total

========6.4==========
0.0000 s for: start.
3.2175 s for: dist.
3.2175 s in total

========6.6==========
0.0000 s for: start.
3.2209 s for: dist.
3.2209 s in total

========6.8==========
0.0000 s for: start.
3.2158 s for: dist.
3.2159 s in total

========7.0==========
0.0000 s for: start.
3.2143 s for: dist.
3.2143 s in total

========7.2==========
0.0000 s for: start.
3.2278 s for: dist.
3.2278 s in total

========7.4==========
0.0000 s for: start.
3.2276 s for: dist.
3.2276 s in total

========7.6==========
0.0000 s for: start.
3.2271 s for: dist.
3.2271 s in total

========7.8==========
0.0000 s for: start.
3.2380 s for: dist.
3.2380 s in total

========8.0==========
0.0000 s for: start.
3.3592 s for: dist.
3.3592 s in total

========8.2==========
0.0000 s for: start.
3.2871 s for: dist.
3.2871 s in total

========8.4==========
0.0000 s for: start.
3.2520 s for: dist.
3.2520 s in total

========8.6==========
0.0000 s for: start.
3.2474 s for: dist.
3.2474 s in total

========8.8==========
0.0000 s for: start.
3.2588 s for: dist.
3.2588 s in total

========9.0==========
0.0000 s for: start.
3.3609 s for: dist.
3.3609 s in total

========9.2==========
0.0000 s for: start.
3.2668 s for: dist.
3.2668 s in total

========9.4==========
0.0000 s for: start.
3.2580 s for: dist.
3.2580 s in total

========9.6==========
0.0000 s for: start.
3.2626 s for: dist.
3.2626 s in total

========9.8==========
0.0000 s for: start.
3.2577 s for: dist.
3.2577 s in total

In [101]:
timer2 = MyTimeCLS()
timer2.refresh('start')
temp2 = mycdist(a, b, p=3, w=myweight)
timer2.refresh('dist')
timer2.show()


0.0001 s for: start.
0.0001 s for: w newaxis.
0.0000 s for: a,b newaxis.
8.1686 s for: broad cast.
4.0428 s for: mul weight.
6.4985 s for: ABS.
217.2015 s for: power func.
0.0624 s for: dist.
235.9739 s in total

In [91]:
np.abs(temp2 -temp3).mean()


Out[91]:
5.3035656150050956e-15

In [66]:
(temp3 -temp1) > 0


Out[66]:
array([[False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       ..., 
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False],
       [False, False, False, ..., False, False, False]], dtype=bool)

In [ ]:


In [395]:
temp = np.random.rand(3,4)

matrix exponential


In [459]:
from scipy import linalg

In [464]:
mat = np.random.rand(1234, 1234, 80)

In [465]:
%timeit mat**2.579


---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-465-05110665da53> in <module>()
----> 1 get_ipython().magic(u'timeit mat**2.579')

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
   2163         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2164         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2165         return self.run_line_magic(magic_name, magic_arg_s)
   2166 
   2167     #-------------------------------------------------------------------------

/usr/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
   2084                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2085             with self.builtin_trap:
-> 2086                 result = fn(*args,**kwargs)
   2087             return result
   2088 

/usr/lib/python2.7/dist-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell)

/usr/lib/python2.7/dist-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
    189     # but it's overkill for just that one bit of state.
    190     def magic_deco(arg):
--> 191         call = lambda f, *a, **k: f(*a, **k)
    192 
    193         if callable(arg):

/usr/lib/python2.7/dist-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell)
    933                 number *= 10
    934 
--> 935         best = min(timer.repeat(repeat, number)) / number
    936 
    937         print u"%d loops, best of %d: %s per loop" % (number, repeat,

/usr/lib/python2.7/timeit.pyc in repeat(self, repeat, number)
    221         r = []
    222         for i in range(repeat):
--> 223             t = self.timeit(number)
    224             r.append(t)
    225         return r

/usr/lib/python2.7/timeit.pyc in timeit(self, number)
    193         gc.disable()
    194         try:
--> 195             timing = self.inner(it, self.timer)
    196         finally:
    197             if gcold:

<magic-timeit> in inner(_it, _timer)

KeyboardInterrupt: 

In [469]:
%timeit np.power(mat, 2.579)


1 loops, best of 3: 11.7 s per loop