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 implement tensorflow in python to realize zebra crossing recognition

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly shows you "how to achieve zebra crossing recognition in tensorflow in python", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to achieve zebra crossing recognition in python tensorflow" this article.

First, the data set of zebra crossing

Composition of the dataset:

Testtrainzebra corssing:56zebra corssing:168other:54other:164 II, code part 1. Guide package

Import tensorflow as tffrom tensorflow.keras.preprocessing.image import ImageDataGeneratorimport numpy as npimport matplotlib.pyplot as pltimport keras2. Data import

Train_dir=r'C:\ Users\ zx\ Deep Learning\ Zebra\ train'test_dir=r'C:\ Users\ zx\ Deep Learning\ Zebra\ test'train_datagen = ImageDataGenerator (rescale=1/255, rotation_range=10, # rotation horizontal_flip=True) train_generator = train_datagen.flow_from_directory (train_dir (50, 50), batch_size=1, class_mode='binary' Shuffle=False) test_datagen = ImageDataGenerator (rescale=1/255) test_generator = test_datagen.flow_from_directory (test_dir, (50 Magazine 50), batch_size=1 Class_mode='binary', shuffle=False) 3. Build a model

Different people have different opinions on the establishment of the model, and they can adjust themselves to find a better model.

Model = tf.keras.models.Sequential ([# layer 1 convolution, convolution kernel is 16, input is 150, 150, 1 tf.keras.layers.Conv2D (16, (3), activation='relu',padding='same',input_shape= (50, (2), tf.keras.layers.MaxPooling2D ((2)), # layer 2 convolution, convolution kernel is 3, 3, a total of 32 Tf.keras.layers.Conv2D (32, (3jue 3), activation='relu'), tf.keras.layers.MaxPooling2D ((2jue 2)), # layer 3 convolution, convolution kernel is 3x 3, a total of 64, tf.keras.layers.Conv2D (64, (3jue 3), activation='relu'), tf.keras.layers.MaxPooling2D ((2jue 2)), # layer 4 convolution, convolution kernel is 3o 3 A total of 128pieces of # tf.keras.layers.Conv2D (128c, (3Magne3), activation='relu'), # tf.keras.layers.MaxPooling2D ((2Mague 2)), # data smoothing tf.keras.layers.Flatten (), tf.keras.layers.Dense (32pr), tf.keras.layers.Dense (16pr), tf.keras.layers.Dense (2) Activation='softmax')]) print (model.summary ()) model.compile (optimize='adam', loss=tf.keras.losses.sparse_categorical_crossentropy, metrics= ['acc']) 4 Model training

History = model.fit (train_generator, epochs=20, verbose=1) model.save ('. / Zebra.h6')

Model training process:

We can see that the acc of our model has increased from 0.63 to 0.96 after 20 rounds of training.

5. Model evaluation

Model.evaluate (test_generator)

# Visual plt.plot (history.history ['acc'], label='accuracy') plt.xlabel (' Epoch') plt.ylabel ('Accuracy') plt.ylim ([0.7,1]) plt.legend (loc='lower right') plt.title (' acc') plt.show ()

6. Model prediction.

Although the acc of our model reached 0.96 during training, the test set is the only standard for testing the model, and the score in model.evaluate (test_generator) is only about 0.91. it shows that our model has been able to complete the two-classification problem of "zebra crossing" and "non-zebra crossing" with a high correct rate, but we still have to see which data are not correctly identified by the model.

Pred=model.predict (test_generator) # get the output of the test set filenames = test_generator.filenames # get the file name of the test data

Error output process:

1, loop the length of the test set, first judge others or zebra by if statement, and then judge whether the prediction is correct by one-hot coding.

2, according to labels, we can know others': 0, 'zebra crossing': 1, so as to judge whether the prediction is correct.

3. Slice filenames [0] = 'others\\ 103.png'.

4, find the's'of others or the 'gathers of zebra crossing, and use find () on the basis of + 2 as the starting point of the positive slice (the sample number is preceded by a'\ 'symbol, so + 2 can take out the number correctly).

5, for example, assigning the value of filenames [I] to int a [int (a.find ('s') + 2):] is expressed as' xx.png'.

6, splice the sample number with the path, read and draw.

7. Break out of the cycle.

For i in range (len (filenames)): if filenames [I] [: 6] = = 'others': if np.argmax (pred [I])! = 0: a=filenames [I] plt.figure () print (' picture of prediction error:'+ a [int (a.find ('s') + 2):]) print ('misidentified as "zebra crossing" The correct type is "others") print ('Forecast tag is:' + str (np.argmax (pred [I])) +' The real tag is: 0') img = plt.imread ('Zebra/test/others/'+a [int (a.find (' s') + 2):]) plt.imshow (img) plt.title (a [a.find (a.find ('s') + 2):]) plt.grid (False) break if filenames [I] [: 6] = 'zebra': If np.argmax (pred [I])! = 1: B = filenames [I] plt.figure () print ('picture of prediction error:' + b [int (b.find ('g') + 2):]) print ('misidentified as "others" The correct type is "zebra crossing") print ('Forecast tag is:' + str (np.argmax (pred [I])) +' The real tag is: 1') img = plt.imread ('Zebra/test/zebra crossing/'+b [int (b.find (' g') + 2):]) plt.imshow (img) plt.title (b [int (b.find ('g') + 2):]) plt.grid (False) break

Seeing this wrong sample, I guess it may be because the part of the zebra crossing only accounts for about half of the image, so the prediction is wrong.

Here is my way to make predictive judgments, which could not have been so complicated to use test_generator.labels to get the data tags, and then make judgments.

Test_generator.labels

Only the first erroneous sample is output above, so next we will look at all the mispredicted samples

Sum=0for i in range (len (filenames)): if filenames [I] [: 6] = = 'others': if np.argmax (pred [I])! = 0: a=filenames [I] print (' picture of misprediction:'+ a [int (a.find ('s') + 2):] +'is incorrectly identified as "zebra crossing" The correct type is "others") sum=sum+1 if filenames [I] [: 6] = = 'zebra': if np.argmax (pred [I])! = 1: B = filenames [I] print ('incorrect picture:' + b [int (b.find ('g') + 2):] +', misidentified as "others" The correct type is "zebra crossing") sum=sum+1print ('error rate:' + str (sum/100) +'%') print ('correct:' + str ((10000-sum) / 100) +'%')

Third, analysis

When building the model, I try to use only one neuron in the last layer, use sigmoid to activate the function, other parameters remain the same, in the same epochs=20 conditions, can also quickly converge to a very high acc, the score of the test set can also be around 0.9. but in the final output of all the error samples, I found that the error samples are far more than softmax, maybe some of the parameters I did not adjust according to sigmoid, so there will be such a high error rate.

These are all the contents of the article "how to achieve zebra crossing recognition with tensorflow in python". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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