Keras TFLearn TensorLayer实例【转】

来自:http://blog.csdn.net/chenhaifeng2016/article/details/72763439

Keras MNIST CNN

[python]  view plain  copy
  1. '''''Trains a simple convnet on the MNIST dataset. 
  2.  
  3. Gets to 99.25% test accuracy after 12 epochs 
  4. (there is still a lot of margin for parameter tuning). 
  5. 16 seconds per epoch on a GRID K520 GPU. 
  6. '''  
  7.   
  8. from __future__ import print_function  
  9. import keras  
  10. from keras.datasets import mnist  
  11. from keras.models import Sequential  
  12. from keras.layers import Dense, Dropout, Flatten  
  13. from keras.layers import Conv2D, MaxPooling2D  
  14. from keras import backend as K  
  15.   
  16. batch_size = 128  
  17. num_classes = 10  
  18. epochs = 12  
  19.   
  20. # input image dimensions  
  21. img_rows, img_cols = 2828  
  22.   
  23. # the data, shuffled and split between train and test sets  
  24. (x_train, y_train), (x_test, y_test) = mnist.load_data()  
  25.   
  26. if K.image_data_format() == 'channels_first':  
  27.     x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)  
  28.     x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)  
  29.     input_shape = (1, img_rows, img_cols)  
  30. else:  
  31.     x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)  
  32.     x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)  
  33.     input_shape = (img_rows, img_cols, 1)  
  34.   
  35. x_train = x_train.astype('float32')  
  36. x_test = x_test.astype('float32')  
  37. x_train /= 255  
  38. x_test /= 255  
  39. print('x_train shape:', x_train.shape)  
  40. print(x_train.shape[0], 'train samples')  
  41. print(x_test.shape[0], 'test samples')  
  42.   
  43. # convert class vectors to binary class matrices  
  44. y_train = keras.utils.to_categorical(y_train, num_classes)  
  45. y_test = keras.utils.to_categorical(y_test, num_classes)  
  46.   
  47. model = Sequential()  
  48. model.add(Conv2D(32, kernel_size=(33),  
  49.                  activation='relu',  
  50.                  input_shape=input_shape))  
  51. model.add(Conv2D(64, (33), activation='relu'))  
  52. model.add(MaxPooling2D(pool_size=(22)))  
  53. model.add(Dropout(0.25))  
  54. model.add(Flatten())  
  55. model.add(Dense(128, activation='relu'))  
  56. model.add(Dropout(0.5))  
  57. model.add(Dense(num_classes, activation='softmax'))  
  58.   
  59. model.compile(loss=keras.losses.categorical_crossentropy,  
  60.               optimizer=keras.optimizers.Adadelta(),  
  61.               metrics=['accuracy'])  
  62.   
  63. model.fit(x_train, y_train,  
  64.           batch_size=batch_size,  
  65.           epochs=epochs,  
  66.           verbose=1,  
  67.           validation_data=(x_test, y_test))  
  68. score = model.evaluate(x_test, y_test, verbose=0)  
  69. print('Test loss:', score[0])  
  70. print('Test accuracy:', score[1])  


TFLearn

[python]  view plain  copy
  1. # -*- coding: utf-8 -*-  
  2.   
  3. """ Convolutional Neural Network for MNIST dataset classification task. 
  4.  
  5. References: 
  6.     Y. LeCun, L. Bottou, Y. Bengio, and P. Haffner. "Gradient-based 
  7.     learning applied to document recognition." Proceedings of the IEEE, 
  8.     86(11):2278-2324, November 1998. 
  9.  
  10. Links: 
  11.     [MNIST Dataset] http://yann.lecun.com/exdb/mnist/ 
  12.  
  13. """  
  14.   
  15. from __future__ import division, print_function, absolute_import  
  16.   
  17. import tflearn  
  18. from tflearn.layers.core import input_data, dropout, fully_connected  
  19. from tflearn.layers.conv import conv_2d, max_pool_2d  
  20. from tflearn.layers.normalization import local_response_normalization  
  21. from tflearn.layers.estimator import regression  
  22.   
  23. # Data loading and preprocessing  
  24. import tflearn.datasets.mnist as mnist  
  25. X, Y, testX, testY = mnist.load_data(one_hot=True)  
  26. X = X.reshape([-128281])  
  27. testX = testX.reshape([-128281])  
  28.   
  29. # Building convolutional network  
  30. network = input_data(shape=[None28281], name='input')  
  31. network = conv_2d(network, 323, activation='relu', regularizer="L2")  
  32. network = max_pool_2d(network, 2)  
  33. network = local_response_normalization(network)  
  34. network = conv_2d(network, 643, activation='relu', regularizer="L2")  
  35. network = max_pool_2d(network, 2)  
  36. network = local_response_normalization(network)  
  37. network = fully_connected(network, 128, activation='tanh')  
  38. network = dropout(network, 0.8)  
  39. network = fully_connected(network, 256, activation='tanh')  
  40. network = dropout(network, 0.8)  
  41. network = fully_connected(network, 10, activation='softmax')  
  42. network = regression(network, optimizer='adam', learning_rate=0.01,  
  43.                      loss='categorical_crossentropy', name='target')  
  44.   
  45. # Training  
  46. model = tflearn.DNN(network, tensorboard_verbose=0)  
  47. model.fit({'input': X}, {'target': Y}, n_epoch=20,  
  48.            validation_set=({'input': testX}, {'target': testY}),  
  49.            snapshot_step=100, show_metric=True, run_id='convnet_mnist')  


