深度学习之CNN②——类的封装(TensorFlow)

面向对象的四大特征:抽象,继承,封装,多态
核心:对象是类的实例、类是对象的类型、模板

详情查看

  • Python3 面向对象–RUNOOB
  • 面向对象编程–廖雪峰

实现代码

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

tf.set_random_seed(1)

mnist = input_data.read_data_sets('../../datas/MNIST.data',one_hot=True)

# 类
class Model:
    
    # 构造函数
    def __init__(self,sess):
        self.sess = sess        #初始化seesion对象
        self._build_net()       #调用CNN五层底层  实例化时自动调用
    
    # cnn底层封装
    def _build_net(self):

        self.x = tf.placeholder(tf.float32,[None,784])
        self.y = tf.placeholder(tf.float32,[None,10])

        x_img = tf.reshape(self.x,[-1,28,28,1])

        self.keep_prob = tf.placeholder(tf.float32)

        w1 = tf.Variable(tf.random_normal([3,3,1,32],stddev=0.01))
        L1 = tf.nn.conv2d(x_img,w1,strides=[1,1,1,1],padding='SAME')
        L1 = tf.nn.relu(L1)
        L1 = tf.nn.max_pool(L1,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
        L1 = tf.nn.dropout(L1,keep_prob=self.keep_prob)

        w2 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev=0.01))
        L2 = tf.nn.conv2d(L1, w2, strides=[1, 1, 1, 1], padding='SAME')
        L2 = tf.nn.relu(L2)
        L2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],padding='SAME')
        L2 = tf.nn.dropout(L2, keep_prob=self.keep_prob)

        w3 = tf.Variable(tf.random_normal([3, 3, 64, 128], stddev=0.01))
        L3 = tf.nn.conv2d(L2, w3, strides=[1, 1, 1, 1], padding='SAME')
        L3 = tf.nn.relu(L3)
        L3 = tf.nn.max_pool(L3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],padding='SAME')
        L3 = tf.nn.dropout(L3, keep_prob=self.keep_prob)
        L3_flat = tf.reshape(L3,[-1,128*4*4])

        w4 = tf.get_variable('w4',shape=[128*4*4,65],initializer=tf.contrib.layers.xavier_initializer())
        b4 = tf.Variable(tf.random_normal([65]))
        L4 = tf.nn.relu(tf.matmul(L3_flat,w4) + b4)
        L4 = tf.nn.dropout(L4, keep_prob=self.keep_prob)

        w5 = tf.get_variable('w5', shape=[65,10], initializer=tf.contrib.layers.xavier_initializer())
        b5 = tf.Variable(tf.random_normal([10]))
        self.a5 = tf.nn.softmax(tf.matmul(L4, w5) + b5)

        self.cost = -tf.reduce_mean(tf.reduce_sum(self.y*tf.log(self.a5),axis=1))

        self.optimize = tf.train.AdamOptimizer(0.001).minimize(self.cost)

        self.accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(self.a5,1),tf.argmax(self.y,1)),tf.float32))
    
    # 训练model封装
    def train(self,data_x,data_y,keep_prob1 = 0.7):
        return self.sess.run([self.cost,self.optimize],feed_dict = {self.x:data_x,self.y:data_y,self.keep_prob:keep_prob1})
    
    # 准确率封装
    def accuracy1(self,data_x,data_y,keep_prob1 = 1):
        return self.sess.run(self.accuracy,feed_dict={self.x: data_x, self.y: data_y, self.keep_prob: keep_prob1})

sess = tf.Session()

# 实例化对象
m = Model(sess)

sess.run(tf.global_variables_initializer())

training = 1
batch_size = 200

for i in range(training):
    avg_cost = 0
    batch = int(mnist.train.num_examples / batch_size)

    for k in range(batch):
        batch_x,batch_y = mnist.train.next_batch(batch_size)

        c,_ = m.train(batch_x,batch_y)

        avg_cost += c/batch

    print(i,avg_cost)


# 调用方法
print(m.accuracy1(mnist.test.images,mnist.test.labels))

你可能感兴趣的:(深度学习之CNN②——类的封装(TensorFlow))