mnist softmax函数

# -*- coding: utf-8 -*-


# 读取数据图片,预处理
import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data  # 加载mnist数据
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)  # one_hot为是否将标签转为一维数组形式


# 构建softmax回归模型
sess = tf.InteractiveSession()  # 交互作用类(不需用在计算前构建整个图)


# 占位符(x和y_)
x = tf.placeholder("float", shape=[None, 784])  # 浮点数,二维数组(第一维大小不定,第二维是784)
y_ = tf.placeholder("float", shape=[None, 10])  # 用于代表对应某一MNIST图片的类别


# 变量(w权重和b偏置)
w = tf.Variable(tf.zeros([784, 10]))  # 784*10的可变参数值二维矩阵
b = tf.Variable(tf.zeros([10]))  # 10维的向量
sess.run(tf.initialize_all_variables())  # 初始化所有变量为0


# 类别预测与损失函数
y = tf.nn.softmax(tf.matmul(x, w) + b)  # 计算每个分类的softmax概率值
cross_entropy = -tf.reduce_sum(y_ * tf.log(y))  # 损失函数(目标类别和预测类别之间的交叉熵)


# 训练模型
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)  # 最速下降法,步长为0.01
for i in range(1000):
    batch = mnist.train.next_batch(50)  # 每步加载50个样本
    train_step.run(feed_dict={x: batch[0], y_: batch[1]})  # feed_dict被每次训练的数据替代


# 模型评估
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))  # 检测预测值与实际值是否匹配
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))  # 将布尔数组转化为正确率
print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))  # 输出最终正确率

猜你喜欢

转载自blog.csdn.net/zhangyu4863/article/details/81136300