环境:anaconda64位+python3.6+TensorFlow 1.9.0
重点:
(1)如果你实现此代码,加载数据集Mnist失败,请前往:https://blog.csdn.net/landcruiser007/article/details/79346982,手动下载mnist数据集
(2)分类问题,当然要用到softmax和交叉熵,softmax我也只是简单的了解了一下,大家想知道细节的自己找一下。
交叉熵j精品!!传送门:https://blog.csdn.net/tsyccnh/article/details/79163834
话不多说,贴上代码
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist=input_data.read_data_sets("D:/BaiduNetdiskDownload/MNIST_data/",one_hot=True)
#增加一个层
def add_layer(inputs,in_size,out_size,activation_function=None):
Weights=tf.Variable(tf.random_normal([in_size,out_size]))
#bias维度:1*outsize
biases=tf.Variable(tf.zeros([1,out_size])+0.1)
Wx_plus_b = tf.matmul(inputs,Weights)+biases
if activation_function is None:
outputs=Wx_plus_b
else:
outputs=activation_function(Wx_plus_b)
return outputs
#计算准确率
def compute_accuracy(v_xs,v_ys):
global prediction
y_pre=sess.run(prediction,feed_dict={xs:v_xs})
#tf.argmax()返回各行元素最大值的位置,形成一维向量
#tf.equal()两个值相等返回True
correct_prediction=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
#计算准确率
accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
result=sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})
print(y_pre.shape)
return result
xs=tf.placeholder(tf.float32,[None,784])#28*28
ys=tf.placeholder(tf.float32,[None,10])
#激活函数是softmax
prediction=add_layer(xs,784,10,activation_function=tf.nn.softmax)
#两个tf的一维向量相乘,每个元素相乘
cross_entroy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entroy)
init=tf.global_variables_initializer()#variable需要初始化
with tf.Session() as sess:
sess.run(init)
for i in range(500):
#取100个数据进行学习
batch_xs,batch_ys=mnist.train.next_batch(100)
sess.run(train_step,feed_dict={xs: batch_xs,ys:batch_ys})
if i%50 ==0:
print(compute_accuracy(mnist.test.images,mnist.test.labels))