Tensorflow的hello world =MNIST入门

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hello_java_Android/article/details/84390128

主题流程是这样的:首先下载数据,mnist自动解析为训练数据和测试数据,每张图解析为784维向量,根据图片中像素加权,通过softMax函数计算图片中数字是0~9中某个数字的概率,使用梯度下降最小化交叉熵,最后根据真实值和预测值评估模型准确度

#-*- coding=utf-8 -*-
import tensorflow as tf
import input_data
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

#输入数据,可以展开为784维的向量
x = tf.placeholder('float', [None, 784])
#初始化w(权重)和b(偏置),初始值可以随意设置,这里设置为0
w = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

#使用softMax函数进行概率分布计算
y = tf.nn.softmax(tf.matmul(x,w) + b)
#定义一个指标用于衡量预测的准确性,这里使用交叉熵(也是一种成本或者叫损失函数),根据输入的实际值和我们的预测
#值来计算这个交叉熵,首先定义真实值占位
y_ = tf.placeholder('float', [None, 10])
#根据交叉熵公式计算
cross_entropy = -tf.reduce_sum(y_*tf.log(y))

#构建训练模型  学习率(步长)=0.01   
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

#模型评估  预测是否与真实标签匹配  输出一组boolean值
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
#评估  boolean值转化为浮点数,然后求平均值  即为正确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, 'float'))

#初始化变量
init_op = tf.global_variables_initializer()
#创建会话,准备运行
sess = tf.Session()
sess.run(init_op)

#开始训练模型
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x:batch_xs, y_:batch_ys})
    print('weight is == ', sess.run(w))
    print('bias is == ', sess.run(b))

#打印正确率
print(sess.run(accuracy, feed_dict={x:mnist.test.images, y_:mnist.test.labels}))

猜你喜欢

转载自blog.csdn.net/hello_java_Android/article/details/84390128