自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

圖解機(jī)器學(xué)習(xí):神經(jīng)網(wǎng)絡(luò)和TensorFlow的文本分類(lèi)

人工智能 機(jī)器學(xué)習(xí)
在本文中,我們將創(chuàng)建一個(gè)機(jī)器學(xué)習(xí)模型來(lái)將文本分類(lèi)到類(lèi)別中。

開(kāi)發(fā)人員經(jīng)常說(shuō),如果你想開(kāi)始機(jī)器學(xué)習(xí),你應(yīng)該首先學(xué)習(xí)算法。但是我的經(jīng)驗(yàn)則不是。

我說(shuō)你應(yīng)該首先了解:應(yīng)用程序如何工作。一旦了解了這一點(diǎn),深入探索算法的內(nèi)部工作就會(huì)變得更加容易。

那么,你如何 開(kāi)發(fā)直覺(jué)學(xué)習(xí),并實(shí)現(xiàn)理解機(jī)器學(xué)習(xí)這個(gè)目的?一個(gè)很好的方法是創(chuàng)建機(jī)器學(xué)習(xí)模型。

假設(shè)您仍然不知道如何從頭開(kāi)始創(chuàng)建所有這些算法,您可以使用一個(gè)已經(jīng)為您實(shí)現(xiàn)所有這些算法的庫(kù)。那個(gè)庫(kù)是 TensorFlow。

在本文中,我們將創(chuàng)建一個(gè)機(jī)器學(xué)習(xí)模型來(lái)將文本分類(lèi)到類(lèi)別中。我們將介紹以下主題:

  1. TensorFlow 的工作原理
  2. 什么是機(jī)器學(xué)習(xí)模型
  3. 什么是神經(jīng)網(wǎng)絡(luò)
  4. 神經(jīng)網(wǎng)絡(luò)如何學(xué)習(xí)
  5. 如何操作數(shù)據(jù)并將其傳遞給神經(jīng)網(wǎng)絡(luò)
  6. 如何運(yùn)行模型并獲得預(yù)測(cè)結(jié)果

你可能會(huì)學(xué)到很多新東西,所以讓我們開(kāi)始吧!

TensorFlow

TensorFlow 是一個(gè)機(jī)器學(xué)習(xí)的開(kāi)源庫(kù),由 Google 首創(chuàng)。庫(kù)的名稱(chēng)幫助我們理解我們?cè)鯓邮褂盟簍ensors 是通過(guò)圖的節(jié)點(diǎn)流轉(zhuǎn)的多維數(shù)組。

tf.Graph

在 TensorFlow 中的每一個(gè)計(jì)算都表示為數(shù)據(jù)流圖,這個(gè)圖有兩類(lèi)元素:

  • 一類(lèi) tf.Operation,表示計(jì)算單元
  • 一類(lèi) tf.Tensor,表示數(shù)據(jù)單元

要查看這些是怎么工作的,你需要?jiǎng)?chuàng)建這個(gè)數(shù)據(jù)流圖:

 

(計(jì)算x+y的圖)

你需要定義 x = [1,3,6] 和 y = [1,1,1]。由于圖用 tf.Tensor 表示數(shù)據(jù)單元,你需要?jiǎng)?chuàng)建常量 Tensors:

  1. import tensorflow as tf 
  2.  
  3. x = tf.constant([1,3,6]) 
  4.  
  5. y = tf.constant([1,1,1]) 

現(xiàn)在你將定義操作單元:

  1. import tensorflow as tf 
  2.  
  3. x = tf.constant([1,3,6]) 
  4.  
  5. y = tf.constant([1,1,1]) 
  6.  
  7. op = tf.add(x,y)  

你有了所有的圖元素?,F(xiàn)在你需要構(gòu)建圖:

  1. import tensorflow as tf 
  2.  
  3. my_graph = tf.Graph() 
  4.  
  5. with my_graph.as_default(): 
  6.  
  7. x = tf.constant([1,3,6]) 
  8.  
  9. y = tf.constant([1,1,1]) 
  10.  
  11. op = tf.add(x,y)  

這是 TensorFlow 工作流的工作原理:你首先要?jiǎng)?chuàng)建一個(gè)圖,然后你才能計(jì)算(實(shí)際上是用操作‘運(yùn)行’圖節(jié)點(diǎn))。你需要?jiǎng)?chuàng)建一個(gè) tf.Session 運(yùn)行圖。

