本帖最后由 XJTU DJI CLUB 于 2017-4-25 16:28 编辑
#######################这是代码######################## '''Trains a simple convnet on the MNIST dataset. Gets to 99.25% test accuracy after 12epochs (there is still a lot of margin forparameter tuning). 16 seconds per epoch on a GRID K520 GPU. ''' #准确率99.25%非常高了,那些搞错的我觉得我看了也有可能搞错,所以结果已经很好啦。 from __future__ import print_function import keras from keras.datasets import mnist #数据集也不用自己操心啦 from keras.models import Sequential from keras.layers import Dense, Dropout,Flatten from keras.layers import Conv2D,MaxPooling2D from keras import backend as K #import了很多东西,这些都是CNN里面的经典的单元。学了CNN就明白啦
batch_size = 128 num_classes = 10 epochs = 12 #这三行定义了CNN里面必要的参数 # input image dimensions img_rows, img_cols = 28, 28 #MNIST数据集的图片的长宽是28*28的,这里定义了CNN输入图片的大小 # the data, shuffled and split betweentrain and test sets (x_train, y_train), (x_test, y_test) =mnist.load_data() #这里加载了训练和测试的数据集 if K.image_data_format() =='channels_first': x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols) x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols) input_shape = (1, img_rows, img_cols) else: x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1) x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1) input_shape =(img_rows, img_cols, 1) #因为数据集的格式不同嘛,这里先判断一下 x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 #图片做个归一化,把0-255的范围变到0-1 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') print(x_test.shape[0], 'test samples') # convert class vectors to binary classmatrices y_train =keras.utils.to_categorical(y_train, num_classes) y_test = keras.utils.to_categorical(y_test,num_classes) #转化一下label的格式 model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3),activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes,activation='softmax')) model.compile(loss=keras.losses.categorical_crossentropy, optimizer=keras.optimizers.Adadelta(), metrics=['accuracy']) #上面这一段呢,定义了这个CNN的结构,两个Conv层,pooling,然后一个全连接,再来一个softmax输出,就这么简单 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, verbose=1, validation_data=(x_test, y_test)) #上面这一句话呢,就是训练,代码跑起来就不用管啦,看着loss在欢快的降,GPU不错的话,几分钟就搞定。 score = model.evaluate(x_test, y_test,verbose=0) print('Test loss:', score[0]) print('Test accuracy:', score[1]) #测试以下网络的效果,你得到的结果可能不是99.25%,但是差的不多,因为初始化是随机的嘛。
#等等,这就完啦? #让我看看这个令人开心的99.25%然后就没然后啦? #网络结构和参数都没有保存啊。。。。。。 #以下代码是我写的。。。。保存一下网络结构和参数。 net_save_path='./network_structure/mnist.json' weight_save_path='./network_structure/mnist.h5' #自己设置的保存路径 json_string = model.to_json() open(net_save_path,'w').write(json_string) model.save_weights(weight_save_path) print 'network saved'
########################代码结束############################
我们训练得到了一个CNN,就是那个黑箱子,现在我们要开始使用它了。 #######################这是代码######################## import cv2 #记得安装opencv,用来做图片预处理,当然其他库也可以 import numpy as np import keras from keras.models import model_from_json from keras.optimizers import SGD #前面图像预处理的部分我就不写啦,聪明的你肯定能把数字的部分从图片中分离出来,然后二值化,resize到28*28,除以255,转成(1, img_rows, img_cols)或者(img_rows, img_cols,1)的格式,记得要和训练时候一样哦。 net_save_path='./network_structure/mnist.json' weight_save_path='./network_structure/mnist.h5' model =model_from_json(open(net_save_path).read()) model.load_weights(weight_save_path) print 'model loaded' #加载网络格式和参数的文件 sgd = SGD(lr=0.01, decay=1e-9,momentum=0.6, nesterov=True) model.compile(loss='mean_squared_error',optimizer=sgd) #这里一定要先compile一下,以为原理上来说么,keras 的网络是compile以后使用的,为了快嘛。 cls_output=model.predict_on_batch(X_input) #得到结果,是不是很简单 ########################代码结束############################ 我觉的可能大概一个小时左右吧,当然如果你用CPU训练的话速度会慢一点,网络不好的话安装会慢一点。嘿嘿,没有吹牛,任务完成。
|