CNN2 多层卷积

延续上一篇进行修改,可用于多层卷积网络,按mini batch传播,正确率96%左右。

存在的问题是卷积速度过慢,学习率更新方式。

下一篇将使用im2col。

 

# coding:utf8
import cPickle
import numpy as np
from  scipy.signal.signaltools import convolve2d

class ConvPoolLayer(object):  
    def __init__(self, image_shape,filter_shape,poolsize=(2,2)):
        self.filter_shape = filter_shape
        self.image_shape = image_shape
        self.w = np.random.normal(loc=0, scale=np.sqrt(1.0/np.prod(filter_shape[1:])),
                                  size=filter_shape)
        self.b = np.random.normal(loc=0, scale=0.2, size=(filter_shape[0],))
        self.poolsize = poolsize
        self.samp_shape=(image_shape[-2] - filter_shape[-2] + 1,image_shape[-1] - filter_shape[-1] + 1)
        self.out_shape=(self.samp_shape[0]/poolsize[0],self.samp_shape[1]/poolsize[1])

    def conv(self,a, v,b=0,mod=-1,r1=0,r2=0):
        n, m, h, w = np.shape(a)
        vn, vm, vh, vw = np.shape(v)
        assert m == vm, 'wrong filter shape'
        d, s = h + mod*(vh - 1), w + mod*(vw - 1)
        z = np.zeros((n, vn, d, s))
        for i in range(n):
            for j in range(vn):
                for k in range(m):
                    if mod==-1:
                        z[i][j] += convolve2d(a[i][k], np.rot90(v[j][k],r1), mode='valid')
                    else:
                        z[i][j] += convolve2d(a[i][k], np.rot90(v[j][k],r1), mode='full')
                if r2==1:
                    z[i][j]=np.rot90(z[i][j],2)
            if type(b)!=int:
                    z[i]+=b[j]
        return z

    def feedforward(self, a):
        self.out = self.relu(self.conv(a, self.w,self.b))
        return np.array(self.pool2d(self.out))

    def backprop(self, x, dnext,eta=0.001):
        if dnext.ndim<3:
            dnext = np.reshape(dnext,(self.image_shape[0],self.filter_shape[0], self.out_shape[0], self.out_shape[1]))
        u = self.relu_prime(self.out)
        delta = np.multiply(u,self.up(dnext,self.poolsize[0]))
        delta=np.rollaxis(delta,1,0)
        out_delta = self.conv(np.rollaxis(delta, 1, 0), np.rollaxis(self.w, 1, 0), mod=1,r1=2)
        b = np.array([np.sum(d_) for d_ in delta])
        w = np.array(self.conv(np.rollaxis(x,1,0), delta,r1=2,r2=1))
        w = np.rollaxis(w,1,0)
        self.w -= eta * w/self.image_shape[0]
        self.b -= eta * b/self.image_shape[0]
        return out_delta

    def pool2d(self,input, ds=(2, 2), mode='max'):
        fun = np.max
        if mode == 'sum':
            fun = np.sum
        elif mode == 'average':
            fun = np.average
        n, m, h, w = np.shape(input)
        d, s = ds
        zh = h / d + h % d
        zw = w / s + w % s
        z = np.zeros((n, m, zh, zw))
        for k in range(n):
            for o in range(m):
                for i in range(zh):
                    for j in range(zw):
                        z[k, o, i, j] = fun(input[k, o, d * i:min(d * i + d, h), s * j:min(s * j + s, w)])
        return z

    def up(self,a,l):
        b=np.ones((l,l))
        return np.kron(a,b)

    def relu(self,z):
        return np.maximum(z, 0.0)

    def relu_prime(self,z):
        z[z>0]=1
        return z

class SoftmaxLayer(object):
    def __init__(self, in_num=100,out_num=10):
        self.weights = np.random.randn(in_num, out_num)/np.sqrt(out_num)

    def feedforward(self, input):
        self.out=self.softmax(np.dot(input, self.weights))
        return self.out

    def backprop(self, input, y,eta=0.001):
        o=self.out
        delta =o-y
        out_delta=np.dot(delta,self.weights.T)
        w = np.dot(input.T,delta)
        self.weights-=eta*(w)
        return out_delta

    def softmax(self,a):
        m = np.exp(a)
        return m / (np.sum(m,axis=1)[:,np.newaxis])

