吴裕雄 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.01
LEARNING_RATE_DECAY = 0.99
REGULARAZTION_RATE = 0.0001
TRAINING_STEPS = 5000
MOVING_AVERAGE_DECAY = 0.99  

def inference(input_tensor, avg_class, weights1, biases1, weights2, biases2):
    # 不使用滑动平均类
    if avg_class == None:
        layer1 = tf.matmul(input_tensor, weights1) + biases1
        return tf.matmul(layer1, weights2) + biases2
    else:
        # 使用滑动平均类
        layer1 = 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)

    # 损失函数的计算
    regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)
    regularaztion = regularizer(weights1) + regularizer(weights2)
    loss = cross_entropy_mean + regularaztion

    # 设置指数衰减的学习率。
    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()

原文地址:https://www.cnblogs.com/tszr/p/10875658.html

时间: 2024-07-29 18:01:56

吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用激活函数的相关文章

吴裕雄 python 神经网络——TensorFlow训练神经网络:MNIST最佳实践

import os import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 OUTPUT_NODE = 10 LAYER1_NODE = 500 def get_weight_variable(shape, regularizer): weights = tf.get_variable("weights", shape, initializer

吴裕雄 python 神经网络——TensorFlow 输入数据处理框架

import tensorflow as tf files = tf.train.match_filenames_once("E:\\MNIST_data\\output.tfrecords") filename_queue = tf.train.string_input_producer(files, shuffle=False) # 读取文件. reader = tf.TFRecordReader() _,serialized_example = reader.read(filen

吴裕雄 python深度学习与实践(17)

import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import time # 声明输入图片数据,类别 x = tf.placeholder('float', [None, 784]) y_ = tf.placeholder('float', [None, 10]) # 输入图片数据转化 x_image = tf.reshape(x, [-1, 28, 28, 1]) #第一层卷积层

吴裕雄 python 神经网络——TensorFlow 使用卷积神经网络训练和预测MNIST手写数据集

import tensorflow as tf import numpy as np from tensorflow.examples.tutorials.mnist import input_data #设置输入参数 batch_size = 128 test_size = 256 # 初始化权值与定义网络结构,建构一个3个卷积层和3个池化层,一个全连接层和一个输出层的卷积神经网络 # 首先定义初始化权重函数 def init_weights(shape): return tf.Variabl

吴裕雄 python 神经网络——TensorFlow实现回归模型训练预测MNIST手写数据集

import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("E:\\MNIST_data\\", one_hot=True) #构建回归模型,输入原始真实值(group truth),采用sotfmax函数拟合,并定义损失函数和优化器 #定义回归模型 x = tf.placeholder(tf.float32,

吴裕雄 python 神经网络——TensorFlow 数据集高层操作

import tempfile import tensorflow as tf train_files = tf.train.match_filenames_once("E:\\output.tfrecords") test_files = tf.train.match_filenames_once("E:\\output_test.tfrecords") # 解析一个TFRecord的方法. def parser(record): features = tf.pa

吴裕雄 python 神经网络——TensorFlow 图像预处理完整样例

import numpy as np import tensorflow as tf import matplotlib.pyplot as plt def distort_color(image, color_ordering=0): if color_ordering == 0: image = tf.image.random_brightness(image, max_delta=32./255.) image = tf.image.random_saturation(image, low

吴裕雄 python 神经网络——TensorFlow pb文件保存方法

import tensorflow as tf from tensorflow.python.framework import graph_util v1 = tf.Variable(tf.constant(1.0, shape=[1]), name = "v1") v2 = tf.Variable(tf.constant(2.0, shape=[1]), name = "v2") result = v1 + v2 init_op = tf.global_varia

吴裕雄 python 神经网络——TensorFlow TFRecord样例程序

import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 定义函数转化变量类型. def _int64_feature(value): return tf.train.Feature(int64_list=tf.train.Int64List(value=[value])) def _bytes_feature(value): return tf.