kears 實現CNN 01

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 30 09:35:53 2019

@author: txx
"""
import numpy as np
np.random.seed(1337)  # for reproducibility
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import Sequential
#from keras.optimizers import SGD
from keras.optimizers import Adam
from keras.layers import Dense,Activation,Convolution2D,MaxPooling2D,Flatten


# download the minst to the path '~/.keras/datasets/' if it is the first time to be called
# X shape (60000,28,28) , y shape (10000,)
(X_train,y_train),(X_test,y_test)=mnist.load_data()

# data pre-processing
X_train=X_train.reshape(-1,1,28,28)  #-1 代表smple的個數,即例子的個數
X_test=X_test.reshape(-1,1,28,28)
y_train=np_utils.to_categorical(y_train,num_classes=10)
y_test=np_utils.to_categorical(y_test,num_classes=10)


#bulid your CNN
model=Sequential()

# Conv layer 1 output shape(32,28,28)
model.add(Convolution2D(32,(5,5),border_mode='same',
                        input_shape=(1,28,28),))  #第一層要定義input_shape

model.add(Activation('relu'))

# Pooling layer 1 (max pooling) output shape (32,14,14)
model.add(MaxPooling2D(pool_size=(2,2),strides=(2,2),border_mode='same',))

# Conv layer 2 output shape (64,14,14)
model.add(Convolution2D(64,5,5,border_mode='same'))
model.add(Activation('relu'))

# Conv layer2 (max pooling) output shape (64,7,7)
model.add(MaxPooling2D(pool_size=(2,2),border_mode='same'))

# Fully connected layer 1 input shape (64*7*7)=(3136),output shape (1024)

model.add(Flatten())
model.add(Dense(1024))
model.add(Activation('relu'))

# Fully connected layer 2 to shape (10) for 10 classes
model.add(Dense(10))
model.add(Activation('softmax'))

# Another way to define your optimizer
adam=Adam(lr=1e-4)

# We add metrics to get more results you want to see
model.compile(optimizer=adam,
              loss='categorical_crossentropy',
              metrics=['accuracy'])

print('Training -----------')

# Anther way to train the model
model.fit(X_train,y_train,nb_epoch=1,batch_size=32)
print('Training ------------')

# Evaluate the model with the metrics we defined earlier
loss,accuracy=model.evaluate(X_test,y_test)

print('\ntest loss:',loss)
print('\ntest accuracy',accuracy)


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章