1.建立一个神经网络添加层

    输入值、输入的大小、输出的大小和激励函数

    学过神经网络的人看下面这个图就明白了,不懂的去看看我的另一篇博客

 def add_layer(inputs , in_size , out_size , activate = None):
Weights = tf.Variable(tf.random_normal([in_size,out_size]))#随机初始化
baises = tf.Variable(tf.zeros([1,out_size])+0.1)#可以随机但是不要初始化为0,都为固定值比随机好点
y = tf.matmul(inputs, Weights) + baises #matmul:矩阵乘法,multipy:一般是数量的乘法
if activate:
y = activate(y)
return y

  2.训练一个二次函数

 import tensorflow as tf
import numpy as np def add_layer(inputs , in_size , out_size , activate = None):
Weights = tf.Variable(tf.random_normal([in_size,out_size]))#随机初始化
baises = tf.Variable(tf.zeros([1,out_size])+0.1)#可以随机但是不要初始化为0,都为固定值比随机好点
y = tf.matmul(inputs, Weights) + baises #matmul:矩阵乘法,multipy:一般是数量的乘法
if activate:
y = activate(y)
return y
if __name__ == '__main__':
x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis]#创建-1,1的300个数,此时为一维矩阵,后面转化为二维矩阵===[1,2,3]-->>[[1,2,3]]
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32)#噪声是(1,300)格式,0-0.05大小
y_data = np.square(x_data) - 0.5 + noise #带有噪声的抛物线 xs = tf.placeholder(tf.float32,[None,1]) #外界输入数据
ys = tf.placeholder(tf.float32,[None,1]) l1 = add_layer(xs,1,10,activate=tf.nn.relu)
prediction = add_layer(l1,10,1,activate=None) loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))#误差
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#对误差进行梯度优化,步伐为0.1 sess = tf.Session()
sess.run( tf.global_variables_initializer())
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})#训练
if i%50 == 0:
print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))#查看误差

  3.动态显示训练过程

    显示的步骤程序之中部分进行说明,其它说明请看其它博客

 import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt def add_layer(inputs , in_size , out_size , activate = None):
Weights = tf.Variable(tf.random_normal([in_size,out_size]))#随机初始化
baises = tf.Variable(tf.zeros([1,out_size])+0.1)#可以随机但是不要初始化为0,都为固定值比随机好点
y = tf.matmul(inputs, Weights) + baises #matmul:矩阵乘法,multipy:一般是数量的乘法
if activate:
y = activate(y)
return y
if __name__ == '__main__':
x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis]#创建-1,1的300个数,此时为一维矩阵,后面转化为二维矩阵===[1,2,3]-->>[[1,2,3]]
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32)#噪声是(1,300)格式,0-0.05大小
y_data = np.square(x_data) - 0.5 + noise #带有噪声的抛物线
fig = plt.figure('show_data')# figure("data")指定图表名称
ax = fig.add_subplot(111)
ax.scatter(x_data,y_data)
plt.ion()
plt.show()
xs = tf.placeholder(tf.float32,[None,1]) #外界输入数据
ys = tf.placeholder(tf.float32,[None,1]) l1 = add_layer(xs,1,10,activate=tf.nn.relu)
prediction = add_layer(l1,10,1,activate=None) loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))#误差
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#对误差进行梯度优化,步伐为0.1 sess = tf.Session()
sess.run( tf.global_variables_initializer())
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})#训练
if i%50 == 0:
try:
ax.lines.remove(lines[0])
except Exception:
pass
prediction_value = sess.run(prediction, feed_dict={xs: x_data})
lines = ax.plot(x_data,prediction_value,"r",lw = 3)
print(sess.run(loss, feed_dict={xs: x_data, ys: y_data}))#查看误差
plt.pause(2)
while True:
plt.pause(0.01)

   4.TensorBoard整体结构化显示

    A.利用with tf.name_scope("name")创建大结构、利用函数的name="name"去创建小结构:tf.placeholder(tf.float32,[None,1],name="x_data")

    B.利用writer = tf.summary.FileWriter("G:/test/",graph=sess.graph)创建一个graph文件

    C.利用TessorBoard去执行这个文件

      这里得注意--->>>首先到你存放文件的上一个目录--->>然后再去运行这个文件

      tensorboard  --logdir=test

  5.TensorBoard局部结构化显示  

      A. tf.summary.histogram(layer_name+"Weight",Weights):直方图显示

     

     B.  tf.summary.scalar("Loss",loss):折线图显示,loss的走向决定你的网络训练的好坏,至关重要一点

       C.初始化与运行设定的图表

 merge = tf.summary.merge_all()#合并图表
