Keras实现一个简单的CNN的分类例子
2017-07-29 10:09
676 查看
还是将keras样例库中的mnist中的数据集使用CNN进行分类。
注意引包的时候多了一些CNN需要的层。
运行结果如下:
这是训练之后的loss&accuracy,经过两轮完全训练
这是测试之后的
注意引包的时候多了一些CNN需要的层。
import numpy as np np.random.seed(1337) from keras.datasets import mnist from keras.utils import np_utils from keras.models import Sequential from keras.layers import Dense,Activation,Convolution2D,MaxPooling2D,Flatten from keras.optimizers import Adam # download the mnist to the path '~/.keras/datasets/' if it is the first time to be called # X shape (60,000 28x28), y shape (10,000, ) (X_train, y_train), (X_test, y_test) = mnist.load_data() # data pre-processing,-1 represents the number of samples;1 represents the num of channels,28&28 represents the length,width respectively X_train = X_train.reshape(-1,1,28,28) # normalize X_test = X_test.reshape(-1,1,28,28) # normalize y_train = np_utils.to_categorical(y_train,nb_classes=10) y_test = np_utils.to_categorical(y_test, nb_classes=10) #build neural network model=Sequential( ) model.add(Convolution2D( nb_filter=32, nb_col=5, nb_row=5, border_mode='same', #padding method input_shape=(1, #channels 28,28) #length and width )) model.add(Activation('relu')) model.add(MaxPooling2D( pool_size=(2,2), strides=(2,2), border_mode='same', #padding method )) //这是添加第二层神经网络,卷积层,激励函数,池化层 model.add(Convolution2D(64,5,5,border_mode='same')) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2),border_mode='same')) //将经过池化层之后的三维特征,整理成一维。方便后面建立全链接层 model.add(Flatten()) //1024像素 model.add(Dense(1024)) model.add(Activation('relu')) //输出压缩到10维,因为有10个标记 model.add(Dense(10)) //使用softmax进行分类 model.add(Activation('softmax')) # Another way to define your optimize adam=Adam(lr=1e-4) model.compile( loss='categorical_crossentropy', optimizer=adam, metrics=['accuracy']) print('\nTraining-----------') model.fit(X_train,y_train,nb_epoch=2,batch_size=32) print('\nTesting------------') loss,accuracy=model.evaluate(X_test,y_test) print('test loss: ', loss) print('test accuracy: ', accuracy)
运行结果如下:
这是训练之后的loss&accuracy,经过两轮完全训练
这是测试之后的
相关文章推荐
- Tensorflow实现一个CNN分类的例子
- SVM实现多分类的程序基础工作(二)——通过一个简单libsvm例子迈入libsvm学习的大门
- 一个简单的jQuery插件ajaxfileupload实现ajax上传文件例子
- JBPM学习(一):实现一个简单的工作流例子全过程
- 用go的goroutine和channel实现一个简单的“生产、消费”(带有超时控制)小例子
- 位运算实现加法的一个简单例子
- Keras基于TensorFlow实现的简单分类问题
- 【unity3d游戏开发之基础篇】unity3d射线的原理用法以及一个利用射线实现简单拾取的小例子
- 一个C#实现的最简单的委托例子
- 利用Keras实现多层感知器(MLP)模型和卷积神经网络(CNN)模型并对手写数字图像分类
- unity3d射线的原理用法以及一个利用射线实现简单拾取的小例子
- 实现简单的MVC模式,通过一个小例子,不是很完美,但是可以说明一部分的问题
- 一个简单实现多条件查询的例子
- Keras实现一个简单的Regression回归
- webservice xfire实现的一个超简单的例子
- 简单实现一个JSONP协议的小例子
- [Weka]在自己的算法中调用Weka实现文本分类的一个例子
- Keras学习之三:用CNN实现cifar10图像分类模型
- 由最简单的一个例子说起,匿名用户可读可写的实现(LINUX)配置
- unity3d射线的原理用法以及一个利用射线实现简单拾取的小例子