TF之NN:利用神经网络系统自动学习散点(二次函数+noise+优化修正)输出结果可视化(matplotlib动态演示)

简介: TF之NN:利用神经网络系统自动学习散点(二次函数+noise+优化修正)输出结果可视化(matplotlib动态演示)

输出结果

image.png

代码设计

import tensorflow as tf

import numpy as np

import matplotlib.pyplot as plt

def add_layer(inputs, in_size, out_size, activation_function=None):  

   Weights = tf.Variable(tf.random_normal([in_size, out_size]))  

   biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)          

   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]  

noise = np.random.normal(0, 0.05, x_data.shape)

y_data = np.square(x_data) - 0.5 + noise      

# define placeholder for inputs to network

xs = tf.placeholder(tf.float32, [None, 1])  

ys = tf.placeholder(tf.float32, [None, 1])

l1 = add_layer(xs, 1, 10, activation_function=tf.nn.relu)  

prediction = add_layer(l1, 10, 1, activation_function=None)

# the error between prediciton and real data

loss = tf.reduce_mean(

   tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1])

   )

train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)  

# important step

init = tf.global_variables_initializer()

sess = tf.Session()                  

sess.run(init)                      

# plot the real data

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):

   # training

   sess.run(train_step, feed_dict={xs: x_data, ys: y_data})

   if i % 50 == 0:  

       # to visualize the result and improvement

       try:

           ax.lines.remove(lines[0])

       except Exception:

           pass

       prediction_value = sess.run(prediction, feed_dict={xs: x_data})

       # plot the prediction

       lines = ax.plot(x_data, prediction_value, 'r-', lw=5)

       plt.title('Matplotlib,NN,Efficient learning,Approach,Quadratic function --Jason Niu')

       plt.pause(0.1)


相关文章
|
2天前
计算机网络学习记录 物理层 Day2
计算机网络学习记录 物理层 Day2
7 3
|
2天前
计算机网络学习记录 数据链路层 Day3 (上)(2)
计算机网络学习记录 数据链路层 Day3 (上)(2)
8 2
|
2天前
计算机网络学习记录 数据链路层 Day3 (上)(1)
计算机网络学习记录 数据链路层 Day3 (上)(1)
9 2
|
2天前
|
网络协议 Apache 网络架构
计算机网络学习记录 网络的大概认识 Day1(下)
计算机网络学习记录 网络的大概认识 Day1(下)
6 2
|
1天前
|
机器学习/深度学习
激活函数:神经网络的生命之花
激活函数:神经网络的生命之花
激活函数:神经网络的生命之花
|
2天前
|
网络协议
计算机网络学习记录 运输层 Day5(2)
计算机网络学习记录 运输层 Day5(2)
8 1
|
2天前
|
存储 数据处理 网络架构
计算机网络学习记录 网络的大概认识 Day1(上)
计算机网络学习记录 网络的大概认识 Day1(上)
7 1
|
6天前
|
安全 物联网 Linux
学习Linux对网络安全的重要性
**学习Linux对网络安全至关重要:** 1. 开源操作系统广泛应用于服务器、网络设备,掌握Linux是安全专家必备技能。 2. Linux内置安全特性,如最小权限和防火墙,加上丰富的安全工具,提供强大保障。 3. 可定制性允许灵活配置,满足安全需求,开源社区提供持续更新和教育资源。 4. 学习Linux能提升攻防能力,用于系统加固和渗透测试,适应跨平台安全场景。 5. 随着云计算和物联网发展,Linux在网络安全中的角色日益关键。
30 3
|
2天前
计算机网络学习记录 应用层 Day6(2)
计算机网络学习记录 应用层 Day6(2)
5 0
|
2天前
|
网络协议
计算机网络学习记录 应用层 Day6(1)
计算机网络学习记录 应用层 Day6(1)
6 0