Tensorflow 实现Mnist手写识别 与 Tensorboard使用来画图(基于pycharmIDE) Ubuntu环境

Tensorflow中的tensorboard是个非常强大的可视化工具,这里直接进入主题:(代码见下面),关于tensorboard知识见我上一篇转载的博客:https://blog.csdn.net/weili_/article/details/81840459

这是我的代码,这无所谓,毕竟不是我要说的重点

简单的使用方法是:

tensorboard --logdir=logs

这里的logs默认放在程序的文件下

执行上述代码之后,Tensorflow会将生成图所需的数据序列化到本地文件中,我指定了生成到目录/home/lvv/Pictures/logs 中,生成成功之后,可以在PyCharm的终端中输入(一定要到你的logs文件路径下):

  train_summary = tf.summary.FileWriter(logdir='/home/lvv/Pictures/logs', graph =tf.get_default_graph())

     在终端下执行:

        tensorboard --logdir = logs

成果图:

这里有个网址:我们在浏览器中输入这个网址:http://ominisky:6006,这样就可以在tensorboard中看到你的图了。

(2)这是画整个网络的框架的代码:

  with tf.summary.FileWriter(logdir='logs', graph=tf.get_default_graph()) as train_summary:
       train_summary.flush()

这样就结束了,画图完成。

代码 :

#encoding: utf-8
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data # download and extract the data set automatically


#初始化权重
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

#初始化偏差
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)


def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def max_pool_2x2_1X1(x):
    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,1,1,1],padding='SAME')


# get the data source
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# input image:pixel 28*28 = 784
#
with tf.name_scope('input'):#占位符
    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder('float', [None, 10])  # y_ is realistic result
    #此时的真实的输入和输出需要最后运行的时候feed_dict

with tf.name_scope('image'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])  # any dim, width, height, channel(depth)
    tf.summary.image('input_image', x_image, 8)

# the first convolution layer
with tf.name_scope('conv_layer1'):
    W_conv1 = weight_variable([5, 5, 1, 32])  # convolution kernel: 5*5*1, number of kernel: 32
    b_conv1 = bias_variable([32])

    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)  # make convolution, output: 28*28*32

with tf.name_scope('pooling_layer'):
    h_pool1 = max_pool_2x2(h_conv1)  # make pooling, output: 14*14*32

# the second convolution layer
with tf.name_scope('conv_layer2'):
    W_conv2 = weight_variable([5, 5, 32, 64])  # convolution kernel: 5*5, depth: 32, number of kernel: 64
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)  # output: 14*14*64

with tf.name_scope('pooling_layer'):
    h_pool2 = max_pool_2x2(h_conv2)  # output: 7*7*64

with tf.name_scope('conv_layer3'):
    W_conv3 =weight_variable([7,7,64,64])
    b_conv3 = bias_variable([64])
    h_conv3 = tf.nn.relu(conv2d(h_pool2,W_conv3)+b_conv3)

with tf.name_scope("pooling_layer"):
    h_pool3 = max_pool_2x2_1X1(h_conv3)

# the first fully connected layer
with tf.name_scope('fc_layer3'):
    W_fc1 = weight_variable([7 * 7 * 64,1024])
    b_fc1 = bias_variable([1024])  # size: 1*1024
    h_pool3_flat = tf.reshape(h_pool3, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1)  # output: 1*1024

# dropout
with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)


# the second fully connected layer
# train the model: y = softmax(x * w + b)
with tf.name_scope('output_fc_layer4'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])  # size: 1*10

with tf.name_scope('softmax'):
    y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)  # output: 1*10

with tf.name_scope('lost'):
    cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
    tf.summary.scalar('lost', cross_entropy)


with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    tf.summary.scalar('accuracy', accuracy)

merged = tf.summary.merge_all()


with tf.summary.FileWriter(logdir='/home/lvv/Pictures/logs', graph=tf.get_default_graph()) as train_summary:
    train_summary.flush()
# init all variables
init = tf.global_variables_initializer()

# run session
with tf.Session() as sess:
    sess.run(init)
   # train_summary = tf.summary.FileWriter(logdir='/home/lvv/Pictures/logs', graph=tf.get_default_graph())
    # train data: get w and b
    for i in range(2000):  # train 2000 times
        batch = mnist.train.next_batch(50)

        result, _ = sess.run([merged, train_step], feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
        # train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

        if i % 100 == 0:
            # train_accuracy = sess.run(accuracy, feed_dict)
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})  # no dropout
            print('step %d, training accuracy %g' % (i, train_accuracy))

            # result = sess.run(merged, feed_dict={x: batch[0], y_: batch[1]})
            train_summary.add_summary(result, i)
    train_summary.close()

    print('test accuracy %g' % accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值