TensorFlow邏輯回歸
實驗目的
1.掌握使用TensorFlow進行邏輯回歸
2.掌握邏輯回歸的原理
實驗原理
邏輯回歸是機器學習中很簡答的一個例子,這篇文章就是要介紹如何使用tensorflow實現一個簡單的邏輯回歸算法。
邏輯回歸可以看作只有一層網絡的前向神經網絡,並且參數連接的權重只是一個值,而非矩陣。公式為:y_predict=logistic(X*W+b),其中X為輸入,W為輸入與隱含層之間的權重,b為隱含層神經元的偏置,而logistic為激活函數,一般為sigmoid或者tanh,y_predict為最終預測結果。
邏輯回歸是一種分類器模型,需要函數不斷的優化參數,這里目標函數為y_predict與真實標簽Y之間的L2距離,使用隨機梯度下降算法來更新權重和偏置。
實驗環境
Windows10
Pycharm
TensorFlow
實驗內容
使用TensorFlow進行邏輯回歸操作。
實驗步驟
1.打開Pycharm,選擇Create New Project,右鍵選擇New=>Python File,
創建名為logistic_regression的Python文件。
2.打開logistic_regression.py文件,編寫tensorflow邏輯回歸代碼。
導入實驗所需要的模塊
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
3.導入實驗所需的數據
mnist = input_data.read_data_sets("C:/Users/32016/Desktop/spark/深度學習算法部分/",one_hot = True)
4.設置訓練參數
learning_rate=0.01
training_epochs=25
batch_size=100
display_step=1
5.構造計算圖,使用占位符placeholder函數構造變量x,y,代碼如下:
x=tf.placeholder(tf.float32,[None,784])
y=tf.placeholder(tf.float32,[None,10])
6.使用Variable函數,設置模型的初始權重
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
7.構造邏輯回歸模型
pred=tf.nn.softmax(tf.matmul(x,W)+b)
8.構造代價函數cost
cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1))
9.使用梯度下降法求最小值,即最優解
optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
10.初始化全部變量
init=tf.global_variables_initializer()
11.使用tf.Session()創建Session會話對象,會話封裝了Tensorflow運行時的狀態和控制。
with tf.Session() as sess:
sess.run(init)
12.調用會話對象sess的run方法,運行計算圖,即開始訓練模型。
for epoch in range(training_epochs):
avg_cost = 0
total_batch = int(mnist.train.num_examples / batch_size)
for i in range(total_batch):
batch_xs, batch_ys = mnist.train.next_batch(batch_size)
_, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys})
avg_cost += c / total_batch
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch + 1), "Cost:","{:.09f}".format(avg_cost))
print("Optimization Finished!")
13.測試模型
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
14.評估模型的准確度。
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print("Accuracy:", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]}))
15.完整代碼:
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #導入實驗所需的數據 mnist = input_data.read_data_sets("C:/Users/32016/Desktop/spark/深度學習算法部分/",one_hot = True) #設置訓練參數 learning_rate=0.01 training_epochs=25 batch_size=100 display_step=1 #構造計算圖,使用占位符placeholder函數構造變量x,y, x=tf.placeholder(tf.float32,[None,784]) y=tf.placeholder(tf.float32,[None,10]) #使用Variable函數,設置模型的初始權重 W=tf.Variable(tf.zeros([784,10])) b=tf.Variable(tf.zeros([10])) #構造邏輯回歸模型 pred=tf.nn.softmax(tf.matmul(x,W)+b) #構造代價函數cost cost=tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred),reduction_indices=1)) #使用梯度下降法求最小值,即最優解 optimizer=tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) #初始化全部變量 init=tf.global_variables_initializer() #.使用tf.Session()創建Session會話對象,會話封裝了Tensorflow運行時的狀態和控制 with tf.Session() as sess: sess.run(init) #調用會話對象sess的run方法,運行計算圖,即開始訓練模型 for epoch in range(training_epochs): avg_cost = 0 total_batch = int(mnist.train.num_examples / batch_size) for i in range(total_batch): batch_xs, batch_ys = mnist.train.next_batch(batch_size) _, c = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys}) avg_cost += c / total_batch if (epoch+1) % display_step == 0: print("Epoch:", '%04d' % (epoch + 1), "Cost:","{:.09f}".format(avg_cost)) print("Optimization Finished!") #測試模型 correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1)) #評估模型的准確度 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print("Accuracy:", accuracy.eval({x: mnist.test.images[:3000], y: mnist.test.labels[:3000]}))
16.運行結果為: