tensorflow入门——基于mnist数据集

from minist import imput_data
import tensorflow as tf
mnist = imput_data.read_data_sets("MNIST_data/", one_hot=True)
x=tf.placeholder(tf.float32,[None,784])#占位符,其中[None,784]表示列为784,行不定
y_=tf.placeholder("float",[None,10])

w=tf.Variable(tf.zeros([784,10])) 
b=tf.Variable(tf.zeros([10]))  #tf.zeros([10])表示生成一行十列的0向量
y=tf.nn.softmax(tf.matmul(x+b)+b)  #tf.matmul表示矩阵乘法,tf.nn.softmax(激活函数)
#更多tf.nn函数详见http://www.tensorfly.cn/tfdoc/api_docs/python/nn.html

cross_entropy=-tf.reduce_sum(y_*tf.log(y)) #累积求和
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#minimize最小化,
#tf.train.GradientDescentOptimizer梯度下降算法,0.01学习率
init=tf.global_variables_initializer() #初始化所有变量sess=tf.Session()sess.run(init) for i in range( 1000): batch_x,batch_y=mnist.train.next_batch( 100) #mnist.train.next_batch一次获取100行数据
sess.run(train_step, feed_dict={x:batch_x,y_:batch_y})#feed_dict字典形式correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1)) #tf.argmax最大值
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # 计算所学习到的模型在测试数据集上面的正确率 print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))

你可能感兴趣的:(tensorflow)