tf.Session

tf.Session 對(duì)象封裝了 Operation 對(duì)象的執(zhí)行環(huán)境。Tensor 對(duì)象是被計(jì)算過(guò)的(從文檔中)。為了做到這些,我們需要在 Session 中定義哪個(gè)圖將被使用到:

  1. import tensorflow as tf 
  2.  
  3. my_graph = tf.Graph() 
  4.  
  5. with tf.Session(graph=my_graph) as sess: 
  6.  
  7.   x = tf.constant([1,3,6]) 
  8.  
  9.   y = tf.constant([1,1,1]) 
  10.  
  11.   op = tf.add(x,y)  

為了執(zhí)行操作,你需要使用方法 tf.Session.run()。這個(gè)方法通過(guò)運(yùn)行必要的圖段去執(zhí)行每個(gè) Operation 對(duì)象并通過(guò)參數(shù) fetches 計(jì)算每一個(gè) Tensor 的值的方式執(zhí)行 TensorFlow 計(jì)算的一’步’:

  1. import tensorflow as tf 
  2.  
  3. my_graph = tf.Graph() 
  4.  
  5. with tf.Session(graph=my_graph) as sess: 
  6.  
  7.   x = tf.constant([1,3,6]) 
  8.  
  9.   y = tf.constant([1,1,1]) 
  10.  
  11.   op = tf.add(x,y) 
  12.  
  13.   result = sess.run(fetches=op) 
  14.  
  15.   print(result) 
  16.  
  17. >>> [2 4 7]  

預(yù)測(cè)模型

現(xiàn)在你知道了 TensorFlow 的工作原理,那么你得知道怎樣創(chuàng)建預(yù)測(cè)模型。簡(jiǎn)而言之

機(jī)器學(xué)習(xí)算法+數(shù)據(jù)=預(yù)測(cè)模型

構(gòu)建模型的過(guò)程就是這樣:

 

(構(gòu)建預(yù)測(cè)模型的過(guò)程)

正如你能看到的,模型由數(shù)據(jù)“訓(xùn)練過(guò)的”機(jī)器學(xué)習(xí)算法組成。當(dāng)你有了模型,你就會(huì)得到這樣的結(jié)果:

 

(預(yù)測(cè)工作流)

你創(chuàng)建的模型的目的是對(duì)文本分類(lèi),我們定義了:

input: text, result: category

我們有一個(gè)使用已經(jīng)標(biāo)記過(guò)的文本(每個(gè)文本都有了它屬于哪個(gè)分類(lèi)的標(biāo)記)訓(xùn)練的數(shù)據(jù)集。在機(jī)器學(xué)習(xí)中,這種任務(wù)的類(lèi)型是被稱(chēng)為監(jiān)督學(xué)習(xí)。

“我們知道正確的答案。該算法迭代的預(yù)測(cè)訓(xùn)練數(shù)據(jù),并由老師糾正

” — Jason Brownlee

你會(huì)把數(shù)據(jù)分成類(lèi),因此它也是一個(gè)分類(lèi)任務(wù)。

為了創(chuàng)建這個(gè)模型,我們將會(huì)用到神經(jīng)網(wǎng)絡(luò)。

神經(jīng)網(wǎng)絡(luò)

神經(jīng)網(wǎng)絡(luò)是一個(gè)計(jì)算模型(一種描述使用機(jī)器語(yǔ)言和數(shù)學(xué)概念的系統(tǒng)的方式)。這些系統(tǒng)是自主學(xué)習(xí)和被訓(xùn)練的,而不是明確編程的。

神經(jīng)網(wǎng)絡(luò)是也從我們的中樞神經(jīng)系統(tǒng)受到的啟發(fā)。他們有與我們神經(jīng)相似的連接節(jié)點(diǎn)。

 

感知器是***個(gè)神經(jīng)網(wǎng)絡(luò)算法。這篇文章 很好地解釋了感知器的內(nèi)部工作原理(“人工神經(jīng)元內(nèi)部” 的動(dòng)畫(huà)非常棒)。

為了理解神經(jīng)網(wǎng)絡(luò)的工作原理,我們將會(huì)使用 TensorFlow 建立一個(gè)神經(jīng)網(wǎng)絡(luò)架構(gòu)。在這個(gè)例子中,這個(gè)架構(gòu)被 Aymeric Damien 使用過(guò)。

