Home > Technology peripherals > AI > Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

PHPz
Release: 2023-05-16 09:34:16
forward
1335 people have browsed it

Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

In this article, we will use TensorFlow and Keras to create an image classifier that can distinguish between images of cats and dogs. To do this, we will use the cats_vs_dogs dataset from the TensorFlow dataset. The dataset consists of 25,000 labeled images of cats and dogs, of which 80% are used for training, 10% for validation, and 10% for testing.

Loading data

We start by loading the dataset using TensorFlow Datasets. Split the data set into training set, validation set and test set, accounting for 80%, 10% and 10% of the data respectively, and define a function to display some sample images in the data set.

<code>import tensorflow as tfimport matplotlib.pyplot as pltimport tensorflow_datasets as tfds# 加载数据(train_data, validation_data, test_data), info = tfds.load('cats_vs_dogs', split=['train[:80%]', 'train[80%:90%]', 'train[90%:]'], with_info=True, as_supervised=True)# 获取图像的标签label_names = info.features['label'].names# 定义一个函数来显示一些样本图像plt.figure(figsize=(10, 10))for i, (image, label) in enumerate(train_data.take(9)):ax = plt.subplot(3, 3, i + 1)plt.imshow(image)plt.title(label_names[label])plt.axis('off')</code>
Copy after login

Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

Preprocessing data

Before training the model, the data needs to be preprocessed. The image will be resized to a uniform size of 150x150 pixels, the pixel values ​​will be normalized between 0 and 1, and the data will be batch processed so that it can be imported into the model in batches.

<code>IMG_SIZE = 150</code>
Copy after login
<code>def format_image(image, label):image = tf.cast(image, tf.float32) / 255.0# Normalize the pixel valuesimage = tf.image.resize(image, (IMG_SIZE, IMG_SIZE))# Resize to the desired sizereturn image, labelbatch_size = 32train_data = train_data.map(format_image).shuffle(1000).batch(batch_size)validation_data = validation_data.map(format_image).batch(batch_size)test_data = test_data.map(format_image).batch(batch_size)</code>
Copy after login

Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

##Build the model

This article will use the pre-trained MobileNet V2 model as the basic model. And add a global average pooling layer and a compact layer to it for classification. This article will freeze the weights of the base model so that only the top layer weights are updated during training.

<code>base_model = tf.keras.applications.MobileNetV2(input_shape=(IMG_SIZE, IMG_SIZE, 3), include_top=False, weights='imagenet')base_model.trainable = False</code>
Copy after login
<code>global_average_layer = tf.keras.layers.GlobalAveragePooling2D()prediction_layer = tf.keras.layers.Dense(1)model = tf.keras.Sequential([base_model,global_average_layer,prediction_layer])model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.0001),loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),metrics=['accuracy'])</code>
Copy after login
Copy after login

Training model

This article will train the model for 3 cycles and test it on the validation set after each cycle authenticating. We will save the model after training so that we can use it in future tests.

<code>global_average_layer = tf.keras.layers.GlobalAveragePooling2D()prediction_layer = tf.keras.layers.Dense(1)model = tf.keras.Sequential([base_model,global_average_layer,prediction_layer])model.compile(optimizer=tf.keras.optimizers.RMSprop(lr=0.0001),loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),metrics=['accuracy'])</code>
Copy after login
Copy after login
<code>history = model.fit(train_data,epochs=3,validation_data=validation_data)</code>
Copy after login

Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

Model History

If you want to know how the Mobilenet V2 layer works, the following figure is a result of this layer.

Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

Evaluate the model

After training is completed the model will be evaluated on the test set to see how it works How it performs on new data.

<code>loaded_model = tf.keras.models.load_model('cats_vs_dogs.h5')test_loss, test_accuracy = loaded_model.evaluate(test_data)</code>
Copy after login
<code>print('Test accuracy:', test_accuracy)</code>
Copy after login

Prediction

Finally, this article will use the model to predict some sample images in the test set and display the results.

<code>for image , _ in test_.take(90) : passpre = loaded_model.predict(image)plt.figure(figsize = (10 , 10))j = Nonefor value in enumerate(pre) : plt.subplot(7,7,value[0]+1)plt.imshow(image[value[0]])plt.xticks([])plt.yticks([])if value[1] > pre.mean() :j = 1color = 'blue' if j == _[value[0]] else 'red'plt.title('dog' , color = color)else : j = 0color = 'blue' if j == _[value[0]] else 'red'plt.title('cat' , color = color)plt.show()</code>
Copy after login

Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras

Done! We created an image classifier that can differentiate between images of cats and dogs by using TensorFlow and Keras. With some adjustments and fine-tuning, this approach can also be applied to other image classification problems.

The above is the detailed content of Create a deep learning classifier for cat and dog pictures using TensorFlow and Keras. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:51cto.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template