使用tensorflow框架中的tensorboard 可以帮助我们更方便实现可视化
tensorflow 中 graphs的一个测试可行性
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow import float32
#载入数据,会自动通过一个脚本下载好数据集
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
#每个批次大小以及多少批次
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
#命名空间
with tf.name_scope('input'):
#设置两个占位符
x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='x-input')
y = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='y-input')
#创建一个简单的神经网络
W = tf.Variable(tf.zeros([784, 10], float32))
b = tf.Variable(tf.zeros([10]), float32)
prediction = tf.nn.softmax(tf.matmul(x, W)+b)
#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
#使用交叉熵代价函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=prediction))
#使用梯度下降方法
#train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
train_step = tf.train.AdamOptimizer(1e-2).minimize(loss) #使用别的优化方式
#初始化变量
init = tf.global_variables_initializer()
#结果放在布尔型列表中,其中argmax返回数列中最大值所在的位置
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction, 1))
#求准确性
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(init)
writer = tf.summary.FileWriter('logs/', sess.graph)#想路径中添加一个文件,不会影响训练速度
for epoch in range (1):
for batch in range (n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys})
acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})
print("Iter" + str(epoch) + "Testing Accuracy" + str(acc))
结果会生成一个文件夹,里面保存着要保存的文件
使用命令行进入logs文件夹所在的盘,比如E:/ 输入启动tensorboad的代码
tensorboard --logdir=E:/tf2/logs
然后复制cmd命令行的一个网址在谷歌浏览器打开,发现有了这个流程图,其中很大一部分是默认的图,只有input是我们在上面代码设置好的。
优化成完整的graphs图
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow import float32
#载入数据,会自动通过一个脚本下载好数据集
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
#每个批次大小以及多少批次
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
#命名空间
with tf.name_scope('input'):
#设置两个占位符
x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='x-input')
y = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='y-input')
with tf.name_scope("layer"):
#创建一个简单的神经网络
with tf.name_scope("wights"):
W = tf.Variable(tf.zeros([784, 10], float32), name='W')
with tf.name_scope("biases"):
b = tf.Variable(tf.zeros([10]), float32, name='b')
with tf.name_scope("wx_plus_b"):
wx_plus_b = tf.matmul(x, W) + b
with tf.name_scope("softmax"):
prediction = tf.nn.softmax(wx_plus_b)
#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
#使用交叉熵代价函数
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=prediction))
#使用梯度下降方法
#train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
with tf.name_scope("train"):
train_step = tf.train.AdamOptimizer(1e-2).minimize(loss) #使用别的优化方式
#初始化变量
init = tf.global_variables_initializer()
with tf.name_scope("accuracy"):
#结果放在布尔型列表中,其中argmax返回数列中最大值所在的位置
with tf.name_scope("correct_prediction"):
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction, 1))
#求准确性
with tf.name_scope("accuracy"):
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(init)
writer = tf.summary.FileWriter('logs/', sess.graph)#想路径中添加一个文件,不会影响训练速度
for epoch in range (1):
for batch in range (n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x:batch_xs, y:batch_ys})
acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})
print("Iter" + str(epoch) + "Testing Accuracy" + str(acc))
可以通过这样的图表(流程图),可以清晰看出数据流的流向,增加对数据的理解
优化增加tensorboard中例如scalars 、histograms 等的操作、
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow import float32
#载入数据,会自动通过一个脚本下载好数据集
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
#每个批次大小以及多少批次
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
# 参数概要
def variable_summaries(var):
with tf.name_scope("summaries"):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)# 平均值
with tf.name_scope("stddev"):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev) #标注差
tf.summary.scalar('max', tf.reduce_max(var)) #最大值
tf.summary.scalar('min', tf.reduce_min(var)) # 最小值
tf.summary.histogram('histogram', var) #直方图
#命名空间
with tf.name_scope('input'):
#设置两个占位符
x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='x-input')
y = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='y-input')
with tf.name_scope("layer"):
#创建一个简单的神经网络
with tf.name_scope("wights"):
W = tf.Variable(tf.zeros([784, 10], float32), name='W')
variable_summaries(W)
with tf.name_scope("biases"):
b = tf.Variable(tf.zeros([10]), float32, name='b')
variable_summaries(b)
with tf.name_scope("wx_plus_b"):
wx_plus_b = tf.matmul(x, W) + b
with tf.name_scope("softmax"):
prediction = tf.nn.softmax(wx_plus_b)
#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
#使用交叉熵代价函数
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=prediction))
tf.summary.scalar('loss', loss)
#使用梯度下降方法
#train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
with tf.name_scope("train"):
train_step = tf.train.AdamOptimizer(1e-2).minimize(loss) #使用别的优化方式
#初始化变量
init = tf.global_variables_initializer()
with tf.name_scope("accuracy"):
#结果放在布尔型列表中,其中argmax返回数列中最大值所在的位置
with tf.name_scope("correct_prediction"):
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction, 1))
#求准确性
with tf.name_scope("accuracy"):
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', accuracy)
# 合并所有的summary
merged = tf.summary.merge_all()
with tf.Session() as sess:
sess.run(init)
writer = tf.summary.FileWriter('logs/', sess.graph)#想路径中添加一个文件,不会影响训练速度
for epoch in range (51):
for batch in range (n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
summary,_ = sess.run([merged, train_step], feed_dict={x:batch_xs, y:batch_ys})
writer.add_summary(summary, epoch)
acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})
print("Iter" + str(epoch) + "Testing Accuracy" + str(acc))
tensorflow可视化
在使用tensorboard以上的功能后,还有一个更重要的可视化模块,可是使人能立体的看待训练过程。
先创建合适的文件存放区
其中在/projector/projector/是空的,用来存放代码生成的数据 /data/中的图片可以在以下链接下载名如mnist_10k_sprite.png的文件,然后放在/data/文件夹中:点击打开链接
import tensorflow as tf
from tensorflow.contrib.tensorboard.plugins import projector
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow import float32
#载入数据,会自动通过一个脚本下载好数据集
mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
#运行次数
max_steps = 1001
#图片数量
image_num = 3000
#文件路径
DIR = "E:/tf2/"
#定义会话
sess = tf.Session()
#载入图片
embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding')
# 参数概要
def variable_summaries(var):
with tf.name_scope("summaries"):
mean = tf.reduce_mean(var)
tf.summary.scalar('mean', mean)# 平均值
with tf.name_scope("stddev"):
stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
tf.summary.scalar('stddev', stddev) #标注差
tf.summary.scalar('max', tf.reduce_max(var)) #最大值
tf.summary.scalar('min', tf.reduce_min(var)) # 最小值
tf.summary.histogram('histogram', var) #直方图
#命名空间
with tf.name_scope('input'):
#设置两个占位符
x = tf.placeholder(dtype=tf.float32, shape=[None, 784], name='x-input')
y = tf.placeholder(dtype=tf.float32, shape=[None, 10], name='y-input')
#显示图片
with tf.name_scope('input_reshape'):
image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
tf.summary.image('input', image_shaped_input, 10)
with tf.name_scope("layer"):
#创建一个简单的神经网络
with tf.name_scope("wights"):
W = tf.Variable(tf.zeros([784, 10], float32), name='W')
variable_summaries(W)
with tf.name_scope("biases"):
b = tf.Variable(tf.zeros([10]), float32, name='b')
variable_summaries(b)
with tf.name_scope("wx_plus_b"):
wx_plus_b = tf.matmul(x, W) + b
with tf.name_scope("softmax"):
prediction = tf.nn.softmax(wx_plus_b)
#二次代价函数
#loss = tf.reduce_mean(tf.square(y-prediction))
#使用交叉熵代价函数
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=prediction))
tf.summary.scalar('loss', loss)
#使用梯度下降方法
#train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
with tf.name_scope("train"):
train_step = tf.train.AdamOptimizer(1e-2).minimize(loss) #使用别的优化方式
#初始化变量
sess.run(tf.global_variables_initializer())
with tf.name_scope("accuracy"):
#结果放在布尔型列表中,其中argmax返回数列中最大值所在的位置
with tf.name_scope("correct_prediction"):
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(prediction, 1))
#求准确性
with tf.name_scope("accuracy"):
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
tf.summary.scalar('accuracy', accuracy)
#产生metadata文件
if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'):
tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv' )
with open(DIR + 'projector/projector/metadata.tsv', 'w') as f:
labels = sess.run(tf.argmax(mnist.test.labels[:], 1))
for i in range(image_num):
f.write(str(labels[i]) + '/n')
# 合并所有的summary
merged = tf.summary.merge_all()
projector_writer = tf.summary.FileWriter(DIR + 'projector/projector', sess.graph)
saver = tf.train.Saver()
config = projector.ProjectorConfig()
embed = config.embeddings.add()
embed.tensor_name = embedding.name
embed.metadata_path = DIR + 'projector/projector/metadata.tsv'
embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png'
embed.sprite.single_image_dim.extend([28, 28])
projector.visualize_embeddings(projector_writer, config)
for i in range(max_steps):
#每个批次100样本
batch_xs, batch_ys = mnist.train.next_batch(100)
run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
run_metadata = tf.RunMetadata()
summary,_ = sess.run([merged, train_step], feed_dict={x:batch_xs, y:batch_ys},options=run_options,run_metadata=run_metadata)
projector_writer.add_run_metadata(run_metadata, 'step%03d' % i)
projector_writer.add_summary(summary, i)
if i % 100 == 0:
acc = sess.run(accuracy, feed_dict={x:mnist.test.images, y:mnist.test.labels})
print("Tter " + str(i) + ", Testing Accuracy= " + str(acc))
saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step = max_steps)
projector_writer.close()
sess.close()
在浏览器上查看结果数据: 结果增加了一块projector模块
可以在上面调用学习率等,在观看训练效果。