Keras实现一个简单的CNN的分类例子

还是将keras样例库中的mnist中的数据集使用CNN进行分类。
注意引包的时候多了一些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,经过两轮完全训练
这里写图片描述

这是测试之后的
这里写图片描述

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值