【人工智能项目】Fashion Mnist识别实验

[Pytorch框架] 5.3 Fashion MNIST进行分类 文章目录5.3 Fashion MNIST进行分类Fashion MNIST 介绍数据集介绍分类格式数据提交数据加载创建网络损失函数优化器开始训练训练后操作可视化损失函数保存模型模型评估进一步优化再次进行评估总结 import torch,math from pathlib import Path import pandas as pd import numpy as np import matplotlib.pyplot as plt import torchvision.datasets as ds 阅读详情
AI摘要

本文介绍了使用词袋模型、HOG特征、MLP多层感知器及CNN卷积神经网络四种方法对FashionMnist数据集进行图像识别的过程及结果。

【人工智能项目】Fashion Mnist识别实验

本次主要通过四个方法对fashion mnist进行识别实验,主要为词袋模型、hog特征、mlp多层感知器和cnn卷积神经网络。那么话不多说,走起来瓷!!!
在这里插入图片描述

Fashion Mnist

Fashion MNIST 是一个包含 70000 张灰度图像,涵盖 10 个类别(T恤,鞋子等类别)的图像数据集。以下图像显示了单件服饰在较低分辨率(28x28 像素)下的效果:

在这里插入图片描述

下面将做什么呢?

在这里插入图片描述

一、导入Fashion Mnist

1.导入模块

