windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

事情的由来

深度学习,有种让人上瘾的感觉,你学的越多,发现自己欠缺的越多,这是一个跨学科的技术,需要一个系统学习的过程。但我个人认为深度学习的前景真的很好,虽然现在有点过热的现象,甚至有点吹过头的感觉。
之前看了几本书,学了一下理论知识,然后就打算搞个环境实践一下,这个作为本人深度学习的环境搭建笔记,简单做个记录。毕竟,搭建环境一般都是各种坑,浪费时间,我们应该把更多的时间花在学习理论知识和编程实践上面去。可是,工欲善其事,必先利其器,这一步又是绕不过去的。
之前都是用cpu来做练习,发现cpu基本没什么用,运算太慢了,后来实在受不了了,就去买了个便宜显卡,装上之后发现计算速度提升至少50倍,虽然大型网络还是训练不了,但对于书上的例子,是全部都没问题的,都是几分钟就可以算完出结果。

第一步,你得先有个windows7操作系统

这是我电脑的配置,很一般哈。
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

第二步,去买个显卡

我买的是很便宜的显卡,毕竟,只是为了学习一些简单的案例,这个2G内存的显卡对我来说够了,再便宜的显卡估计就不好用了,可能连软件都不支持了。我这个显卡都需要用一些旧版本的软件,最新的都不支持
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
显卡的驱动理论上要去官网下载,可是我硬是没找到在哪里下载,最后用驱动精灵,驱动了一下,也挺好的。
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

第三步,先搞定caffe

微软公司为windows专门提供了一个caffe的分支,最好安装这个,安装这个会非常方便
https://github.com/microsoft/caffe
可以先仔细看看页面下方的安装指导,我就是按照这个指导一步一步安装的

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

cuda的安装比较简单,下一步,下一步就好了,cudnn安装其实就是把cudnn解压出来,放到cuda的安装目录下就可以了,就像这样:
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
把从GitHub下载下来的源码包解压后,进入Windows目录,用visual studio 2013打开caffe.sln
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
按照GitHub上的说明,Copy .\windows\CommonSettings.props.example to .\windows\CommonSettings.props,我只修改了一个地方,就是那个CuDnnPath,在这个配置里面填了个$(CUDA_PATH),如下图所示,然后就“生成解决方案”,(编译caffe所需要的各种依赖,vs2013都会帮你搞定)等了好久,出了n多警告,最终效果如下:
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
验证一下,caffe是不是可以用了
首先去caffe-master/data/mnist目录下执行脚本下载mnist的数据集,结果发现这个脚本是Linux系统的shell脚本,我是把这个脚本考到Linux虚拟机中,运行一下下载了四个文件,再把四个文件拷贝到Windows系统中的,其实,打开这个脚本看看,写的很简单,就是从一个网址下载文件,其实也可以把文件链接复制出来,自己下载也是可以的,下载完了,还要解压一下,最后的文件是这样的:
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

下载下来的原始数据集为二进制文件,需要转换为LEELDB或者LMDB才能被Caffe识别。有个脚本可以用来转换:caffe-master/examples/mnist/create_mnist.sh 可惜的是它也是个shell脚本,打开看看,也很简单,意思就是说,用一个程序去转换,而这个程序其实已经被我们编译出来了,就是convert_mnist_data.exe (linux系统下编译出来的后缀才是bin)
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
把caffe编译生成的可执行文件路径加入到系统的path环境变量中,这样,之后运行命令就可以不用带上完整的路径了
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
cd到原始数据所在目录caffe-master/data/mnist,运行一下命令:

convert_mnist_data.exe train-images-idx3-ubyte train-labels-idx1-ubyte mnist_train_lmdb --backend=lmdb
convert_mnist_data.exe t10k-images-idx3-ubyte t10k-labels-idx1-ubyte mnist_test_lmdb --backend=lmdb

得到两个文件夹,即转换好的数据
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
准备训练网络
查看caffe-master/examples/mnist/train_lenet.sh
感觉挺简单的
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

拷贝上一步生成的两个文件夹到caffe-master/examples/mnist/目录下
在cmd下执行命令训练网络,注意要cd到caffe-master那一级目录去执行caffe.exe命令,不然会出现找不到文件的问题,其中的lenet_solver.prototxt文件还使用了net: “examples/mnist/lenet_train_test.prototxt”,也是用的相对于caffe-master那一级目录

cd C:\Users\zhoushenghuang\Documents\Visual Studio 2013\Projects\caffe-master
caffe.exe train --solver=examples/mnist/lenet_solver.prototxt

