import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)
sess = tf.InteractiveSession()
x = tf.placeholder(tf.float32, [None, 784]) #placeholder是输入数据的地方
'''初始化权重矩阵、偏置值'''
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
'''回归softmax regression'''
y = tf.nn.softmax(tf.matmul(x, W) + b) #tf.nn包含了大量神经网络的组建;tf.matmul是tensorflow中的矩阵乘法函数
'''损失函数loss function'''
#用于描述模型对问题对分类精度
#此处使用cross-entropy
y_ = tf.placeholder(tf.float32, [None, 10]) #输入label,label的独热编码是10位
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) #tf.reduce_mean求平均值,tf.reduce_sum求和,y_ * tf.log(y)是cross-entropy的公式
'''优化算法:随机梯度下降SGD'''
#使用一小部分样本进行训练称为随机梯度下降,比传统的全样本训练的收敛速度快很多
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) #设置学习速率为0.5,优化目标为cross_entropy取得最小值(loss越小精确度越高)
'''全局参数初始化'''
tf.global_variables_initializer().run() #global_variables_initializer为全局参数初始化器
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100) #每次都随机取100条样本构成mini-batch,并feed给placeholder。返回的是两个元素(图片+label)label就是0123456789共10种
train_step.run({x: batch_xs, y_: batch_ys})
#以上完成了所有的训练,总结一下就是用x、W、b得出y,用标签y_进行损失函数计算获得模型对问题的分类精度,得到精度后进行梯度下降以获得优化
#接下来将计算模型的准确率
'''验证模型准确率'''
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #对bool类型进行转换成float型后,求平均
# print(accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))
print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
运行结果模型准确率:
参考书籍:《TensorFlow实战》