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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值