TensorLayer

[python]  view plain  copy
  1. def main_test_cnn_layer():  
  2.     """Reimplementation of the TensorFlow official MNIST CNN tutorials: 
  3.     - https://www.tensorflow.org/versions/r0.8/tutorials/mnist/pros/index.html 
  4.     - https://github.com/tensorflow/tensorflow/blob/master/tensorflow/models/image/mnist/convolutional.py 
  5.  
  6.     More TensorFlow official CNN tutorials can be found here: 
  7.     - tutorial_cifar10.py 
  8.     - https://www.tensorflow.org/versions/master/tutorials/deep_cnn/index.html 
  9.  
  10.     - For simplified CNN layer see "Convolutional layer (Simplified)" 
  11.       in read the docs website. 
  12.     """  
  13.     X_train, y_train, X_val, y_val, X_test, y_test = \  
  14.                     tl.files.load_mnist_dataset(shape=(-128281))  
  15.   
  16.     X_train = np.asarray(X_train, dtype=np.float32)  
  17.     y_train = np.asarray(y_train, dtype=np.int64)  
  18.     X_val = np.asarray(X_val, dtype=np.float32)  
  19.     y_val = np.asarray(y_val, dtype=np.int64)  
  20.     X_test = np.asarray(X_test, dtype=np.float32)  
  21.     y_test = np.asarray(y_test, dtype=np.int64)  
  22.   
  23.     print('X_train.shape', X_train.shape)  
  24.     print('y_train.shape', y_train.shape)  
  25.     print('X_val.shape', X_val.shape)  
  26.     print('y_val.shape', y_val.shape)  
  27.     print('X_test.shape', X_test.shape)  
  28.     print('y_test.shape', y_test.shape)  
  29.     print('X %s   y %s' % (X_test.dtype, y_test.dtype))  
  30.   
  31.     sess = tf.InteractiveSession()  
  32.   
  33.     # Define the batchsize at the begin, you can give the batchsize in x and y_  
  34.     # rather than 'None', this can allow TensorFlow to apply some optimizations  
  35.     # – especially for convolutional layers.  
  36.     batch_size = 128  
  37.   
  38.     x = tf.placeholder(tf.float32, shape=[batch_size, 28281])   # [batch_size, height, width, channels]  
  39.     y_ = tf.placeholder(tf.int64, shape=[batch_size,])  
  40.   
  41.     network = tl.layers.InputLayer(x, name='input')  
  42.     ## Professional conv API for tensorflow user  
  43.     # network = tl.layers.Conv2dLayer(network,  
  44.     #                     act = tf.nn.relu,  
  45.     #                     shape = [5, 5, 1, 32],  # 32 features for each 5x5 patch  
  46.     #                     strides=[1, 1, 1, 1],  
  47.     #                     padding='SAME',  
  48.     #                     name ='cnn1')     # output: (?, 28, 28, 32)  
  49.     # network = tl.layers.PoolLayer(network,  
  50.     #                     ksize=[1, 2, 2, 1],  
  51.     #                     strides=[1, 2, 2, 1],  
  52.     #                     padding='SAME',  
  53.     #                     pool = tf.nn.max_pool,  
  54.     #                     name ='pool1',)   # output: (?, 14, 14, 32)  
  55.     # network = tl.layers.Conv2dLayer(network,  
  56.     #                     act = tf.nn.relu,  
  57.     #                     shape = [5, 5, 32, 64], # 64 features for each 5x5 patch  
  58.     #                     strides=[1, 1, 1, 1],  
  59.     #                     padding='SAME',  
  60.     #                     name ='cnn2')     # output: (?, 14, 14, 64)  
  61.     # network = tl.layers.PoolLayer(network,  
  62.     #                     ksize=[1, 2, 2, 1],  
  63.     #                     strides=[1, 2, 2, 1],  
  64.     #                     padding='SAME',  
  65.     #                     pool = tf.nn.max_pool,  
  66.     #                     name ='pool2',)   # output: (?, 7, 7, 64)  
  67.     ## Simplified conv API for beginner (the same with the above layers)  
  68.     network = tl.layers.Conv2d(network, n_filter=32, filter_size=(55), strides=(11),  
  69.             act=tf.nn.relu, padding='SAME', name='cnn1')  
  70.     network = tl.layers.MaxPool2d(network, filter_size=(22), strides=(22),  
  71.             padding='SAME', name='pool1')  
  72.     network = tl.layers.Conv2d(network, n_filter=64, filter_size=(55), strides=(11),  
  73.             act=tf.nn.relu, padding='SAME', name='cnn2')  
  74.     network = tl.layers.MaxPool2d(network, filter_size=(22), strides=(22),  
  75.             padding='SAME', name='pool2')  
  76.     ## end of conv  
  77.     network = tl.layers.FlattenLayer(network, name='flatten')  
  78.     network = tl.layers.DropoutLayer(network, keep=0.5, name='drop1')  
  79.     network = tl.layers.DenseLayer(network, n_units=256,  
  80.                                     act = tf.nn.relu, name='relu1')  
  81.     network = tl.layers.DropoutLayer(network, keep=0.5, name='drop2')  
  82.     network = tl.layers.DenseLayer(network, n_units=10,  
  83.                                     act = tf.identity,  
  84.                                     name='output')  
  85.   
  86.     y = network.outputs  
  87.   
  88.     cost = tl.cost.cross_entropy(y, y_, 'cost')  
  89.   
  90.     correct_prediction = tf.equal(tf.argmax(y, 1), y_)  
  91.     acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  
  92.   
  93.     # train  
  94.     n_epoch = 200  
  95.     learning_rate = 0.0001  
  96.     print_freq = 10  
  97.   
  98.     train_params = network.all_params  
  99.     train_op = tf.train.AdamOptimizer(learning_rate, beta1=0.9, beta2=0.999,  
  100.         epsilon=1e-08, use_locking=False).minimize(cost, var_list=train_params)  
  101.   
  102.     tl.layers.initialize_global_variables(sess)  
  103.     network.print_params()  
  104.     network.print_layers()  
  105.   
  106.     print('   learning_rate: %f' % learning_rate)  
  107.     print('   batch_size: %d' % batch_size)  
  108.   
  109.     for epoch in range(n_epoch):  
  110.         start_time = time.time()  
  111.         for X_train_a, y_train_a in tl.iterate.minibatches(  
  112.                                     X_train, y_train, batch_size, shuffle=True):  
  113.             feed_dict = {x: X_train_a, y_: y_train_a}  
  114.             feed_dict.update( network.all_drop )        # enable noise layers  
  115.             sess.run(train_op, feed_dict=feed_dict)  
  116.   
  117.         if epoch + 1 == 1 or (epoch + 1) % print_freq == 0:  
  118.             print("Epoch %d of %d took %fs" % (epoch + 1, n_epoch, time.time() - start_time))  
  119.             train_loss, train_acc, n_batch = 000  
  120.             for X_train_a, y_train_a in tl.iterate.minibatches(  
  121.                                     X_train, y_train, batch_size, shuffle=True):  
  122.                 dp_dict = tl.utils.dict_to_one( network.all_drop )    # disable noise layers  
  123.                 feed_dict = {x: X_train_a, y_: y_train_a}  
  124.                 feed_dict.update(dp_dict)  
  125.                 err, ac = sess.run([cost, acc], feed_dict=feed_dict)  
  126.                 train_loss += err; train_acc += ac; n_batch += 1  
  127.             print("   train loss: %f" % (train_loss/ n_batch))  
  128.             print("   train acc: %f" % (train_acc/ n_batch))  
  129.             val_loss, val_acc, n_batch = 000  
  130.             for X_val_a, y_val_a in tl.iterate.minibatches(  
  131.                                         X_val, y_val, batch_size, shuffle=True):  
  132.                 dp_dict = tl.utils.dict_to_one( network.all_drop )    # disable noise layers  
  133.                 feed_dict = {x: X_val_a, y_: y_val_a}  
  134.                 feed_dict.update(dp_dict)  
  135.                 err, ac = sess.run([cost, acc], feed_dict=feed_dict)  
  136.                 val_loss += err; val_acc += ac; n_batch += 1  
  137.             print("   val loss: %f" % (val_loss/ n_batch))  
  138.             print("   val acc: %f" % (val_acc/ n_batch))  
  139.             try:  
  140.                 tl.visualize.CNN2d(network.all_params[0].eval(),  
  141.                                     second=10, saveable=True,  
  142.                                     name='cnn1_'+str(epoch+1), fig_idx=2012)  
  143.             except:  
  144.                 raise Exception("# You should change visualize.CNN(), if you want to save the feature images for different dataset")  
  145.   
  146.     print('Evaluation')  
  147.     test_loss, test_acc, n_batch = 000  
  148.     for X_test_a, y_test_a in tl.iterate.minibatches(  
  149.                                 X_test, y_test, batch_size, shuffle=True):  
  150.         dp_dict = tl.utils.dict_to_one( network.all_drop )    # disable noise layers  
  151.         feed_dict = {x: X_test_a, y_: y_test_a}  
  152.         feed_dict.update(dp_dict)  
  153.         err, ac = sess.run([cost, acc], feed_dict=feed_dict)  
  154.         test_loss += err; test_acc += ac; n_batch += 1  
  155.     print("   test loss: %f" % (test_loss/n_batch))  
  156.     print("   test acc: %f" % (test_acc/n_batch))  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值