1、前向传播:

  • 搭建从输入到输出的网络结构
  • forward.py:
# 定义前向传播过程
def forward(x, regularizer):w = b = y = return y# 给w赋初值,并把w的正则化损失加到总损失中
def get_weight(shape, regularizer):w = tf.Variable()tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))return wdef get_bias(shape)b = tf.Variable()return b

2、反向传播

  • 训练网络,优化网络参数,提高模型准确性
  • backward.py:
# 定义反向传播
def backward():# 对数据集x和标准答案y_占位x = tf.placeholder()y_ = tf.placeholder()# 利用forward模块复现前向传播网络的结构,计算得到yy = forward.forward(x, REGULARIZER)# 定义轮数计数器global_step = tf.Variable(0, trainable = False)# 定义损失函数loss = '''# 均方误差loss = tf.reduce_mean(tf.square(y - y_))# 交叉熵ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = y, lables = tf.argmax(y_, 1))loss = tf.reduce_mean(ce)'''# 在训练网络模型时# 常常将1正则化、2指数衰减学习率、3滑动平均这三个方法作为优化模型的方法'''# 使用正则化时的损失函数loss = loss(y, y_) + tf.add_n(tf.get_collection('losses'))# 使用指数衰减的学习率时,加上:learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,global_step,数据集总样本数/BATCH_SIZE,LEARNING_RATE_DECAY,staircase = True)'''# 上面的损失函数和学习率选好之后,定义反向传播过程使用梯度下降train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step = global_step)# 如果使用滑动平均时,加上:'''ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)ema_op = ema.apply(tf.trainable_variables())with tf.control_dependencies([train_step, ema_op]):train_op = tf.no_op(name = 'train')'''# 训练过程with tf.Session() as sess:# 初始化所有参数init_op = tf.global_variables_initializer()sess.run(init_op)# 循环迭代for i in range(STEPS):# 每轮调用sess.run执行训练过程train_stepsess.run(train_step, feed_dict = {x: , y_: })# 每运行一定轮数,打印出当前的loss信息if i %  轮数==0print

3、判断主文件

# 判断python运行文件是否为主文件,如果是,则执行
if __name__ == '__main__':backward()

4、实例模块化展示

  • 加入指数衰减学习率–优化效率
  • 加入正则化–提高泛化性能
  • 模块化设计
    generateds.py
# modelNN_generateds.py
# 数据导入模块,生成模拟数据集
# coding: utf-8import numpy as np
import matplotlib.pyplot as plt
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'  #hide warningsseed = 2def generateds():# 基于seed产生随机数rdm = np.random.RandomState(seed)# 随机数返回300行2列的矩阵,表示300组坐标点,作为输入数据集X = rdm.randn(300, 2)# 手工标注数据分类Y_ = [int(x0*x0 + x1*x1 < 2)for (x0, x1) in X]# Y_为1,标记红色,否则蓝色Y_c = [['red' if y else 'blue'] for y in Y_]# 对数据集和标签进行reshape, X整理为n行2列,Y为n行1列,第一个元素-1表示n行X = np.vstack(X).reshape(-1, 2)Y_ = np.vstack(Y_).reshape(-1, 1) return X, Y_, Y_cprint("X:\n")print(X)print("Y_:\n")print(Y_)print("Y_c:\n")print(Y_c)

forward.py

# modelNN_generateds.py
# 前向传播模块
# 定义神经网络的输入、参数和输出,定义前向传播过程
# coding: utf-8import tensorflow as tf
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'  #hide warnings# 给w赋初值,并把w的正则化损失加到总损失中
def get_weight(shape, regularizer):w = tf.Variable(tf.random_normal(shape), dtype = tf.float32)tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w))return w# 给b赋初值
def get_bias(shape):b = tf.Variable(tf.constant(0.01, shape = shape))return bdef forward(x, regularizer):w1 = get_weight([2, 11], regularizer)b1 = get_bias([11])y1 = tf.nn.relu(tf.matmul(x, w1) + b1)w2 = get_weight([11, 1], regularizer)b2 = get_bias([1])y = tf.matmul(y1, w2) + b2 #输出层不通过激活函数return y

