先放结果图:这个架构还是前面day8里面用到的
点击打开链接
主要的流程图分为:input, layer, loss, train这几个部分
在建立每个部分的时候,需要对该部分命名:
import tensorflow as tf
with tf.name_scope('此处为命名'):
如果想在每个部分里面再细分内容,比如我想在input层里划分 x_input y_input,那么就在上面的代码后面继续使用with tf.name_scope(' ')
【code】:
def add_layer(inputs,in_size,out_size,activation_function=None):
with tf.name_scope('layers'):
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.add(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] # 300个 -1~1 行矩阵变成列矩阵
# add noises
noise=np.random.normal(0,0.05,x_data.shape)
y=np.square(x_data)-0.5+noise
with tf.name_scope('inputs'):
xs=tf.placeholder(tf.float32,[None,1],name='x_input') #None 无论多少例子都可以
ys=tf.placeholder(tf.float32,[None,1],name='y_input')
# create NN
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),
reduction_indices=[1])) #维度为1
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
init=tf.initialize_all_variables()
sess=tf.Session()
writer=tf.summary.FileWriter("E:\\python\\tensorflow",sess.graph)
sess.run(init)
#visiualization
for i in range(1000):
sess.run(train_step,feed_dict={xs: x_data, ys: y})
if i % 100==0:
print("i is:",i,"error is:",sess.run(loss,feed_dict={xs:x_data,ys:y}))
if i==999:
fig=plt.figure()
ax=fig.add_subplot(111)
ax.scatter(x_data,y)
prediction_value=sess.run(prediction,feed_dict={xs:x_data,ys:y})
lines=ax.plot(x_data,prediction_value,'r-',lw=5) #|线宽为5
plt.savefig("1.png")
plt.show()
writer.close()
sess.close()
【loss:】