神經(jīng)網(wǎng)絡(luò)架構(gòu)

神經(jīng)網(wǎng)絡(luò)有兩個(gè)隱藏層(你得選擇 網(wǎng)絡(luò)會(huì)有多少隱藏層,這是結(jié)構(gòu)設(shè)計(jì)的一部分)。每一個(gè)隱藏層的任務(wù)是 把輸入的東西轉(zhuǎn)換成輸出層可以使用的東西。

隱藏層 1

 

(輸入層和***個(gè)隱藏層)

你也需要定義***個(gè)隱藏層會(huì)有多少節(jié)點(diǎn)。這些節(jié)點(diǎn)也被稱(chēng)為特征或神經(jīng)元,在上面的例子中我們用每一個(gè)圓圈表示一個(gè)節(jié)點(diǎn)。

輸入層的每個(gè)節(jié)點(diǎn)都對(duì)應(yīng)著數(shù)據(jù)集中的一個(gè)詞(之后我們會(huì)看到這是怎么運(yùn)行的)

如 這里 所述,每個(gè)節(jié)點(diǎn)(神經(jīng)元)乘以一個(gè)權(quán)重。每個(gè)節(jié)點(diǎn)都有一個(gè)權(quán)重值,在訓(xùn)練階段,神經(jīng)網(wǎng)絡(luò)會(huì)調(diào)整這些值以產(chǎn)生正確的輸出(過(guò)會(huì),我們將會(huì)學(xué)習(xí)更多關(guān)于這個(gè)的信息)

除了乘以沒(méi)有輸入的權(quán)重,網(wǎng)絡(luò)也會(huì)增加一個(gè)誤差 (在神經(jīng)網(wǎng)絡(luò)中誤差的角色)。

在你的架構(gòu)中,將輸入乘以權(quán)重并將值與偏差相加,這些數(shù)據(jù)也要通過(guò)激活函數(shù)傳遞。這個(gè)激活函數(shù)定義了每個(gè)節(jié)點(diǎn)的最終輸出。比如說(shuō):想象一下,每一個(gè)節(jié)點(diǎn)是一盞燈,激活函數(shù)決定燈是否會(huì)亮。

有很多類(lèi)型的激活函數(shù)。你將會(huì)使用 Rectified Linear Unit (ReLu)。這個(gè)函數(shù)是這樣定義的:

f(x) = max(0,x) [輸出 x 或者 0(零)中***的數(shù)]

例如:如果 x = -1, f(x) = 0(zero); 如果 x = 0.7, f(x) = 0.7.

隱藏層 2

第二個(gè)隱藏層做的完全是***個(gè)隱藏層做的事情,但現(xiàn)在第二層的輸入是***層的輸出。

 

(***和第二隱藏層)

輸出層

現(xiàn)在終于到了***一層,輸出層。你將會(huì)使用 One-Hot 編碼 得到這個(gè)層的結(jié)果。在這個(gè)編碼中,只有一個(gè)比特的值是 1,其他比特的值都是 0。例如,如果我們想對(duì)三個(gè)分類(lèi)編碼(sports, space 和computer graphics)編碼:

 

因此輸出節(jié)點(diǎn)的編號(hào)是輸入的數(shù)據(jù)集的分類(lèi)的編號(hào)。

輸出層的值也要乘以權(quán)重,并我們也要加上誤差,但是現(xiàn)在激活函數(shù)不一樣。

你想用分類(lèi)對(duì)每一個(gè)文本進(jìn)行標(biāo)記,并且這些分類(lèi)相互獨(dú)立(一個(gè)文本不能同時(shí)屬于兩個(gè)分類(lèi))。考慮到這點(diǎn),你將使用 Softmax 函數(shù)而不是 ReLu 激活函數(shù)。這個(gè)函數(shù)把每一個(gè)完整的輸出轉(zhuǎn)換成 0 和 1 之間的值,并且確保所有單元的和等于一。這樣,輸出將告訴我們每個(gè)分類(lèi)中每個(gè)文本的概率。

  1. | 1.2 0.46| 
  2.  
  3. | 0.9 -> [softmax] -> 0.34| 
  4.  
  5. | 0.4 0.20|  

