时装类别识别(神经网络实现fashion数据分类)

一、问题描述

时装类别识别
时装类别识别问题是预测一张图片中的时装类别。
数据集:fashionMnist
训练集:60000张时装图片,每张图片是28*28的灰度矩阵,有一个{0,1,…,9}的类标签,表示时装的类别。测试数据:10000张测试数据。
要求:
导入fashionMnist数据。
设计神经网络算法,完成时装类别的预测问题。
上机报告中应写出遇到问题和解决方法。
注意:fashionMnist数据集的导入,会遇到一些问题,自主尝试解决。
在这里插入图片描述

时装类别识别问题是预测一张图片中的时装类别。
数据集:fashionMnist
训练集:60000张时装图片,每张图片是28*28的灰度矩阵,有一个{0,1,…,9}的类标签,表示时装的类别。测试数据:10000张测试数据。

二、实验目的

设计神经网络算法,完成时装类别的预测问题。

三、实验内容

3.1数据导入

import tensorflow as tf
from tensorflow import keras

import numpy as np
import matplotlib.pyplot as plt

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

3.2数据预处理

在训练网络之前,必须对数据进行预处理。如果检查训练集中的第个六图像,会看到像素值处于 0 到 255 之间。
在这里插入图片描述

plt.figure()
plt.imshow(train_images[5])
plt.colorbar()
plt.grid(False)
plt.show()

将这些值缩小至 0 到 1 之间,然后将其馈送到神经网络模型。为此,请将这些值除以 255。接下里以相同的方式对训练集和测试集进行预处理,并且展示出来。
在这里插入图片描述

train_images = train_images / 255.0
test_images = test_images / 255.0
plt.figure(figsize=(10,10))
# 画出25个图片,展示
for i in range(25):
    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]])
plt.show()

3.3算法描述

神经网络分类算法是模型假设是一个含有n个输入 和k个输出的网络结构, k元交叉熵为目标函数的经验损失最小化算法。
神经网络的基本组成部分是层。层会从向其馈送的数据中提取表示形式。大多数深度学习都包括将简单的层链接在一起。大多数层(如 tf.keras.layers.Dense)都具有在训练期间才会学习的参数。
该网络的第一层 tf.keras.layers.Flatten 将图像格式从二维数组(28 x 28 像素)转换成一维数组(28 x 28 = 784 像素)。将该层视为图像中未堆叠的像素行并将其排列起来。该层没有要学习的参数,它只会重新格式化数据。
展平像素后,网络会包括两个 tf.keras.layers.Dense 层的序列。它们是密集连接或全连接神经层。第一个 Dense 层有 128 个节点(或神经元)。第二个(也是最后一个)层会返回一个长度为 10 的数组。每个节点都包含一个得分,用来表示当前图像属于 10 个类中的哪一类。

model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)), #输入图像的像素
    keras.layers.Dense(128, activation='relu'),# 计算参数 activation 激励函数 relu过滤>0
    keras.layers.Dense(10) #数据集服装10分类 softmax选出最大
])

# 神经网络初始是采用的都是随机参数
# 通过损失函数评价训练模型 通过优化函数优化模型参数
# metrics 用于监控训练和测试步骤
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
# 训练
model.fit(train_images, train_labels, epochs=10)
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

3.4主要代码(完整代码)

#首先我们需哟引入我们需要的工具模块
import tensorflow as tf
from tensorflow import keras
# 引入数据分析工具和画图工具
import numpy as np
import matplotlib.pyplot as plt

from main import predictions
# 画图函数
def plot_image(i, predictions_array, true_label, img):
 predictions_array, true_label, img = predictions_array, true_label[i], img[i]
 plt.grid(False)
 plt.xticks([])
 plt.yticks([])
 plt.imshow(img, cmap=plt.cm.binary)
 predicted_label = np.argmax(predictions_array)
 # 预测对了,显示蓝色;错了显示红色
 if predicted_label == true_label:
  color = 'blue'
 else:
  color = 'red'

 plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                      100 * np.max(predictions_array),
                                      class_names[true_label]),
            color=color)

