機器學習環境配置系列四之theano
決定撰寫機器學習環境配置的主要原因就是因為theano的配置問題,為了能夠用上gpu和cudnn加速,我是費勁了力氣,因為theano1.0.0在配置方面出現了重大改變,而網上絕大多數都很老,無法解決新版本的問題。
1、安裝基於anaconda進行theano安裝
conda install theano
2、環境配置
echo "[global] device = cuda floatX = float32" > ~/.theanorc
官網上的floatX預設float32,原因是float64的執行速度沒有float32快,本人沒有測試,直接聽從了官網的勸告。
device配置是最大的一個坑,網上絕大多數都說就device = gpu 在新版本的theano上是不正確的,為此我吃了很多苦頭
3、cuDNN加速
在.theanorc中還要新增如下內容
[dnn] enabled = True include_path = /usr/local/cuda/include library_path = /usr/local/cuda/lib64
4、出錯問題
在執行theano的時候出現了錯誤,問題是頭版本與庫版本不一致,原因是建立的執行環境裡面安裝的cudnn是7.2.1版本,而系統級別安裝的cudnn是7.3.1,導致了衝突,為了解決這個問題嘗試了各種方法都沒有用,最後刪除了環境裡面的cudnn解決了這個問題
conda remove -n cudnn
5、在theano必須是cudnn5以上的版本,如果安裝了7.0.0以上的cudnn會提示,但是不必理會。
6、測試theano可以執行的gpu和進行了cudnn加速的程式碼如下
from theano import function, config, shared, tensor import numpy import time vlen = 10 * 30 * 768# 10 x #cores x # threads per core iters = 1000 rng = numpy.random.RandomState(22) x = shared(numpy.asarray(rng.rand(vlen), config.floatX)) f = function([], tensor.exp(x)) print(f.maker.fgraph.toposort()) t0 = time.time() for i in range(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, tensor.Elemwise) and ('Gpu' not in type(x.op).__name__) for x in f.maker.fgraph.toposort()]): print('Used the cpu') else: print('Used the gpu')
執行命令
python 程式碼檔名.py
輸出如下資訊代表配置成功
/home/使用者名稱/anaconda3/envs/包名/lib/python2.7/site-packages/theano/gpuarray/dnn.py:184: UserWarning: Your cuDNN version is more recent than Theano. If you encounter problems, try updating Theano or downgrading cuDNN to a version >= v5 and <= v7.
warnings.warn("Your cuDNN version is more recent than "
Using cuDNN version 7301 on context None
Mapped name None to device cuda:GPU型號 (0000:04:00.0)
[GpuElemwise{exp,no_inplace}(<GpuArrayType<None>(float32, vector)>), HostFromGpu(gpuarray)(GpuElemwise{exp,no_inplace}.0)]
Looping 1000 times took 0.270748 seconds
Result is [ 1.23178029 1.61879349 1.52278066 ..., 2.20771813 2.29967761
1.62323296]
Used the gpu
這個帖子的成果用了我大約7天的時間,希望可以幫助到大家。