Tensor Flow实战之CNN

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data',one_hot=True)

class Net:
    def __init__(self):
        self.x = tf.placeholder(dtype=tf.float32,shape=[None,28,28,1])
        self.y = tf.placeholder(dtype=tf.float32,shape=[None,10])
        self.conv1_w = tf.Variable(tf.truncated_normal([3,3,1,8],dtype=tf.float32,stddev=0.1))
        self.conv1_b = tf.Variable(tf.zeros([8],dtype=tf.float32))
        self.conv2_w = tf.Variable(tf.truncated_normal([3,3,8,16],dtype=tf.float32,stddev=0.1))
        self.conv2_b = tf.Variable(tf.zeros([16],dtype=tf.float32))
        self.w = tf.Variable(tf.truncated_normal(dtype=tf.float32,shape=[7*7*16,10],stddev=0.1))
        self.b = tf.Variable(tf.zeros([10]))
    def forward(self):
        self.conv1 = tf.nn.relu(tf.nn.conv2d(self.x,self.conv1_w,strides=[1,1,1,1],padding='SAME')+self.conv1_b)
        self.pool1 = tf.nn.max_pool(self.conv1,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
        self.conv2 = tf.nn.relu((tf.nn.conv2d(self.pool1,self.conv2_w,strides=[1,1,1,1],padding='SAME')+self.conv2_b))
        self.pool2 = tf.nn.max_pool(self.conv2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
        self.flat = tf.reshape(self.pool2,[-1,7*7*16])
        self.yo = tf.nn.softmax(tf.matmul(self.flat,self.w)+self.b)
    def backward(self):
        self.loss = tf.reduce_mean((self.y-self.yo)**2)
        self.opt = tf.train.AdamOptimizer().minimize(self.loss)
def zql(y,y_hat):
    return tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y,1),tf.argmax(y_hat,1)),'float'))
if __name__ == '__main__':
    net = Net()
    net.forward()
    net.backward()
    init = tf.global_variables_initializer()
    with tf.Session() as sess:
        sess.run(init)
        for i in range(1000):
            x,y = mnist.train.next_batch(100)
            x = x.reshape([100,28,28,1])
            loss,_ = sess.run([net.loss,net.opt],feed_dict={net.x:x,net.y:y})
            if i%10 == 0:
                x_test,y_test = mnist.test.next_batch(100)
                x_test = x_test.reshape([100,28,28,1])
                out = sess.run(net.yo,feed_dict={net.x:x_test})
                print(sess.run(zql(y_test,out)))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值