必应壁纸供图
Tensorflow神经网络模型-鲜花种类识别
数据集:https://download.csdn.net/download/weixin_53742691/87982215
导入相关依赖
import warnings
import re
from IPython.display import clear_output, display
from tkinter import Tk, filedialog
from ipywidgets import Button
import cv2
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import tensorflow as tf
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
warnings.filterwarnings("ignore")
数据探索
flower_category = "flowers"
categorys = 0
categorys_list = []
for category in os.listdir(flower_category):
categorys += 1
categorys_list.append(category)
print("种类总数为:%d" % categorys)
print(categorys_list)
种类总数为:5
['daisy', 'dandelion', 'rose', 'sunflower', 'tulip']
file_path = "flowers/sunflower/"
file_count = 0
for file in os.listdir(file_path):
if re.match(r'\S*\.?[jpg,png,jpeg]', file):
file_count += 1
print("文件总数是:%d" % file_count)
文件总数是:733
图片处理器
def img_deal(img_path):
img = cv2.imread(img_path)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2RGB)
img = cv2.resize(img, (224, 224))
return img
图片预览
sample_list = []
num = 0
for sample in os.listdir(file_path):
num += 1
sample = "flowers/sunflower/"+sample
sample_list.append(sample)
if num == 5:
break
print(sample_list)
['flowers/sunflower/1008566138_6927679c8a.jpg', 'flowers/sunflower/1022552002_2b93faf9e7_n.jpg', 'flowers/sunflower/1022552036_67d33d5bd8_n.jpg', 'flowers/sunflower/10386503264_e05387e1f7_m.jpg', 'flowers/sunflower/10386522775_4f8c616999_m.jpg']
plt.figure(figsize=(20, 20))
for i in range(5):
plt.subplot(1, 5, i+1)
img = img_deal(sample_list[i])
plt.imshow(img)
plt.xlabel("sunflower "+str(i+1))
plt.xticks([])
plt.yticks([])
plt.show()
数据预处理
# 输入图片大小
img_size = (224, 224)
# 图像数据生成
gen = tf.keras.preprocessing.image.ImageDataGenerator(
img_size,
validation_split=0.25,
preprocessing_function=tf.keras.applications.mobilenet_v2.preprocess_input
)
设置训练集
train_generator = gen.flow_from_directory(
# 设置图片加载路径
"flowers/",
# 设置加载图片大小
img_size,
# 设置批次大小
batch_size=32,
class_mode="categorical",
subset="training"
)
Found 3238 images belonging to 5 classes.
设置验证集
validation_generator = gen.flow_from_directory(
"flowers/",
img_size,
batch_size=32,
class_mode="categorical",
subset="validation"
)
Found 1079 images belonging to 5 classes.
处理后的图片预览shuffle
plt.figure(figsize=(26, 10))
for i in range(32):
plt.subplot(4, 8, i+1)
sample = train_generator[0][0][i]
# 设置图片色彩通道最小值
sample = np.maximum(sample, 0)
# 设置图片标签
plt.imshow(sample)
plt.xlabel(i)
plt.xticks([])
plt.yticks([])
plt.show()
模型搭建和训练
# 基础模型
base_model = tf.keras.applications.MobileNetV2(
weights="imagenet",
include_top=False,
input_shape=(224, 224, 3)
)
# 锁定其他节点
for layers in base_model.layers:
layers.trainable = False
# 重建模型
model = tf.keras.Sequential([
base_model,
# 展平
tf.keras.layers.Flatten(),
# 添加神经元
tf.keras.layers.Dense(units=128, activation="relu"),
tf.keras.layers.Dense(units=64, activation="relu"),
tf.keras.layers.Dense(units=5, activation="softmax")
])
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
mobilenetv2_1.00_224 (Funct (None, 7, 7, 1280) 2257984
ional)
flatten (Flatten) (None, 62720) 0
dense (Dense) (None, 128) 8028288
dense_1 (Dense) (None, 64) 8256
dense_2 (Dense) (None, 5) 325
=================================================================
Total params: 10,294,853
Trainable params: 8,036,869
Non-trainable params: 2,257,984
_________________________________________________________________
model.compile(loss="categorical_crossentropy",
optimizer="adam", metrics=['accuracy'])
history = model.fit(train_generator,
epochs=5,
validation_data=validation_generator)
Epoch 1/5
102/102 [==============================] - 49s 320ms/step - loss: 1.1481 - accuracy: 0.7712 - val_loss: 0.5897 - val_accuracy: 0.8360
Epoch 2/5
102/102 [==============================] - 35s 343ms/step - loss: 0.1766 - accuracy: 0.9469 - val_loss: 0.6906 - val_accuracy: 0.8573
Epoch 3/5
102/102 [==============================] - 30s 289ms/step - loss: 0.0371 - accuracy: 0.9864 - val_loss: 0.6850 - val_accuracy: 0.8703
Epoch 4/5
102/102 [==============================] - 28s 273ms/step - loss: 0.0144 - accuracy: 0.9957 - val_loss: 0.7199 - val_accuracy: 0.8703
Epoch 5/5
102/102 [==============================] - 29s 282ms/step - loss: 0.0013 - accuracy: 1.0000 - val_loss: 0.6943 - val_accuracy: 0.8749
model.save("models/flower_model.h5")
自主测试
model = tf.keras.models.load_model("models/flower_model.h5")
model.summary()
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
mobilenetv2_1.00_224 (Funct (None, 7, 7, 1280) 2257984
ional)
flatten (Flatten) (None, 62720) 0
dense (Dense) (None, 128) 8028288
dense_1 (Dense) (None, 64) 8256
dense_2 (Dense) (None, 5) 325
=================================================================
Total params: 10,294,853
Trainable params: 8,036,869
Non-trainable params: 2,257,984
_________________________________________________________________
def select_file(b):
clear_output()
root = Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
b.files = filedialog.askopenfilename(multiple=True)
print(b.files)
fileselect = Button(description="选择文件")
fileselect.on_click(select_file)
display(fileselect)
Button(description='选择文件', style=ButtonStyle())
len(fileselect.files)
25
plt.figure(figsize=(20, 20))
for i in range(25):
plt.subplot(5, 5, i+1)
img = img_deal(fileselect.files[i])
plt.imshow(img)
plt.xlabel(i+1)
plt.xticks([])
plt.yticks([])
plt.show()
# 图片进行打包
from tensorflow.keras.applications.densenet import preprocess_input
test_img = []
for i in range(25):
img = img_deal(fileselect.files[i])
test_img.append(img)
test_img = np.asarray(test_img)
test_pre_image = preprocess_input(test_img)
test_pre_image.shape
(25, 224, 224, 3)
decoder_dict = dict(zip(train_generator.class_indices.values(),
train_generator.class_indices.keys()))
decoder_dict
{0: 'daisy', 1: 'dandelion', 2: 'rose', 3: 'sunflower', 4: 'tulip'}
predictions = model.predict(test_pre_image)
for prediction in predictions:
print(decoder_dict[prediction.argmax()], end=" ")
sunflower tulip tulip rose rose rose rose tulip daisy sunflower dandelion rose daisy dandelion dandelion rose tulip tulip tulip daisy daisy sunflower dandelion dandelion rose
整体输出可视化测试
font = {
"size": "22",
"color": "red"
}
plt.figure(figsize=(20, 20))
for i in range(25):
plt.subplot(5, 5, i+1)
img = img_deal(fileselect.files[i])
plt.imshow(img)
img = preprocess_input(img)
img = np.expand_dims(img, 0)
result = model.predict(img)
label = decoder_dict[result.argmax()]
plt.xlabel(label, font)
plt.xticks([])
plt.yticks([])
plt.show()