为了caffe(七)做kaggle上的mnist

 

为了caffe(七)做kaggle上的mnist

 

因为蠢啊,因为不懂才写这么详细啊

 


这篇文正对我来说重点的问题是: 把test.csv文件,输入网络进行预测,再把结果保存在csv文件里面。 本质上说是数据格式转化,和,对函数各个参数的理解


第0步:

刚刚不能验证注册kaggle,注册需要VPN翻墙一下

 

 

 

 

 

 

第一步:

 老样子 

 

dong@dong-Lenovo-G480:~$ sudo modprobe nvidia_352_uvm

[sudo] password for dong:

dong@dong-Lenovo-G480:~$ ./NVIDIA_CUDA-7.5_Samples/bin/x86_64/linux/release/deviceQuery

./NVIDIA_CUDA-7.5_Samples/bin/x86_64/linux/release/deviceQuery Starting...

 

 CUDA Device Query (Runtime API) version (CUDART static linking)

 

Detected 1 CUDA Capable device(s)

 

Device 0: "GeForce 610M"

  CUDA Driver Version / Runtime Version          7.5 / 7.5

  CUDA Capability Major/Minor version number:    2.1

  Total amount of global memory:                 1024 MBytes (1073479680 bytes)

  ( 1) Multiprocessors, ( 48) CUDA Cores/MP:     48 CUDA Cores

  GPU Max Clock rate:                            950 MHz (0.95 GHz)

  Memory Clock rate:                             900 Mhz

  Memory Bus Width:                              64-bit

  L2 Cache Size:                                 65536 bytes

  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65535), 3D=(2048, 2048, 2048)

  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers

  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers

  Total amount of constant memory:               65536 bytes

  Total amount of shared memory per block:       49152 bytes

  Total number of registers available per block: 32768

  Warp size:                                     32

  Maximum number of threads per multiprocessor:  1536

  Maximum number of threads per block:           1024

  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)

  Max dimension size of a grid size    (x,y,z): (65535, 65535, 65535)

  Maximum memory pitch:                          2147483647 bytes

  Texture alignment:                             512 bytes

  Concurrent copy and kernel execution:          Yes with 1 copy engine(s)

  Run time limit on kernels:                     No

  Integrated GPU sharing Host Memory:            No

  Support host page-locked memory mapping:       Yes

  Alignment requirement for Surfaces:            Yes

  Device has ECC support:                        Disabled

  Device supports Unified Addressing (UVA):      Yes

  Device PCI Domain ID / Bus ID / location ID:   0 / 1 / 0

  Compute Mode:

     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

 

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 7.5, CUDA Runtime Version = 7.5, NumDevs = 1, Device0 = GeForce 610M

Result = PASS

dong@dong-Lenovo-G480:~$ python

Python 2.7.12 |Anaconda custom (64-bit)| (default, Jul  2 2016, 17:42:40)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

Anaconda is brought to you by Continuum Analytics.

Please check out: http://continuum.io/thanks and https://anaconda.org

>>> import caffe

/home/dong/anaconda2/lib/python2.7/site-packages/matplotlib/font_manager.py:273: UserWarning: Matplotlib is building the font cache using fc-list. This may take a moment.

  warnings.warn('Matplotlib is building the font cache using fc-list. This may take a moment.')

>>>

 

红色字部分先做一边,一步都不能少

 

 

 

 

 

 

第二步

 

http://blog.csdn.net/bea_tree/article/details/51704838

参考这位大哥的

 

但是我针对人家的训练集训练,还是用了上一篇文章的caffemodel,,,

准确率0.23  呵呵                                                   


 后面写:这是因为我的就是这个准确率??还是代码其实写错了导致的,想了想caffemodel,生成的时候用的数据是:3通道的图片,测试的时候输入的可是单通道的数据啊!那是因为这个原因不行吗?     想要知道为什么可以在spyder里面运行两份代码,看看输入网络的测试的那个图到底是什么数据??还没做这步

 

第三步:

换成官方的lenet_iter_10000.caffemodel更烂了,预料之用,自己的deploy +官方的caffemodel ,果然不行啊                 后面写:其实这时候不行是因为我的deploy文件写错了

 

 

 

第四步

 

csv文件--》读取csv文件---》转化为lmdb文件    搞不定啊   什么也看不懂啊           后面写:我也不需要这个lmdb文件训练吧,我前面用60000个训练集,进行了训练,得到了caffemodel。

 

第五步

用官方lenet_iter_10000.caffemodel   ,自己写一个基于官方lenet_train_test 文件的deploy文件

先把正确率提上去  (就算过了第四步,还是要有一个deploy,那时候可以用自己的了)

 

失败

乱七八糟的  呵呵   
后面写:其实这时候不行是因为我的deploy文件写错了

 

 

 

 

第六步::  解决了下面所有问题后   终于成功了!!!!!


 成功的代码:

import matplotlib.pyplot as plt

import numpy as np
import pandas as pd
import lmdb
import caffe
import sys

from  sklearn.cross_validation import train_test_split


caffe_root = '/home/dong/caffe/' 

sys.path.append(caffe_root+'python')