backward.py

# modelNN_generateds.py
# 反向传播模块
# 定义神经网络的反向传播过程
# coding: utf-8import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import modelNN_generateds
import modelNN_forward
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'  #hide warnings# 定义超参数
STEPS = 40000 #训练轮数
BATCH_SIZE = 30
LEARNING_RATE_BASE = 0.001 #初始学习率
LEARNING_RATE_DECAY = 0.999 # 学习率衰减率
REGULARIZER = 0.01 # 正则化参数def backward():# placeholder占位x = tf.placeholder(tf.float32, shape = (None, 2))y_ = tf.placeholder(tf.float32, shape = (None, 1))# 生成数据集X, Y_, Y_c = modelNN_generateds.generateds()# 前向传播推测输出yy = modelNN_forward.forward(x, REGULARIZER)# 定义global_stepglobal_step = tf.Variable(0, trainable = False)# 定义指数衰减学习率learning_rate = tf.train.exponential_decay(LEARNING_RATE_BASE,global_step, 300/BATCH_SIZE,LEARNING_RATE_DECAY,staircase = True)# 定义损失函数loss_mse = tf.reduce_mean(tf.square(y - y_))loss_total = loss_mse + tf.add_n(tf.get_collection('losses'))# 定义反向传播方法:包含正则化train_step = tf.train.AdamOptimizer(learning_rate).minimize(loss_total)# 定义训练过程with tf.Session() as sess:init_op = tf.global_variables_initializer()sess.run(init_op)for i in range(STEPS):start = (i * BATCH_SIZE) % 300end = start + BATCH_SIZEsess.run(train_step, feed_dict = {x: X[start:end], y_:Y_[start:end]})if i % 2000==0:loss_v = sess.run(loss_total, feed_dict = {x: X, y_: Y_})print("after %d steps, loss for total is %f" %(i, loss_v))xx, yy = np.mgrid[-3:3:.01, -3:3:.01]grid = np.c_[xx.ravel(), yy.ravel()]probs = sess.run(y, feed_dict = {x: grid})probs = probs.reshape(xx.shape)# 可视化plt.scatter(X[:, 0], X[:, 1], c = np.squeeze(Y_c))# 给probs值为0.5的所有点(xx, yy)上色plt.contour(xx, yy, probs, levels = [.5])plt.show()# 判断python运行文件是否为主文件,如果是,则执行
if __name__ == '__main__':backward()