writer = tf.summary.FileWriter("G:/test/",graph=sess.graph)#写进文件
result = sess.run(merge,feed_dict={xs:x_data,ys:y_data})#运行打包的图表merge
writer.add_summary(result,i)#写入文件,并且单步长50
     完整代码及显示效果:
 import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt def add_layer(inputs , in_size , out_size , n_layer = 1 , activate = None):
layer_name = "layer" + str(n_layer)
with tf.name_scope(layer_name):
with tf.name_scope("Weights"):
Weights = tf.Variable(tf.random_normal([in_size,out_size]),name="W")#随机初始化
tf.summary.histogram(layer_name+"Weight",Weights)
with tf.name_scope("Baises"):
baises = tf.Variable(tf.zeros([1,out_size])+0.1,name="B")#可以随机但是不要初始化为0,都为固定值比随机好点
tf.summary.histogram(layer_name+"Baises",baises)
y = tf.matmul(inputs, Weights) + baises #matmul:矩阵乘法,multipy:一般是数量的乘法
if activate:
y = activate(y)
tf.summary.histogram(layer_name+"y_sum",y)
return y
if __name__ == '__main__':
x_data = np.linspace(-1,1,300,dtype=np.float32)[:,np.newaxis]#创建-1,1的300个数,此时为一维矩阵,后面转化为二维矩阵===[1,2,3]-->>[[1,2,3]]
noise = np.random.normal(0,0.05,x_data.shape).astype(np.float32)#噪声是(1,300)格式,0-0.05大小
y_data = np.square(x_data) - 0.5 + noise #带有噪声的抛物线
fig = plt.figure('show_data')# figure("data")指定图表名称
ax = fig.add_subplot(111)
ax.scatter(x_data,y_data)
plt.ion()
plt.show()
with tf.name_scope("inputs"):
xs = tf.placeholder(tf.float32,[None,1],name="x_data") #外界输入数据
ys = tf.placeholder(tf.float32,[None,1],name="y_data")
l1 = add_layer(xs,1,10,n_layer=1,activate=tf.nn.relu)
prediction = add_layer(l1,10,1,n_layer=2,activate=None)
with tf.name_scope("loss"):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys - prediction),reduction_indices=[1]))#误差
tf.summary.scalar("Loss",loss)
with tf.name_scope("train_step"):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)#对误差进行梯度优化,步伐为0.1 sess = tf.Session()
merge = tf.summary.merge_all()#合并
writer = tf.summary.FileWriter("G:/test/",graph=sess.graph)
sess.run( tf.global_variables_initializer())
for i in range(1000):
sess.run(train_step, feed_dict={xs: x_data, ys: y_data})#训练
if i%100 == 0:
result = sess.run(merge,feed_dict={xs:x_data,ys:y_data})#运行打包的图表merge
writer.add_summary(result,i)#写入文件,并且单步长50

注意: 假设你的py文件中写了tf的summary,并且存放在了此目录下“D:\test\logs” 调出cmd,cd到D:\test,然后输入tensorboard –logdir=logs。一定要cd到logs这个文件夹的上一级,其他会出现No graph definition files were found.问题。

主要参考莫凡大大:https://morvanzhou.github.io/

可视化出现问题了,参考这位大神:http://blog.csdn.net/fengying2016/article/details/54289931

