Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize digit recognition and change parameters by CNN

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

1. Overview of network hierarchy

Input layer: input data into the original training image

Conv1:6 5 * 5 convolution kernels with a step size Stride of 1

Pooling1: convolution kernel size is 2 * 2, step size Stride is 2

Conv2:12 5 * 5 convolution kernels with a step size Stride of 1

Pooling2: convolution kernel size is 2 * 2, step size Stride is 2

Output layer: output to 10-dimensional vector

two。 Basic process of experiment

(1) obtain training data and test data

Directly use the handwritten dataset in keras

From keras.datasets import mnist

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

(2) define the network hierarchy.

Code:

Def get_model ():

Model = Sequential ()

Model.add (Conv2D (filters=6, kernel_size= (5,5), strides=1,activation='relu',input_shape= (28,28,1)

Model.add (MaxPooling2D (pool_size= (2,2), strides=2))

Model.add (Conv2D (filters=12, kernel_size= (5,5), strides=1,activation='relu'))

Model.add (MaxPooling2D (pool_size= (2,2), strides=2))

Model.add (Flatten ())

# model.add (Conv2D (filters=120, kernel_size= (5,5), activation='relu'))

Model.add (Dense (120, activation='relu'))

Model.add (Dense (84, activation='relu'))

Model.add (Dropout, 0.5)

Model.add (Dense (10, activation='softmax'))

# compilation model, using multi-classification loss function, and the optimizer is Adadelta

Model.compile (loss='categorical_crossentropy'

Optimizer='Adadelta'

Metrics= ['accuracy'])

Return model

(3) Cross-validation

Attach the code directly

Def k_cross (data,target,bsize,epoch,sp):

Print ("- perform cross-validation -")

The sum of ans=0 # cross-validation accuracy

Kf = KFold (n_splits=sp, shuffle = True)

For train, test in kf.split (data):

Model.fit (data [train], target [train]

Batch_size=bsize

Epochs=epoch

Verbose=0

Validation_data= (data [test], target [test])

Score = model.evaluate (data [test], target [test], verbose=0)

Ans+=score [1]

Return ans/sp

3 complete code

I have a 70% discount here, which is too much and takes too long to run.

Finally, the complete code:

#-*-coding: utf-8-*-

""

Created on Tue Dec 10 15:42:27 2019

@ author: pff

""

From _ _ future__ import print_function

Import numpy as np

Import keras

From keras.datasets import mnist

From keras.models import Sequential

From keras.layers import Dense, Dropout, Flatten

From keras.layers import Conv2D, MaxPooling2D

From sklearn.model_selection import KFold

Import matplotlib.pyplot as plt

Def getdata ():

# extract training set and test set

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

X_train = x_train.astype ('float32')

X_test = x_test.astype ('float32')

X_train / = 255

X_test / = 255

X_train = x_train.reshape (x_train.shape [0], 28,28,1)

X_test = x_test.reshape (x_test.shape [0], 28,28,1)

# using one-hot coding

Y_train = keras.utils.to_categorical (y_train, 10)

Y_test = keras.utils.to_categorical (y_test, 10)

# merge the test set and the training set for later cross-validation

Data = np.row_stack ((Xerox girls drones x test))

Target = np.row_stack ((yawdust dint yearly test))

Return data, target

# Building a model

Def get_model ():

Model = Sequential () the cost of painless induced abortion in Zhengzhou http://www.zzzykdfk.com/

Model.add (Conv2D (filters=6, kernel_size= (5,5), strides=1,activation='relu',input_shape= (28,28,1)

Model.add (MaxPooling2D (pool_size= (2,2), strides=2))

Model.add (Conv2D (filters=12, kernel_size= (5,5), strides=1,activation='relu'))

Model.add (MaxPooling2D (pool_size= (2,2), strides=2))

Model.add (Flatten ())

# model.add (Conv2D (filters=120, kernel_size= (5,5), activation='relu'))

Model.add (Dense (120, activation='relu'))

Model.add (Dense (84, activation='relu'))

Model.add (Dropout, 0.5)

Model.add (Dense (10, activation='softmax'))

# compilation model, using multi-classification loss function, using Adadelta algorithm as optimization method

Model.compile (loss='categorical_crossentropy'

Optimizer='Adadelta'

Metrics= ['accuracy'])

Return model

Def kcross (data,target,bsize,epoch,sp):

Print ("- perform cross-validation -")

Ans=0

Kf = KFold (n_splits=sp, shuffle = True)

For train, test in kf.split (data):

# print ("the {} start" .format (iTunes 1))

Model.fit (data [train], target [train]

Batch_size=bsize

Epochs=epoch

Verbose=0

Validation_data= (data [test], target [test])

Score = model.evaluate (data [test], target [test], verbose=0)

Ans+=score [1]

Return ans/sp

# draw the result picture

Def draw (batch_size,y,epoch):

Plt.figure ()

Plt.rcParams ['font.sans-serif'] =' SimHei'

Plt.ylabel ('correct')

Plt.xlabel ('batch_size')

Plt.title ('convolutional Neural Network digit recognition Diagram with different parameters')

For i in range (len (y)):

Plt.scatter (batch_size, y [I], swarm 30, clockwise ritual, marker='x', linewidths=1)

Plt.plot (batch_size,y [I], label= "epoch:" + str (epoch [I]))

Plt.legend ()

Plt.show ()

If _ _ name__== "_ _ main__":

Data,target=getdata ()

Model=get_model ()

''

Set epoch and baitch_size parameters

Y: store the results of each time

''

Epoch= [1,3,5,7]

Size= [50100150200250]

Y=np.zeros ([4pr 5])

For i in range (len (epoch)):

For j in range (len (size)):

Print ("now:", iMagna j)

Y [iMagnej] = kcross (data,target,size [j], epoch [I], 3)

Draw (size,y,epoch)

Finally, the running result is obtained.

Thank you for reading, the above is the content of "how to achieve digital recognition and change parameters in CNN". After the study of this article, I believe you have a deeper understanding of how to achieve digital recognition and change parameters in CNN, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report