TensorFlow神经网络:模块化的神经网络八股相关推荐

  1. 用Tensorflow搭建第一个神经网络

    简述 https://blog.csdn.net/a19990412/article/details/82913189 根据上面链接中的前两个学习教程学习 其中Mofan大神的例子非常好,学到了很多 ...

  2. tensorflow 进阶(三),BP神经网络之两层hidden_layer

    本文与上一篇文章有一点不同,就是中间的隐藏层由一层变成两层,在神经网络搭建的过程中,曾出现一点问题,就是正确率图突然变成0.11,通过调整隐藏节点的数量和W2的初值,正确率达到0.97,不如只有一层神 ...

  3. [Python人工智能] 一.TensorFlow环境搭建及神经网络入门

    从本篇文章开始,作者正式开始研究Python深度学习.神经网络及人工智能相关知识.第一篇文章主要讲解神经网络基础概念,同时讲解TensorFlow2.0的安装过程及基础用法,主要结合作者之前的博客和& ...

  4. .net 初学者_在此初学者课程中学习使用TensorFlow 2.0开发神经网络

    .net 初学者 Learn how to use TensorFlow 2.0 in this full video course from Tech with Tim. This course w ...

  5. 04.卷积神经网络 W1.卷积神经网络(作业:手动/TensorFlow 实现卷积神经网络)

    文章目录 作业1:实现卷积神经网络 1. 导入一些包 2. 模型框架 3. 卷积神经网络 3.1 Zero-Padding 3.2 单步卷积 3.3 卷积神经网络 - 前向传播 4. 池化层 5. 卷 ...

  6. 基于tensorflow实现图像分类——理解神经网络运作过程、tensorflow入门

    1. 人工神经网络 1.1 神经网络结构 人工神经网络(简称神经网络)是模拟人类大脑神经元构造的一个数学计算模型. 一个神经网络的搭建,需要满足三个条件. 输入和输出 权重(w)和阈值(b) 多层感知 ...

  7. TensorFlow学习笔记——深层神经网络

    引言 TensorFlow 版本1.15pip3 install tensorflow==1.15.0. 这是<TensorFlow实战Google深度学习框架(第2版)>的学习笔记,所有 ...

  8. 基于TensorFlow实现的CNN神经网络 花卉识别系统Demo

    基于TensorFlow实现的CNN神经网络 花卉识别系统Demo Demo展示 登录与注册 主页面 模型训练 识别 神经网络 训练 Demo下载 Demo展示 登录与注册 主页面 模型训练 识别 神 ...

  9. 【神经网络】tensorflow实验10 -- 人工神经网络(1)

    1. 实验目的 ①理解并掌握误差反向传播算法: ②能够使用单层和多层神经网络,完成多分类任务: ③了解常用的激活函数. 2. 实验内容 ①设计单层和多层神经网络结构,并使用TensorFlow建立模型 ...

  10. Tensorflow使用CNN卷积神经网络以及RNN(Lstm、Gru)循环神经网络进行中文文本分类

    Tensorflow使用CNN卷积神经网络以及RNN(Lstm.Gru)循环神经网络进行中文文本分类 本案例采用清华大学NLP组提供的THUCNews新闻文本分类数据集的一个子集进行训练和测试http ...

最新文章

  1. Coefficients: (1 not defined because of singularities)
  2. Linux下安全扫描工具Nmap用法详解
  3. j2ee性能调优之最小化资源压力测试法则
  4. 命令行参数 - 和 -- 的区别
  5. 互联网项目开始时需要去谈的产品需求分析:
  6. 梅林安装opkg后安装iperf3_centos7安装完成后没网
  7. 岗位内推 | 阿里巴巴达摩院决策智能实验室招聘全职/实习生
  8. imp oracle full,Oracle 10g imp 之 full database (转官档)
  9. 海外服务器搭建网站访问很慢,海外服务器访问速度变慢了怎么办
  10. 如何提高UDP的可靠性
  11. 信息学奥赛一本通C++语言——1067:整数的个数
  12. Java中方法和数组
  13. cpu与简单模型机设计实验_180套经典夹具设计方案(附详解+模型),原来夹具设计这么简单!...
  14. paip.spring3 mvc servlet的配置以及使用最佳实践
  15. intellij运行awt项目时,菜单栏中的汉字乱码问题
  16. Springboot整合七牛云上传图片
  17. matplotlib添加字体、字体格式自定义
  18. AAAI2021 | 在手机上实现19FPS实时的YOLObile目标检测,准确率超高
  19. vue子路由跳转回父级,刷新部分父页面接口,push跳转
  20. 鸿蒙秘境怎么玩,鸿蒙秘境

热门文章

  1. css3之背景属性之background-size
  2. POJ 2425 A Chess Game(有向图SG函数)题解
  3. Selenium+PhantomJS自动化登录爬取博客文章
  4. Qt信号槽中槽函数为虚函数的一些感想
  5. 返回行javascript比较时间大小
  6. shell脚本实现一个彩色进度条
  7. jmeter脚本增强
  8. sstap tun虚拟网卡没有安装_虚拟设备之TUN和TAP
  9. 各层作用_OSI模型中各层在通信中的作用
  10. 2021年面试前端岗位需要注意什么?