2013年12月12日

fast rolling window

假設有兩個array S1 (size m), S2 (size n), m>n,要計算S2相對於S1的滑動函數值(如mean或是std等),一般的做法是使用loop實作,但是python的迴圈速度相當的慢,所以建議使用numpy strides的功能來加速,在測試當中,計算stdev大約能夠加速100倍,程式碼如下:

def rolling_window(a, window):
    shape = a.shape[:-1] + (a.shape[-1] - window + 1, window)
    print shape
    strides = a.strides + (a.strides[-1],)
    return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides)

def test_rolling_window(winsize=3):
    import time
    t = time.clock()
    observations = np.random.randn(1000)
    np.std(rolling_window(observations, winsize), 1)
    print "strided %.6f secs"%(time.clock()-t)

    t = time.clock()
    for idx in xrange(winsize, len(observations)):
        np.std(observations[idx-winsize: idx])
    print "loop %.6f secs"%(time.clock()-t)

2013年10月1日

numpy multiply broadcast by column

假設array a的size為(2,5),array c的size為(2,),如果要做elementwise multiplication時,我的做法:
(a.T*c).T
但是這個做法需要寫到兩次transpose,式子變長時不易理解。

後來在trace別人的code時,看到了以下的寫法:
a*c[:, np.newaxis]
即可達到相同的效果,且較容易理解。

2013年8月10日

[Theano] 在Eclipse中使用GPU執行程式

首先在{HOME}下建立.theanorc檔案,內容如下:
 [global] floatX = float32
 device = gpu0 
 [nvcc] fastmath = True 
存檔後,退出至{HOME}中。 
輸入nvcc指令測試cuda套件是否已經安裝完成。 

然後到eclipse隨便建立一個python檔,import theano後,執行該程式, 此時可能會出現以下錯誤:
 ERROR (theano.sandbox.cuda): nvcc compiler not found on $PATH. Check your nvcc installation and try again.

 這是因為eclipse的pydev套件使用的PATH變數與linux中不同,
用以下指令修正:
 window->preferences->PyDev->Interpreter-Python->Environment->New-> Name: PATH, Value: ${env_var:PATH}:/usr/local/cuda-5.0/bin 

設定完成後,可在python檔使用
 import os 
print os.environ['PATH'] 
 確定環境變數修改完成。

2013年5月11日

[R] install.packages without graphics

由於我經常使用linux + screen的方式在遠端執行R ,在安裝R套件時無法使用graphics套件來選擇mirror,所以改用以下的方式在console下設定mirror site後,再來安裝套件。
chooseCRANmirror(graphics=FALSE);
install.packages("pkgName")
即可安裝套件。

2013年3月16日

postgresql備份與還原

 OS: Ubuntu 12.04 & Postgresql 9.1
因為備份與還原資料時,需要相當長的時間,因此我所使用的備份與還原的工具都是在screen環境下使用pg_backup備份,psql還原。

備份
  • pg_dump -h [host](localhost) -F [format, p: sql script(default), t: tar, c: compress] [資料庫名稱 ] -U [帳號] -f [備份檔名稱.sql] -v
  • 以db_chenhh這個帳號,備份investment資料庫,則命令:pg_dump investment -U db_chenhh -f investment_backup.sql

還原
  • 命令:psql -f [備份檔名稱.sql] [資料庫] [帳號]
  • psql -f investment_backup.sql investment db_chehh
  • 命令: pg_restore, 參數與pg_dump相同
  • pg_restore -f investment_backup.sql investment


2013年3月9日

更換BLAS implementation

使用openBLAS替換ATLAS(Ubuntu 12.04)
  1. sudo apt-get install libopenblas-base, libopenblas-dev
  2. sudo update-alternatives --all
  3. set liblapack.so.3gf to/usr/lib/lapack/liblapack.so.3gf

其它的BLAS替代方案可參考Debian wiki:http://wiki.debian.org/DebianScience/LinearAlgebraLibraries

2013年2月5日

linux新增字型

OS: ubuntu 12.04 
新增字型的方法:
  1. 在/usr/share/fonts新增資料夾(e.g. winfonts)
  2. 將字型檔案copy至/usr/share/fonts/winfonts/
  3. 執行sudo fc-cache -f -v