卷积神经网络(CNN)服装图像分类

卷积神经网络(CNN)服装图像分类

## 1. 设置GPU

import tensorflow as tf 
gpus=tf.config.list_physical_devices("GPU")
if gpus:
    gpu0 =gpus[0]
    tf.config.experimental.set_memory_growth(gpu0,True)
    tf.config.set_visible_devices([gpu0],"GPU")

## 2. 导入数据

import tensorflow as tf
from tensorflow.keras import datasets, layers, models
import matplotlib.pyplot as plt
 
(train_images, train_labels), (test_images, test_labels) = datasets.fashion_mnist.load_data()在这里插入代码片

卷积神经网络(CNN)服装图像分类_第1张图片

## 3. 归一化

train_images,test_images=train_images/255.0 ,test_images/255.0
train_images.shape,test_images.shape,train_labels.shape,test_labels.shape

在这里插入图片描述

## 4.调整图片格式

train_images = train_images.reshape((60000, 28, 28, 1))
test_images = test_images.reshape((10000, 28, 28, 1))
 
train_images.shape,test_images.shape,train_labels.shape,test_labels.shape

## 5. 可视化

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
 
plt.figure(figsize=(20,10))
for i in range(20):
    plt.subplot(5,10,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

卷积神经网络(CNN)服装图像分类_第2张图片

# 二、构建CNN网络

model = models.Sequential([
    layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)), #卷积层1,卷积核3*3
    layers.MaxPooling2D((2, 2)),                   #池化层1,2*2采样
    layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层2,卷积核3*3
    layers.MaxPooling2D((2, 2)),                   #池化层2,2*2采样
    layers.Conv2D(64, (3, 3), activation='relu'),  #卷积层3,卷积核3*3
     
    layers.Flatten(),                      #Flatten层,连接卷积层与全连接层
    layers.Dense(64, activation='relu'),   #全连接层,特征进一步提取
    layers.Dense(10)                       #输出层,输出预期结果
])
 
model.summary()  # 打印网络结构

卷积神经网络(CNN)服装图像分类_第3张图片

# 三、编译

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
 

# 四、训练模型

history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))
 

卷积神经网络(CNN)服装图像分类_第4张图片

# 五、预测

plt.imshow(test_images[1])

卷积神经网络(CNN)服装图像分类_第5张图片

import numpy as np
 
pre = model.predict(test_images)
print(class_names[np.argmax(pre[1])])
 

卷积神经网络(CNN)服装图像分类_第6张图片

# 六、模型评估

plt.plot(history.history['accuracy'], label='accuracy')
plt.plot(history.history['val_accuracy'], label = 'val_accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.ylim([0.5, 1])
plt.legend(loc='lower right')
plt.show()
 
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)
 

卷积神经网络(CNN)服装图像分类_第7张图片

print("测试准确率为:",test_acc)

在这里插入图片描述

你可能感兴趣的:(深度学习案例,分类,cnn,机器学习)