現(xiàn)在有了神經(jīng)網(wǎng)絡(luò)的數(shù)據(jù)流圖。把我們所看到的都轉(zhuǎn)換為代碼,結(jié)果是:

  1. # Network Parameters 
  2.  
  3. n_hidden_1 = 10        # 1st layer number of features 
  4.  
  5. n_hidden_2 = 5         # 2nd layer number of features 
  6.  
  7. n_input = total_words  # Words in vocab 
  8.  
  9. n_classes = 3          # Categories: graphics, space and baseball 
  10.  
  11. def multilayer_perceptron(input_tensor, weights, biases): 
  12.  
  13.     layer_1_multiplication = tf.matmul(input_tensor, weights['h1']) 
  14.  
  15.     layer_1_addition = tf.add(layer_1_multiplication, biases['b1']) 
  16.  
  17.     layer_1_activation = tf.nn.relu(layer_1_addition) 
  18.  
  19. # Hidden layer with RELU activation 
  20.  
  21.     layer_2_multiplication = tf.matmul(layer_1_activation, weights['h2']) 
  22.  
  23.     layer_2_addition = tf.add(layer_2_multiplication, biases['b2']) 
  24.  
  25.     layer_2_activation = tf.nn.relu(layer_2_addition) 
  26.  
  27. Output layer with linear activation 
  28.  
  29.     out_layer_multiplication = tf.matmul(layer_2_activation, weights['out']) 
  30.  
  31.     out_layer_addition = out_layer_multiplication + biases['out']return out_layer_addition  

(我們將會(huì)在后面討論輸出層的激活函數(shù))

神經(jīng)網(wǎng)絡(luò)怎么學(xué)習(xí)

就像我們前面看到的那樣,神經(jīng)網(wǎng)絡(luò)訓(xùn)練時(shí)會(huì)更新權(quán)重值。現(xiàn)在我們將看到在 TensorFlow 環(huán)境下這是怎么發(fā)生的。

tf.Variable

權(quán)重和誤差存儲(chǔ)在變量(tf.Variable)中。這些變量通過(guò)調(diào)用 run() 保持在圖中的狀態(tài)。在機(jī)器學(xué)習(xí)中我們一般通過(guò) 正太分布 來(lái)啟動(dòng)權(quán)重和偏差值。

  1. weights = { 
  2.  
  3.     'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 
  4.  
  5.     'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])), 
  6.  
  7.     'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes])) 
  8.  
  9.  
  10. biases = { 
  11.  
  12.     'b1': tf.Variable(tf.random_normal([n_hidden_1])), 
  13.  
  14.     'b2': tf.Variable(tf.random_normal([n_hidden_2])), 
  15.  
  16.     'out': tf.Variable(tf.random_normal([n_classes])) 
  17.  
  18.  

當(dāng)我們***次運(yùn)行神經(jīng)網(wǎng)絡(luò)的時(shí)候(也就是說(shuō),權(quán)重值是由正態(tài)分布定義的):

  1. input values: x 
  2.  
  3. weights: w 
  4.  
  5. bias: b 
  6.  
  7. output values: z 
  8.  
  9. expected values: expected  

為了知道網(wǎng)絡(luò)是否正在學(xué)習(xí),你需要比較一下輸出值(Z)和期望值(expected)。我們要怎么計(jì)算這個(gè)的不同(損耗)呢?有很多方法去解決這個(gè)問(wèn)題。因?yàn)槲覀冋谶M(jìn)行分類(lèi)任務(wù),測(cè)量損耗的***的方式是 交叉熵誤差。

James D. McCaffrey 寫(xiě)了一個(gè)精彩的解釋?zhuān)f(shuō)明為什么這是這種類(lèi)型任務(wù)的***方法。

通過(guò) TensorFlow 你將使用 tf.nn.softmax_cross_entropy_with_logits() 方法計(jì)算交叉熵誤差(這個(gè)是 softmax 激活函數(shù))并計(jì)算平均誤差 (tf.reduced_mean())。

  1. # Construct model 
  2.  
  3. prediction = multilayer_perceptron(input_tensor, weights, biases) 
  4.  
  5. # Define loss 
  6.  
  7. entropy_loss = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=output_tensor) 
  8.  
  9. loss = tf.reduce_mean(entropy_loss)  

你希望通過(guò)權(quán)重和誤差的***值,以便最小化輸出誤差(實(shí)際得到的值和正確的值之間的區(qū)別)。要做到這一點(diǎn),將需使用 梯度下降法。更具體些是,需要使用 隨機(jī)梯度下降。

 