model_file = '/home/dong/caffe/examples/mnist/deploy/deploydong.prototxt'
###这里用了 修改自官方网络的deploy文件和 用官方网络训练出来的caffemodel(对,就是那个训练集60000张图的那个)
## 而不使用  <span style="font-family: Arial, Helvetica, sans-serif;">修改自 自己写的 网络的deploy文件和 用自己网络训练出来的caffemodel,虽然自己网络和官方网络仅有一丁点不同,但是它的正确率仅为20%左右</span>
<span style="font-family:Arial, Helvetica, sans-serif;">###后面的问题7 涉及到了这个问题,   我猜是csv数据处理出来是,单通道。自己网络是3通道黑白图,训练的??是吗?下次吧,下次试试
</span>
pretrained = '/home/dong/caffe/examples/mnist/lenet_iter_10000.caffemodel'




net = caffe.Classifier(model_file, pretrained,image_dims=(28, 28))####这个函数返回一个net,我也是直接搜索这个函数,又从很多网页里推断出来的,它可以被叫做别的名字,但它本质就是一个net
caffe.set_device(0)
caffe.set_mode_gpu()


test=pd.read_csv('/home/dong/kaggle_mnist/test.csv')  #很关键的csv文件处理方法,怎么测试数据输入,的办法
test_array=test.values
n=np.shape(test_array)[0]
 
a=[]

for i in xrange(n):
    input=test_array[i,:]/255.                           #很关键的csv文件处理方法
    input=input.reshape((1,28,28,1))         
    prediction=net.predict(input,oversample=False)   ####就这样输入测试数据
    #prediction=net.predict(input)
    reslut =prediction[0].argmax()
    a.append(reslut)
    
    
ImageId=[i+1 for i in range(n)]
submit_pd=pd.DataFrame({'ImageId':ImageId,'Label':a})
submit_pd.to_csv('/home/dong/kaggle_mnist/model.csv',index=False)


'''

prediction = net.predict([input_image])  # predict takes any number of images, and formats them for the Caffe net automatically
print 'prediction shape:', prediction[0].shape
plt.plot(prediction[0])
print 'predicted class:', prediction[0].argmax()

prediction = net.predict([input_image], oversample=False)
print 'prediction shape:', prediction[0].shape
plt.plot(prediction[0])
print 'predicted class:', prediction[0].argmax()
'''


 结果:

ImageId	Label
1	2
2	0
3	9
4	0
5	3
6	7
7	0
8	3
9	0
10	3
11	5
12	7
13	4
14	0
15	4
16	3
17	3

 

 最后上交kaggle得到的 正确率是:


0.99786   排名第25名    哇 好开心



 

问题1 

import lmdb  ImportError: No module named lmdb

 

解决:

http://stackoverflow.com/questions/30769048/error-in-creating-lmdb-database-file-in-python-for-caffe

 

 

 

Well, the apt-get install liblmdb-devmight work with bash (in the terminal) but apparently it doesn't work with Anaconda Python. I figured Anaconda Python might require it's own module for lmdb and I followedthislink. The Python installation for lmdb module can be performed byrunning the commandpip install lmdbin the terminal. And then import lmdbin Python works like a charm!

apt-get install是按在系统上的

pip install 是安装在python上的,特别是此处我用的就是 Anaconda,

 

 

 

问题2 支持的数据源

 

这是开始尝试使用Caffe时要克服的首要心理障碍之一。它不像使用一些CSV来提供Caffe可执行的方式那样简单。实际上,对于没有图像的数据,你有三种选择。

 

• LMDB(闪电内存映射数据库),,,,只用这个

• LevelDB

• HDF5格式

 

HDF5可能是最容易使用的,因为你只需要采用HDF5格式把数据集存储到文件中。LMDB和LevelDB是数据库,所以你必须按照他们的协议。HDF5格式存储数据集的大小会被内存限制,这就是为什么我抛弃它的原因。LMDB和LevelDB之间的选择是相当随便的——从我掠过的资源来看,LMDB似乎更强大,速度更快,更成熟。然后从GitHub来看,LevelDB的维护似乎更积极,也具有较大的Google和StackOverflow的足迹。

 

 

问题3 官方是怎么生成lmdb文件的

 比如说mnist  

home/dong/caffe/examples/mnist/convert_mnist_data.cpp

把原始非图像数据(一个图像数据,一个标签数据)转化为lmdb

再比如cifar10也有类似的文件,

但是看不懂啊   

 

问题4 

python  flatten()函数 ::变成一个元组,元组里面只有一个列表

 

python 元组  ()

列表list   用【】

 

 

array 

 

问题5

    #prediction=net.predict(input,oversample=False)    正确率0.23243

    prediction=net.predict(input)   正确率 0.15343

有什么区别啊?                                                    后面写::这个问题不是很懂,后面也没有测试

 

 

 

问题6

model_file = '/home/dong/mnist/deploy.prototxt'   

pretrained = '/home/dong/caffe/examples/mnist/lenet_iter_10000.caffemodel'

 

0.14271,

 

 

 

问题7::  莫名其妙的崩溃:

如果运行这几行

