機器學習實戰:TensorFlow構建邏輯迴歸模型

import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow .examples .tutorials .mnist import input_data
#使用MNIST數據集-10個手寫體數據,對其進行分類
print("Download and Extract MNIST dataset")
mnist = input_data .read_data_sets('data/',one_hot=True)

trainimg = mnist.train.images
trainlabel = mnist.train.labels
testimg = mnist.test.images
testlabel = mnist.test.labels
print("MNIST loaded")

print(trainimg.shape)
print(trainlabel.shape)
print(testimg.shape)
print(testlabel.shape)

x = tf.placeholder("float",[None,784])#float表示數據類型,None表示多少個數據,784表示網絡中輸入層的特徵個數
y = tf.placeholder("float",[None,10])
W = tf.Variable(tf.zeros([784,10]))#W的維度是根據特徵個數(784)和該層神經元個數(10)
b = tf.Variable(tf.zeros([10]))

#邏輯迴歸解決二分類問題,將之變形爲softmax
actv = tf.nn.softmax(tf.matmul(x,W)+b)

#損失函數
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(actv),axis=1))
'''
求最大值tf.reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None)
求平均值tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)
reduce_sum應該理解爲壓縮求和,用於降維
reduce_sum ( 
    input_tensor , 
    axis = None , 
    keep_dims = False , 
    name = None , 
    reduction_indices = None
 )
input_tensor:要減少的張量.應該有數字類型.
axis:要減小的尺寸.如果爲None(默認),則縮小所有尺寸.必須在範圍[-rank(input_tensor), rank(input_tensor)).0-列求和,1-行求和
keep_dims:如果爲true,則保留長度爲1的縮小尺寸.
name:操作的名稱(可選).
reduction_indices:axis的廢棄的名稱.
'''

#梯度下降中需要給的學習率參數值
learning_rate = 0.01

#tf.train.GradientDescentOptimizer()使用隨機梯度下降算法,使參數沿着 梯度的反方向,即總損失減小的方向移動,實現更新參數.裏面的參數是步長(學習率)
optm = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)#訓練的過程就是最小化這個誤差值

#找出每個樣本的最大預測值與真正所屬是否相同
pred = tf.equal(tf.argmax(actv,1),tf.argmax(y,1))
'''
tf.argmax(input, axis=None, name=None, dimension=None)--返回最大值的索引,從0開始
input:輸入值
axis:0表示按列計算每列最大數的下標,1表示按行計算每行最大數的下標
name:名稱
dimension:和axis功能一樣,默認axis取值優先

equal(x, y, name=None)
equal,相等的意思。顧名思義,就是判斷,x, y 是不是相等,它的判斷方法不是整體判斷,而是逐個元素進行判斷,如果相等就是 True,不相等,就是 False。
由於是逐個元素判斷,所以 x,y 的維度要一致。
'''

acc = tf.reduce_mean(tf.cast(pred,'float'))
'''
cast(   x,    dtype,    name=None)
將x的數據格式轉化成dtype.例如,原來x的數據格式是bool, 
那麼將其轉化成float以後,就能夠將其轉化成01的序列。反之也可以
'''

init = tf.global_variables_initializer()
#邏輯框架已經完成。

training_epochs = 50#所有的樣本迭代50次
batch_size = 100#每進行一次迭代要選擇多少樣本
display_step = 5#展示
sess = tf.Session()
sess.run(init)

for epoch in range(training_epochs):
    avg_cost = 0
    num_batch = int(mnist.train.num_examples/batch_size)
    for i in range(num_batch):
        batch_xs,batch_ys = mnist.train.next_batch(batch_size)
        sess.run(optm,feed_dict={x:batch_xs,y:batch_ys})
        #avg_cost += sess.run(cost,feed_dict={x:batch_xs,y:batch_ys})/num_batch
        avg_cost = avg_cost +sess.run(cost,feed_dict={x:batch_xs,y:batch_ys})#迭代一次時,整個數據集被劃分成多個塊,for一次循環中是求的每個塊的損失
    avg_cost = avg_cost /num_batch#這邊將所有塊的損失求和取平均得到平均損失
    if epoch % display_step ==0:#每5個epoch打印一次
        feeds_train = {x:batch_xs,y:batch_ys}
        feeds_test = {x:mnist.test.images,y:mnist.test.labels}
        train_acc = sess.run(acc,feed_dict=feeds_train)
        test_acc = sess.run(acc,feed_dict=feeds_test)
        print("Epoch: %03d/%03d cost: %.9f train_acc: %.3f test_acc: %.3f" % (
        epoch, training_epochs, avg_cost, train_acc, test_acc))

print("DONE")

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章