• Tenserflow学习(一)——MNIST数据集分类简单版本


    编写简单的单层网络实现MNIST数据集分类(代码如下)

    import tensorflow as tf
    from tensorflow.examples.tutorials.mnist import input_data
    
    
    # 载入数据
    
    """one_hot参数把标签转化到0-1之间
    """
    mnist = input_data.read_data_sets("MNIST_data", one_hot=True)
    # 每个批次大小(每次放入训练图像数量)
    batch_size = 100
    # 批次数量
    num_batch = mnist.train.num_examples // batch_size
    
    x = tf.placeholder(tf.float32, [None, 784])
    y = tf.placeholder(tf.float32, [None, 10])
    w = tf.Variable(tf.zeros([784, 10]))
    b = tf.Variable(tf.random_normal([10]))
    prediction = tf.nn.softmax(tf.matmul(x, w) + b)     # 概率值转化: softmax()
    
    # loss = tf.reduce_mean(tf.square(y - prediction))  # 二次代价函数
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y, logits=prediction))     # 交叉熵代价函数
    train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
    
    init = tf.global_variables_initializer()
    correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))    # argmax()返回一维张量中最大值所在的位置
    # 计算准确率
    """cast()将correct_prediction列表变量中的值转换成float32 --> true=1.0,false=0.0
    """
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))  # cast()相当于类型转换函数
    with tf.Session() as sess:
        sess.run(init)
        for epoch in range(21):
            for batch in range(num_batch):
                batch_xs, batch_ys = mnist.train.next_batch(batch_size)
                sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})
            acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
            print('iter' + str(epoch) + ', testing accuracy:' + str(acc))
  • 相关阅读:
    有效的完全平方数
    除自身以外数组的乘积leetcode
    三个数的最大乘积 leetcode
    不同的二叉搜索树
    fenzhi
    leetcode二分查找之大于给定元素的最小元素744. Find Smallest Letter Greater Than Target (Easy)
    leetcode二分查找之求开方
    总结U-Net网络及他的变体
    451. Sort Characters By Frequency (Medium) 按照字符出现次数对字符串排序(leetcode排序)
    记一次 PHP调用Java Webservice
  • 原文地址:https://www.cnblogs.com/horacle/p/13167760.html
Copyright © 2020-2023  润新知