CentOS6.8 + cuda + caffe安装记录 (之三 caffe使用)

来源:互联网 发布:直线电机选型算法 编辑:程序博客网 时间:2024/05/21 17:56

Caffe使用需要用Python或者matlab调用,这里我们使用Python。
使用Python调用caffe的官方指导http://nbviewer.jupyter.org/github/BVLC/caffe/blob/master/examples/00-classification.ipynb

该示例是使用ipython进行编译的。如果在自己的环境中使用系统自带的python xxx.py编译,可能有些非法语句。
因为我连接的服务器只能进行命令行操作,没有图形界面,所以进行打印的语句都被注释掉了。

该示例的作用是:给一张图片,然后调用已经训练好的caffemodel(其实里边存的是网络的参数),通过深度学习的网络来给这张图片分类。最后得到的结果是该图是哪一类的。PS:在进一步学习caffe以后可以知道,caffe在训练的时候类别都是从1、2、3……往上排的,所以最后预测出的结果也只是一个数字,例如这个实例的结果是281,就是训练集的第281类,但是至于281代表什么,要到类别指定的那个文档中去查找,找到以后发现是tabby cat。

# 导入Python,numpy,matplotlib.import numpy as npimport matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as plt# display plots in this notebook#%matplotlib inline# set display defaultsplt.rcParams['figure.figsize'] = (10, 10)        # large imagesplt.rcParams['image.interpolation'] = 'nearest'  # don't interpolate: show square pixelsplt.rcParams['image.cmap'] = 'gray'  # use grayscale output rather than a (potentially misleading) color heatmap# 导入caffe,其中注意caffe的路径设置.# The caffe module needs to be on the Python path;# we'll add it here explicitly.import syscaffe_root = '/home/XIExl/caffe-master/'  # 这里要设置自己的路径sys.path.insert(0, caffe_root + 'python')sys.path.append("/home/XIExl/caffe-master/python")import caffe# If you get "No module named _caffe", either you have not built pycaffe or you have the wrong path# 第一次运行需要联网下载模型.该部分如果报错的话建议删掉,自己手动下载,即到scripts目录下执行download_model_binary.py,然后查看models/bvlc_reference_caffenet目录下是否有bvlc_reference_caffenet.caffemodelimport osif os.path.isfile(caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'):    print 'CaffeNet found.'else:    print 'Downloading pre-trained CaffeNet model...'    os.system('../scripts/download_model_binary.py ../models/bvlc_reference_caffenet')# 设置CPU模式并从本地加载网络.caffe.set_mode_cpu()model_def = caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt'model_weights = caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'net = caffe.Net(model_def,      # defines the structure of the model                model_weights,  # contains the trained weights                caffe.TEST)     # use test mode (e.g., don't perform dropout)# CaffeNet默认的输入图像格式是BGR模式,像素值是[0,255]然后减去ImageNet的像素平均值,而且图像通道的维数是在第一维。# matplotlib导入图像的格式是RGB,像素值的范围是[0,1],通道维数在第三维,所以我们需要进行转换。# load the mean ImageNet image (as distributed with Caffe) for subtractionmu = np.load(caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy')mu = mu.mean(1).mean(1)  # average over pixels to obtain the mean (BGR) pixel valuesprint 'mean-subtracted values:', zip('BGR', mu)# create transformer for the input called 'data'transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})transformer.set_transpose('data', (2,0,1))  # move image channels to outermost dimensiontransformer.set_mean('data', mu)            # subtract the dataset-mean value in each channeltransformer.set_raw_scale('data', 255)      # rescale from [0, 1] to [0, 255]transformer.set_channel_swap('data', (2,1,0))  # swap channels from RGB to BGR# 设置输入的大小net.blobs['data'].reshape(50,        # batch size                          3,         # 3-channel (BGR) images                          227, 227)  # image size is 227x227# 加载图片并转换image = caffe.io.load_image(caffe_root + 'examples/images/cat.jpg')transformed_image = transformer.preprocess('data', image)plt.imshow(image)# 进行分类# copy the image data into the memory allocated for the netnet.blobs['data'].data[...] = transformed_image### perform classificationoutput = net.forward()output_prob = output['prob'][0]  # the output probability vector for the first image in the batchprint 'predicted class is:', output_prob.argmax()# 如果正确输出,会看到我们输入的图片得到的类别可能是第281类,但是并不知道它对应的标签,加载ImageNet的标签(首次需要联网,若报错,可手动下载到data/ilsvrc12目录下执行get_ilsvrc_aux.sh)。labels_file = caffe_root + 'data/ilsvrc12/synset_words.txt'if not os.path.exists(labels_file):os.system('../data/ilsvrc12/get_ilsvrc_aux.sh')labels = np.loadtxt(labels_file, str, delimiter='\t')print 'output label:', labels[output_prob.argmax()]# sort top five predictions from softmax outputtop_inds = output_prob.argsort()[::-1][:5]  # reverse sort and take five largest itemsprint 'probabilities and labels:'zip(output_prob[top_inds], labels[top_inds])

