• 结果可视化


     1 import tensorflow as tf
     2 import numpy as np
     3 import matplotlib.pyplot as plt
     4 def add_layer(inputs, in_size, out_size,activation_function=None):
     5         Weights = tf.Variable(tf.random_normal([in_size, out_size]))
     6         biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
     7         Wx_plus_b = tf.matmul(inputs, Weights) + biases
     8         if activation_function is None:
     9             outputs = Wx_plus_b
    10         else:
    11             outputs = activation_function(Wx_plus_b)
    12     return outputs
    13 
    14 x_data=np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis]
    15 noise = np.random.normal(0, 0.05, x_data.shape).astype(np.float32)
    16 y_data=np.square(x_data)-0.5+noise
    17 xs=tf.placeholder(tf.float32,[None,1],name='x_input')
    18 ys=tf.placeholder(tf.float32,[None,1],name='y_input')
    19 
    20 l1=add_layer(xs,1,10,activation_function=tf.nn.relu)  #隐藏层
    21 prediction=add_layer(l1,10,1,activation_function=None) #输出层
    22 loss=tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),
    23             reduction_indices=[1]))
    24 train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
    25 init = tf.global_variables_initializer()
    26 sess = tf.Session()
    27 sess.run(init)
    28 fig = plt.figure()  #生成图片框架
    29 ax=fig.add_subplot(1,1,1)  #连续性的画图
    30 ax.scatter(x_data,y_data)  #用点的形式把真实的数据画出来
    31 plt.ion()  #用于连续显示,不会show一下就停止显示
    32 plt.show()
    33 for i in range(1000):
    34     sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
    35     if i%50==0:
    36         print(sess.run(loss,feed_dict={xs:x_data,ys:y_data}))
    37         try:
    38             ax.lines.remove(lines[0])  #在图片中去除第一条线
    39         except Exception:
    40             pass
    41         prediction_value = sess.run(prediction,feed_dict={xs:x_data})
    42         lines=ax.plot(x_data,prediction_value,'r-',lw=5) #红色,宽度为5的线,x,y轴的数据plot上去
    43 plt.pause(0.1) #暂停0.1s

        

  • 相关阅读:
    Use Module and Function instead of Class in Python
    以命令行方式使用Desktop版Ubuntu
    python中两种拷贝目录方法的比较
    查找重复文件并删除的工具
    Manage sshd Service on CentOS
    Java多线程间的数据共享
    并发 总结
    MapReduce 过程分析
    java能不能自己写一个类叫java.lang.System/String正确答案
    生产者消费者模式--阻塞队列--LOCK,Condition--线程池
  • 原文地址:https://www.cnblogs.com/Lazycat1206/p/11927813.html
Copyright © 2020-2023  润新知