model_file = '/home/dong/caffe/examples/mnist/deploy/deploy.prototxt'

pretrained = '/home/dong/caffe/examples/mnist/lenet_iter_10000.caffemodel'

net = caffe.Classifier(model_file, pretrained,image_dims=(28, 28))

 

就会崩溃,Spyder崩溃

It seems the kernel died unexpectedly. Use 'Restart kernel' to continue using this console.

解决过程:

 spyder只显示崩溃,不显示具体在哪一步坏了。。。

换到ipython上进行调试。

 

F0831 17:33:28.100298  8095 insert_splits.cpp:29] Unknown bottom blob 'data' (layer 'conv1', bottom index 0)

就是deploy文件写错了

 

layer {

  name: "data"

  type: "Input"

  input:"data" 加上这行

 

 

  input_param { shape: { dim: 1 dim: 3 dim: 28 dim: 28 } }

}

还是不行:

[libprotobuf ERROR google/protobuf/text_format.cc:245] Error parsing text-format caffe.NetParameter: 5:8: Message type "caffe.LayerParameter" has no field named "input".

F0831 17:36:36.218029  8170 upgrade_proto.cpp:79] Check failed: ReadProtoFromTextFile(param_file, param) Failed to parse NetParameter file: /home/dong/caffe/examples/mnist/deploy/deploydong.prototxt

*** Check failure stack trace: ***

Aborted (core dumped)

 

 

 

不行

Network initialization done.

I0831 17:42:47.176527  8242 net.cpp:761] Ignoring source layer mnist

F0831 17:42:47.176565  8242 net.cpp:774] Cannot copy param 0 weights from layer 'conv1'; shape mismatch.  Source param shape is 20 1 5 5 (500); target param shape is 20 3 5 5 (1500). To learn this layer's parameters from scratch rather than copying from a saved net, rename the layer.

*** Check failure stack trace: ***

Aborted (core dumped)

 

不行

831 18:03:07.601783  8421 net.cpp:434] conv2 <- pool1

I0831 18:03:07.601795  8421 net.cpp:408] conv2 -> conv2

F0831 18:03:07.602075  8421 blob.cpp:115] Check failed: data_

*** Check failure stack trace: ***

 

瞎比改  应该看看教程啊

http://blog.csdn.net/sunshine_in_moon/article/details/49472901写deploy.prototxt的注意事项

 

看完教程还有这个错误

 

F0831 17:42:47.176565  8242 net.cpp:774] Cannot copy param 0 weights from layer 'conv1'; shape mismatch.  Source param shape is 20 1 5 5 (500); target param shape is 20 3 5 5 (1500). To learn this layer's parameters from scratch rather than copying from a saved net, rename the layer.

*** Check failure stack trace: ***

 

解决办法

 

name: "LeNet"

 

input:"data"

input_dim:1

input_dim:1   ##这里一开始是3 表示三通道,,但是我用的都是黑白的,是一层图片,应该用1。

原作者http://www.cnblogs.com/denny402/p/5685818.html,用的3,是因为人家在下一篇文章里面输入的是png图片来分类啊,虽然是黑白的图片,但是还是一个3通道的图片啊。。。这样就理解了

 

input_dim:28

input_dim:28 

因为蠢啊,因为不懂才写这么详细啊
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
在Ubuntu上安装Caffe,可以按照以下步骤进行操作: 1. 安装依赖: - 打开终端并执行以下命令: ``` sudo apt-get update sudo apt-get install build-essential cmake git pkg-config libprotobuf-dev libleveldb-dev libsnappy-dev libhdf5-serial-dev protobuf-compiler libgflags-dev libgoogle-glog-dev liblmdb-dev libatlas-base-dev libopenblas-dev libopencv-dev python3-dev ``` 2. 克隆Caffe源代码: - 执行以下命令克隆Caffe的Github仓库: ``` git clone https://github.com/BVLC/caffe.git ``` 3. 修改配置: - 进入Caffe源代码目录: ``` cd caffe ``` - 复制Makefile.config.example文件并重命名为Makefile.config: ``` cp Makefile.config.example Makefile.config ``` - 使用文本编辑器打开Makefile.config文件并进行必要的修改: ``` vim Makefile.config ``` - 根据你的系统配置,可以修改以下选项: - `CPU_ONLY`设置为`1`以仅使用CPU(如果你没有安装NVIDIA GPU驱动和CUDA) - 如果你使用NVIDIA GPU进行加速,请确保以下选项设置正确: - `CUDA_DIR`:CUDA安装路径 - `CUDA_ARCH`:你的NVIDIA GPU架构 - 如果你使用OpenCV 3.x,请设置以下选项: - `OPENCV_VERSION`:3 - `INCLUDE_DIRS`和`LIBRARY_DIRS`:根据你的OpenCV 3.x安装路径进行设置 4. 编译和安装Caffe: - 执行以下命令编译Caffe: ``` make all -j$(nproc) make test -j$(nproc) make runtest -j$(nproc) make pycaffe -j$(nproc) make distribute ``` - 执行以下命令将Caffe安装到系统目录: ``` sudo make install ``` 现在,你已经成功在Ubuntu上安装了Caffe

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值