TessorFlow学习 之 神经网络的构建的更多相关文章

  1. Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.2

    3.Spark MLlib Deep Learning Convolution Neural Network(深度学习-卷积神经网络)3.2 http://blog.csdn.net/sunbow0 ...

  2. 针对深度学习(神经网络)的AI框架调研

    针对深度学习(神经网络)的AI框架调研 在我们的AI安全引擎中未来会使用深度学习(神经网络),后续将引入AI芯片,因此重点看了下业界AI芯片厂商和对应芯片的AI框架,包括Intel(MKL CPU). ...

  3. Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.1

    3.Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.1 http://blog.csdn.net/sunbow0 ...

  4. ArcGIS案例学习笔记2_2_模型构建器和山顶点提取批处理

    ArcGIS案例学习笔记2_2_模型构建器和山顶点提取批处理 计划时间:第二天下午 背景:数据量大,工程大 目的:自动化,批处理,定制业务流程,不写程序 教程:Pdf/343 数据:chap8/ex5 ...

  5. Spark MLlib Deep Learning Convolution Neural Network (深度学习-卷积神经网络)3.3

    3.Spark MLlib Deep Learning Convolution Neural Network(深度学习-卷积神经网络)3.3 http://blog.csdn.net/sunbow0 ...

  6. ReLeQ:一种自动强化学习的神经网络深度量化方法

    ReLeQ:一种自动强化学习的神经网络深度量化方法     ReLeQ:一种自动强化学习的神经网络深度量化方法ReLeQ: An Automatic Reinforcement Learning Ap ...

  7. 深度学习——卷积神经网络 的经典网络(LeNet-5、AlexNet、ZFNet、VGG-16、GoogLeNet、ResNet)

    一.CNN卷积神经网络的经典网络综述 下面图片参照博客:http://blog.csdn.net/cyh_24/article/details/51440344 二.LeNet-5网络 输入尺寸:32 ...

  8. 【CV知识学习】神经网络梯度与归一化问题总结+highway network、ResNet的思考

    这是一篇水货写的笔记,希望路过的大牛可以指出其中的错误,带蒟蒻飞啊~ 一.    梯度消失/梯度爆炸的问题 首先来说说梯度消失问题产生的原因吧,虽然是已经被各大牛说烂的东西.不如先看一个简单的网络结构 ...

  9. ML学习笔记- 神经网络

    神经网络 有的模型可以有多种算法.而有的算法可能可用于多种模型.在神经网络中,对外部环境提供的模式样本进行学习训练,并能存储这种模式,则称为感知器;对外部环境有适应能力,能自动提取外部环境变化特征,则 ...

随机推荐

  1. PxCook 像素大厨 标注切图,一起搞定!专注设计本质

    http://www.fancynode.com.cn/pxcook

  2. 窗体Form的FormStyle属性设置为fsStayOnTop时属性设置不起作用问题探讨。

    procedure CreateParams(var Params: TCreateParams); override; procedure MainForm.Createparams(var Par ...

  3. Release Notes for XE5

    开发者之前说明 http://docwiki.embarcadero.com/RADStudio/XE5/en/Release_Notes_for_XE5

  4. Team Foundation Server 2010简体中文版

    文件名称:Team Foundation Server 2010简体中文版 文件大小:1.8 GBhttp://www.google.com/profiles/dedecms.com 下载地址: th ...

  5. 《JavaScript设计模式与开发》笔记 7.单例模式

    废话一箩筐就这个原来 var instance; return function asdf(name){ if(!this.instance){ this.instance = new asdf(na ...

  6. [Android] JNI中的Local Reference

    参考文章:<在 JNI 编程中避免内存泄漏> 一.Local Reference 深层解析 JNI Local Reference 的生命期是在 native method 的执行期(从 ...

  7. ALGO-119_蓝桥杯_算法训练_寂寞的数

    问题描述 道德经曰:一生二,二生三,三生万物. 对于任意正整数n,我们定义d(n)的值为为n加上组成n的各个数字的和.例如,d()=++=, d()=++++=. 因此,给定了任意一个n作为起点,你可 ...

  8. Office 2016 Pro Plus \ Project 专业版 \ Visio 专业版 \ 64 位vol版本方便KMS小马oem

    在使用上,零售版和批量授权版并没有区别,只是授权方式方面的区别,相对而言,VOL 版的更容易激活一些,其他并没有什么区别了. 有需要的可以在下面下载:(以下均是 64位VL 版) 版本:Office ...

  9. 无法启动程序,因为计算机中丢失mfc90ud.dll的解决方案

    我的编程环境是vs2008-MFC,电脑系统是win7(64位) 解决方法:“工具”—>“选项”—>“项目和解决方案”—>“VC++目录”,在可执行文件栏中加上如下路径: $(Sys ...

  10. [转][layui]table 的一个BUG

    转换静态表格,一直只能显示 10 行,研究发现解决方法有两个:1.参数里: limit: 30, 添加参数以确保显示更多行2.修改 table.js 里面的 F.prototype.config ,添 ...