若为首次执行,该过程中可能会出现一些问题,下面就我出现的问题进行记录。

matplotlib安装

复制该指导中的代码到test.py再使用python test.py进行测试,开始报错ImportError: No module named matplotlib.pyplot,这是因为没有安装matplotlib。参考http://matplotlib.org/faq/installing_faq.html
检测有没有安装matplotlib的方法有两种:一为whereis matplotlib,如果结果中没有则没有安装;二为写一个脚本调用一下matplotlib,如果报错没有该包则没有安装。例如,simple_plot.py,内容:

from pylab import *plot([1,2,3])show()

安装方式如下:

git clone git://github.com/matplotlib/matplotlib.gitcd matplotlibpython setup.py install

这里报错,ImportError: cannot import name check_output,原因是机器上装了两个版本的python(2.6.6和2.7.9)而且默认的是2.6.6,但是check_output是在2.7上。
查看默认版本的方法即直接在命令行输入python。

# pythonPython 2.6.6 (r266:84292, Jul 10 2013, 22:48:45) [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> # /usr/local/bin/python2.7Python 2.7.9 (default, Oct  8 2013, 15:53:09) [GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> # which python/usr/bin/python

因为系统预安装的是2.6版本的,便有很多系统应用是基于2.6,一些由2.6版本写的程序用2.7版本执行也是有风险的,因此鲁莽地卸载掉2.6是不明智的。
解决方法:把python2.7改成默认的就好

vim ~/.bashrcalias python=/usr/local/bin/python2.7

这时在命令行输入python,得到是2.7.9版本
参考:http://stackoverflow.com/questions/19256127/two-versions-of-python-on-linux-how-to-make-2-7-the-default

3.2 numpy安装

安装完成matplotlib后,再运行test.py,报错ImportError: No module named numpy,但是这一句是在matplotlib之前的,为什么之前这里没有报错呢?其实机器上是安装了numpy的,只是之前安装的是基于python2.6的,现在把默认的python2.7版本的了,所以需要重新安装。
numpy1.9.2下载地址: https://sourceforge.net/projects/numpy/files/NumPy/1.9.2/
本地下载推送到服务器后,直接解压缩,python setup.py install即可。
事实证明应该下载1.11版本的,之后报错Importing opencv and getting numpy.core.multiarray failed to import
原因:是当前的numpy版本不是最新的
改正方法:

pip install –U numpy

参考http://stackoverflow.com/questions/28157976/importing-opencv-and-getting-numpy-core-multiarray-failed-to-import

matplotlib的相关模块

ImportError: No module named six
下载python的six模块并安装,下载地址:https://pypi.python.org/pypi/six/
安装方式与numpy同。

ImportError: matplotlib requires dateutil
For some reason, uninstalling and reinstalling python-dateutil fixes this issue.

pip install python-dateutil

注:使用pip的前提是需要pip安装在当前默认的版本下。
参考:https://www.quora.com/How-do-I-resolve-the-error-in-Python-opencv-ImportError-matplotlib-requires-dateutil

其他各种报错及解决方法

  • 1

%matplotlib inline
SyntaxError: invalid syntax

%并不是标准python中的符号,这是python编辑器ipython中的命令。所以%这行会报错。

解决方法1,下载一个ipython,但是我没有安装成功;
解决方法2,忽略这一行,继续使用其他编辑器,当然,因为给出的例子是ipython写的,所以后边还可能会出现类似的问题。

参考http://www.gossamer-threads.com/lists/python/python/1237953

  • 2

ImportError: No module named functools32
解决方法是

pip install functools32

