tensorflow二元或softmax分类例子(手写体)

来源:互联网 发布:php.cgi漏洞 编辑:程序博客网 时间:2024/05/19 09:36

参考这个官方文档


王津的例子

from tensorflow.examples.tutorials.mnist import input_data#或import input_dataimport osos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'mnist = input_data.read_data_sets('MNIST_data', one_hot=True)print(mnist.train.labels)print(mnist.train.num_examples)print(mnist.validation.num_examples)#read_data_sets自动将数据分为train,validation,test#out:[[0000001000]#     ......#     [0000000001]]#     55000#     5000#训练数据集的图片是 mnist.train.images #训练数据集的标签是 mnist.train.labels#测试集图片:mnist.test.images#测试集标签:mnist.test.labelsimport tensorflow as tfsess = tf.InteractiveSession()x = tf.placeholder("float", shape=[None, 784])y_ = tf.placeholder("float", shape=[None, 10])W = tf.Variable(tf.zeros([784,10]))b = tf.Variable(tf.zeros([10]))sess.run(tf.global_variables_initializer())#init = tf.initialize_all_variables()#sess.run(init)y = tf.nn.softmax(tf.matmul(x,W) + b)cross_entropy = -tf.reduce_sum(y_*tf.log(y))#我们把 y_ 的每一个元素和 tf.log(y) 的对应元素相乘。最后,用 tf.reduce_sum 计算张量的所有元素的总和。train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)#tf.train.GradientDescentOptimizer优化算法很多,这里是梯度下降for i in range(1000):    batch = mnist.train.next_batch(50)    #mnist.train.next_batch 可以从所有的训练数据中读一小部分作为训练batch    train_step.run(feed_dict={x: batch[0], y_: batch[1]})    '''用这些数据点作为参数替换之前的占位符来运行train_step。使用一小部分的随机数据来进行训练被称为随机训练(stochastic training)- 在这里更确切的说是随机梯度下降训练。也可以:batch_xs, batch_ys = mnist.train.next_batch(100)ess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})tf.argmax给出某个tensor对象在某一维上的其数据最大值所在的索引值correct_prediction是一组布尔值,如[True, False, True, True] tf.cast可以把布尔值变成[1,0,1,1] ,redyce_mean取平均值后得到 0.75.'''correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))






0 0