Update 2017.02.27: Theano已經內建進了python标準庫,可以通過
pip install theano
指令一鍵安裝。但是需要編譯安裝的同學依然可以借鑒本文。
Update 2016.06.16:在Win10上也成功了,有需要的讀者請看這一篇:《Win10下安裝Python2.7+Theano0.7+CUDA7.5》
為了感受深度學習算法,從deeplearning.org上接觸到了Python的Theano庫,這是一個有透明GPU加速的算法庫。最開始想在Windows上裝的,但是折騰了一天沒搞成,轉而到Linux上先搞成了。
1.需要的環境和軟體
首先確定在Linux上CUDA可用(否則是用不了GPU加速的),我已經在Ubuntu14.04x64上安裝好了CUDA7.5(Nivida官網有deb安裝包)。其次點選此連結下載下傳pycuda-2015.1.3.tar.gz。然後保證Internet可用。
2.安裝步驟
首先配置幾個環境變量。修改/etc/profile檔案,在尾部添加如下指令:
#For CUDA and pycuda
export CUDA_INC_DIR=/usr/local/cuda-/include
export PATH=$PATH:/usr/local/cuda-/bin
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-/targets/x86_64-linux/lib:/usr/local/cuda-/lib64
這三條指令分别添加了CUDA7.5的include、bin和lib目錄到環境變量,使得CUDA能被編譯器找到。
然後運作如下指令:
sudo apt-get install python-numpy python-scipy python-dev python-pip python-nose g++ libopenblas-dev git
sudo pip install Theano
這兩條指令會下載下傳Theano的依賴項,正常情況下你的Theano就裝好了。但是這時Theano隻能用CPU,GPU還不可用。
現在解壓前面下載下傳的pycuda-2015.1.3.tar.gz,進入目錄運作如下指令:
./configure.py
make
sudo make install
此時GPU子產品應該也可用了。注意,我嘗試過用pip install pycuda來安裝pycuda,但是總是會編譯失敗,于是嘗試手動configure之後make安裝成功。
3.運作測試
運作如下代碼測試Theano在GPU和CPU上的運作時間。設定 useGPU=True是用GPU,否則是用CPU。
'''
Created on 2015-11-12
@author: tomheaven
'''
# settings
useGPU = True
import os
# 通過環境變量控制theano使用GPU或者CPU
if useGPU:
os.environ["THEANO_FLAGS"] = "device=gpu"
else:
os.environ["THEANO_FLAGS"] = "device=cpu"
from theano import function, config, shared, sandbox
import theano.tensor as T
import numpy
import time
vlen = * * # 10 x #cores x # threads per core
iters =
rng = numpy.random.RandomState()
x = shared(numpy.asarray(rng.rand(vlen), config.floatX))
f = function([], T.exp(x))
print(f.maker.fgraph.toposort())
t0 = time.time()
for i in xrange(iters):
r = f()
t1 = time.time()
print("Looping %d times took %f seconds" % (iters, t1 - t0))
print("Result is %s" % (r,))
if numpy.any([isinstance(x.op, T.Elemwise) for x in f.maker.fgraph.toposort()]):
print('Used the cpu')
else:
print('Used the gpu')
我的GPU測試結果是:
Using gpu device : GeForce GTX 870M
[GpuElemwise{exp,no_inplace}(<CudaNdarrayType(float32, vector)>), HostFromGpu(GpuElemwise{exp,no_inplace})]
Looping times took seconds
Result is [ ...,
]
Used the gpu
我的CPU測試結果是:
[Elemwise{exp,no_inplace}(<TensorType(float32, vector)>)]
Looping times took seconds
Result is [ ...,
]
Used the cpu
可以看出GPU比CPU快5倍以上,加速效果明顯。
有了Linux的經驗,Windows上會繼續折騰,弄好了再發文。