Ubuntu14.04下安装Python2.7+Theano0.7+CUDA7.5

来源:互联网 发布:大数据的4v特征是什么 编辑:程序博客网 时间:2024/05/17 07:01

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 pycudaexport CUDA_INC_DIR=/usr/local/cuda-7.5/includeexport PATH=$PATH:/usr/local/cuda-7.5/binexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-7.5/targets/x86_64-linux/lib:/usr/local/cuda-7.5/lib64

这三条指令分别添加了CUDA7.5的include、bin和lib目录到环境变量,使得CUDA能被编译器找到。

然后运行如下命令:

sudo apt-get install python-numpy python-scipy python-dev python-pip python-nose g++ libopenblas-dev gitsudo pip install Theano

这两条命令会下载Theano的依赖项,正常情况下你的Theano就装好了。但是这时Theano只能用CPU,GPU还不可用。

现在解压前面下载的pycuda-2015.1.3.tar.gz,进入目录运行如下命令:

./configure.pymakesudo make install

此时GPU模块应该也可用了。注意,我尝试过用pip install pycuda来安装pycuda,但是总是会编译失败,于是尝试手动configure之后make安装成功。

3.运行测试

运行如下代码测试Theano在GPU和CPU上的运行时间。设置 useGPU=True是用GPU,否则是用CPU。

'''Created on 2015-11-12@author: tomheaven'''# settingsuseGPU = Trueimport os# 通过环境变量控制theano使用GPU或者CPUif useGPU:    os.environ["THEANO_FLAGS"] = "device=gpu"else:    os.environ["THEANO_FLAGS"] = "device=cpu"from theano import function, config, shared, sandboximport theano.tensor as Timport numpyimport timevlen = 10 * 30 * 768  # 10 x #cores x # threads per coreiters = 1000rng = numpy.random.RandomState(22)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 0: GeForce GTX 870M[GpuElemwise{exp,no_inplace}(<CudaNdarrayType(float32, vector)>), HostFromGpu(GpuElemwise{exp,no_inplace}.0)]Looping 1000 times took 0.395766 secondsResult is [ 1.23178029  1.61879349  1.52278066 ...,  2.20771813  2.29967761  1.62323296]Used the gpu

我的CPU测试结果是:

[Elemwise{exp,no_inplace}(<TensorType(float32, vector)>)]Looping 1000 times took 2.213337 secondsResult is [ 1.23178029  1.61879337  1.52278066 ...,  2.20771813  2.29967761  1.62323284]Used the cpu

可以看出GPU比CPU快5倍以上,加速效果明显。

有了Linux的经验,Windows上会继续折腾,弄好了再发文。

0 0