Tensorflow_01_分类问题

代码:

# coding = utf-8
from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 加载数据集
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

def add_layer(inputs, in_size, out_size, activation_function=None, ):
    # 添加层 返回这一层的输出
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1, )
    Wx_plus_b = tf.matmul(inputs, Weights) + biases
    if activation_function is None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b, )
    return outputs


# 计算准确度(准确率)
def compute_accuracy(v_xs, v_ys):
    global prediction
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})

    # tf.equal判断相等 相等返回True 否则返回False
    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))

    # 预测值 tf.cast 转换类型 将布尔类型转换为
    # 按照平均值横纵降低维度 (作为概率)
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

    # result是一个百分比 读取accuracy作为结果
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result


# 定义输入
# 每张图片有784个像素点
xs = tf.placeholder(tf.float32, [None, 784])  # 28x28
# 有10个输出
ys = tf.placeholder(tf.float32, [None, 10])

# 添加层  softmax一般用来做分类(将输入整理成0-1的数 且相加为1 符合概率属性)
prediction = add_layer(xs, 784, 10, activation_function=tf.nn.softmax)

# 生成分类算法(也就是loss)

# 交叉熵评估代价(分类器计算loss常用这个函数)
# tf.reduce_mean 函数用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,主要用作降维或者计算tensor(图像)的平均值
# reduce就是“对矩阵降维”的含义,下划线后面的部分就是降维的方式,在reduce_sum()中就是按照求和的方式对矩阵降维 reduction_indices=[1] 横向求和
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))  # loss

# 随机梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

# 开启会话
sess = tf.Session()
# 初始化变量
init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):

    # 先学习100个 mnist.train取训练集
    batch_xs, batch_ys = mnist.train.next_batch(100)

    sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys})
    if i % 50 == 0:
        # 用测试集来计算精确素
        print(compute_accuracy(mnist.test.images, mnist.test.labels))

猜你喜欢

转载自blog.csdn.net/DylanYuan/article/details/86489824