tensorflow——深度学习实现服饰识别

tensorflow——深度学习实现服饰识别

'''
服饰识别
'''
import os.path

import numpy as np
import tensorflow as tf
# 导入服饰数据 下载包
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets


class FashionMnist:
    out_features1 = 12  # 第一组卷积核数量
    out_features2 = 24  # 第二组卷积核数量
    con_neurons = 512  # 全连接层神经元数量
    model_path = './model/fashion_mnist/'

    def __init__(self, path):
        # 获取数据
        self.mnist = read_data_sets(path, one_hot=True)
        self.sess = tf.Session()

    def close(self):
        self.sess.close()

    def get_weight_var(self, shape):
        return tf.Variable(tf.truncated_normal(shape=shape, stddev=0.1))

    def get_bias_var(self, shape):
        return tf.Variable(tf.constant(0.1, shape=shape))

    def get_conv2d(self, x, w):
        # 卷积层
        # w格式为[filter_height, filter_width, in_channels, out_channels]
        return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

    def get_max_pool(self, x):
        # 池化层
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

    def create_conv_pooled_layer(self, x, input_feature, out_feature):
        w = self.get_weight_var([5, 5, input_feature, out_feature])  # 卷积核
        b = self.get_bias_var([out_feature])  # 偏置
        conv = self.get_conv2d(x, w) + b  # 卷积层
        p = self.get_max_pool(tf.nn.relu(conv))  # 激活层和池化层
        return p

    def create_fc_layer(self, x, input_feature, out_feature):
        w = self.get_weight_var([input_feature, out_feature])  # 权重
        b = self.get_bias_var([out_feature])  # 偏置
        return tf.matmul(x, w) + b  # 全连接层

    def build_model(self):
        # 输入层
        self.x = tf.placeholder(tf.float32, [None, 784])  # 图片数据
        self.y = tf.placeholder(tf.int64, [None, 10])  # 标签
        x_image = tf.reshape(self.x, [-1, 28, 28, 1])  # 将输入数据格式化为[batch, height, width, channels]
        # 第一组卷积层
        conv1 = self.create_conv_pooled_layer(x_image, 1, self.out_features1)
        # 第二组卷积层
        conv2 = self.create_conv_pooled_layer(conv1, self.out_features1, self.out_features2)
        # 全连接层
        fc = self.create_fc_layer(tf.reshape(conv2, [-1, 7 * 7 * self.out_features2]), 7 * 7 * self.out_features2,
                                  self.con_neurons)
        # 丢弃层
        dropout = tf.nn.dropout(fc, 0.5)
        # 输出层
        w = self.get_weight_var([self.con_neurons, 10])
        b = self.get_bias_var([10])
        y = tf.matmul(dropout, w) + b
        # 损失函数
        cross = tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=self.y)
        # 交叉熵
        avg_cost = tf.reduce_mean(cross)
        # 优化器
        self.train_step = tf.train.AdamOptimizer(0.001).minimize(avg_cost)
        # 准确率
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(self.y, 1))
        self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    def train(self):
        # 训练模型
        self.sess.run(tf.global_variables_initializer())  # 初始化变量
        batch_size = 100  # 每次训练的批次大小
        tra_steps = int(self.mnist.train.num_examples / batch_size)  # 训练步数
        print('开始训练')
        self.load_model()
        for i in range(2):
            total_ac = 0
            for j in range(tra_steps):
                x, y = self.mnist.train.next_batch(batch_size)  # 取一个批次的数据
                _, ac = self.sess.run([self.train_step, self.accuracy], feed_dict={
                    self.x: x,
                    self.y: y})  # 训练模型
                total_ac += ac  # 计算损失
            print('step: %d, ac: %.3f' % (i + 1, total_ac / tra_steps))
        self.save_model()

    def test(self):
        # 测试模型
        print('测试准确率:', self.sess.run([self.accuracy], feed_dict={self.x: self.mnist.test.images,
                                                                       self.y: self.mnist.test.labels}))
        self.close()

    def load_model(self):
        # 加载模型
        self.saver = tf.train.Saver()
        if os.path.exists(self.model_path):
            self.saver.restore(self.sess, self.model_path)
            print('加载模型成功')
        else:
            print('没有找到模型')

    def save_model(self):
        # 保存模型
        if not os.path.exists(self.model_path):
            os.makedirs(self.model_path)
        self.saver.save(self.sess, self.model_path)
        print('保存模型成功')


if __name__ == '__main__':
    path = './fashion/'
    fm = FashionMnist(path)
    accuracy = fm.build_model()
    fm.train()
    fm.test()
    fm.close()
    print('结束')

运行结果:

开始训练

加载模型成功

step: 1, ac: 0.991

step: 2, ac: 0.991

保存模型成功

测试准确率: [0.9869]

结束


最后编辑于:2024/05/23作者: 牛逼PHP

发表评论