用了一分钟左右,就训练完了,用gpu还是蛮快的,结果是如下,caffe应该是没有问题了
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

第四步, TensorFlow-GPU

强烈推荐使用Anaconda来安装TensorFlow和Keras,可以省很多事
首先,下载并按照Anaconda,没啥好说的
https://www.anaconda.com/download/
我下载安装的是Anaconda3-5.3.0-Windows-x86_64.exe
开始菜单->Anaconda3(64位)->Anaconda3 Prompt 启动命令提示符
输入命令 显示现有的python环境

conda info --envs

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
创建新的环境

conda create --name gpu-test python=3.6

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
**该环境,即进入该环境

activate gpu-test

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
搜索TensorFlow-GPU的安装包

conda search tensorflow-gpu

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
选择安装一个最低的版本,我试了其他的,好像都不行,对cuda的要求太高,我的显卡不支持那么高的cuda,从这个依赖项可以看出,还是需要cudatoolkit 8.0版本,和之前安装caffe时安装的cuda7.5不一样,还得再安装一个cuda8.0,还好,这两个是可以共存的

conda install tensorflow-gpu=1.1.0

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
验证一下TensorFlow-GPU是不是已经ok了
启动Pycharm,配置环境
使用 conda info --envs 可以看到环境的具体路径,把这个路径设置到pycharm里面去
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
运行一个示例程序看看结果

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import datetime
import tensorflow as tf
sess = tf.InteractiveSession()

# Create softmax regration model
# Generate placeholder variables to represent the input tensors.
# x is images placeholder
# y_ is Labels placeholder

x = tf.placeholder("float", shape=[None, 784])
y_ = tf.placeholder("float", shape=[None, 10])

# Create and init weight and bias variable
def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

# conv and pool
def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

# First layer CNN
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
x_image = tf.reshape(x, [-1,28,28,1])

# Convolve x_image with the weight tensor, add the bias,
# apply the ReLU function, and finally max pool.
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)

# Second layer CNN
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

# Intensive link layer
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

# Output, softmax layer (in the last example, the graph only have this layer)
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])

y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

starttime =  datetime.datetime.now()
print('Start:\t\t'+starttime.strftime("%Y-%m-%d %X"))

# Trainning and evaluate
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess.run(tf.global_variables_initializer ())
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print ("step %d, training accuracy %g"%(i, train_accuracy))
  train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

endtime =  datetime.datetime.now()
print('End:\t\t'+endtime.strftime("%Y-%m-%d %X"))
duringtime = endtime-starttime
print ('Spend Time:\t'+str(duringtime))

结果如下,TensorFlow已经启用GPU进行计算了:
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

第五步, Keras-GPU

搜索Keras-GPU的安装包

conda search keras-gpu

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
选择安装一个较低的版本,这个版本的选择和之前安装的TensorFlow的版本有关系,不能太高,因为keras会调用TensorFlow,我试了几下,发现这个2.1.2可以和之前的TensorFlow兼容。

conda install keras-gpu=2.1.2

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境
如果安装的版本不合适,可以删掉,再换个版本安装

conda uninstall keras-gpu

测试一下keras-gpu是不是搞定了

from keras import layers
from keras import models

model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPool2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPool2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
model.summary()

from keras.datasets import mnist
from keras.utils import to_categorical
(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
train_images = train_images.reshape((60000,28,28,1))
train_images = train_images.astype('float32')/255
test_images = test_images.reshape((10000,28,28,1))
test_images = test_images.astype('float32')/255
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
model.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(train_images,train_labels,epochs=5,batch_size=64)

test_loss,test_acc = model.evaluate(test_images,test_labels)
print(test_acc)

结果如下,keras应该也已经用上GPU了哈:
windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

windows7系统,NVIDIA GeForce GTX 750 Ti 2G显卡搭建caffe、TensorFlow、Keras深度学习GPU环境

第六步, 去看看caffe是不是好的

回到visual studio 2013,重新生成一下解决方案,发现找不到cudnn.h的头文件编译失败了.
管他三七二十一,把cudnn的文件从cuda7.5的文件夹拷贝到cuda8.0的文件夹,就解决了,估计还是那个CommonSettings.props文件里面的cudnn的路径没有设置好,算了,就这样吧,能用就行了

第七步,列几本入门的书

最后列几本入门的书,我觉得还不错的,我都看完了的:
1.Neural Networks and Deep Learning
2.Machine learning with tensorflow
3.deep learning with python
4.深度学习 21天实战caffe