最近在看莫烦大佬的tensorflow视频教程,然后在用tensorboard实现权重Weights,偏差biases,损失loss的时候,显示不太正常
参考bilibili弹幕上小伙伴的留言,我把代码稍稍改动了一下,上代码
import tensorflow as tf
import numpy as np
def add_layer(input,in_size,out_size,activation_function=None):
# random_normal:从正态分布中输出随机值。
# random_uniform:从均匀分布中返回随机值
with tf.name_scope('weights'):
Weights=tf.Variable(tf.random_normal([in_size,out_size]),tf.float32,name='W')
tf.summary.histogram('/weights',Weights)
with tf.name_scope('biases'):
biases=tf.Variable(tf.zeros([1,out_size]),name='b')#机器学习中推荐不为0
tf.summary.histogram( '/biases', biases)
with tf.name_scope('Wx_plus_b'):
Wx_plus_b=tf.add(tf.matmul(input,Weights,name='multiply'),biases,name='add')
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
tf.summary.histogram( '/outputs', outputs)
return outputs
#np.newaxis的作用就是在这一位置增加一个一维
#x1 = np.array([1, 2, 3, 4, 5])# the shape of x1 is (5,)
#x1_new = x1[:, np.newaxis]
# now, the shape of x1_new is (5, 1)
# array([[1],
# [2],
# [3],
# [4],
# [5]])
#x1_new = x1[np.newaxis,:]
# now, the shape of x1_new is (1, 5)
# array([[1, 2, 3, 4, 5]])
x_data=np.linspace(-1,1,300)[:,np.newaxis].astype(np.float32)
# numpy.random.rand() 均匀分布,范围 [0, 1)
# numpy.random.normal(loc=mu, scale=sigma, size)正态分布
# numpy.random.randn(size)标准正态分布
noise=np.random.normal(0,0.05,x_data.shape).astype(np.float32)
y_data=np.square(x_data)-0.5+noise
with tf.name_scope('inputs'):
xs=tf.placeholder(tf.float32,(None,1),name='x_input')
ys=tf.placeholder(tf.float32,(None,1),name='y_input')
#add hidden layer
with tf.name_scope('layer1'):
layer1=add_layer(xs,1,10,activation_function=tf.nn.relu)
#add output layer
with tf.name_scope('layer2'):
prediction=add_layer(layer1,10,1,activation_function=None)
with tf.name_scope('loss'):
loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1]))
tf.summary.scalar('loss',loss)
with tf.name_scope('train'):
train=tf.train.GradientDescentOptimizer(0.5).minimize(loss)
init=tf.initialize_all_variables()
sess = tf.Session()
merged=tf.summary.merge_all()
writer=tf.summary.FileWriter('E:\logfile2',sess.graph)
sess.run(init)
for i in range(1000):
sess.run(train,feed_dict={xs:x_data,ys:y_data})
if i%50==0:
result=sess.run(merged,feed_dict={xs:x_data,ys:y_data})
writer.add_summary(result,i)
#在pycharm中,点开左下角的Terminal,我的默认路径就是E盘根目录
#所以直接输入:tensorboard --logdir=logfile2
最后显示结果正常了