python2版本-莫烦tensorflow可视化2

import tensorflow._api.v2.compat.v1 as tf
import numpy as np
tf.disable_v2_behavior()
def add_layer(input, insize, outsize, n_layer, active_function=None):
    layer_name = 'layer%s' % n_layer  
    with tf.name_scope(layer_name):  # 定义层的大框架,用做神经网络的结构图
        with tf.name_scope('Weights'):  # 定义大框架之中的小内容
            Wights = tf.Variable(tf.random_normal([insize, outsize]))
            tf.summary.histogram(layer_name + '/weights', Wights)#要进行可视化的参数
        with tf.name_scope('biases'):
            bias = tf.Variable(tf.zeros([1, outsize]) + 0.1)
            tf.summary.histogram(layer_name + '/biases', bias)
        with tf.name_scope('Wx_plus_bias'):
            Wx_plus_bias = tf.matmul(input, Wights) + bias
        if active_function is None:
            output = Wx_plus_bias
        else:
            output = active_function(Wx_plus_bias)
        tf.summary.histogram(layer_name + '/output', output)
        return output
# 要进行拟合的数据
x_data = np.linspace(-1, 1, 300)[:, np.newaxis].astype('float32')
# 在-1和1之间随机生成300个数,定义类型为float32,newaxis表示维度
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

# 对输入的数据进行占位符
with tf.name_scope('inputs'):  # 为生成神经网络的结构图,将两个输入放入 ’inputs‘的框架之中
    x = tf.placeholder(tf.float32, [None, 1], name='x_input')
    y = tf.placeholder(tf.float32, [None, 1], name='y_input')
l1 = add_layer(x, 1, 10, n_layer=1, active_function=tf.nn.relu)
prediction = add_layer(l1, 10, 1, n_layer=2, active_function=None)

# 定义损失
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.reduce_sum(tf.square(y - prediction, name='reduce_sum'), reduction_indices=[1], name='reduce_sum'),
        name='reduce_mean')
    tf.summary.scalar('loss', loss)
with tf.name_scope('train_step'):
    train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)


sess = tf.Session()
merged = tf.summary.merge_all()
# 合并前面的各项参数图
writer = tf.summary.FileWriter('E:\python_file\logs', sess.graph)
# 将可视化的图表文件保存到指定文件夹
init = tf.global_variables_initializer()
#初始化所有变量
sess.run(init)
for i in range(1000):
    sess.run(train_step, feed_dict={x: x_data, y: y_data})
#进行训练
    if i % 50 == 0:  # print(sess.run(loss,feed_dict={x:x_data,y:y_data}))
        result = sess.run(merged, feed_dict={x: x_data, y: y_data})
        writer.add_summary(result, i)   #每间隔50步记录一个点

先运行代码,最后打开terminal终端

运行tensorboard --logdir =logs

 如果类似loss曲线图中的曲线太多,是保存的logs文件夹中文件太多。可以删除多余的文件

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值