基于CNN的猫狗识别:TensorFlow实战教程
基于CNN的猫狗识别:TensorFlow实战教程
本教程将引导您使用TensorFlow和卷积神经网络 (CNN) 构建一个简单的猫狗识别模型。
一、 项目数据集及数据预处理
1.1 项目数据集
请将您的训练集和测试集分别放置在以下目录中:
train_dir = 'path/to/train/directory'test_dir = 'path/to/test/directory'
1.2 数据预处理pythonimport tensorflow as tffrom tensorflow.keras import layersfrom tensorflow.keras.preprocessing.image import ImageDataGeneratorimport matplotlib.pyplot as plt
img_size = (150, 150)batch_size = 32
数据增强和预处理train_datagen = ImageDataGenerator( rescale=1./255, rotation_range=20, width_shift_range=0.2, height_shift_range=0.2, shear_range=0.2, zoom_range=0.2, horizontal_flip=True)
test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory( train_dir, target_size=img_size, batch_size=batch_size, class_mode='binary')
test_generator = test_datagen.flow_from_directory( test_dir, target_size=img_size, batch_size=batch_size, class_mode='binary')
二、 卷积神经网络模型搭建及模型训练
2.1 卷积神经网络模型pythonmodel = tf.keras.Sequential([ layers.Conv2D(32, (3, 3), activation='relu', input_shape=(150, 150, 3)), layers.MaxPooling2D((2, 2)), layers.Conv2D(64, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Conv2D(128, (3, 3), activation='relu'), layers.MaxPooling2D((2, 2)), layers.Flatten(), layers.Dense(128, activation='relu'), layers.Dense(1, activation='sigmoid')])
2.2 模型搭建pythonmodel.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
2.3 模型训练pythonhistory = model.fit(train_generator, steps_per_epoch=train_generator.n//batch_size, epochs=10, validation_data=test_generator, validation_steps=test_generator.n//batch_size)
三、 训练集和测试集损失率及准确率的数据可视化
3.1 训练集和测试集的损失率变化pythonplt.plot(history.history['loss'], label='Training Loss')plt.plot(history.history['val_loss'], label='Validation Loss')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()plt.show()
3.2 训练集和测试集的准确率变化pythonplt.plot(history.history['accuracy'], label='Training Accuracy')plt.plot(history.history['val_accuracy'], label='Validation Accuracy')plt.xlabel('Epoch')plt.ylabel('Accuracy')plt.legend()plt.show()
四、 模型预测及预测展示
4.1 模型预测pythontest_image_path = 'path/to/test/image.jpg'test_image = tf.keras.preprocessing.image.load_img(test_image_path, target_size=img_size)test_image = tf.keras.preprocessing.image.img_to_array(test_image)test_image = tf.expand_dims(test_image, axis=0)prediction = model.predict(test_image)[0][0]
4.2 预测展示pythonif prediction < 0.5: print('Predicted: Cat')else: print('Predicted: Dog')
五、 图片预测及识别
5.1 图片预测pythondef predict_image(image_path): image = tf.keras.preprocessing.image.load_img(image_path, target_size=img_size) image = tf.keras.preprocessing.image.img_to_array(image) image = tf.expand_dims(image, axis=0) prediction = model.predict(image)[0][0] return prediction
5.2 图片识别pythondef recognize_image(image_path): prediction = predict_image(image_path) if prediction < 0.5: return 'Cat' else: return 'Dog'
请注意:
- 请将代码中的路径进行正确设置,并根据实际情况调整模型的架构和训练参数。* 您需要安装 TensorFlow 和 matplotlib 等相关依赖库。* 在预测图片时,可以调用
predict_image(image_path)函数来获取预测结果,也可以调用recognize_image(image_path)函数来获取预测结果的简化显示 ('Cat' 或 'Dog')。
希望本教程能够帮助您入门使用 TensorFlow 进行猫狗识别!
原文地址: http://www.cveoy.top/t/topic/DUJ 著作权归作者所有。请勿转载和采集!