• 手写数字识别


    from tensorflow.examples.tutorials.mnist import input_data
    import tensorflow as tf
    
    # 载入MNIST数据集
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    sess = tf.InteractiveSession()
    
    # 先定义好初始化函数, 该卷积神经网络会有很多的权重和偏置需要创建
    # 我们需要给权重制造一些随机噪声来打破完全对称
    # 比如截断的正态分布噪声, 标准差设为0.1. 同时因为我们使用ReLU,
    # 也给偏置增加一些小的正值(0.1)用来避免死亡结点
    def weight_variable(shape):
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial)
    
    def bias_variable(shape):
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial)
    
    # 卷积层, 池化层接下来也要重复使用, 因此也定义创建函数
    # [] 前面两个代表卷积核的尺寸, 第三个代表有多少个channel
    # 最后一个代表卷积核的数量, 也就是这个卷积层会提取多少类的特征
    def conv2d(x, w):
        return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
    
    def max_pool_2x2(x):
        return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],
                              padding='SAME')
    
    # 设置占位符
    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])
    x_image = tf.reshape(x, [-1, 28, 28, 1])
    
    # 第一层卷积 + 池化
    w_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
    
    # 第二层卷积 + 池化
    # 不同之处在于卷积核的数量变成了64
    w_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)
    
    # 连接一个全连接层, 隐含结点为1024, 并使用ReLU激活函数
    w_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])
    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)
    
    # 为了减轻过拟合, 使用Dropout层
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    
    # 我们将Dropout层的输出连接一个Softmax层, 得到最后的概率输出
    w_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])
    y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)
    
    # 定义损失函数, 使用优化器Adam, 并给于一个较小的学习速率1e-4
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),
                                                  reduction_indices=[1]))
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    
    # 定义评价准确率的操作
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    
    # 下面开始训练
    tf.global_variables_initializer().run()
    for i in range(20000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            # 预测时保留全部数据来追求最好的预测性能
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1],
                                                      keep_prob: 1.0})
            print("step %d, training accuracy %g"%(i, train_accuracy))
        # 训练时, 随机丢弃一部分结点的数据来减轻过拟合
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    
    # 全部训练完成后, 我们在最终的测试集上进行全面的测试,
    # 得到整体的分类准确率
    print("test accuracy %g" % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0
    }))
    

      

  • 相关阅读:
    Docker简单的使用命令
    iPad 3g版完美实现打电话功能(phoneitipad破解)
    提供一个免费的CSDN下载账号
    2011年一次面试的实际记录
    VC皮肤库SkinSharp 1.0.6.6的使用
    oracle 数组
    从网页抓取数据的一般方法
    IJ:Idea 常用代码
    un-公司-Continental AG(大陆集团):百科
    un-公司-维珍集团:百科
  • 原文地址:https://www.cnblogs.com/mjn1/p/11218319.html
Copyright © 2020-2023  润新知