import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
def add_Layer(inputs, in_size, out_size, activation_Func=None):#添加神经网络层函数
Weights = tf.Variable(tf.random_normal([in_size, out_size]))#定义权重,记得要在列表中规定行列数
Biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
Wx_b = tf.matmul(inputs, Weights) + Biases
if activation_Func is None:
outputs = Wx_b
else:
outputs = activation_Func(Wx_b)#选择使用的激励函数
return outputs
x_data = np.linspace(-1, 1, 300)[:,np.newaxis]#定义[-1,1]的等差数组,并使用(n,1)shape的格式
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise
xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
hidelayer = add_Layer(xs, 1, 10, activation_Func=tf.nn.relu)#隐藏层
prediction = add_Layer(hidelayer, 10, 1, activation_Func= tf.nn.tanh)#输出层
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction), reduction_indices=[1]))#计算误差 reduction_indices作用为维度上进行加
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#根据梯度下降法来调整参数,0.1为学习率
init = tf.initialize_all_variables()#激活变量
sess = tf.Session()
sess.run(init)
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)#表示一共有1个子图,这是第1个子图,该函数返回坐标
ax.scatter(x_data, y_data)
plt.ion()
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys:y_data})#feed_dict类似于占位符,它既是run调用的函数的参数
if i % 50 == 0:
try:
ax.lines.remove(lines[0])
except Exception: pass
print(sess.run(loss, feed_dict={xs: x_data, ys:y_data}))
prediction_value = sess.run(prediction, feed_dict= {xs:x_data})
lines = ax.plot(x_data, prediction_value, 'r-', lw = 5)
plt.pause(0.1)
plt.show()
有关数据可视化
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("Bias"):
Biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, name='B')
with tf.name_scope("Wx_b"):
Wx_b = tf.matmul(inputs, Weights) + Biases
with tf.name_scope("Loss"):
.....
tf.summary.scalar('Loss', loss)#将loss信息放入event里
.....
merged = tf.summary.merge_all()#将所有总结信息打包
......
write = tf.summary.FileWriter("D://File//tensor//", tf.get_default_graph())#写可视化文件
write.close()
完成后在D://File//tensor//目录下会生成
随后进入cmd打开文件
进入网址即完成任务