keras学习笔记(1)-Keras的模块架构

1.keras介绍

  keras是基于Tensorflow、Theano、CNTK后端的高层神经网络API,它简单快速的原型设计,让你可以快速的将idea转化为结果,并且可以在CPU和GPU之间无缝切换。

2. keras模块思维导图

keras学习笔记(1)-Keras的模块架构_第1张图片

3.快速上手-mnist手写字识别

#-*-coding:utf-8-*-
from keras.models import Sequential
from keras.datasets import mnist
from keras.optimizers import Adam
from keras.losses import categorical_crossentropy
from keras.layers import Dense,Reshape,Dropout,Flatten,Conv2D,MaxPool2D
from keras.utils import to_categorical

def loadData():
    (x_train,y_train),(x_test,y_test) = mnist.load_data()
    return x_train,y_train,x_test,y_test

def shuffle():
    pass

def createModel():
    model = Sequential()

    #reshape image to tensorflow backend shape (rows,clos,channels)
    model.add(Reshape(input_shape=(28,28),target_shape=(28,28,1)))
    # layer1-conv 卷积核大小:(5,5),激活函数:relu,卷积核个数:32,第一层一定要指定input_shape
    model.add(Conv2D(32,kernel_size=(5,5),input_shape=(28,28,1),activation='relu'))
    # 2*2的最大池化
    model.add(MaxPool2D(pool_size=(2,2)))

    #layer2-conv 卷积核大小:(5,5),激活函数:relu,卷积核个数:64
    model.add(Conv2D(64,kernel_size=(5,5),activation='relu'))
    # 2*2的最大池化
    model.add(MaxPool2D(pool_size=(2,2)))

    #数据一维化
    model.add(Flatten())

    #layer3-dense,输出1024
    model.add(Dense(1024,activation='relu'))
    #layer4-drop,断开神经元比例50%
    model.add(Dropout(0.5))

    #output,10个类,激活函数:softmax
    model.add(Dense(10,activation='softmax'))
    return model

def train():
    model = createModel()
    #损失函数:交叉熵 ,优化函数:adam,评估标准:精度
    model.compile(loss=categorical_crossentropy,optimizer='adam',metrics=['accuracy'])
    x_train, y_train, x_test, y_test = loadData()
    #数据归一化
    x_train = x_train.astype('float32')/255
    x_test = x_test.astype('float32')/255
    #转换为独热编码[1,2],[[0.1,0.5,...],[0.5,0.8,...]]
    y_train = to_categorical(y_train,10)
    y_test = to_categorical(y_test,10)
    #epochs:数据轮10遍,每个batch64,verbose=1: 输出日志信息
    model.fit(x=x_train,y=y_train,batch_size=64,epochs=1,shuffle=True,verbose=1, validation_data=(x_test,y_test))
    score = model.evaluate(x=x_test,y=y_test,batch_size=128,verbose=1)
    print('Test loss:', score[0])
    print('Test accuracy:', score[1])

if __name__=="__main__":
    train()

你可能感兴趣的:(机器学习)