Home > Software engineering >  Opencv - python ANN minist data set of neural network training, after training Predict the return va
Opencv - python ANN minist data set of neural network training, after training Predict the return va

Time:09-16



 
The import OS
The import struct
The import numpy as np
The import cv2

Def load_mnist (path, kind='train') :
"" "the Load MNIST data from ` path ` "" "
Labels_path=OS. Path. Join (path,
'% s - labels. Idx1 - ubyte'
% kind)
Images_path=OS. Path. Join (path,
'% s - images. Idx3 does - ubyte'
% kind)
With the open (labels_path, 'rb') as lbpath:
Magic, n=struct. Unpack (' & gt; II ',
Lbpath. Read (8))
Labels=np. Fromfile (lbpath,
Dtype=np. Uint8)

With the open (images_path, 'rb') as imgpath:
Magic, num, rows, cols=struct. Unpack (' & gt; IIII ',
Imgpath. Read (16))
Images=np. Fromfile (imgpath,
Dtype=np. Uint8). Reshape (len (labels), 784)

The return of images, labels

The image and labels=load_mnist (r 'C: \ Users \ \ Desktop \ Python Image_processing \ data_number', '" train ")

CharNum=10
"' n of the data set update label format for n X 10 '"'
TrainingLabel=[]
For I in range (len (labels) :
LabelArraytoAppend=[]
For j in range (charNum) :
If labels [I]==j:
LabelArraytoAppend. Append (1)
The else:
LabelArraytoAppend. Append (0)
TrainingLabel. Append (labelArraytoAppend)

"' training multi-layer neural network MLP '
Ann=cv2. Ml. ANN_MLP_create ()
Ann. SetActivationFunction (cv2. Ml. ANN_MLP_SIGMOID_SYM)
Ann. SetTrainMethod (cv2. Ml. ANN_MLP_BACKPROP)
Ann. SetBackpropMomentumScale (0.1)
Ann. SetBackpropWeightScale (0.001)
Ann. SetTermCriteria ((cv2 TERM_CRITERIA_COUNT | cv2. TERM_CRITERIA_EPS, 500, 0.05))

Ann. SetLayerSizes (np) array ([np. Array (image). Shape [1], 128, charNum], dtype=np, uint16))

Ann. "train" (np) array (image, dtype=np. Float32), cv2. Ml. ROW_SAMPLE, np, array (trainingLabel, dtype=np. Float32))
Ann. Save (r 'C: \ Users \ bj0lt5 \ \ Desktop \ Python Image_processing \ data_number \ characterRecognize XML')

"' test neural network" '
TestImage, testLabels=load_mnist (r 'C: \ Users \ \ Desktop \ Python Image_processing \ data_number', 't10k')
# result=np. Zeros ((testLabels shape [0], charNum), dtype=np. Float32)
Retval, result=Ann predict (np) array (image, dtype=np. Float32))
Print (result) [: 2]

CodePudding user response:

Why did you use python without tensorflow, data are more

CodePudding user response:

New haven't come into contact with the Tensor flow,, I go to learn, but so should also can realize, don't know where is there a problem

CodePudding user response:

Hello ~ I want to ask you that you solve this problem? Because I now also in the use of opencv to train the neural network, I also encountered this problem,
  • Related