# 画图函数
def plot_value_array(i, predictions_array, true_label):
 predictions_array, true_label = predictions_array, true_label[i]
 plt.grid(False)
 plt.xticks(range(10))
 plt.yticks([])
 thisplot = plt.bar(range(10), predictions_array, color="#777777")
 plt.ylim([0, 1])
 predicted_label = np.argmax(predictions_array)

 thisplot[predicted_label].set_color('red')
 thisplot[true_label].set_color('blue')

# 导入数据
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
plt.figure()
plt.imshow(train_images[5])
plt.colorbar()
plt.grid(False)
plt.show()

train_images = train_images / 255.0
test_images = test_images / 255.0
plt.figure(figsize=(10,10))
# 画出25个图片,展示
for i in range(25):
    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]])
plt.show()
# 序贯模型(Sequential):单输入单输出,一条路通到底,层与层之间只有相邻关系,没有跨层连接。这种模型编译速度快,操作也比较简单
model = keras.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)), #输入图像的像素
    keras.layers.Dense(128, activation='relu'),# 计算参数 activation 激励函数 relu过滤>0
    keras.layers.Dense(10) #数据集服装10分类 softmax选出最大
])
# 神经网络初始是采用的都是随机参数
# 通过损失函数评价训练模型 通过优化函数优化模型参数
# metrics 用于监控训练和测试步骤
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
# 训练
model.fit(train_images, train_labels, epochs=10)
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print('\nTest accuracy:', test_acc)
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))

# 展示运算的结果
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions[i], test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions[i], test_labels)
plt.tight_layout()
plt.show()

四、实验结果及分析

在这里插入图片描述
在这里插入图片描述

蓝色表示预测正确,红色表示预测错误。最终训练出的模型达到88%。

五、遇到的问题和解决方法

1.导入图片
一开始导入代码如下:

train_image = "D:\pythonProject\MachineLearning\homework\homework6\data\train-labels-idx1-ubyte\train-labels.idx1-ubyte"
test_image = "D:\pythonProject\MachineLearning\homework\homework6\data\train-labels-idx1-ubyte"
train_label = "D:/PyCharm/Project/machine_learning/machine_learning/homework/week13/train-labels-idx1-ubyte"
test_label = "D:\pythonProject\MachineLearning\homework\homework6\data\train-labels-idx1-ubyte"

一直出现错误。
后来采用在线下载导入。
导入数据

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

资料获取

在这里插入图片描述
1.关注微信公众号:汪程序员,回复26121600,即可获取
在这里插入图片描述

2.https://download.csdn.net/download/m0_61504367/85620097

  • 8
    点赞
  • 40
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要使用PyTorch实现MNIST分类,你可以按照以下步骤进行操作: 1. 导入所需的库和模块: ```python import torch import torchvision import torchvision.transforms as transforms import torch.nn as nn import torch.optim as optim ``` 2. 准备数据集: ```python transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) trainset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform) trainloader = torch.utils.data.DataLoader(trainset, batch_size=64, shuffle=True, num_workers=2) testset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform) testloader = torch.utils.data.DataLoader(testset, batch_size=64, shuffle=False, num_workers=2) ``` 3. 定义神经网络模型: ```python class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 4 * 4, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = x.view(-1, 16 * 4 * 4) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return x net = Net() ``` 4. 定义损失函数和优化器: ```python criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) ``` 5. 训练模型: ```python for epoch in range(10): # 迭代10个epoch running_loss = 0.0 for i, data in enumerate(trainloader, 0): inputs, labels = data optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 200 == 199: print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 200)) running_loss = 0.0 print('Finished Training') ``` 6. 测试模型: ```python correct = 0 total = 0 with torch.no_grad(): for data in testloader: images, labels = data outputs = net(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the 10000 test images: %d %%' % ( 100 * correct / total)) ``` 这就是使用PyTorch实现MNIST分类的基本步骤。你可以根据需要进行进一步的修改和优化。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

汪程序猿

就当请我吃顿饭

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

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

打赏作者

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

抵扣说明:

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

余额充值