然而又报错
RuntimeError: maximum recursion depth exceeded in cmp
解决方法是

pip install --upgrade distribute 

参考http://stackoverflow.com/questions/31273332/pip-install-upgrade-sqlalchemy-gives-maximum-recursion-depth-exceeded

  • 3

ImportError: No module named _tkinter

先安装tkinter,然后再重新编译安装python。

参考http://www.qttc.net/201304306.html

  • 4

cp: omitting directory `XXX’

原因:这是文件夹,里边还有内容不能直接复制。

解决方法:命令后边加 -r 就好了。

参考http://chenzhou123520.iteye.com/blog/1624671

  • 5

ImportError: No module named caffe
解决方法:

make pycaffemake distribute

参考https://github.com/BVLC/caffe/issues/263

如果已经编译过pycaffe了还报该错,可以尝试以下解决方法

find –name .bashrc /home #在/home下找文件.bashrc

然后找到在/home/admin/.bashrc

vim .bashrc

加一行

export PYTHONPATH=/your/caffe/dir/python

我的路径是export PYTHONPATH=/root/caffe-master/python
然后在test.py中import sys后加一行sys.path.append(“/root/caffe-master/python”)
参考https://groups.google.com/forum/#!topic/caffe-users/paNIlx1ynYU
https://github.com/BVLC/caffe/issues/720
http://seraphli.insecterswar.com/archives/tag/caffe

  • 6

python.h:No such file or directory

因为python2.7是后来安装的,系统自带的是python2.6,所以机器上在/usr/include/目录下只有python2.6文件夹里有Python.h,而caffe是用2.7编译的,所以报错说找不到Python.h,我的解决方式是找到2.7的,然后拷过去。

cp -r /usr/local/python27/include/python2.7 /usr/include/python2.7

参考http://blog.csdn.net/hello_orange/article/details/6184420

  • 7

ImportError: No module named skimage.io

pip install scikit-image

参考https://github.com/BVLC/caffe/issues/50

  • 8

ImportError: No module named google.protobuf.internal

原因:之前在安装protobuf的时候没有编译python接口

改正:

cd ~/protobuf-2.5.0/pythonpython setup.py buildpython setup.py testpython setup.py install

参考http://www.voidcn.com/blog/woainiwss/article/p-5002715.html

  • 9

RuntimeError: Could not open file /root/caffe-master/models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel
有人说需要先下载,然后才能打开,可是我进入/root/caffe-master/models/bvlc_reference_caffenet目录下看,明明是有bvlc_reference_caffenet.caffemodel这个文件的。
但是我又没有好的解决方案,只能姑且一试。

cd scriptspython download_model_binary.py

然后又报错,ImportError: No module named yaml

pip search yamlpip install pyyaml

参考http://stackoverflow.com/questions/14261614/how-do-i-install-the-yaml-package-for-python

然后又报错error: too few arguments

原因:说参数不够。也就是说,调用download_model_binary.py是要写参数的,这个脚本是用来下载模型参数的,要在调用的时候给出下载文件的目标文件夹。

python download_model_binary.py /root/caffe-master/models/bvlc_reference_caffenet
  • 10

no display name and no $DISPLAY environment variable

vim test.pyimport matplotlibmatplotlib.use(‘Agg’)

参考:http://stackoverflow.com/questions/2801882/generating-a-png-with-matplotlib-when-display-is-undefined

  • 11
Traceback (most recent call last):      File "examples/myfile/usenet.py", line 61, in <module>      output_prob = output['prob'][0] # the output probability vector for the first image in the batch                        ^     KeyError: 'prob'

在我改了网络配置信息后报了这个错。

原因:prob是示例网络配置中最后一层(softmax)的输出结果名称。换了新的配置文件后,最后一层不是这个,也没有叫prob的关键词。

更改办法:把示例网络中的最后一层复制到新的测试文件中。

  • 12

Check failed: mdb_status == 0 (2 vs. 0) No such file or directory
原因:lmdb路径不对。
修改方法:在定义网络的配置文件中修改(例如lenet_auto_test.prototxt)

  • 13

在终端里不能按ctrl+S,不然终端就停了,没有反应了。
因为在linux终端中,ctrl+S的意思是暂停该终端,如果误按了,要退出这种状态,让终端继续运行,很简单,按下Ctrl + q就行了

0 0
原创粉丝点击