minist例子相当于深度学习中的'hello,world'
下面以lasagne中的minist为原型解析:
首先需要了解使用的数据集:
minist数据集:共有100000张图片,每张图片大小为28X28,通道数为1,如果是彩色图片,通道数为3,图片显示为0~9手写体数字,每张图片仅包含一个数字,训练集为80000张图片,测试集为20000图片。
1.加载包:
import numpy as np
import theano
import theano.tensor as T
import lasagne
lasagne使用的底层包为theano
2.加载数据集:
def load_dataset(): 3.建立训练模型,分为3种:
A.Multi-Layer Perceptron(MLP)
该网络是在全连接网络中加入了dropoutLayer,防止过拟合,是最简单的一种网络结构。
输入层:
def build_mlp(input_var = None):
l_in = lasagne.layers.InputLayer(shape=(None,1,28,28),input_var = input_var)
l_in_drop = lasagne.layers.DropoutLayers(l_in,p=0.2)
隐藏层:
l_hid1 = lasagne.layers.DenseLayer(
l_in_drop, num_units=800,
nonlinearity=lasagne.nonlinearities.rectify,
W=lasagne.init.GlorotUniform())
神经元个数为800,激活函数为RELU,W为权重初始值
隐藏层加入dropout
l_hid1_drop = lasagne.layers.DropoutLayer(l_hid1, p=0.5)
l_hid2 = lasagne.layers.DenseLayer(
l_hid1_drop, num_units=800,
nonlinearity=lasagne.nonlinearities.rectify)
l_hid2_drop = lasagne.layers.DropoutLayer(l_hid2, p=0.5)
每层的dropout值为0.5
最后是输出层:
l_out = lasagne.layers.DenseLayer(
l_hid2_drop, num_units=10,
nonlinearity=lasagne.nonlinearities.softmax)
神经元个数为10,表示有10个类别,因为数字有10种,激活函数为softmax,一般softmax都是在输出层,表示每个类别的概率是多少,方便对输出的理解与计算。
B.Custom MLP
第二种函数稍微延伸一下:
def build_custom_mlp(input_var=None, depth=2, width=800, drop_input=.2,
drop_hidden=.5):
默认参数会构建一个和上述一样的网络,但是用户也可以通过修改参数自定义输入大小,dropout参数和每层的神经元个数,这比直接调用层更加灵活。
# Input layer and dropout (with shortcut `dropout` for `DropoutLayer`):
network = lasagne.layers.InputLayer(shape=(None, 1, 28, 28),
input_var=input_var)
if drop_input:
network = lasagne.layers.dropout(network, p=drop_input)
# Hidden layers and dropout:
nonlin = lasagne.nonlinearities.rectify
for _ in range(depth):
network = lasagne.layers.DenseLayer(
network, width, nonlinearity=nonlin)
if drop_hidden:
network = lasagne.layers.dropout(network, p=drop_hidden)
# Output layer:
softmax = lasagne.nonlinearities.softmax
network = lasagne.layers.DenseLayer(network, 10, nonlinearity=softmax)
return network
通过两个if子句和一个for循环,这个网络定义允许改变架构,这是Pylearn2中的.yaml文件或cuda-convnet中的.cfg文件所做不到的。
注意,为了使代码更容易,在这里所有的层只是称为网络,没有必要给他们不同的名称,如果我们返回的是我们创建的最后一个层; 我们只是使用不同的名称。
C. Convolutional Neural Network (CNN)
最后,build_cnn()函数创建两个卷积层和池级的CNN和完全连接的隐藏层和完全连接的输出层。 该函数开始像其他函数:
def build_cnn(input_var=None):
network = lasagne.layers.InputLayer(shape=(None, 1, 28, 28),
input_var=input_var)
我们不对输入应用dropout,因为这对于卷积层来说往往不太有效。 而不是DenseLayer,我们现在添加一个Conv2DLayer,有32个滤波器,每个大小为
5x5
:
network = lasagne.layers.Conv2DLayer(
network, num_filters=32, filter_size=(5, 5),
nonlinearity=lasagne.nonlinearities.rectify,
W=lasagne.init.GlorotUniform())
接下来定义一个池化层:
network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2))
和上面一样,再定义一个卷积层和一个池化层
network = lasagne.layers.Conv2DLayer(
network, num_filters=32, filter_size=(5, 5),
nonlinearity=lasagne.nonlinearities.rectify)
network = lasagne.layers.MaxPool2DLayer(network, pool_size=(2, 2))
接着是一个256个神经元的全连接层,drop = 0.5
network = lasagne.layers.DenseLayer(
lasagne.layers.dropout(network, p=.5),
num_units=256,
nonlinearity=lasagne.nonlinearities.rectify)
最后是一个softmax,神经元个数和类别数一致为10
network = lasagne.layers.DenseLayer(
lasagne.layers.dropout(network, p=.5),
num_units=10,
nonlinearity=lasagne.nonlinearities.softmax)
return network
4.训练网络
数据如何输入网络?需要对加载的数据再预处理一下。
为防止输入的训练集相同类别的都在一起我们需要把输入打乱,如果输入本身就是乱的这步就不需要了。
def iterate_minibatches(inputs, targets, batchsize, shuffle=False):
if shuffle:
...
for ...:
yield inputs[...], targets[...]
准备工作:
X_train, y_train, X_val, y_val, X_test, y_test = load_dataset()
# Prepare Theano variables for inputs and targets
input_var = T.tensor4('inputs')
target_var = T.ivector('targets')
# Create neural network model
network = build_mlp(input_var)
加载数据集,创建输入和输出,这里的类型为theano中张量,其本质还是向量,
input_var为4维向量(,1,28,28)第一维为batch size。输出为一维向量。
定义损失函数和更新参数:
lasagne.objectives里含有各种损失函数:
binary_crossentropy |
Computes the binary cross-entropy between predictions and targets. |
categorical_crossentropy |
Computes the categorical cross-entropy between predictions and targets. |
squared_error |
Computes the element-wise squared difference between two tensors. |
binary_hinge_loss |
Computes the binary hinge loss between predictions and targets. |
multiclass_hinge_loss |
Computes the multi-class hinge loss between predictions and targets. |
params = lasagne.layers.get_all_params(network, trainable=True)
updates = lasagne.updates.nesterov_momentum(
loss, params, learning_rate=0.01, momentum=0.9)
定义测试集的损失函数,和训练集一样,只是换了个名称。
test_prediction = lasagne.layers.get_output(network, deterministic=True)
test_loss = lasagne.objectives.categorical_crossentropy(test_prediction, target_var) test_loss = test_loss.mean()
test_acc = T.mean(T.eq(T.argmax(test_prediction, axis=1), target_var),dtype=theano.config.floatX)
这里需要说明,test_prediction是一个1X10的向量,
T.argmax(test_prediction, axis=1),求出该向量中元素的最大值的下标,和target_var比较,所以target_var是一个常量,不是向量
把定义好的损失函数包装好:
train_fn = theano.function([input_var, target_var], loss, updates=updates)
val_fn = theano.function([input_var, target_var], [test_loss, test_acc])
最后是整个训练流程
for epoch in range(num_epochs):
# In each epoch, we do a full pass over the training data:
train_err = 0
train_batches = 0
start_time = time.time()
for batch in iterate_minibatches(X_train, y_train, 500, shuffle=True):
inputs, targets = batch
train_err += train_fn(inputs, targets)
train_batches += 1
# And a full pass over the validation data:
val_err = 0
val_acc = 0
val_batches = 0
for batch in iterate_minibatches(X_val, y_val, 500, shuffle=False):
inputs, targets = batch
err, acc = val_fn(inputs, targets)
val_err += err
val_acc += acc
val_batches += 1
# Then we print the results for this epoch:
print("Epoch {} of {} took {:.3f}s".format(
epoch + 1, num_epochs, time.time() - start_time))
print(" training loss:\t\t{:.6f}".format(train_err / train_batches))
print(" validation loss:\t\t{:.6f}".format(val_err / val_batches))
print(" validation accuracy:\t\t{:.2f} %".format(
val_acc / val_batches * 100))
每次输入500张图片训练,计算损失,修正权重,直到训练集都输入一遍,一个训练周期结束,开始下一个训练周期。
测试时每次输入500张图片,计算误差,当测试集全部输入完毕汇总误差计算总体误差。