"""
1. 放入mnist数据到项目根目录mnist/MINIST_data下
"""
def test03_mnist():
# 载入数据,将数据进行one_hot向量化
mnist = input_data.read_data_sets('mnist/MNIST_data', one_hot=True)
# 每个批次的大小
batch_size = 100
# 计算共有多少个批次
n_batch = mnist.train.num_examples // batch_size
# 定义两个placeholder
# None:任意值:每个批次一次一次的传值到placeholder中,实现动态传值,比如传100行数据进去,None就变为100
# 784列:每个图片的为28 * 28的格式,将图片转换为一维数组的方式,所有有 None行、874列
x = tf.placeholder(tf.float32, [None, 784])
y = tf.placeholder(tf.float32, [None, 10]) # 一共有10个数字:0-9
# 创建神经网络
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x, W) + b)
# 定义二次代价函数
loss = tf.reduce_mean(tf.square(y-prediction))
# 使用梯度下降法
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# 初始化变量
init = tf.global_variables_initializer()
# 结果存放在一个bool列表中
# argmax返回一个一维张量中最大的值所在的位置
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1))
# 求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
with tf.Session() as sess:
sess.run(init)
for e in range(200):
for batch in range(n_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys})
acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})
print("Iter" + str(e) + ", Testing Accuracy " + str(acc))
if __name__ == "__main__":
test03_mnist()
网友评论