class FullLayer(object):
    def __init__(self, in_num=720,out_num=100):
        self.in_num=in_num
        self.out_num=out_num
        self.biases = np.random.randn(out_num)
        self.weights = np.random.randn(in_num, out_num)/np.sqrt(out_num)

    def feedforward(self, x):
        if x.ndim>2:
            x = np.reshape(x, (len(x), self.in_num))
        self.out = self.sigmoid(np.dot(x, self.weights)+self.biases)
        return self.out

    def backprop(self, x,delta,eta=0.001):
        if x.ndim>2:
            x = np.reshape(x, (len(x), self.in_num))
        sp=self.sigmoid_prime(self.out)
        delta = delta * sp
        out_delta = np.dot(delta, self.weights.T)
        w = np.dot( x.T,delta)
        self.weights-=eta*w
        self.biases -= eta*np.sum(delta,0)
        return out_delta

    def sigmoid(self,z):
        return 1.0/(1.0+np.exp(-z))

    def sigmoid_prime(self,z):
        return z*(1-z)

class Network(object):
    def __init__(self, layers):
        self.layers=layers
        self.num_layers = len(layers)
        self.a=[]

    def feedforward(self, x):
        self.a.append(x)
        for layer in self.layers:
            x=layer.feedforward(x)
            self.a.append(x)
        return x

    def SGD(self, training_data, test_data,epochs, mini_batch_size, eta=0.001):
        self.n = len(training_data[0])
        self.mini_batch_size=mini_batch_size
        self.eta = eta
        cx=range(epochs)
        for j in cx:
            for k in xrange(0, self.n , mini_batch_size):
                batch_x = np.array(training_data[0][k:k + mini_batch_size])
                batch_y = training_data[1][k:k + mini_batch_size]
                self.backprop(batch_x,batch_y)
                if k%500==0:
                    print "Epoch {0}:{1} cost={3}, test:{2}".format(j,k,
                    self.evaluate([test_data[0],test_data[1]]),self.cost)

    def backprop(self, x_in, y):
        self.feedforward(x_in)
        for i in range(self.num_layers):
            delta=self.layers[-i-1].backprop(self.a[-i-2],y,eta=self.eta)
            y=delta

    def evaluate(self, test_data):
        x,y=test_data
        num=len(x)
        size=self.mini_batch_size
        x=[self.feedforward(np.array(x[size*i:size*i+size])) for i in range((num/size))]
        x=np.reshape(x,(num,np.shape(x)[-1]))
        xp = np.argmax(x, axis=1)
        yp= np.argmax(y, axis=1) if y[0].ndim else y
        self.cost = -np.mean(np.log(x)[np.arange(num),yp])
        return np.mean(yp == xp)*100


if __name__ == '__main__':
        def get_data(data):
            return [np.reshape(x, (1,28,28)) for x in data[0]]

        def get_label(i):
            c = np.zeros((10))
            c[i] = 1
            return c

        f = open('data/mnist.pkl', 'rb')
        training_data, validation_data, test_data = cPickle.load(f)
        training_inputs = get_data(training_data)
        training_label=[get_label(y_) for y_ in training_data[1]]
        test_inputs = get_data(test_data)
        test = zip(test_inputs,test_data[1])
        size=10
        net = Network([ConvPoolLayer(image_shape=[size,1,28,28],filter_shape=[8,1,5,5],poolsize=(2,2)),
                       ConvPoolLayer(image_shape=[size,8,12,12],filter_shape=[16,8,5,5], poolsize=(2,2)),
                       FullLayer(in_num=16*4*4,out_num=100),
                       SoftmaxLayer(in_num=100,out_num=10)])
        net.SGD([training_inputs,training_label],[test_inputs[:500],test_data[1][:500]],
                epochs=3,mini_batch_size=size, eta=0.05)
        
        #  Epoch 0:10000 cost=0.137396947661, test:95.6

 

posted on 2017-02-04 23:00  1357  阅读(625)  评论(0编辑  收藏  举报

导航