吴裕雄 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 ...
随机推荐
- NOIP2012 疫情控制 题解(LuoguP1084)
NOIP2012 疫情控制 题解(LuoguP1084) 不难发现,如果一个点向上移动一定能控制更多的点,所以可以二分时间,判断是否可行. 但根节点不能不能控制,存在以当前时间可以走到根节点的点,可使 ...
- Linux - Shell - find - 基础
概述 find 基础 背景 查找文件 人的记忆能力, 是有限的 计算机里的文件数量, 虽然不是无限, 但是也不少 要去找那些 记不清楚的文件, 必然要用查找 准备 OS centos7 用户 root ...
- 并发队列 ConcurrentLinkedQueue 及 BlockingQueue 接口实现的四种队列
队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作.进行插入操作的端称为队尾,进行删除操作的端称为队头.队列中没有元素时,称为空队列. 在队列这 ...
- RNGCryptoServiceProvider 生成订单号
先生成1~1000的随机数 class Program { // Create a new instance of the RNGCryptoServiceProvider. private stat ...
- js将后台传入得时间格式化
//格式化时间函数Date.prototype.Format = function (fmt) { var o = { "M+": this.getMonth() + 1, //月 ...
- Java:反射机制学习笔记
目录 一.反射机制 1.概述 2.优缺点 3.类加载的过程 二.获取Class对象的三种方式 1.Class.forName("全类名") 2.类名.class 3.对象.getC ...
- Dockerfile文档编写
图片显示问题,附上有道云笔记中链接:http://note.youdao.com/noteshare?id=fba6d2f53fd6447ba32c3b7accfeb89b&sub=B36B5 ...
- 6_7 树的层次遍历(UVa122)<二叉树的动态创建与BFS>
树状结构在计算机科学的许多领域中都相当重要.本问题牵涉到建立树及走访树.给你一二叉树,你的任务是写一个程序来打印依「阶层(level-order)」走访的结果.在本问题中,二叉树的每个节点含有一个正整 ...
- 吴裕雄 python 神经网络——TensorFlow 三层简单神经网络的前向传播算法
import tensorflow as tf w1= tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1)) w2= tf.Variable( ...
- Java面向对象编程 -6
数组的基本概念 数组的本质:一组相关变量的集合. 但是需要注意的一点是:在java里面讲数组定义为了引用数据类型,所以数组的使用一定要牵扯到内存分配,那么首先一定要想到使用关键字new来处理 数组的定 ...