大数据,机器学习,人工智能机器学习与数据挖掘人工智能/模式识别/机器学习精华专题

CNN in Keras

2018-08-06  本文已影响22人  上行彩虹人

CNN 架构

CNN-1.png

使用CNN进行手写数字辨识

import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense, Dropout
from keras.layers import Convolution2D, MaxPooling2D, Flatten
from keras.utils import np_utils

np.random.seed(1337)



def load_data():
    '''
    :return:测试数据 每张图片的28*28的矩阵
    '''
    path = './mnist.npz'
    f = np.load(path)
    x_train, y_train = f['x_train'], f['y_train']
    x_test, y_test = f['x_test'], f['y_test']
    f.close()
    x_train = x_train.reshape(x_train.shape[0], 28, 28,1).astype('float32')
    x_test = x_test.reshape(x_test.shape[0],28, 28,1).astype('float32')
    X_train = x_train / 255
    X_test = x_test / 255
    y_train = np_utils.to_categorical(y_train)
    y_test = np_utils.to_categorical(y_test)
    num_classes = y_test.shape[1]
    return (x_train, y_train), (x_test, y_test)


(x_train, y_train), (x_test, y_test) = load_data()

model = Sequential()
'''
CNN部分
Convolution -->  Maxpooling --> Convolution -->  Maxpooling --> Flatten
'''
#                      30个3*3的filter       输入:28*28*1(28*28*3 RGB3色)
model.add(Convolution2D(30, 5, 5,input_shape=(28,28,1),activation='relu'))
model.add(Dropout(0.4))
#maxpooling
model.add(MaxPooling2D(2,2))
model.add(Convolution2D(15, 3, 3,activation='relu'))
model.add(Dropout(0.4))
#flatten
model.add(Flatten())
'''
Deep Neural Nerwork部分 
'''
model.add(Dense(units=128, activation='relu'))
model.add(Dense(units=50, activation='relu'))
model.add(Dense(units=10,activation='softmax'))
model.compile(loss='categorical_crossentropy',optimizer='adam', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=200, epochs=10)
'''
输出结果
'''
result = model.evaluate(x_train, y_train, batch_size=10000)
print('\nTrain Acc:', result[1])
result = model.evaluate(x_test,y_test,batch_size=10000)
print('\nTest Acc-Chini:', result[1])

测试结果:测试结果理想!!!!


result.png
上一篇下一篇

猜你喜欢

热点阅读