這里有一個例子演示使用softmax算法對mnist數(shù)據(jù)集做邏輯回歸訓(xùn)練。代碼在這里
這里的例子與temsorflow tutorials下的例子有較大差異。官方的源碼在這里
主要差異在官方例子嚴(yán)格封裝了四部曲:預(yù)測、損失、訓(xùn)練、評估。本文的例子也都有相應(yīng)的步驟,但是沒有將每一步封裝成函數(shù)。所以推薦大家去看下tensorflow官網(wǎng)例子的代碼風(fēng)格。
四部曲的一個講解圖片:
image
本次先來研究TensorFlow-Examples這個項目的例子,后面研究tensorflow官網(wǎng)的例子。
'''
一個使用tensorflow的邏輯回歸算法的例子
本例程使用了MNIST手寫數(shù)據(jù)集:
(http://yann.lecun.com/exdb/mnist/)
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
from __future__ import print_function
import tensorflow as tf
#導(dǎo)入MNIST數(shù)據(jù)集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('./data/', one_hot=True)
#超參數(shù)
learning_rate = 0.02
training_epochs = 25
batch_size = 100
display_step = 1
#tf計算圖的輸入
x = tf.placeholder(tf.float32, [None, 784]) #mnist中的圖片形狀是28*28=784
y = tf.placeholder(tf.float32, [None, 10]) #共有0~9十個分類
#模型權(quán)重參數(shù)
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
#構(gòu)造模型,前向預(yù)測
pred = tf.nn.softmax(tf.matmul(x, W) + b) #soft max
#使用交叉熵最小化誤差,構(gòu)造損失函數(shù)
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
#使用梯度下降作為優(yōu)化函數(shù)
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
#初始化變量
init = tf.global_variables_initializer()
#開始訓(xùn)練
with tf.Session() as sess:
#首先執(zhí)行初始化的動作
sess.run(init)
#循環(huán)訓(xùn)練
for epoch in range(training_epochs):
avg_cost = 0.
total_batch = int(mnist.train.num_examples/batch_size)
#在batch內(nèi)的數(shù)據(jù)上循環(huán)訓(xùn)練
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
# 運(yùn)行優(yōu)化操作和求代loss
_, c = sess.run([optimizer, cost], feed_dict={x:batch_xs,
y:batch_ys})
#計算loss的平均值
avg_cost += c/total_batch
#每個epoch都顯示日志信息
if (epoch+1)%display_step == 0:
print('Epoch', '%04d' % (epoch+1), 'cost=', '{:.9f}'.format(avg_cost))
print('Optimization Finished!')
#評估模型
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y,1))
#計算準(zhǔn)確率
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print('Accuracy:', accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))
本次輸出為:
Extracting ./data/train-images-idx3-ubyte.gz
Extracting ./data/train-labels-idx1-ubyte.gz
Extracting ./data/t10k-images-idx3-ubyte.gz
Extracting ./data/t10k-labels-idx1-ubyte.gz
2018-03-21 23:03:01.409627: I C:\tf_jenkins\home\workspace\rel-win\M\windows\PY\36\tensorflow\core\platform\cpu_feature_guard.cc:137] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2
Epoch 0001 cost= 0.925978589
Epoch 0002 cost= 0.526254420
Epoch 0003 cost= 0.454482552
Epoch 0004 cost= 0.419291513
Epoch 0005 cost= 0.397361512
Epoch 0006 cost= 0.381882034
Epoch 0007 cost= 0.370305932
Epoch 0008 cost= 0.361112824
Epoch 0009 cost= 0.353574065
Epoch 0010 cost= 0.347223472
Epoch 0011 cost= 0.341899154
Epoch 0012 cost= 0.337232508
Epoch 0013 cost= 0.333123128
Epoch 0014 cost= 0.329476996
Epoch 0015 cost= 0.326202850
Epoch 0016 cost= 0.323313250
Epoch 0017 cost= 0.320611633
Epoch 0018 cost= 0.318096246
Epoch 0019 cost= 0.315851949
Epoch 0020 cost= 0.313741414
Epoch 0021 cost= 0.311840049
Epoch 0022 cost= 0.310004324
Epoch 0023 cost= 0.308363335
Epoch 0024 cost= 0.306689580
Epoch 0025 cost= 0.305273963
Optimization Finished!
Accuracy: 0.9183
[Finished in 21.0s]
我嘗試了調(diào)整學(xué)習(xí)率和batch_size及training_epoch,準(zhǔn)確率沒有超過0.93,這可能是這種算法的天花板。
本此運(yùn)行的程序包含了以下知識點:
- softmax函數(shù)
- from tensorflow.examples.tutorials.mnist import input_data
- batch和epoch
tensorflow.examples.tutorials.mnist下的input_data是mnist數(shù)據(jù)集的載入程序,如果本地沒有代碼就會從網(wǎng)上下載,只下載一次。為了使用方便,它將圖像格式化輸入,支持批量取出。
由于數(shù)據(jù)集比較大,使用全部數(shù)據(jù)集訓(xùn)練浪費時間,所以定義了batch_size每次隨機(jī)取一部分?jǐn)?shù)據(jù)訓(xùn)練。一個輪回稱為一個epoch。
其它知識點:
- tf.argmax(vector, 1):返回的是vector中的最大值的索引號
- tf.cast()用來轉(zhuǎn)換類型
- accuracy.eval({x:mnist.test.images, y:mnist.test.labels})和sess.run(accuracy, feed_dict = {x:mnist.test.images, y:mnist.test.labels})作用一樣