import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#loading data
mnist = input_data.read_data_sets("MNIST_data",one_hot=True) #路径 / one hot vector
#every batch size
batch_size = 100
#calculate the sum of batches
n_batch = mnist.train.num_examples // batch_size
#define placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10]) #拉伸成为一个数组
#construct the neural network 没有隐藏层
weight = tf.Variable(tf.zeros([784,10]))
bias = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,weight)+bias)
#define loss function
loss = tf.reduce_mean(tf.square(y-prediction))
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)
#initialization
init = tf.global_variables_initializer()
#布尔型列表中 放置 对比结果
correct_predition = tf.equal(tf.arg_max(y,1),tf.arg_max(prediction,1)) #argmax 返回张量中最大的值所在的位置
#accuracy
accuracy = tf.reduce_mean(tf.cast(correct_predition,tf.float32)) #格式转换 从 布尔 变成 float
with tf.Session() as sess:
sess.run(init)
for e in range(21):
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))
#可优化的地方:
#批次 的 大小
#添加隐藏层 改变激活函数
#权值与偏执址的初始化改变
#loss函数改用交叉熵cross-entrpy
#学习率改变
#使用其他的优化方式
#训练次数
深度学习:Demo1-MNIST
最新推荐文章于 2024-10-01 15:55:36 发布