tensorflow convolutional mnist

上篇博客讲述了使用了tensorflow 用全连接网络完成mnist的分类,我们将博客中的fully contact net 替换成 convolutional net测试mnist分类

import tensorflow as tf
import numpy as np
from tf_utils import *
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
#定义下权重变量,防止每次定义卷积层重新定义一次
def w_variable(shape):

  initial = tf.truncated_normal(shape, stddev=0.1)

  return tf.Variable(initial)
#定义下偏置,防止重复定义
def b_variable(shape):

  return tf.Variable(tf.constant(0.1, shape=shape))
#定义卷积
def conv2d(input_, w):

  return tf.nn.conv2d(input_, w, strides = [1, 1, 1, 1], padding = 'SAME')
#定义池化
def max_pool(input_):

  return tf.nn.max_pool(input_, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')

#定义标签维度
label_dim = 10
#定义batch_size维度
batch_size = 100
#定义图像维度
image_dim = 784

input_image = tf.placeholder(tf.float32, [None, image_dim])

input_label = tf.placeholder(tf.float32, [None, label_dim])

image = tf.reshape(input_image, [-1, 28, 28, 1])

#第一层卷积
w1 = w_variable([5, 5, 1, 32])

b1 = b_variable([32])

conv1 = tf.nn.relu(conv2d(image, w1) + b1)

output1 = max_pool(conv1)
#第二层卷积
w2 = w_variable([5, 5, 32, 64])

b2 = b_variable([64])

conv2 = tf.nn.relu(conv2d(output1, w2) + b2)

output2 = max_pool(conv2)
#全连接网络第一层
fc1 = tf.reshape(output2, [-1, 7*7*64])

w3 = w_variable([7*7*64, 1024])

b3 = b_variable([1024])

fc2 = tf.nn.relu(tf.matmul(fc1, w3) +b3)
#全连接网络第二层
w4 = w_variable([1024,10])

b4 = b_variable([10])

fc3 = tf.nn.softmax(tf.matmul(fc2, w4) +b4)

cross_entropy = tf.reduce_mean(-tf.reduce_sum(input_label * tf.log(fc3)))

train_loss = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

prediction = tf.equal(tf.argmax(input_label, 1), tf.argmax(fc3, 1))

accuary = tf.reduce_sum(tf.cast(prediction, "float"))

init = tf.global_variables_initializer()

with tf.Session() as sess:

  sess.run(init)

  for i in range(1000):

    batch_x, batch_y = mnist.train.next_batch(batch_size)

    sess.run(train_loss, feed_dict = {input_image : batch_x, input_label : batch_y})

    if i % 10 == 0:

      print(sess.run(accuary, feed_dict = {input_image:batch_x, input_label:batch_y}))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值