(梯度下降。源: https://sebastianraschka.com/faq/docs/closed-form-vs-gd.html)

為了計(jì)算梯度下降,將要使用 Adaptive Moment Estimation (Adam)。要在 TensorFlow 中使用此算法,需要傳遞 learning_rate 值,該值可確定值的增量步長(zhǎng)以找到***權(quán)重值。

方法 tf.train.AdamOptimizer(learning_rate).minimize(loss) 是一個(gè) 語(yǔ)法糖,它做了兩件事情:

  1. compute_gradients(loss, <list of variables>)
  2. apply_gradients(<list of variables>)

這個(gè)方法用新的值更新了所有的 tf.Variables ,因此我們不需要傳遞變量列表?,F(xiàn)在你有了訓(xùn)練網(wǎng)絡(luò)的代碼:

  1. learning_rate = 0.001 
  2.  
  3. # Construct model 
  4.  
  5. prediction = multilayer_perceptron(input_tensor, weights, biases) 
  6.  
  7. # Define loss 
  8.  
  9. entropy_loss = tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=output_tensor) 
  10.  
  11. loss = tf.reduce_mean(entropy_loss) 
  12.  
  13. optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)  

數(shù)據(jù)操作

將要使用的數(shù)據(jù)集有很多英文文本,我們需要操作這些數(shù)據(jù)將其傳遞給神經(jīng)網(wǎng)絡(luò)。要做到這一點(diǎn),需要做兩件事:

  1. 為每一個(gè)工作創(chuàng)建索引
  2. 為每一個(gè)文本創(chuàng)建矩陣,在矩陣?yán)?,如果單詞在文本中則值為 1,否則值為 0

讓我們看著代碼來(lái)理解這個(gè)過(guò)程:

  1. import numpy as np    #numpy is a package for scientific computing 
  2.  
  3. from collections import Counter 
  4.  
  5. vocab = Counter() 
  6.  
  7. text = "Hi from Brazil"#Get all wordsfor word in text.split(' '): 
  8.  
  9.     vocab[word]+=1 
  10.  
  11.         #Convert words to indexes 
  12.  
  13. def get_word_2_index(vocab): 
  14.  
  15.     word2index = {}    for i,word in enumerate(vocab): 
  16.  
  17.         word2index[word] = i         
  18.  
  19.     return word2index 
  20.  
  21. #Now we have an index 
  22.  
  23. word2index = get_word_2_index(vocab) 
  24.  
  25. total_words = len(vocab) 
  26.  
  27. #This is how we create a numpy array (our matrix) 
  28.  
  29. matrix = np.zeros((total_words),dtype=float
  30.  
  31. #Now we fill the valuesfor word in text.split(): 
  32.  
  33.     matrix[word2index[word]] += 1print(matrix) 
  34.  
  35. >>> [ 1.  1.  1.]  

上面例子中的文本是‘Hi from Brazil’,矩陣是 [ 1. 1. 1.]。如果文本僅是‘Hi’會(huì)怎么樣?

  1. matrix = np.zeros((total_words),dtype=float
  2.  
  3. text = "Hi"for word in text.split(): 
  4.  
  5. matrix[word2index[word.lower()]] += 1print(matrix) 
  6.  
  7. >>> [ 1. 0. 0.]  

將會(huì)與標(biāo)簽(文本的分類(lèi))相同,但是現(xiàn)在得使用獨(dú)熱編碼(one-hot encoding):

  1. y = np.zeros((3),dtype=float)if category == 0: 
  2.  
  3. y[0] = 1. # [ 1. 0. 0.] 
  4.  
  5. elif category == 1: 
  6.  
  7. y[1] = 1. # [ 0. 1. 0.]else
  8.  
  9. y[2] = 1. # [ 0. 0. 1.]  

運(yùn)行圖并獲取結(jié)果

現(xiàn)在進(jìn)入最精彩的部分:從模型中獲取結(jié)果。先仔細(xì)看看輸入的數(shù)據(jù)集。

數(shù)據(jù)集

對(duì)于一個(gè)有 18.000 個(gè)帖子大約有 20 個(gè)主題的數(shù)據(jù)集,將會(huì)使用到 20個(gè)新聞組。要加載這些數(shù)據(jù)集將會(huì)用到 scikit-learn 庫(kù)。我們只使用 3 種類(lèi)別:comp.graphics, sci.space 和 rec.sport.baseball。scikit-learn 有兩個(gè)子集:一個(gè)用于訓(xùn)練,另一個(gè)用于測(cè)試。建議不要查看測(cè)試數(shù)據(jù),因?yàn)檫@可能會(huì)在創(chuàng)建模型時(shí)干擾你的選擇。你不會(huì)希望創(chuàng)建一個(gè)模型來(lái)預(yù)測(cè)這個(gè)特定的測(cè)試數(shù)據(jù),因?yàn)槟阆M麆?chuàng)建一個(gè)具有很好的泛化性能的模型。

