吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用正则化
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 # 输入节点
OUTPUT_NODE = 10 # 输出节点
LAYER1_NODE = 500 # 隐藏层数 BATCH_SIZE = 100 # 每次batch打包的样本个数 # 模型相关的参数
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99 TRAINING_STEPS = 5000
MOVING_AVERAGE_DECAY = 0.99 def inference(input_tensor, avg_class, weights1, biases1, weights2, biases2):
# 不使用滑动平均类
if avg_class == None:
layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)
return tf.matmul(layer1, weights2) + biases2
else:
# 使用滑动平均类
layer1 = tf.nn.relu(tf.matmul(input_tensor, avg_class.average(weights1)) + avg_class.average(biases1))
return tf.matmul(layer1, avg_class.average(weights2)) + avg_class.average(biases2) def train(mnist):
x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input')
# 生成隐藏层的参数。
weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))
biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))
# 生成输出层的参数。
weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))
biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE])) # 计算不含滑动平均类的前向传播结果
y = inference(x, None, weights1, biases1, weights2, biases2) # 定义训练轮数及相关的滑动平均类
global_step = tf.Variable(0, trainable=False)
variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
variables_averages_op = variable_averages.apply(tf.trainable_variables())
average_y = inference(x, variable_averages, weights1, biases1, weights2, biases2) # 计算交叉熵及其平均值
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
cross_entropy_mean = tf.reduce_mean(cross_entropy) # 损失函数的计算
loss = cross_entropy_mean # 设置指数衰减的学习率。
learning_rate = tf.train.exponential_decay(
LEARNING_RATE_BASE,
global_step,
mnist.train.num_examples / BATCH_SIZE,
LEARNING_RATE_DECAY,
staircase=True) # 优化损失函数
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step) # 反向传播更新参数和更新每一个参数的滑动平均值
with tf.control_dependencies([train_step, variables_averages_op]):
train_op = tf.no_op(name='train') # 计算正确率
correct_prediction = tf.equal(tf.argmax(average_y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) # 初始化会话,并开始训练过程。
with tf.Session() as sess:
tf.global_variables_initializer().run()
validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels}
test_feed = {x: mnist.test.images, y_: mnist.test.labels} # 循环的训练神经网络。
for i in range(TRAINING_STEPS):
if i % 1000 == 0:
validate_acc = sess.run(accuracy, feed_dict=validate_feed)
print("After %d training step(s), validation accuracy using average model is %g " % (i, validate_acc))
xs,ys=mnist.train.next_batch(BATCH_SIZE)
sess.run(train_op,feed_dict={x:xs,y_:ys})
test_acc=sess.run(accuracy,feed_dict=test_feed)
print(("After %d training step(s), test accuracy using average model is %g" %(TRAINING_STEPS, test_acc))) def main(argv=None):
mnist = input_data.read_data_sets("E:\\MNIST_data\\", one_hot=True)
train(mnist) if __name__=='__main__':
main()
吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用正则化的更多相关文章
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用滑动平均
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用隐藏层
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用激活函数
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用指数衰减的学习率
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:全模型
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:花瓣识别
import os import glob import os.path import numpy as np import tensorflow as tf from tensorflow.pyth ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:MNIST最佳实践
import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_N ...
- 吴裕雄 python 神经网络——TensorFlow训练神经网络:卷积层、池化层样例
import numpy as np import tensorflow as tf M = np.array([ [[1],[-1],[0]], [[-1],[2],[1]], [[0],[2],[ ...
- 吴裕雄--天生自然 Tensorflow卷积神经网络:花朵图片识别
import os import numpy as np import matplotlib.pyplot as plt from PIL import Image, ImageChops from ...
随机推荐
- 题解【洛谷P1074】[NOIP2009]靶形数独
题面 题解 一开始写了一个朴素的数独,无任何剪枝优化,得到了\(55\)分的好成绩. 就是这道题加一个计算分数. 代码如下(\(\mathrm{55\ pts}\)): /************** ...
- C语言 strlen
C语言 strlen #include <string.h> size_t strlen(const char *s); 功能:计算指定指定字符串s的长度,不包含字符串结束符‘\0’ 参数 ...
- centos7 命令 对比 cenots6 命令
1) 列出所有service开机启动项 centos 7 systemctl list-unit-files |grep enabled centos 6 chkconfig --list|grep ...
- Vue-cli3 项目配置 Vue.config.js( 代替vue-cli2 build config)
Vue-cli3 搭建的项目 界面相对之前较为简洁 之前的build和config文件夹不见了,那么应该如何配置 如webpack等的配那 只需要在项目的根目录下新建 vue.config.js 文件 ...
- Scrapy爬取伯乐在线的所有文章
本篇文章将从搭建虚拟环境开始,爬取伯乐在线上的所有文章的数据. 搭建虚拟环境之前需要配置环境变量,该环境变量的变量值为虚拟环境的存放目录 1. 配置环境变量 2.创建虚拟环境 用mkvirtualen ...
- js无缝滚动跑马灯
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- sublime 最常用的快捷键.gif
Ctrl+D 把光标放在文本上,按下⌘+ D将选择这个文本.多次按下⌘+ D则会增加匹配项 Alt+F3 会选中光标所在文本的所有匹配项 Ctrl+Shift+' 这是一个法宝,也许你希望所有的属性保 ...
- Python(一):一行解法参考
#一行快速排序quick_sort = lambda array: array if len(array) <= 1 else quick_sort([item for item in arra ...
- vue 实现上一周、下一周切换功能
效果图: html 显示部分: js 显示部分: preNextBtn(val){ let _this = this; this.tableList = []; //数据重置为空 _this.show ...
- [坑] js indexOf is not a function
今天写js的时候,本来没有问题的代码突然出现了问题,就是本来下拉框里面在更新之后会出现内容的 但是并没有出现内容,按下F12 查看了Console之后发现确实是接收到了数据,但是却也报错了 内容是 我 ...