家具分类:基于卷积神经网络的最新版本代码实现
数据集收集、读取
import os import numpy as np import matplotlib.pyplot as plt import tensorflow as tf from tensorflow.keras.preprocessing.image import ImageDataGenerator
data_dir = r'C:\Users\24423\Desktop\Course Design for Deep Learning\image' train_dir = os.path.join(data_dir, 'train') test_dir = os.path.join(data_dir, 'test')
导入所需库
加载数据集并进行数据可视化
class_names = sorted(os.listdir(train_dir)) print('Class names:', class_names)
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, fill_mode='nearest') test_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(train_dir, target_size=(224, 224), batch_size=32, class_mode='categorical') test_generator = test_datagen.flow_from_directory(test_dir, target_size=(224, 224), batch_size=32, class_mode='categorical')
将标签进行one-hot编码
train_labels = train_generator.classes train_labels = tf.keras.utils.to_categorical(train_labels)
test_labels = test_generator.classes test_labels = tf.keras.utils.to_categorical(test_labels)
将数据集划分为训练集和验证集
train_data, val_data = tf.split(train_generator, [1600, 400]) train_labels, val_labels = tf.split(train_labels, [1600, 400])
搭建卷积神经网络模型
model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Conv2D(64, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Conv2D(128, (3, 3), activation='relu'), tf.keras.layers.MaxPooling2D((2, 2)), tf.keras.layers.Flatten(), tf.keras.layers.Dense(512, activation='relu'), tf.keras.layers.Dense(4, activation='softmax') ])
参数优化
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
训练模型
history = model.fit(train_data, train_labels, epochs=50, batch_size=32, validation_data=(val_data, val_labels))
显示模型结构
model.summary()
绘制准确率及Loss曲线图
acc = history.history['accuracy'] val_acc = history.history['val_accuracy'] loss = history.history['loss'] val_loss = history.history['val_loss'] epochs = range(len(acc))
plt.plot(epochs, acc, 'r', label='Training accuracy') plt.plot(epochs, val_acc, 'b', label='Validation accuracy') plt.title('Training and validation accuracy') plt.legend(loc=0) plt.figure()
plt.plot(epochs, loss, 'r', label='Training loss') plt.plot(epochs, val_loss, 'b', label='Validation loss') plt.title('Training and validation loss') plt.legend(loc=0) plt.show()
图像识别展示
test_image = tf.keras.preprocessing.image.load_img(r'C:\Users\24423\Desktop\Course Design for Deep Learning\image\test\chair\00000013.jpg', target_size=(224, 224)) test_image = tf.keras.preprocessing.image.img_to_array(test_image) test_image = np.expand_dims(test_image, axis=0) result = model.predict(test_image) print(result) predicted_class_indices=np.argmax(result,axis=1) print(predicted_class_indices) labels = (train_generator.class_indices) print(labels) labels = dict((v,k) for k,v in labels.items()) predictions = [labels[k] for k in predicted_class_indices] print(predictions)
原文地址: https://www.cveoy.top/t/topic/oy4f 著作权归作者所有。请勿转载和采集!