theano中训练方法和模型的一些写法

按照这theano的tutorial开始跟着写了,因为去年年底之前学习过一段时间,但是当时时间少,并且很多地方也没搞懂,大多都是看着书来模仿,结果出错不好找地方之外,自己如果根据自己的想法随便写下结果就出错了。这几天好好的学习了下。我来总结下

在softmax或者逻辑回归的代码中:

1:在教程中写法是,先写一个类,在类的init方法中初始化w和b,以及计算概率。

2:然后分别再另外的函数中计算cost和error。

3:在类外来进行训练。

以上方法由于在init方法中,要进行概率计算,所以在初始化类的时候至少要传递进去x,在计算cost和error的时候要传递进去y。所以如果此时训练方法写在类内的话就不行。因为数据也是在训练方法内生成的,在类别没办法传递进去(此时,你也许会说在类外面单独加载数据怎么样?因为训练方法内其实传递进去的是数据的索引,所以这个在外面单独加载数据的话也不太现实。所以加载数据还是和训练方法写在一起是最方便的)


为了解决以上问题,很容易,就是把init方法中,把在类外面不能传递的参数,全部去掉,然后在别的计算的地方用到的话,再传递进去。比如把概率预测拿出来,写成一个函数,把x传递进去。然后其余的保持不变。这样在训练方法内,因为有对x和y的声明,以及对应数据的传递进去,所以不会出问题


我这里写好了一个,发上来作为备忘吧,为下一步的更高层次的封装做准备:

[python]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. import numpy, theano, theano.tensor as T, gzip, cPickle  
  2.   
  3. class NN():  
  4.       
  5.     def __init__(self, n_in, n_out):  
  6.         self.w = theano.shared(numpy.asarray(numpy.zeros([n_in, n_out]), theano.config.floatX))  
  7.         self.b = theano.shared(numpy.asarray(numpy.zeros(n_out), theano.config.floatX))  
  8.     def get_probalblity(self, x):  
  9.         return  T.nnet.softmax(T.dot(x, self.w) + self.b)    
  10.     def get_prediction(self, x, y):  
  11.         return T.argmax(self.get_probalblity(x), 1)  
  12.     def cost(self, x, y):  
  13.         p_y_given_x = self.get_probalblity(x)  
  14.         return  -T.mean(T.log(p_y_given_x[T.arange(y.shape[0]), y]))  
  15.     def error(self, x, y):  
  16.         prediction = self.get_prediction(x, y)  
  17.         return T.mean(T.neq(prediction, y))  
  18.     def load_data(self):  
  19.         f = gzip.open('mnist.pkl.gz')  
  20.         trainxy, validatexy, testxy = cPickle.load(f)  
  21.         def share_data(xy):  
  22.             x,y = xy  
  23.             x = theano.shared(numpy.asarray(x, theano.config.floatX))  
  24.             y = theano.shared(numpy.asarray(y, theano.config.floatX))  
  25.             return [x, T.cast(y, 'int32')]  
  26.         trainx, trainy = share_data(trainxy)  
  27.         validatex,validatey = share_data(validatexy)  
  28.         testx, testy = share_data(testxy)  
  29.         return [(trainx,trainy),(validatex,validatey),(testx,testy)]  
  30.     def train(self):  
  31.         x = T.matrix('x', theano.config.floatX)  
  32.         y = T.ivector('y')  
  33.         [(trainx,trainy),(validatex,validatey),(testx,testy)] = self.load_data()  
  34.         gw,gb = T.grad(self.cost(x,y), [self.w, self.b])  
  35.         index = T.lscalar()  
  36.          
  37.         batch_size = 600  
  38.         trainModel = theano.function([index], self.cost(x,y), updates=[(self.w, self.w-0.13*gw), (self.b, self.b-0.13*gb)], givens={x:trainx[index*batch_size:(index+1)*batch_size], y:trainy[index*batch_size:(index+1)*batch_size]})  
  39.         validateModel = theano.function([index], self.error(x,y), givens={x:validatex[index*batch_size:(index+1)*batch_size], y:validatey[index*batch_size:(index+1)*batch_size]})  
  40.         testModel = theano.function([index], self.error(x,y), givens={x:testx[index*batch_size:(index+1)*batch_size], y:testy[index*batch_size:(index+1)*batch_size]})  
  41.           
  42.         best_validate_error = numpy.Inf  
  43.         best_test_error = 0  
  44.         patience = 5000  
  45.         increasement = 2  
  46.         train_batchs = trainx.get_value().shape[0]/batch_size  
  47.         validate_batchs = validatex.get_value().shape[0]/batch_size  
  48.         test_batchs = testx.get_value().shape[0]/batch_size  
  49.         validate_frequency = min(patience/2, train_batchs)  
  50.         epochs = 1000  
  51.         epoch = 1  
  52.         ite = 0  
  53.         stopping = False  
  54.         while (epoch < epochs) and (not stopping):  
  55.             for i in xrange(train_batchs):  
  56.                 ite += 1  
  57.                 this_cost = trainModel(i)  
  58.                 if ite%validate_frequency == 0:  
  59.                     this_validate_error = numpy.mean([validateModel(j) for j in xrange(validate_batchs)])  
  60.                     print ('ite:%d/%d, cost:%f, validate:%f'%(ite, epoch, this_cost, this_validate_error))      
  61.                     if this_validate_error < best_validate_error:  
  62.                         if this_validate_error < 0.995*best_validate_error:  
  63.                             patience = max(patience, ite*increasement)  
  64.                         this_test_error = numpy.mean([testModel(j) for j in xrange(test_batchs)])  
  65.                         best_validate_error = this_validate_error  
  66.                         best_test_error = this_test_error  
  67.                         print ('ite:%d/%d, cost:%f, validate:%f, test:%f'%(ite, epoch, this_cost, this_validate_error, this_test_error))      
  68.                 if patience <= ite:  
  69.                     stopping = True  
  70.                     break  
  71.             epoch +=1  
  72.         print ('best validate error:%f, best test error:%f'%(best_validate_error, best_test_error))  
  73.           
  74.           
  75. if __name__ == '__main__':  
  76.     nn = NN(78410)  
  77.     nn.train()  

以上训练结果,和tutorial给出的基本一致。

。。。。。

ite:5810/70, cost:0.329380, validate:0.075104
ite:5810/70, cost:0.329380, validate:0.075104, test:0.075000
ite:5893/71, cost:0.329054, validate:0.075208
ite:5976/72, cost:0.328735, validate:0.075104
ite:5976/72, cost:0.328735, validate:0.075104, test:0.075104
ite:6059/73, cost:0.328422, validate:0.075000
ite:6059/73, cost:0.328422, validate:0.075000, test:0.074896
ite:6142/74, cost:0.328116, validate:0.074792
ite:6142/74, cost:0.328116, validate:0.074792, test:0.074896
best validate error:0.074792, best test error:0.074896

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值