這里是如何加載數(shù)據(jù)集的代碼:

  1. from sklearn.datasets import fetch_20newsgroups 
  2.  
  3. categories = ["comp.graphics","sci.space","rec.sport.baseball"
  4.  
  5. newsgroups_train = fetch_20newsgroups(subset='train', categories=categories) 
  6.  
  7. newsgroups_test = fetch_20newsgroups(subset='test', categories=categories  

訓(xùn)練模型

在 神經(jīng)網(wǎng)絡(luò)的術(shù)語(yǔ)里,一次 epoch = 一個(gè)向前傳遞(得到輸出的值)和一個(gè)所有訓(xùn)練示例的向后傳遞(更新權(quán)重)。

還記得 tf.Session.run() 方法嗎?讓我們仔細(xì)看看它:

  1. tf.Session.run(fetches, feed_dict=None, options=None, run_metadata=None) 

在這篇文章開(kāi)始的數(shù)據(jù)流圖里,你用到了和操作,但是我們也可以傳遞一個(gè)事情的列表用于運(yùn)行。在這個(gè)神經(jīng)網(wǎng)絡(luò)運(yùn)行中將傳遞兩個(gè)事情:損耗計(jì)算和優(yōu)化步驟。

feed_dict 參數(shù)是我們?yōu)槊坎竭\(yùn)行所輸入的數(shù)據(jù)。為了傳遞這個(gè)數(shù)據(jù),我們需要定義tf.placeholders(提供給 feed_dict)

正如 TensorFlow 文檔中說(shuō)的:

“占位符的存在只作為輸入的目標(biāo),它不需要初始化,也不包含數(shù)據(jù)。” — Source

因此將要像這樣定義占位符:

  1. n_input = total_words # Words in vocab 
  2.  
  3. n_classes = 3 # Categories: graphics, sci.space and baseball 
  4.  
  5. input_tensor = tf.placeholder(tf.float32,[None, n_input],name="input"
  6.  
  7. output_tensor = tf.placeholder(tf.float32,[None, n_classes],name="output" 

還將要批量分離你的訓(xùn)練數(shù)據(jù):

“如果為了能夠輸入而使用占位符,可通過(guò)使用 tf.placeholder(…, shape=[None, …]) 創(chuàng)建占位符來(lái)指定變量批量維度。shape 的 None 元素對(duì)應(yīng)于大小可變的維度。” — Source

在測(cè)試模型時(shí),我們將用更大的批處理來(lái)提供字典,這就是為什么需要定義一個(gè)可變的批處理維度。

get_batches() 函數(shù)為我們提供了批處理大小的文本數(shù)?,F(xiàn)在我們可以運(yùn)行模型:

  1. training_epochs = 10# Launch the graph 
  2.  
  3. with tf.Session() as sess: 
  4.  
  5.     sess.run(init) #inits the variables (normal distribution, remember?) 
  6.  
  7.     # Training cycle    for epoch in range(training_epochs): 
  8.  
  9.         avg_cost = 0. 
  10.  
  11.         total_batch = int(len(newsgroups_train.data)/batch_size) 
  12.  
  13.         # Loop over all batches        for i in range(total_batch): 
  14.  
  15.             batch_x,batch_y = get_batch(newsgroups_train,i,batch_size) 
  16.  
  17.             # Run optimization op (backprop) and cost op (to get loss value) 
  18.  
  19.             c,_ = sess.run([loss,optimizer], feed_dict={input_tensor: batch_x, output_tensor:batch_y})  

現(xiàn)在有了這個(gè)經(jīng)過(guò)訓(xùn)練的模型。為了測(cè)試它,還需要?jiǎng)?chuàng)建圖元素。我們將測(cè)量模型的準(zhǔn)確性,因此需要獲取預(yù)測(cè)值的索引和正確值的索引(因?yàn)槲覀兪褂玫氖仟?dú)熱編碼),檢查它們是否相等,并計(jì)算所有測(cè)試數(shù)據(jù)集的平均值:

  1. # Test model 
  2.  
  3. index_prediction = tf.argmax(prediction, 1) 
  4.  
  5. index_correct = tf.argmax(output_tensor, 1) 
  6.  
  7. correct_prediction = tf.equal(index_prediction, index_correct) 
  8.  
  9. # Calculate accuracy 
  10.  
  11. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 
  12.  
  13. total_test_data = len(newsgroups_test.target) 
  14.  
  15. batch_x_test,batch_y_test = get_batch(newsgroups_test,0,total_test_data) 
  16.  
  17. print("Accuracy:", accuracy.eval({input_tensor: batch_x_test, output_tensor: batch_y_test})) 
  18.  
  19. Epoch: 0001 loss= 1133.908114347 
  20.  
  21. Epoch: 0002 loss= 329.093700409 
  22.  
  23. Epoch: 0003 loss= 111.876660109 
  24.  
  25. Epoch: 0004 loss= 72.552971845 
  26.  
  27. Epoch: 0005 loss= 16.673050320 
  28.  
  29. Epoch: 0006 loss= 16.481995190 
  30.  
  31. Epoch: 0007 loss= 4.848220565 
  32.  
  33. Epoch: 0008 loss= 0.759822878 
  34.  
  35. Epoch: 0009 loss= 0.000000000 
  36.  
  37. Epoch: 0010 loss= 0.079848485 
  38.  
  39. Optimization Finished! 
  40.  
  41. Accuracy: 0.75  

