import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
import numpy as np
def add_layer(inputs, in_size, out_size, activation_function = None):
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') # 保证 biases 不为 0
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.add(tf.matmul(inputs, Weights), biases)
if activation_function == None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
return outputs
x_data = np.linspace(-1, 1, 300) #(300,)
x_data = x_data.reshape(300,1) # (300, 1)
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
# 为 batch 做准备
# 使用with tf.name_scope('inputs')可以将xs和ys包含进来,形成一个大的图层,图层的名字就是with tf.name_scope()方法里的参数。
with tf.name_scope('input'):
xs = tf.placeholder(tf.float32, [None, 1], name = 'x_in')
ys = tf.placeholder(tf.float32, [None, 1], name = 'y_in')
l1 = add_layer(xs, 1, 10, activation_function = tf.nn.relu)
prediction = add_layer(l1, 10, 1, activation_function = None)
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), 1))
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# 只要使用 tf.Variable, 就必须全局初始化
init = tf.global_variables_initializer()
print(' \n\n--- 批量梯度下降 --- ')
with tf.Session() as sess:
sess.run(init)
for step in range(1000):
sess.run(train_step, feed_dict = {xs: x_data, ys: y_data})
if step % 50 == 0:
print('loss = ', sess.run(loss, feed_dict = {xs: x_data, ys: y_data}))
# 以下两种方法都能得到 图文件
# method 1
# writer = tf.summary.FileWriter("E:/tensorflowe/graph", tf.get_default_graph())
# writer.close()
# method 2
sess = tf.Session()
writer = tf.summary.FileWriter('E:/graph', sess.graph)
writer.close()
在浏览器(谷歌或者普通浏览器都可以)中打开 http://Dell-PC:6006该网址