代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs, in_size, out_size, activation_function=None):
# add one more layer and return he output of this layer
with tf.name_scope('layer'):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, Weights) + biases #矩阵相乘
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
x_data = np.linspace(-1, 1, 300)[:, np.newaxis] # -1到1的区间,300个单位,并添加一个维度,在指定的间隔范围内返回均匀间隔的数字。
noise = np.random.normal(0, 0.05, x_data.shape) # normal这里是正态的意思
y_data = np.square(x_data) - 0.5 + noise # 二次方-0.5
# define placeholder for inputs to network
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
l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu) #输入层
# add output layer
prediction = add_layer(l1, 10, 1,activation_function=None) #此处激励方程为线性函数
# the error between prediction and real data
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1])) #reduction_indices表示函数处理的维度,tf.reduce_mean表示求平均值
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) #Optimizer优化器0.1效率来减小误差
init = tf.initialize_all_variables()
sess = tf.Session()
writer = tf.summary.FileWriter('logs/',sess.graph)
# important step
sess.run(init)
fig = plt.figure() #生成图片框
ax = fig.add_subplot(1, 1, 1) #参数一,子图总行数;参数二,子图总列数;参数三:子图位置
ax.scatter(x_data, y_data) #绘制散点图
plt.ion()
plt.show()
for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data, ys:y_data})
if i%50==0:
#print(sess.run(loss,feed_dict={xs:x_data, ys:y_data})) #feed_dict表示x_data赋值给xs
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction,feed_dict={xs:x_data,ys:y_data})
lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
plt.pause(0.1)
然后在tensorflow环境下cmd运行tensorboard --logdir C:\Users\shenq\PycharmProjects\pythonProject1\logs --host=127.0.0.1
(路径名是日志文件所在目录的路径)
然后跳出
浏览器地址栏输入后得
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_layer(inputs, in_size, out_size, n_layer,activation_function=None):
# add one more layer and return he output of this layer
layer_name = 'layer%s' % n_layer
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size, out_size]), name='W')
tf.summary.histogram(layer_name+'/weights', Weights)
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='b')
tf.summary.histogram(layer_name + '/biases', biases)
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs, Weights) + biases #矩阵相乘
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
tf.summary.histogram(layer_name + '/outputs', outputs)
return outputs
# Make up some real data
x_data = np.linspace(-1, 1, 300)[:, np.newaxis] # -1到1的区间,300个单位,并添加一个维度,在指定的间隔范围内返回均匀间隔的数字。
noise = np.random.normal(0, 0.05, x_data.shape) # normal这里是正态的意思
y_data = np.square(x_data) - 0.5 + noise # 二次方-0.5
# define placeholder for inputs to network
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
l1 = add_layer(xs, 1, 10, n_layer=1,activation_function=tf.nn.relu) #输入层
# add output layer
prediction = add_layer(l1, 10, 1, n_layer=2, activation_function=None) #此处激励方程为线性函数
# the error between prediction and real data
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),
reduction_indices=[1])) #reduction_indices表示函数处理的维度,tf.reduce_mean表示求平均值
tf.summary.scalar('loss', loss)
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) #Optimizer优化器0.1效率来减小误差
init = tf.initialize_all_variables()
sess = tf.Session()
merge = tf.summary.merge_all()
writer = tf.summary.FileWriter('logs/',sess.graph)
# important step
sess.run(init)
fig = plt.figure() #生成图片框
ax = fig.add_subplot(1, 1, 1) #参数一,子图总行数;参数二,子图总列数;参数三:子图位置
ax.scatter(x_data, y_data) #绘制散点图
plt.ion()
plt.show()
for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data, ys:y_data})
if i%50==0:
result = sess.run(merge, feed_dict={xs:x_data, ys:y_data})
writer.add_summary(result,i)
#print(sess.run(loss,feed_dict={xs:x_data, ys:y_data})) #feed_dict表示x_data赋值给xs
#try:
# ax.lines.remove(lines[0])
# except Exception:
# pass
# prediction_value = sess.run(prediction,feed_dict={xs:x_data,ys:y_data})
# lines = ax.plot(x_data, prediction_value, 'r-', lw=5)
#plt.pause(0.1)
运行之后相同步骤查看数据