TensorFlow實現隨機訓練和批量訓練的方法

來源:互聯網
上載者:User
本篇文章主要介紹了TensorFlow實現隨機訓練和批量訓練的方法,現在分享給大家,也給大家做個參考。一起過來看看吧

TensorFlow更新模型變數。它能一次操作一個資料點,也可以一次操作大量資料。一個訓練例子上的操作可能導致比較“古怪”的學習過程,但使用大批量的訓練會造成計算成本昂貴。到底選用哪種訓練類型對機器學習演算法的收斂非常關鍵。

為了TensorFlow計算變數梯度來讓反向傳播工作,我們必須度量一個或者多個樣本的損失。

隨機訓練會一次隨機抽樣訓練資料和目標資料對完成訓練。另外一個可選項是,一次大批量訓練取平均損失來進行梯度計算,批量訓練大小可以一次上擴到整個資料集。這裡將顯示如何擴充前面的迴歸演算法的例子——使用隨機訓練和批量訓練。

批量訓練和隨機訓練的不同之處在於它們的最佳化器方法和收斂。

# 隨機訓練和批量訓練#----------------------------------## This python function illustrates two different training methods:# batch and stochastic training. For each model, we will use# a regression model that predicts one model variable.import matplotlib.pyplot as pltimport numpy as npimport tensorflow as tffrom tensorflow.python.framework import opsops.reset_default_graph()# 隨機訓練:# Create graphsess = tf.Session()# 聲明資料x_vals = np.random.normal(1, 0.1, 100)y_vals = np.repeat(10., 100)x_data = tf.placeholder(shape=[1], dtype=tf.float32)y_target = tf.placeholder(shape=[1], dtype=tf.float32)# 聲明變數 (one model parameter = A)A = tf.Variable(tf.random_normal(shape=[1]))# 增加操作到圖my_output = tf.multiply(x_data, A)# 增加L2損失函數loss = tf.square(my_output - y_target)# 初始設定變數init = tf.global_variables_initializer()sess.run(init)# 聲明最佳化器my_opt = tf.train.GradientDescentOptimizer(0.02)train_step = my_opt.minimize(loss)loss_stochastic = []# 運行迭代for i in range(100): rand_index = np.random.choice(100) rand_x = [x_vals[rand_index]] rand_y = [y_vals[rand_index]] sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y}) if (i+1)%5==0:  print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)))  temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})  print('Loss = ' + str(temp_loss))  loss_stochastic.append(temp_loss)# 批量訓練:# 重設計算圖ops.reset_default_graph()sess = tf.Session()# 聲明批量大小# 批量大小是指通過計算圖一次傳入多少訓練資料batch_size = 20# 聲明模型的資料、預留位置x_vals = np.random.normal(1, 0.1, 100)y_vals = np.repeat(10., 100)x_data = tf.placeholder(shape=[None, 1], dtype=tf.float32)y_target = tf.placeholder(shape=[None, 1], dtype=tf.float32)# 聲明變數 (one model parameter = A)A = tf.Variable(tf.random_normal(shape=[1,1]))# 增加矩陣乘法操作(矩陣乘法不滿足交換律)my_output = tf.matmul(x_data, A)# 增加損失函數# 批量訓練時損失函數是每個資料點L2損失的平均值loss = tf.reduce_mean(tf.square(my_output - y_target))# 初始設定變數init = tf.global_variables_initializer()sess.run(init)# 聲明最佳化器my_opt = tf.train.GradientDescentOptimizer(0.02)train_step = my_opt.minimize(loss)loss_batch = []# 運行迭代for i in range(100): rand_index = np.random.choice(100, size=batch_size) rand_x = np.transpose([x_vals[rand_index]]) rand_y = np.transpose([y_vals[rand_index]]) sess.run(train_step, feed_dict={x_data: rand_x, y_target: rand_y}) if (i+1)%5==0:  print('Step #' + str(i+1) + ' A = ' + str(sess.run(A)))  temp_loss = sess.run(loss, feed_dict={x_data: rand_x, y_target: rand_y})  print('Loss = ' + str(temp_loss))  loss_batch.append(temp_loss)plt.plot(range(0, 100, 5), loss_stochastic, 'b-', label='Stochastic Loss')plt.plot(range(0, 100, 5), loss_batch, 'r--', label='Batch Loss, size=20')plt.legend(loc='upper right', prop={'size': 11})plt.show()

輸出:

Step #5 A = [ 1.47604525]
Loss = [ 72.55678558]
Step #10 A = [ 3.01128507]
Loss = [ 48.22986221]
Step #15 A = [ 4.27042341]
Loss = [ 28.97912598]
Step #20 A = [ 5.2984333]
Loss = [ 16.44779968]
Step #25 A = [ 6.17473984]
Loss = [ 16.373312]
Step #30 A = [ 6.89866304]
Loss = [ 11.71054649]
Step #35 A = [ 7.39849901]
Loss = [ 6.42773056]
Step #40 A = [ 7.84618378]
Loss = [ 5.92940331]
Step #45 A = [ 8.15709782]
Loss = [ 0.2142024]
Step #50 A = [ 8.54818344]
Loss = [ 7.11651039]
Step #55 A = [ 8.82354641]
Loss = [ 1.47823763]
Step #60 A = [ 9.07896614]
Loss = [ 3.08244276]
Step #65 A = [ 9.24868107]
Loss = [ 0.01143846]
Step #70 A = [ 9.36772251]
Loss = [ 2.10078788]
Step #75 A = [ 9.49171734]
Loss = [ 3.90913701]
Step #80 A = [ 9.6622715]
Loss = [ 4.80727625]
Step #85 A = [ 9.73786926]
Loss = [ 0.39915398]
Step #90 A = [ 9.81853104]
Loss = [ 0.14876099]
Step #95 A = [ 9.90371323]
Loss = [ 0.01657014]
Step #100 A = [ 9.86669159]
Loss = [ 0.444787]
Step #5 A = [[ 2.34371352]]
Loss = 58.766
Step #10 A = [[ 3.74766445]]
Loss = 38.4875
Step #15 A = [[ 4.88928795]]
Loss = 27.5632
Step #20 A = [[ 5.82038736]]
Loss = 17.9523
Step #25 A = [[ 6.58999157]]
Loss = 13.3245
Step #30 A = [[ 7.20851326]]
Loss = 8.68099
Step #35 A = [[ 7.71694899]]
Loss = 4.60659
Step #40 A = [[ 8.1296711]]
Loss = 4.70107
Step #45 A = [[ 8.47107315]]
Loss = 3.28318
Step #50 A = [[ 8.74283409]]
Loss = 1.99057
Step #55 A = [[ 8.98811722]]
Loss = 2.66906
Step #60 A = [[ 9.18062305]]
Loss = 3.26207
Step #65 A = [[ 9.31655025]]
Loss = 2.55459
Step #70 A = [[ 9.43130589]]
Loss = 1.95839
Step #75 A = [[ 9.55670166]]
Loss = 1.46504
Step #80 A = [[ 9.6354847]]
Loss = 1.49021
Step #85 A = [[ 9.73470974]]
Loss = 1.53289
Step #90 A = [[ 9.77956581]]
Loss = 1.52173
Step #95 A = [[ 9.83666706]]
Loss = 0.819207
Step #100 A = [[ 9.85569191]]
Loss = 1.2197


訓練類型 優點 缺點
隨機訓練 脫離局部最小 一般需更多次迭代才收斂
批量訓練 快速得到最小損失 耗費更多計算資源

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.