# 导入库
import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\framework\dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorboard\compat\tensorflow_stub\dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint8 = np.dtype([("qint8", np.int8, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorboard\compat\tensorflow_stub\dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint8 = np.dtype([("quint8", np.uint8, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorboard\compat\tensorflow_stub\dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint16 = np.dtype([("qint16", np.int16, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorboard\compat\tensorflow_stub\dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_quint16 = np.dtype([("quint16", np.uint16, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorboard\compat\tensorflow_stub\dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  _np_qint32 = np.dtype([("qint32", np.int32, 1)])
D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorboard\compat\tensorflow_stub\dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
  np_resource = np.dtype([("resource", np.ubyte, 1)])

在tf.keras中已经集成了下载与加载Fashion-MNIST数据集的骨架程序,只需要导入与加载数据即可,数据集中的60000图片用于训练网络,10000张图片用于评估经过学习的网络分类图像的准确率
注:在机器学习中,我们一般会将数据集按照8:2的比例分为训练数据集和测试数据集,训练数据集用于训练模型,测试数据集用于测试训练好的模型的准确率.

2.加载数据集

# 加载数据集
fashion_mnist = keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

加载完数据集后会返回4个 Numpy 数组

  • train_images 和 train_labels 数组是训练集,即模型用于学习的数据,共有60000张
  • 测试集 test_images 和 test_labels 数组用于测试模型。共有10000张
  • train_images 和 test_images 中都为 28x28 的 NumPy 数组,每个点的值都是介于 0 到 255 之间。代表了当前这张图片 test_images 和test_labels是一个10维的整数数组,每个维度的值都是介于0到9之间。代表了当前图像的标签,这些标签对应于图像代表的服饰所属的类别:

3.探索数据集

#我们先探索数据集的格式,然后再训练模型。我们先查看一下数据集中的图片的形状 
print(train_images.shape)
(60000, 28, 28)
#我们再查看一下 数据集中标签的形状
print(train_labels.shape)
(60000,)
# 可视化
## 创建新的图像
plt.figure()
## 显示图像 (填入图像)
plt.imshow(train_images[0])
## 给子图添加colorbar(颜色条或渐变色条)
plt.colorbar()
## 设置网格线
plt.grid(False)

在这里插入图片描述

4.查看标签

在这里插入图片描述

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
print(train_labels[0])
print(class_names[train_labels[0]])
9
Ankle boot

5.预处理归一化操作

我们将图片中的这些值缩小到 0 到 1 之间,然后将其馈送到神经网络模型。为此,将图像组件的数据类型从整数转换为浮点数,然后除以 255。这样更容易训练,以下是预处理图像的函数:务必要以相同的方式对训练集和测试集进行预处理:

train_images = train_images / 255.0
test_images = test_images / 255.0
# 显示预处理完之后的图像
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)

在这里插入图片描述

#显示训练集中的前 25 张图像,并在每张图像下显示类别名称。验证确保数据格式正确无误,然后我们就可以开始构建和训练网络了。
plt.figure(figsize=(10,10))
for i in range(25):
    ## 在当前图下生成子图 5*5个图
    plt.subplot(5,5,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]])

在这里插入图片描述

二、基于词袋模型

  • (1)依然是对每张图片提取其特征点,比如提取了SIFT特征点
  • (2)对所有图片的所有的SIFT特征点,整体进行kmeans聚类,将词划分成多个不同的类,类的个数定义为wordCount。
  • (3)对每张图片,计算不同的类的SIFT特征的个数,对应所要得到的特征向量中的一个维度。则我们可以对每张图片生成一个wordCount维的向量。

取得一幅图像的BoW向量的步骤:

  • 构建图像库的视觉词典Vocabulary
    • 提取图像库中所有图像的局部特征,如SIFT.
    • 对提取到的图像特征进行聚类,如k-means,得到聚类中心就是图像库的视觉词汇词典Vocabulary
  • 计算一幅图像的BoW向量
    • 提取图像的局部特征
    • 统计Vocabulay中的每个视觉词汇visual word ,在图像中出现的频率。
import os
import cv2
import pickle
import numpy as np
import matplotlib.pyplot as plt
from imutils import paths
from sklearn.cluster import KMeans
from scipy.cluster.vq import vq
from sklearn.model_selection import train_test_split

from sklearn.svm import LinearSVC
print(train_images.shape)
print(train_labels.shape)
print(test_images.shape)
print(test_labels.shape)
(60000, 28, 28)
(60000,)
(10000, 28, 28)
(10000,)
sifts_img = [] # 存放所有图像的文件名和sift特征

limit = 10000 #最大训练个数

count = 0 # 词袋特征个数
num = 0 # 有效个数
label = []
for i in range(limit):
    img = train_images[i].reshape(28,28)
    img = np.uint8(np.double(img) * 255)
    sift = cv2.xfeatures2d.SIFT_create()
    kp,des = sift.detectAndCompute(img,None)
    if des is None:
        continue
    sifts_img.append(des)
    label.append(train_labels[i])
    count = count + des.shape[0]
    num = num + 1

label = np.array(label)

data = sifts_img[0]
for des in sifts_img[1:]:
    data = np.vstack((data, des))

print("train file:",num)
count = int(count / 40)
count = max(4,count)
train file: 9236
# 对sift特征进行聚类
k_means = KMeans(n_clusters=int(count), n_init=4)
k_means.fit(data)


# 构建所有样本的词袋表示
image_features = np.zeros([int(num),int(count)],'float32')
for i in range(int(num)):
    ws, d = vq(sifts_img[i],k_means.cluster_centers_)# 计算各个sift特征所属的视觉词汇
    for w in ws:
        image_features[i][w] += 1  # 对应视觉词汇位置元素加1


x_tra, x_val, y_tra, y_val = train_test_split(image_features,label,test_size=0.2)
# 构建线性SVM对象并训练
clf = LinearSVC(C=1, loss="hinge").fit(x_tra, y_tra)
# 训练数据预测正确率
print (clf.score(x_val, y_val))




# save the training model as pickle
with open('bow_kmeans.pickle','wb') as fw:
    pickle.dump(k_means,fw)
with open('bow_clf.pickle','wb') as fw:
    pickle.dump(clf,fw)
with open('bow_count.pickle','wb') as fw:
    pickle.dump(count,fw)
print('Trainning successfully and save the model')

0.6293290043290043
Trainning successfully and save the model


D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\sklearn\svm\_base.py:947: ConvergenceWarning: Liblinear failed to converge, increase the number of iterations.
  "the number of iterations.", ConvergenceWarning)
with open('bow_kmeans.pickle','rb') as fr:
    k_means = pickle.load(fr)
with open('bow_clf.pickle','rb') as fr:
    clf = pickle.load(fr)
with open('bow_count.pickle','rb') as fr:
    count = pickle.load(fr)

target_file = ['T-shirt','Trouser','Pullover',
               'Dress','Coat','Sandal','Shirt',
               'Sneaker','Bag','Ankle boot']

plt.figure()
cnt = 30
i = 1
while(i<=12):
    img = test_images[cnt].reshape(28,28)
    cnt = cnt + 1
    img = np.uint8(np.double(img) * 255)
    sift = cv2.xfeatures2d.SIFT_create()
    kp,des = sift.detectAndCompute(img,None)
    if des is None:
        continue
    words, distance = vq(des, k_means.cluster_centers_)
    image_features_search = np.zeros((int(count)), "float32")
    for w in words:
        image_features_search[w] += 1
    t = clf.predict(image_features_search.reshape(1,-1))
    plt.subplot(3,4,i)
    i += 1
    plt.imshow(img,'gray')
    plt.title(target_file[t[0]])
    plt.axis('off')
plt.show()

在这里插入图片描述

with open('bow_kmeans.pickle','rb') as fr:
    k_means = pickle.load(fr)
with open('bow_clf.pickle','rb') as fr:
    clf = pickle.load(fr)
with open('bow_count.pickle','rb') as fr:
    count = pickle.load(fr)


i = 0
len = test_images.shape[0]
predict_arr = []

while(i<len):
    img = test_images[i].reshape(28,28)
    img = np.uint8(np.double(img) * 255)
    sift = cv2.xfeatures2d.SIFT_create()
    print(i)
    kp,des = sift.detectAndCompute(img,None)
    if des is None:
        i += 1
        predict_arr.append(0)
        continue
    words, distance = vq(des, k_means.cluster_centers_)
    image_features_search = np.zeros((int(count)), "float32")
    for w in words:
        image_features_search[w] += 1
    t = clf.predict(image_features_search.reshape(1,-1))
    i += 1
    predict_arr.append(t[0])

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35



9995
9996
9997
9998
9999
from sklearn.metrics import accuracy_score,f1_score,confusion_matrix,classification_report

score=accuracy_score(test_labels,predict_arr)
print(score)
0.5651
print(classification_report(test_labels,predict_arr))
              precision    recall  f1-score   support

           0       0.36      0.60      0.45      1000
           1       0.72      0.47      0.57      1000
           2       0.43      0.47      0.45      1000
           3       0.49      0.46      0.47      1000
           4       0.45      0.44      0.44      1000
           5       0.79      0.74      0.76      1000
           6       0.36      0.24      0.29      1000
           7       0.74      0.74      0.74      1000
           8       0.67      0.66      0.66      1000
           9       0.79      0.84      0.81      1000

    accuracy                           0.57     10000
   macro avg       0.58      0.57      0.56     10000
weighted avg       0.58      0.57      0.56     10000
import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
%matplotlib inline
sns.set()

# 混淆矩阵


matrix = confusion_matrix(test_labels,predict_arr)
print(matrix)
sns.heatmap(matrix,annot=True)
[[598  17  56 109  45  20  89  15  38  13]
 [384 473  11  91   7   2   8   7  15   2]
 [ 73  22 465  55 192  22  96  15  53   7]
 [184  46  61 459  63  30  43  33  69  12]
 [ 47  14 245  45 441  19 119  14  48   8]
 [ 43  20   9  25   8 740  13  88  16  38]
 [205  22 161  78 184  23 238  11  59  19]
 [ 41   6   5  22   7  50   8 743   9 109]
 [ 71  32  60  49  39  19  44  17 658  11]
 [ 27   2   3  10   5  17   9  67  24 836]]





<matplotlib.axes._subplots.AxesSubplot at 0x1f384714548>

在这里插入图片描述

三、基于HOG特征

Histogram of Oriented Gridients,缩写为HOG,是目前计算机视觉、模式识别领域很常用的一种描述图像局部纹理的特征。这个特征名字起的也很直白,就是说先计算图片某一区域中不同方向上梯度的值,然后进行累积,得到直方图,这个直方图呢,就可以代表这块区域了,也就是作为特征,可以输入到分类器里面了。那么,接下来介绍一下HOG的具体原理和计算方法,以及一些引申。

因为HOG是一个局部特征,因此如果你对一大幅图片直接提取特征,是得不到好的效果的。原理很简单。从信息论角度讲,例如一幅640*480的图像,大概有30万个像素点,也就是说原始数据有30万维特征,如果直接做HOG的话,就算按照360度,分成360个bin,也没有表示这么大一幅图像的能力。从特征工程的角度看,一般来说,只有图像区域比较小的情况,基于统计原理的直方图对于该区域才有表达能力,如果图像区域比较大,那么两个完全不同的图像的HOG特征,也可能很相似。但是如果区域较小,这种可能性就很小。最后,把图像分割成很多区块,然后对每个区块计算HOG特征,这也包含了几何(位置)特性。例如,正面的人脸,左上部分的图像区块提取的HOG特征一般是和眼睛的HOG特征符合的。

import warnings
warnings.filterwarnings("ignore")

import os
import cv2
import pickle
import numpy as np
import matplotlib.pyplot as plt
from imutils import paths
from skimage.feature import hog
from scipy.cluster.vq import vq
from sklearn.svm import LinearSVC
from sklearn.model_selection import train_test_split
limit = train_images.shape[0]

data = [] # HoG特征
label = []
for i in range(limit):
    img = train_images[i].reshape(28,28)
    img = np.uint8(np.double(img) * 255)
    fd = hog(img)
    data.append(fd)
    label.append(train_labels[i])

data = np.array(data)
label = np.array(label)

x_tra, x_val, y_tra, y_val = train_test_split(data,label,test_size=0.2)

print('train file:',y_tra.size)
print('val file:',y_val.size)

# 构建线性SVM对象并训练
clf = LinearSVC(C=1, loss="hinge").fit(x_tra, y_tra)
# 训练数据预测正确率
print ('accuracy:',clf.score(x_val, y_val))



# save the training model as pickle
with open('hog.pickle','wb') as fw:
    pickle.dump(clf,fw)
print('Trainning successfully and save the model')
train file: 48000
val file: 12000
accuracy: 0.799
Trainning successfully and save the model
with open('hog.pickle','rb') as fr:
    clf = pickle.load(fr)

target_file = ['T-shirt','Trouser','Pullover',
               'Dress','Coat','Sandal','Shirt',
               'Sneaker','Bag','Ankle boot']

plt.figure()
cnt = 30
i = 1
while(i<=12):
    img = test_images[cnt].reshape(28,28)
    cnt = cnt + 1
    img = np.uint8(np.double(img) * 255)
    fd = hog(img)
    t = clf.predict([fd])
    plt.subplot(3,4,i)
    i += 1
    plt.imshow(img,'gray')
    plt.title(target_file[t[0]])
    plt.axis('off')
plt.show()

在这里插入图片描述

with open('hog.pickle','rb') as fr:
    clf = pickle.load(fr)


i = 0
len = test_images.shape[0]
predict_arr = []

while(i<len):
    img = test_images[i].reshape(28,28)
    img = np.uint8(np.double(img) * 255)
    fd = hog(img)
    t = clf.predict([fd])
    i += 1
    predict_arr.append(t[0])
from sklearn.metrics import accuracy_score,f1_score,confusion_matrix,classification_report

score=accuracy_score(test_labels,predict_arr)
print(score)
0.7904
print(classification_report(test_labels,predict_arr))
              precision    recall  f1-score   support

           0       0.70      0.81      0.75      1000
           1       0.94      0.94      0.94      1000
           2       0.62      0.71      0.67      1000
           3       0.79      0.82      0.81      1000
           4       0.61      0.79      0.69      1000
           5       0.92      0.89      0.90      1000
           6       0.47      0.16      0.24      1000
           7       0.87      0.90      0.88      1000
           8       0.91      0.94      0.92      1000
           9       0.94      0.94      0.94      1000

    accuracy                           0.79     10000
   macro avg       0.78      0.79      0.77     10000
weighted avg       0.78      0.79      0.77     10000
import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
%matplotlib inline
sns.set()

# 混淆矩阵


matrix = confusion_matrix(test_labels,predict_arr)
print(matrix)
sns.heatmap(matrix,annot=True)
[[811  15  50  48  21   3  37   0  14   1]
 [  3 943  10  32   4   0   7   0   1   0]
 [ 37   1 715  15 166   1  51   0  14   0]
 [ 25  33  31 817  50   0  37   0   6   1]
 [ 16   5 103  50 790   0  27   0   9   0]
 [  0   0   0   2   1 890   3  86   5  13]
 [253   8 228  57 253   0 159   0  42   0]
 [  0   0   0   0   0  59   1 897   1  42]
 [  6   2   8   8   9   8  13   2 943   1]
 [  0   0   0   0   0  10   2  45   4 939]]





<matplotlib.axes._subplots.AxesSubplot at 0x1f382c92408>

在这里插入图片描述

四、MLP多层感知器

多层感知机(MLP,Multilayer Perceptron)也叫人工神经网络(ANN,Artificial Neural Network),除了输入输出层,它中间可以有多个隐层,最简单的MLP只含一个隐层,即三层的结构

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D
from keras.utils.vis_utils import plot_model
from keras.utils import np_utils
X_train = train_images.reshape((-1,784))
X_test = test_images.reshape(-1,784)
Y_train = np_utils.to_categorical(train_labels,num_classes=10)
Y_test = np_utils.to_categorical(test_labels,num_classes=10)
# Build MLP
model = Sequential()

model.add(Dense(units=256,
                input_dim=784,
                kernel_initializer='normal',
                activation='relu'))

model.add(Dense(units=10,
                kernel_initializer='normal',
                activation='softmax'))

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_3 (Dense)              (None, 256)               200960    
_________________________________________________________________
dense_4 (Dense)              (None, 10)                2570      
=================================================================
Total params: 203,530
Trainable params: 203,530
Non-trainable params: 0
_________________________________________________________________
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, Y_train, batch_size=500, epochs=10, verbose=1, validation_data=(X_test, Y_test))
model.save('mlp_fashion_mnist.h5')
WARNING:tensorflow:From D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\tensorflow\python\ops\math_grad.py:1250: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.
Instructions for updating:
Use tf.where in 2.0, which has the same broadcast rule as np.where
WARNING:tensorflow:From D:\software\Anaconda\anaconda\envs\tensorflow\lib\site-packages\keras\backend\tensorflow_backend.py:977: The name tf.assign_add is deprecated. Please use tf.compat.v1.assign_add instead.

Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 28s 459us/step - loss: 0.6751 - acc: 0.7771 - val_loss: 0.4986 - val_acc: 0.8310
Epoch 2/10
60000/60000 [==============================] - 1s 19us/step - loss: 0.4437 - acc: 0.8480 - val_loss: 0.4469 - val_acc: 0.8400
Epoch 3/10
60000/60000 [==============================] - 2s 31us/step - loss: 0.3997 - acc: 0.8609 - val_loss: 0.4300 - val_acc: 0.8481
Epoch 4/10
60000/60000 [==============================] - 1s 18us/step - loss: 0.3749 - acc: 0.8682 - val_loss: 0.4151 - val_acc: 0.8546
Epoch 5/10
60000/60000 [==============================] - 1s 18us/step - loss: 0.3512 - acc: 0.8767 - val_loss: 0.3819 - val_acc: 0.8646
Epoch 6/10
60000/60000 [==============================] - 1s 19us/step - loss: 0.3345 - acc: 0.8819 - val_loss: 0.3882 - val_acc: 0.8625
Epoch 7/10
60000/60000 [==============================] - 1s 19us/step - loss: 0.3224 - acc: 0.8855 - val_loss: 0.3654 - val_acc: 0.8725
Epoch 8/10
60000/60000 [==============================] - 1s 19us/step - loss: 0.3086 - acc: 0.8889 - val_loss: 0.3558 - val_acc: 0.8723
Epoch 9/10
60000/60000 [==============================] - 1s 18us/step - loss: 0.2980 - acc: 0.8926 - val_loss: 0.3548 - val_acc: 0.8744
Epoch 10/10
60000/60000 [==============================] - 1s 19us/step - loss: 0.2879 - acc: 0.8963 - val_loss: 0.3560 - val_acc: 0.8719
from keras.models import load_model
model = load_model('mlp_fashion_mnist.h5')
plt.figure()
cnt = 30
i = 1
while(i<=12):
    img = [X_test[cnt]]
    cnt = cnt + 1
    img = np.uint8(np.double(img) * 255)
    t = model.predict(img)
    result = np.argmax(t, axis=1)
    plt.subplot(3,4,i)
    i += 1
    plt.imshow(img[0].reshape(28,28),'gray')
    plt.title(target_file[result[0]])
    plt.axis('off')
plt.show()

在这里插入图片描述

loss, accuracy = model.evaluate(X_test, Y_test, verbose=0)
print('loss:', loss)
print('accuracy:', accuracy)
loss: 0.35601275362968443
accuracy: 0.8719
predict = model.predict_classes(X_test)

from sklearn.metrics import accuracy_score,f1_score,confusion_matrix,classification_report

score=accuracy_score(test_labels,predict)
print(score)
0.8719
print(classification_report(test_labels,predict))
              precision    recall  f1-score   support

           0       0.81      0.86      0.83      1000
           1       0.97      0.97      0.97      1000
           2       0.79      0.74      0.76      1000
           3       0.85      0.90      0.87      1000
           4       0.72      0.87      0.79      1000
           5       0.97      0.94      0.96      1000
           6       0.78      0.55      0.65      1000
           7       0.93      0.95      0.94      1000
           8       0.96      0.97      0.96      1000
           9       0.95      0.96      0.96      1000

    accuracy                           0.87     10000
   macro avg       0.87      0.87      0.87     10000
weighted avg       0.87      0.87      0.87     10000
import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
%matplotlib inline
sns.set()

# 混淆矩阵


matrix = confusion_matrix(test_labels,predict)
print(matrix)
sns.heatmap(matrix,annot=True)
[[858   2  14  44   5   2  62   0  13   0]
 [  2 971   0  21   4   0   1   0   1   0]
 [ 22   3 739  15 173   0  46   0   2   0]
 [ 15  22  12 895  36   0  16   0   4   0]
 [  0   1  62  30 874   0  29   0   4   0]
 [  0   0   0   1   0 945   0  35   2  17]
 [161   4 100  45 123   0 551   0  16   0]
 [  0   0   0   0   0  16   0 955   0  29]
 [  4   1   7   4   6   3   0   5 970   0]
 [  0   0   0   0   0   7   1  31   0 961]]





<matplotlib.axes._subplots.AxesSubplot at 0x1f383b67a48>

在这里插入图片描述

五、CNN卷积神经网络

import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Activation
from keras.layers import Conv2D, MaxPooling2D
from keras.utils.vis_utils import plot_model
from keras.utils import np_utils
X_train = train_images.reshape((-1,28,28,1))
X_test = test_images.reshape(-1,28,28,1)
Y_train = np_utils.to_categorical(train_labels,num_classes=10)
Y_test = np_utils.to_categorical(test_labels,num_classes=10)
# Build LeNet-5
model = Sequential()
model.add(Conv2D(filters=6, kernel_size=(5, 5), padding='valid', input_shape=(28, 28, 1), activation='relu')) # C1
model.add(MaxPooling2D(pool_size=(2, 2))) # S2
model.add(Conv2D(filters=16, kernel_size=(5, 5), padding='valid', activation='relu')) # C3
model.add(MaxPooling2D(pool_size=(2, 2))) # S4
model.add(Flatten())
model.add(Dense(120, activation='tanh')) # C5
model.add(Dense(84, activation='tanh')) # F6
model.add(Dense(10, activation='softmax')) # output
model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_3 (Conv2D)            (None, 24, 24, 6)         156       
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 6)         0         
_________________________________________________________________
conv2d_4 (Conv2D)            (None, 8, 8, 16)          2416      
_________________________________________________________________
max_pooling2d_4 (MaxPooling2 (None, 4, 4, 16)          0         
_________________________________________________________________
flatten_2 (Flatten)          (None, 256)               0         
_________________________________________________________________
dense_8 (Dense)              (None, 120)               30840     
_________________________________________________________________
dense_9 (Dense)              (None, 84)                10164     
_________________________________________________________________
dense_10 (Dense)             (None, 10)                850       
=================================================================
Total params: 44,426
Trainable params: 44,426
Non-trainable params: 0
_________________________________________________________________
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, Y_train, batch_size=500, epochs=10, verbose=1, validation_data=(X_test, Y_test))
model.save('cnn_fashion_mnist.h5')
Train on 60000 samples, validate on 10000 samples
Epoch 1/10
60000/60000 [==============================] - 3s 44us/step - loss: 0.3044 - acc: 0.8892 - val_loss: 0.3304 - val_acc: 0.8774
Epoch 2/10
60000/60000 [==============================] - 2s 34us/step - loss: 0.2902 - acc: 0.8948 - val_loss: 0.3259 - val_acc: 0.8809
Epoch 3/10
60000/60000 [==============================] - 2s 35us/step - loss: 0.2826 - acc: 0.8967 - val_loss: 0.3145 - val_acc: 0.8865
Epoch 4/10
60000/60000 [==============================] - 2s 33us/step - loss: 0.2724 - acc: 0.9002 - val_loss: 0.3158 - val_acc: 0.8862
Epoch 5/10
60000/60000 [==============================] - 2s 33us/step - loss: 0.2683 - acc: 0.9025 - val_loss: 0.3174 - val_acc: 0.8843
Epoch 6/10
60000/60000 [==============================] - 2s 34us/step - loss: 0.2610 - acc: 0.9047 - val_loss: 0.3040 - val_acc: 0.8900
Epoch 7/10
60000/60000 [==============================] - 2s 34us/step - loss: 0.2519 - acc: 0.9082 - val_loss: 0.3015 - val_acc: 0.8904
Epoch 8/10
60000/60000 [==============================] - 2s 33us/step - loss: 0.2481 - acc: 0.9086 - val_loss: 0.3097 - val_acc: 0.8877
Epoch 9/10
60000/60000 [==============================] - 2s 34us/step - loss: 0.2432 - acc: 0.9107 - val_loss: 0.2940 - val_acc: 0.8936
Epoch 10/10
60000/60000 [==============================] - 2s 34us/step - loss: 0.2355 - acc: 0.9134 - val_loss: 0.2934 - val_acc: 0.8924
loss, accuracy = model.evaluate(X_test, Y_test, verbose=0)
print('loss:', loss)
print('accuracy:', accuracy)
loss: 0.29342212826013564
accuracy: 0.8924
predict = model.predict_classes(X_test)

from sklearn.metrics import accuracy_score,f1_score,confusion_matrix,classification_report

score=accuracy_score(test_labels,predict)
print(score)
0.8924
print(classification_report(test_labels,predict))
              precision    recall  f1-score   support

           0       0.80      0.88      0.84      1000
           1       0.99      0.97      0.98      1000
           2       0.81      0.87      0.84      1000
           3       0.88      0.91      0.90      1000
           4       0.83      0.82      0.83      1000
           5       0.97      0.97      0.97      1000
           6       0.75      0.62      0.68      1000
           7       0.92      0.97      0.95      1000
           8       0.97      0.98      0.97      1000
           9       0.98      0.94      0.96      1000

    accuracy                           0.89     10000
   macro avg       0.89      0.89      0.89     10000
weighted avg       0.89      0.89      0.89     10000
import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
%matplotlib inline
sns.set()

# 混淆矩阵


matrix = confusion_matrix(test_labels,predict)
print(matrix)
sns.heatmap(matrix,annot=True)
[[876   1  20  26   5   2  59   0  11   0]
 [  1 971   0  20   3   0   3   0   2   0]
 [ 16   1 869  11  53   1  47   0   2   0]
 [ 21   2  10 911  21   1  30   0   3   1]
 [  3   1  83  35 819   0  58   0   1   0]
 [  1   0   0   2   0 967   0  22   0   8]
 [170   1  84  25  82   0 622   0  16   0]
 [  0   0   0   0   0  15   0 973   0  12]
 [  5   1   3   3   1   2   4   5 976   0]
 [  0   0   0   0   0   7   1  52   0 940]]





<matplotlib.axes._subplots.AxesSubplot at 0x1f4444938c8>

在这里插入图片描述

小结

那么本次实验就到此结束,点赞评论收藏一条龙走起来,瓷们!!!!
在这里插入图片描述

【深度学习系列】——Fashion-MNIST数据集简介 图像分类数据集(Fashion-MNIST)1、数据集简介2、获取数据集3、查看数据集4、图像可视化显示5、读取小批量数据 1、数据集简介 \quad \quad不同于MNIST手写数据集,Fashion-MNIST数据集包含了10个类别的图像,分别是:t-shirt(T恤),trouser(牛仔裤),pullover(套衫),dress(裙子),coat(外套),sandal(凉鞋),shirt(衬衫),sneaker(运动鞋),bag(包),ankle boot(短靴)。 2、获取数据集 1、torch 阅读详情

相关推荐

神经网络衣服分类器详解(Fashion-MNIST数据集)

文章目录前言一、Fashion-MNIST是什么?二、代码实现1.引入库2.读取数据集3.数据预处理4.搭建神经网络5.编译和训练神经网络模型6.神经网络预测总结 前言 每个想要学习深度学习、图像识别的同学,想要用到神经网络,入门的实例必定是MNIST手写数字集,这是所有人都绕不开的,我也是,我之前写了三篇关于MNIST的博文。en…但这个数据集毕竟只有手写数字,有时候并不是能够满足我们开发的要求,于是,Fashion-MNIST出现了。 提示:以下是本篇文章正文内容,下面案例可供参考 一、Fash

weixin_43873671的博客 1万+

深度学习实践1--FashionMNIST分类

目录一、深度学习实践目录实践1--FashionMNIST分类文章目录前言二、FashionMNIST分类1.介绍数据集2.获取数据集3.分批迭代数据 4.数据可视化5.构建网络模型​6.选择损失函数和优化器7.训练8.验证 9.训练并验证 10.写成csv 11.完整代码总结随着人工智能的发展,深度学习也越发重要,目前深度学习可以应用到多方面,如图像处理领域、语音识别领域、自然语言处理邻域等。本篇是深度学习的入门篇,FashionMNIST图像分类。

qqqxiao_qi的博客 8692

分别利用KNN与Random Forest 算法完成手绘Fashion-MNIST 10类简笔画的识别

1.Random Forest 1.1 数据准备 将下载好的Fashion-MNIST数据集中的trian集合转化为jpg格式并生成label的train.txt import torchvision.datasets.mnist as mnist root="fashion_mnist/" train_set = ( mnist.read_image_file(os.path.join...

weixin_45750855的博客 2284

【深度学习】Fashion-MNIST数据集简介

文章目录数据集简介操作下载数据集数据格式可视化显示读取小批量完整代码备注 数据集简介 不同于MNIST手写数据集,Fashion-MNIST数据集包含了10个类别的图像,分别是:t-shirt(T恤),trouser(牛仔裤),pullover(套衫),dress(裙子),coat(外套),sandal(凉鞋),shirt(衬衫),sneaker(运动鞋),bag(包),ankle boot(短靴...

qq_28869927的博客 4万+

MNIST、Fashion-MNIST、SmallNORB数据集下载与读取

介绍MNIST、Fashion-MNIST、SmallNORB数据集以及其加载方式。

猫ER 4940

Dataset之Fashion-MNIST:Fashion-MNIST数据集简介与下载

Fashion-MNIST数据集的简介与下载1. Fashion-MNIST数据集简介2. Fashion-MNIST数据集下载2.1 基于python语言下载2.2 基于Tensorflow下载2.3 手动下载 1. Fashion-MNIST数据集简介 Fashion-MNIST数据集是德国Zalando公司提供的衣物图像数据集,包含60,000个样本的训练集和10,000个样本的测试集。每个样本都是 28x28 灰度图像,与10个类别的标签相关联。Fashion-MNIST数据集旨在作为原始MNIST

全网粉丝30W+,优快云、稀土掘金人工智能领域签约作者,人工智能、大模型、Python 爬虫,商务合作,请私信沟通。 9580

PyTorch深度学习(三):Fashion-MNIST 数据集介绍

PyTorch深度学习(三):Fashion-MNIST 数据集介绍

~宪宪的博客 1万+

Fashion-MNIST数据集

Fashion-MNIST数据集,

CNN识别Fashion-MNIST

Fashion_MNIST数据集是一个替代MNIST手写数据集的图片数据集。它是由Zalando(一家德国的时尚科技公司)旗下的研究部门提供。其涵盖了来自10种类别的共7万个不同商品的正面图片。 Fashion_MNIST 的大小、格式和训练集/测试集划分与原始的 MNIST 完全一致。60000/10000 的训练测试数据划分,28x28 的灰度图片。你可以直接用它来测试你的机器学习和深度学习算...

qq_27318693的博客 4584

FashionMNIST数据集

此文件为百度云链接,通过百度云下载此文件为百度云链接,

STM32F103C8T6实战:手把手教你搭建智能火灾报警系统(附MQ-2传感器调试技巧)

本文详细介绍了基于STM32F103C8T6单片机和MQ-2烟雾传感器的智能火灾报警系统搭建过程。从硬件选型、电路设计到软件开发,提供全面的实战指导,特别包含MQ-2传感器调试技巧,帮助开发者快速实现稳定可靠的智能火灾监控系统。

year5的博客 213

TensorFlow 学习(六)时尚(衣服、鞋、包等) Fashion MNIST识别

使用 jupyter notebook 笔记,导入需要的包 # TensorFlow and tf.keras import tensorflow as tf from tensorflow import keras import numpy as np import numpy as np import matplotlib.pyplot as plt import gzip impor...

qq_35200479的博客 1万+

k8s 查看cpu使用率最高的pod

在 Kubernetes 中,可以使用命令查看 Pod 的资源使用情况,从而找到 CPU 使用率最高的 Pod。

u010674101的专栏 3344

Pytorch实现Fashion-mnist分类任务

Fashion_mnist分类任务数据概况数据处理对输入进行归一化数据增强定义Resnet网络训练与测试完整代码 数据概况 Fashion-mnist 经典的MNIST数据集包含了大量的手写数字。十几年来,来自机器学习、机器视觉、人工智能、深度学习领域的研究员们把这个数据集作为衡量算法的基准之一。你会在很多的会议,期刊的论文中发现这个数据集的身影。实际上,MNIST数据集已经成为算法作者的必测的数...

沉梦昂志 5142

西南交通大学车辆工程专业大四上车辆综合实训ame仿真部分

西南交通大学车辆工程专业大四上车辆综合实训ame仿真建模部分

qq_64814052的博客 1244

手把手教你用AD9834 DDS模块DIY一个可调信号源(附AD原理图/PCB/程序)

本文详细介绍了如何使用AD9834 DDS模块DIY一个高精度可调信号源,涵盖硬件搭建、原理图解读、PCB优化和程序烧录等关键步骤。通过STM32控制实现0-10MHz频率范围输出,特别适合电子设计与射频实验,提供完整的AD原理图、PCB设计和程序代码参考。

weixin_31854867的博客 406

Pytorch 基于AlexNet的服饰识别(使用Fashion-MNIST数据集)

Fashion-MNIST是一个替代MNIST手写数字集的图像数据集。它是由Zalando(一家德国的时尚科技公司)旗下的研究部门提供。其涵盖了来自 10 种类别的共 7 万个不同商品的正面图片。的大小、格式和训练集/测试集划分与原始的MNIST完全一致。的训练测试数据划分,28x28的灰度图片。AlexNet 是2012年 ImageNet 竞赛冠军获得者 Hinton 和他的学生 Alex Krizhevsky 设计的。AlexNet 中包含了几个比较新的技术点,也首次在 CNN 中成功应用了 ReLU

小嗷犬的博客 3243

《机器学习》周志华_自学记录

第一章绪论## 1.1引言机器学习所研究的主要内容,是关于在计算机上从数据中产生"模型"(model)的算法,即"学习算法"(learning algorithm).在面对新的情况时(例如看到一个没剖开的西瓜),模型会给我们提供相应的判断(例如好瓜).如果说计算机科学是研究关于"算法"的学问,那么类似的,可以说机器学习是研究关于"学习算法"的学问.## 1.2基本术语:用于预测离散值,例如将样本分为“好瓜”或“坏瓜”。:用于预测连续值,例如西瓜的成熟度(如0.95、0.37)。

2201_75296678的博客 2530

Pytorch 基于ResNet-18的服饰识别(使用Fashion-MNIST数据集)

残差神经网络(ResNet) 是由微软研究院的 何恺明、张祥雨、任少卿、孙剑 等人提出的。ResNet 在 2015 年的 ILSVRC(ImageNet Large Scale Visual Recognition Challenge)中取得了冠军。 残差神经网络 的主要贡献是发现了“退化现象(Degradation)”,并针对退化现象发明了 “快捷连接(Shortcut connection)”,极大的消除了深度过大的神经网络训练困难问题。神经网络的“深度”首次突破了 100 层、最大的神经网络甚至超过

小嗷犬的博客 3644

【华为OD机试真题】459、小扇和小船的数字游戏、数字游戏 | 机试真题+思路参考+代码解析(CD卷)(C++、Java、Py)

### 🎃题目描述 >小扇和小船今天又玩起来了数字游戏,小船给小扇一个正整数 n(1  现在求 m 的最小值

KJ.JK 1717

YOLO26改进105:全网首发--使用BiFPN改进特征金字塔网络

YOLOv6 v3.0在目标检测领域实现重大突破,通过改进网络架构和训练方案显著提升性能。该版本在COCO数据集上展现出优越表现:YOLOv6-N达到37.5% AP/1187 FPS,YOLOv6-S实现45.0% AP/484 FPS,均超越同类检测器。大模型YOLOv6-M/L分别达到50.0%/52.8% AP,L6版本更创下实时检测新纪录。关键技术包括RepVGGBlock、BiFusion等新型模块,通过多分支融合和高效重参数化设计提升性能。研究团队已验证各改进模块有效性,代码已开源。

AIcurator的博客 95

Fashion_mnist数据集介绍

Fashion-MNIST ](https://hanxiao.github.io/2018/09/28/Fashion-MNIST-Year-In-Review/) 目录 为什么要做这个数据集? 获取数据 如何载入数据? 基准测试 数据可视化 参与贡献 联系 在论文中引用Fashion-MNIST License Fashion-MNIST是一个替代MNIST手写数字集的图像数据集。 它是...

种花家的奋斗兔的博客 1万+

Unity零基础到入门 ☀️| 【UI系统学习】轻松学会 Unity 的 UGUI基础控件的使用(包括一个简易血条、蓝条设计)

Unity,UGUI。本篇博客来挑几种Unity中最常用的UI控件如何使用和使用技巧,包括一个简易血条蓝条的小实例

努力前行,总会成为自己心中的那道光 2万+

Pytorch 基于VGG-16的服饰识别(使用Fashion-MNIST数据集)

VGG-16 网络是14年牛津大学计算机视觉组和 Google DeepMind 公司研究员一起研发的深度网络模型。该网络一共有16个训练参数的网络,它的兄弟版本如下图所示,清晰的展示了每一级别的参数量,从11层的网络一直到19层的网络。VGG-16 网络取得了 ILSVRC 2014 比赛分类项目的第2名,定位项目的第1名。VGGNet 网络结构简洁,迁移到其他图片数据上的泛化性能非常好。VGGNet 现在依然经常被用来提取图像特征,该网络训练后的模型参数在其官网上开源了,可以用来在图像分类任务上进行在训

小嗷犬的博客 3470

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

Pytorch使用多层感知机完成MNIST手写数字识别(更新:LeNet实现Fashion-MNIST识别)

利用Pytorch使用多层感知机完成MNIST手写数字识别

qq_43858783的博客 4803

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

超越MNIST:Fashion-MNIST如何重塑机器学习基准测试?

你还在使用手写数字数据集MNIST验证算法性能吗?当经典MNIST的识别准确率已突破99.7%,它是否还能有效检验模型的泛化能力?本文将通过实测数据对比Fashion-MNIST与MNIST的核心差异,教你如何利用这个时尚单品数据集构建更具挑战性的算法评估体系。读完本文你将获得: - 两种数据集的详细特性对比 - 15种主流分类器在双数据集上的性能差异 - 可视化工具揭示的特征空间分布规律 - 从...

gitblog_00246的博客 1086

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

上一篇: 【人工智能项目】混合高斯模型运动目标检测
下一篇: 【人工智能项目】sg2im文字转图像
mind_programmonkey
mind_programmonkey 领域专家: 算法与数据结构技术领域 领域专家: 算法与数据结构技术领域
博客等级 码龄9年 4435粉丝 1111原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mind_programmonkey

你的鼓励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值