就是這樣!你使用神經(jīng)網(wǎng)絡(luò)創(chuàng)建了一個(gè)模型來(lái)將文本分類(lèi)到不同的類(lèi)別中。恭喜!

可在 這里(https://github.com/dmesquita/understanding_tensorflow_nn) 看到包含最終代碼的筆記本。

提示:修改我們定義的值,以查看更改如何影響訓(xùn)練時(shí)間和模型精度。

還有其他問(wèn)題或建議?留下你們的評(píng)論。謝謝閱讀! 

責(zé)任編輯:龐桂玉 來(lái)源: Python開(kāi)發(fā)者
相關(guān)推薦

2017-08-25 14:23:44

TensorFlow神經(jīng)網(wǎng)絡(luò)文本分類(lèi)

2018-03-22 13:34:59

TensorFlow神經(jīng)網(wǎng)絡(luò)

2023-04-19 10:17:35

機(jī)器學(xué)習(xí)深度學(xué)習(xí)

2018-10-18 10:27:15

機(jī)器學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)python

2023-02-28 08:00:00

深度學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)人工智能

2022-02-15 23:38:22

Python機(jī)器學(xué)習(xí)算法

2025-02-24 08:00:00

機(jī)器學(xué)習(xí)ML架構(gòu)

2022-10-09 08:00:00

機(jī)器學(xué)習(xí)文本分類(lèi)算法

2024-10-30 16:59:57

Python機(jī)器學(xué)習(xí)

2017-03-27 16:18:30

神經(jīng)網(wǎng)絡(luò)TensorFlow人工智能

2020-08-06 10:11:13

神經(jīng)網(wǎng)絡(luò)機(jī)器學(xué)習(xí)算法

2021-06-21 10:43:25

Python神經(jīng)網(wǎng)絡(luò)深度學(xué)習(xí)

2020-12-25 10:08:53

Python機(jī)器學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)算法

2017-08-29 13:50:03

TensorFlow深度學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)

2025-02-25 10:50:11

2017-03-10 12:16:46

機(jī)器學(xué)習(xí)

2017-08-28 21:31:37

TensorFlow深度學(xué)習(xí)神經(jīng)網(wǎng)絡(luò)

2022-06-16 10:29:33

神經(jīng)網(wǎng)絡(luò)圖像分類(lèi)算法

2022-04-22 12:36:11

RNN神經(jīng)網(wǎng)絡(luò))機(jī)器學(xué)習(xí)

2024-09-29 09:32:58

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)