本系列文章面向深度學習研發者,希望通過Image Caption Generation,一個有意思的具體任務,深入淺出地介紹深度學習的知識。本系列文章涉及到很多深度學習流行的模型,如CNN,RNN/LSTM,Attention等。本文為第9篇。
作者:李理
目前就職于環信,即時通訊云平臺和全媒體智能客服平臺,在環信從事智能客服和智能機器人相關工作,致力于用深度學習來提高智能機器人的性能。
相關文章:
李理:從Image Caption Generation理解深度學習(part I)
李理:從Image Caption Generation理解深度學習(part II)
李理:從Image Caption Generation理解深度學習(part III)
李理:Theano tutorial和卷積神經網絡的Theano實現 Part1
接上文。
7. 使用Theano實現CNN
接下來我們繼續上文,閱讀代碼network3.py,了解怎么用Theano實現CNN。
完整的代碼參考這里。
7.1 FullyConnectedLayer類
首先我們看怎么用Theano實現全連接的層。
class FullyConnectedLayer(object):? ? def __init__(self, n_in, n_out, activation_fn=sigmoid, p_dropout=0.0):? ? ? ? self.n_in = n_in? ? ? ? self.n_out = n_out? ? ? ? self.activation_fn = activation_fn? ? ? ? self.p_dropout = p_dropout? ? ? ? # Initialize weights and biases? ? ? ? self.w = theano.shared(? ? ? ? ? ? np.asarray(? ? ? ? ? ? ? ? np.random.normal(? ? ? ? ? ? ? ? ? ? loc=0.0, scale=np.sqrt(1.0/n_out), size=(n_in, n_out)),? ? ? ? ? ? ? ? dtype=theano.config.floatX),? ? ? ? ? ? name='w', borrow=True)? ? ? ? self.b = theano.shared(? ? ? ? ? ? np.asarray(np.random.normal(loc=0.0, scale=1.0, size=(n_out,)),? ? ? ? ? ? ? ? ? ? ? dtype=theano.config.floatX),? ? ? ? ? ? name='b', borrow=True)? ? ? ? self.params =[self.w, self.b]? ? def set_inpt(self, inpt, inpt_dropout, mini_batch_size):? ? ? ? self.inpt = inpt.reshape((mini_batch_size, self.n_in))? ? ? ? self.output = self.activation_fn(? ? ? ? ? ? (1-self.p_dropout)*T.dot(self.inpt, self.w) + self.b)? ? ? ? self.y_out = T.argmax(self.output, axis=1)? ? ? ? self.inpt_dropout = dropout_layer(? ? ? ? ? ? inpt_dropout.reshape((mini_batch_size, self.n_in)), self.p_dropout)? ? ? ? self.output_dropout = self.activation_fn(? ? ? ? ? ? T.dot(self.inpt_dropout, self.w) + self.b)? ? def accuracy(self, y):? ? ? ? "Return the accuracy for the mini-batch."? ? ? ? return T.mean(T.eq(y, self.y_out))
7.1.1 init
FullyConnectedLayer類的構造函數主要是定義共享變量w和b,并且隨機初始化。參數的初始化非常重要,會影響模型的收斂速度甚至是否能收斂。這里把w和b初始化成均值0,標準差為sqrt(1.0/n_out)的隨機值。有興趣的讀者可以參考這里。
此外,這里使用了np.asarray函數。我們用np.random.normal生成了(n_in, n_out)的ndarray,但是這個ndarray的dtype是float64,但是我們為了讓它(可能)在GPU上運算,需要用theano.config.floatX,所以用了np.asarray函數。這個函數和np.array不同的一點是它會盡量重用傳入的空間而不是深度拷貝。
另外也會把激活函數activation_fn和dropout保存到self里。activation_fn是一個函數,可能使用靜態語言習慣的讀者不太習慣,其實可以理解為c語言的函數指針或者函數式變成語言的lambda之類的東西。此外,init函數也把參數保存到self.params里邊,這樣的好處是之后把很多Layer拼成一個大的Network時所有的參數很容易通過遍歷每一層的params就行。
7.1.2 set_input
set_inpt函數用來設置這一層的輸入并且計算輸出。這里使用了變量名為inpt而不是input的原因是input是Python的一個內置函數,容易混淆。注意我們通過兩種方式設置輸入:self.inpt和self.inpt_dropout。這樣做的原因是我們訓練的時候需要dropout。我們使用了一層dropout_layer,它會隨機的把dropout比例的神經元的輸出設置成0。而測試的時候我們就不需要這個dropout_layer了,但是要記得把輸出乘以(1-dropout),因為我們訓練的時候隨機的丟棄了dropout個神經元,測試的時候沒有丟棄,那么輸出就會把訓練的時候大,所以要乘以(1-dropout),模擬丟棄的效果。【當然還有一種dropout的方式是訓練是把輸出除以(1-dropout),這樣預測的時候就不用在乘以(1-dropout)了, 感興趣的讀者可以參考這里】
def set_inpt(self, inpt, inpt_dropout, mini_batch_size):
self.inpt = inpt.reshape((mini_batch_size, self.n_in))
self.output = self.activation_fn( (1-self.p_dropout)*T.dot(self.inpt, self.w) + self.b)
self.y_out = T.argmax(self.output, axis=1)
self.inpt_dropout = dropout_layer(inpt_dropout.reshape((mini_batch_size, self.n_in)), self.p_dropout)
self.output_dropout = self.activation_fn( T.dot(self.inpt_dropout, self.w) + self.b)
下面我們逐行解讀。
1.reshape inpt
首先把input reshape成(batch_size, n_in),為什么要reshape呢?因為我們在CNN里通常在最后一個卷積pooling層后加一個全連接層,而CNN的輸出是4維的tensor(batch_size, num_filter, width, height),我們需要把它reshape成(batch_size, num_filter * width * height)。當然我們定義網絡的時候就會指定n_in=num_filter width height了。否則就不對了。
2.定義output
然后我們定義self.output。這是一個仿射變換,然后要乘以(1-p_dropout),原因前面解釋過了。這是預測的時候用的輸入和輸出。【有點讀者可能會疑惑(包括我自己第一次閱讀時),調用這個函數時會同時傳入inpt和inpt_dropout嗎?我們在Theano里只是”定義“符號變量從而定義這個計算圖,所以不是真的計算。我們訓練的時候定義用的是cost損失函數,它用的是inpt_dropout和output_dropout,而test的Theano函數是accuracy,用的是inpt和output以及y_out。
3.定義y_out
這個計算最終的輸出,也就是當這一層作為最后一層的時候輸出的分類結果。ConvPoolLayer是沒有實現y_out的計算的,因為我們不會把卷積作為網絡的輸出層,但是全連接層是有可能作為輸出的,所以通過argmax來選擇最大的那一個作為輸出。SoftmaxLayer是經常作為輸出的,所以也實現了y_out。
4.inpt_dropout 先reshape,然后加一個dropout的op,這個op就是隨機的把一些神經元的輸出設置成0
def dropout_layer(layer, p_dropout):
srng = shared_randomstreams.RandomStreams(np.random.RandomState(0).randint(999999))
mask = srng.binomial(n=1, p=1-p_dropout, size=layer.shape)
return layer*T.cast(mask, theano.config.floatX)
5.定義output_dropout
直接計算
ConvPoolLayer和SoftmaxLayer的代碼是類似的,這里就不贅述了。下面會有network3.py的完整代碼,感興趣的讀者可以自行閱讀。
但是也有一些細節值得注意。對于ConvPoolLayer和SoftmaxLayer,我們需要根據對應的公式計算輸出。不過非常幸運,Theano提供了內置的op,如卷積,max-pooling,softmax函數等等。
當我們實現softmax層時,我們沒有討論怎么初始化weights和biases。之前我們討論過sigmoid層怎么初始化參數,但是那些方法不見得就適合softmax層。這里直接初始化成0了。這看起來很隨意,不過在實踐中發現沒有太大問題。
7.2 ConvPoolLayer類
7.2.1 init
def __init__(self, filter_shape, image_shape, poolsize=(2, 2),? ? ? ? ? ? ? ? activation_fn=sigmoid):? ? ? ? self.filter_shape = filter_shape? ? ? ? self.image_shape = image_shape? ? ? ? self.poolsize = poolsize? ? ? ? self.activation_fn=activation_fn? ? ? ? # initialize weights and biases? ? ? ? n_out = (filter_shape[0]*np.prod(filter_shape[2:])/np.prod(poolsize))? ? ? ? self.w = theano.shared(? ? ? ? ? ? np.asarray(? ? ? ? ? ? ? ? np.random.normal(loc=0, scale=np.sqrt(1.0/n_out), size=filter_shape),? ? ? ? ? ? ? ? dtype=theano.config.floatX),? ? ? ? ? ? borrow=True)? ? ? ? self.b = theano.shared(? ? ? ? ? ? np.asarray(? ? ? ? ? ? ? ? np.random.normal(loc=0, scale=1.0, size=(filter_shape[0],)),? ? ? ? ? ? ? ? dtype=theano.config.floatX),? ? ? ? ? ? borrow=True)? ? ? ? self.params =[self.w, self.b]
首先是參數。
1.filter_shape (num_filter, input_feature_map, filter_width, filter_height)
這個參數是filter的參數,第一個是這一層的filter的個數,第二個是輸入特征映射的個數,第三個是filter的width,第四個是filter的height
2.image_shape(mini_batch, input_feature_map, width, height)
輸入圖像的參數,第一個是mini_batch大小,第二個是輸入特征映射個數,必須要和filter_shape的第二個參數一樣!第三個是輸入圖像的width,第四個是height
3.poolsize
pooling的width和height,默認2*2
4.activation_fn
激活函數,默認是sigmoid
代碼除了保存這些參數之外就是定義共享變量w和b,然后保存到self.params里。
7.2.2 set_inpt
def set_inpt(self, inpt, inpt_dropout, mini_batch_size):
self.inpt = inpt.reshape(self.image_shape)
conv_out = conv.conv2d(
input=self.inpt, filters=self.w, filter_shape=self.filter_shape,
image_shape=self.image_shape)
pooled_out = downsample.max_pool_2d(
input=conv_out, ds=self.poolsize, ignore_border=True)
self.output = self.activation_fn(
pooled_out + self.b.dimshuffle('x', 0, 'x', 'x'))
self.output_dropout = self.output # no dropout in the convolutional layers
我們逐行解讀
1.reshape輸入
2.卷積
使用theano提供的conv2d op計算卷積
3.max-pooling
使用theano提供的max_pool_2d定義pooled_out
4.應用激活函數
值得注意的是dimshuffle函數,pooled_out是(batch_size, num_filter, out_width, out_height),b是num_filter的向量。我們需要通過broadcasting讓所有的pooled_out都加上一個bias,所以我們需要用dimshuffle函數把b變成(1,num_filter, 1, 1)的tensor。dimshuffle的參數’x’表示增加一個維度,數字0表示原來這個tensor的第0維。 dimshuffle(‘x’, 0, ‘x’, ‘x’))的意思就是在原來這個vector的前面插入一個維度,后面插入兩個維度,所以變成了(1,num_filter, 1, 1)的tensor。
5.output_dropout
卷積層沒有dropout,所以output和output_dropout是同一個符號變量
7.3 Network類
7.3.1 init
def __init__(self, layers, mini_batch_size):? ? ? ? self.layers = layers? ? ? ? self.mini_batch_size = mini_batch_size? ? ? ? self.params =[param for layer in self.layers for param in layer.params]? ? ? ? self.x = T.matrix("x")? ? ? ? self.y = T.ivector("y")? ? ? ? init_layer = self.layers[0]? ? ? ? init_layer.set_inpt(self.x, self.x, self.mini_batch_size)? ? ? ? for j in xrange(1, len(self.layers)):? ? ? ? ? ? prev_layer, layer? = self.layers[j-1], self.layers[j]? ? ? ? ? ? layer.set_inpt(? ? ? ? ? ? ? ? prev_layer.output, prev_layer.output_dropout, self.mini_batch_size)? ? ? ? self.output = self.layers[-1].output? ? ? ? self.output_dropout = self.layers[-1].output_dropout
參數layers就是網絡的所有Layers。
比如下面的代碼定義了一個三層的網絡,一個卷積pooling層,一個全連接層和一個softmax輸出層,輸入大小是mini_batch_size 1 28 28的MNIST圖片,卷積層的輸出是mini_batch_size 20 24 24,pooling之后是mini_batch_size 20 12 12。然后接一個全連接層,全連接層的輸入就是pooling的輸出20 12*12,輸出是100。最后是一個softmax,輸入是100,輸出10。
net = Network([ConvPoolLayer(image_shape=(mini_batch_size, 1, 28, 28),? ? ? ? ? ? ? ? ? ? ? filter_shape=(20, 1, 5, 5),? ? ? ? ? ? ? ? ? ? ? poolsize=(2, 2)),? ? ? ? FullyConnectedLayer(n_in=20*12*12, n_out=100),? ? ? ? SoftmaxLayer(n_in=100, n_out=10)], mini_batch_size)
首先是保存layers和mini_batch_size
self.params=[param for layer in …]這行代碼把所有層的參數放到一個list里。Network.SGD方法會使用self.params來更新所以的參數。self.x=T.matrix(“x”)和self.y=T.ivector(“y”)定義Theano符號變量x和y。這代表整個網絡的輸入和輸出。
首先我們調用init_layer的set_inpt
init_layer = self.layers[0]? init_layer.set_inpt(self.x, self.x, self.mini_batch_size)
這里調用第一層的set_inpt函數。傳入的inpt和inpt_dropout都是self.x,因為不論是訓練還是測試,第一層的都是x。
然后從第二層開始:
for j in xrange(1, len(self.layers)):? ? ? ? ? ? prev_layer, layer? = self.layers[j-1], self.layers[j]? ? ? ? ? ? layer.set_inpt(? ? ? ? ? ? ? ? prev_layer.output, prev_layer.output_dropout, self.mini_batch_size)
拿到上一層prev_layer和當前層layer,然后把調用layer.set_inpt函數,把上一層的output和output_dropout作為當前層的inpt和inpt_dropout。
最后定義整個網絡的output和output_dropout`
self.output = self.layers[-1].output? ? ? ? self.output_dropout = self.layers[-1].output_dropout
7.3.2 SGD函數
def SGD(self, training_data, epochs, mini_batch_size, eta,? ? ? ? ? ? validation_data, test_data, lmbda=0.0):? ? ? ? """Train the network using mini-batch stochastic gradient descent."""? ? ? ? training_x, training_y = training_data? ? ? ? validation_x, validation_y = validation_data? ? ? ? test_x, test_y = test_data? ? ? ? # compute number of minibatches for training, validation and testing? ? ? ? num_training_batches = size(training_data)/mini_batch_size? ? ? ? num_validation_batches = size(validation_data)/mini_batch_size? ? ? ? num_test_batches = size(test_data)/mini_batch_size? ? ? ? # define the (regularized) cost function, symbolic gradients, and updates? ? ? ? l2_norm_squared = sum([(layer.w**2).sum() for layer in self.layers])? ? ? ? cost = self.layers[-1].cost(self)+\? ? ? ? ? ? ? 0.5*lmbda*l2_norm_squared/num_training_batches? ? ? ? grads = T.grad(cost, self.params)? ? ? ? updates =[(param, param-eta*grad)? ? ? ? ? ? ? ? ? for param, grad in zip(self.params, grads)]? ? ? ? # define functions to train a mini-batch, and to compute the? ? ? ? # accuracy in validation and test mini-batches.? ? ? ? i = T.lscalar() # mini-batch index? ? ? ? train_mb = theano.function(? ? ? ? ? ? , cost, updates=updates,? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? training_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],? ? ? ? ? ? ? ? self.y:? ? ? ? ? ? ? ? training_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })? ? ? ? validate_mb_accuracy = theano.function(? ? ? ? ? ? , self.layers[-1].accuracy(self.y),? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? validation_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],? ? ? ? ? ? ? ? self.y:? ? ? ? ? ? ? ? validation_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })? ? ? ? test_mb_accuracy = theano.function(? ? ? ? ? ? , self.layers[-1].accuracy(self.y),? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],? ? ? ? ? ? ? ? self.y:? ? ? ? ? ? ? ? test_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })? ? ? ? self.test_mb_predictions = theano.function(? ? ? ? ? ? , self.layers[-1].y_out,? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })? ? ? ? # Do the actual training? ? ? ? best_validation_accuracy = 0.0? ? ? ? for epoch in xrange(epochs):? ? ? ? ? ? for minibatch_index in xrange(num_training_batches):? ? ? ? ? ? ? ? iteration = num_training_batches*epoch+minibatch_index? ? ? ? ? ? ? ? if iteration % 1000 == 0:? ? ? ? ? ? ? ? ? ? print("Training mini-batch number {0}".format(iteration))? ? ? ? ? ? ? ? cost_ij = train_mb(minibatch_index)? ? ? ? ? ? ? ? if (iteration+1) % num_training_batches == 0:? ? ? ? ? ? ? ? ? ? validation_accuracy = np.mean([validate_mb_accuracy(j) for j in xrange(num_validation_batches)])? ? ? ? ? ? ? ? ? ? print("Epoch {0}: validation accuracy {1:.2%}".format(? ? ? ? ? ? ? ? ? ? ? ? epoch, validation_accuracy))? ? ? ? ? ? ? ? ? ? if validation_accuracy >= best_validation_accuracy:? ? ? ? ? ? ? ? ? ? ? ? print("This is the best validation accuracy to date.")? ? ? ? ? ? ? ? ? ? ? ? best_validation_accuracy = validation_accuracy? ? ? ? ? ? ? ? ? ? ? ? best_iteration = iteration? ? ? ? ? ? ? ? ? ? ? ? if test_data:? ? ? ? ? ? ? ? ? ? ? ? ? ? test_accuracy = np.mean([test_mb_accuracy(j) for j in xrange(num_test_batches)])? ? ? ? ? ? ? ? ? ? ? ? ? ? print('The corresponding test accuracy is {0:.2%}'.format(? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? test_accuracy))? ? ? ? print("Finished training network.")? ? ? ? print("Best validation accuracy of {0:.2%} obtained at iteration {1}".format(? ? ? ? ? ? best_validation_accuracy, best_iteration))? ? ? ? print("Corresponding test accuracy of {0:.2%}".format(test_accuracy))
有了之前theano的基礎和實現過LogisticRegression,閱讀SGD應該比較輕松了。
雖然看起來代碼比較多,但是其實邏輯很清楚和簡單,我們下面簡單的解讀一下。
1. 定義損失函數cost?
l2_norm_squared = sum([(layer.w**2).sum() for layer in self.layers])? ? ? ? cost = self.layers[-1].cost(self)+\? ? ? ? ? ? ? 0.5*lmbda*l2_norm_squared/num_training_batches
出來最后一層的cost,我們還需要加上L2的normalization,其實就是把所有的w平方和然后開方。注意 self.layers[-1].cost(self),傳入的參數是Network對象【函數cost的第一個參數self是對象指針,不要調用者傳入的,這里把Network對象自己(self)作為參數傳給了cost函數的net參數】。
下面是SoftmaxLayer的cost函數:
def cost(self, net):? ? ? ? "Return the log-likelihood cost."? ? ? ? return -T.mean(T.log(self.output_dropout)[T.arange(net.y.shape[0]), net.y])
其實net只用到了net.y,我們也可以把cost定義如下:
def cost(self, y):? ? ? ? "Return the log-likelihood cost."? ? ? ? return -T.mean(T.log(self.output_dropout)[T.arange(y.shape[0]), y])
然后調用的時候用
cost = self.layers[-1].cost(self.y)+\? ? ? ? ? ? ? 0.5*lmbda*l2_norm_squared/num_training_batches
我個人覺得這樣更清楚。
2. 定義梯度和updates?
grads = T.grad(cost, self.params)? ? ? ? updates =[(param, param-eta*grad)? ? ? ? ? ? ? ? ? for param, grad in zip(self.params, grads)]
3. 定義訓練函數?
i = T.lscalar() # mini-batch index? ? ? ? train_mb = theano.function(? ? ? ? ? ? , cost, updates=updates,? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? training_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],? ? ? ? ? ? ? ? self.y:? ? ? ? ? ? ? ? training_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })
train_mb函數的輸入是i,輸出是cost,batch的x和y通過givens制定,這和之前的Theano tutorial里的LogisticRegression一樣的。cost函數用到的是最后一層的output_dropout,從而每一層都是走計算圖的inpt_dropout->output_dropout路徑。
4. 定義validation和測試函數?
validate_mb_accuracy = theano.function(? ? ? ? ? ? , self.layers[-1].accuracy(self.y),? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? validation_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],? ? ? ? ? ? ? ? self.y:? ? ? ? ? ? ? ? validation_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })? ? ? ? test_mb_accuracy = theano.function(? ? ? ? ? ? , self.layers[-1].accuracy(self.y),? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size],? ? ? ? ? ? ? ? self.y:? ? ? ? ? ? ? ? test_y[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })
輸出是最后一層的accuracy self.layers[-1].accuracy(self.y)。accuracy使用的是最后一層的output,從而每一層都是用計算圖的inpt->output路徑。
5. 預測函數?
self.test_mb_predictions = theano.function(? ? ? ? ? ? , self.layers[-1].y_out,? ? ? ? ? ? givens={? ? ? ? ? ? ? ? self.x:? ? ? ? ? ? ? ? test_x[i*self.mini_batch_size: (i+1)*self.mini_batch_size]? ? ? ? ? ? })
輸出是最后一層的y_out,也就是softmax的argmax(output)
7.4 用法?
training_data, validation_data, test_data = network3.load_data_shared()mini_batch_size = 10net = Network([ConvPoolLayer(image_shape=(mini_batch_size, 1, 28, 28),? ? ? ? ? ? ? ? ? ? ? filter_shape=(20, 1, 5, 5),? ? ? ? ? ? ? ? ? ? ? poolsize=(2, 2)),? ? ? ? FullyConnectedLayer(n_in=20*12*12, n_out=100),? ? ? ? SoftmaxLayer(n_in=100, n_out=10)], mini_batch_size)net.SGD(training_data, 60, mini_batch_size, 0.1,? ? ? ? ? ? validation_data, test_data)
至此,我們介紹了Theano的基礎知識以及怎么用Theano實現CNN。下一講將會介紹怎么自己用Python(numpy)實現CNN并且介紹實現的一些細節和性能優化,大部分內容來自CS231N的slides和作業assignment2,敬請關注。