-
如何存儲文本數據以使用RNN進行處理
-
如何通過在每個時間步采樣預測並將其傳遞給下一個RNN單元來合成數據
-
如何構建字符級文本生成循環神經網絡
-
為什么剪裁漸變很重要
-
讀取恐龍名稱的數據集
-
創建唯一字符列表(例如a-z)
-
計算數據集和詞匯量。
data = open('dinos.txt', 'r').read() # 加載數據集
data= data.lower() # 將所有數據變小寫
chars = list(set(data)) # 創建唯一字符列表,data中用了什么字符
data_size, vocab_size = len(data), len(chars) # 數據集的大小和詞匯量
print('There are %d total characters and %d unique characters in your data.' % (data_size, vocab_size))
['\n', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
{ 0: '\n', 1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e', 6: 'f', 7: 'g', 8: 'h', 9: 'i', 10: 'j', 11: 'k', 12: 'l', 13: 'm', 14: 'n', 15: 'o', 16: 'p', 17: 'q', 18: 'r', 19: 's', 20: 't', 21: 'u', 22: 'v', 23: 'w', 24: 'x', 25: 'y', 26: 'z'}
-
初始化參數
-
運行優化循環
-
前向傳播以計算損失函數
-
向后傳播根據損失函數計算梯度
-
梯度裁剪以避免梯度爆炸
-
使用梯度下降規則更新你的參數
-
返回學習到的參數
-
每一個時間步長, RNN都會根據之前的字符來預測下一個字符是什么。
-
數據集
\mathbf{X} = (x^{\langle 1 \rangle}, x^{\langle 2 \rangle}, ..., x^{\langle T_x \rangle}) 是訓練集中的字符列表。
-
\mathbf{Y} = (y^{\langle 1 \rangle}, y^{\langle 2 \rangle}, ..., y^{\langle T_x \rangle}) 是相同的字符列表,但是向前移動了一個字符。
-
每個時間步長
t,
y^{\langle t \rangle} = x^{\langle t+1 \rangle}. 在時間
t 處的預測值和時間
t + 1 處的輸入值相同.
-
梯度裁剪:避免梯度爆炸
-
采樣:一種用於生成字符的技術
-
當梯度值非常大時,稱為“梯度爆炸”。
-
梯度爆炸使訓練過程更加困難,因為更新可能太大,以至於在反向傳播過程中“overshoot”了最佳值。
-
向前傳播
-
計算成本函數
-
向后傳播
-
參數更新
-
剪切漸變有多種方法。
-
我們將使用簡單的按元素裁剪程序,其中將梯度向量的每個元素裁剪為位於某個范圍[-N,N]之間。
-
例如,如果N = 10
-
元素的取值范圍是[-10,10]
-
如果任何在梯度向量中大於10的元素,則將其設置為10。
-
如果任何在梯度向量中小於-10的元素,則將其設置為-10。
-
如果任何在-10到10之間的元素,則它們保持原始值。
def clip(gradients, maxValue):
'''
Clips the gradients' values between minimum and maximum.
Arguments:
gradients -- a dictionary containing the gradients "dWaa", "dWax", "dWya", "db", "dby"
maxValue -- everything above this number is set to this number, and everything less than -maxValue is set to -maxValue
Returns:
gradients -- a dictionary with the clipped gradients.
'''
dWaa, dWax, dWya, db, dby = gradients['dWaa'], gradients['dWax'], gradients['dWya'], gradients['db'], gradients['dby']
### START CODE HERE ###
# clip to mitigate exploding gradients, loop over [dWax, dWaa, dWya, db, dby]. (≈2 lines)
for gradient in [dWax, dWaa, dWya, db, dby]:
np.clip(gradient, -maxValue, maxValue, out=gradient)
### END CODE HERE ###
# gradients = {"dWaa": dWaa, "dWax": dWax, "dWya": dWya, "db": db, "dby": dby}
return gradients
x^{\langle 1\rangle} = \vec{0},然后讓網絡一次采樣一個字符。
-
Step 1: 輸入0的 "dummy" 向量
x^{\langle 1 \rangle} = \vec{0}.
-
這是我們生成任何字符之前的默認輸入。 我們還設置了
a^{\langle 0 \rangle} = \vec{0}
-
Step 2: 執行一次向前傳播即可獲得
a^{\langle 1 \rangle} 和
\hat{y}^{\langle 1 \rangle}. 這里是公式:



-
關於
的一些細節:
-
注意
是一個概率向量 (softmax) (它的每個元素值在0到1之間,且總和為1).
-
表示由“ i”索引的字符是下一個字符的概率。
-
我們提供了 softmax() 函數供你使用.
-
x^{\langle 1 \rangle} 在代碼中是 x.當創建one-hot向量時,請創建一個由零的組成numpy數組,其中行數等於唯一字符數,列數等於1。 它是2D而不是1D數組。
-
a^{\langle 0 \rangle} 在代碼中是a_prev. 它是一個由零組成的numpy數組,其中行數為
n_ {a} ,列數為1。它也是2D數組。 通過獲取
W_ {aa} 中的列數來得到
n_ {a} (這些數字必須匹配,以便矩陣乘法
W_{aa}a^{\langle t \rangle}起作用 。
-
a ^ {\ langle 0 \ rangle} 在代碼中為a_prev。
-
你可能想知道為什么我們強調
x^{\langle 1 \rangle}和
a^{\langle 0 \rangle}是2D數組而不是1D向量。
-
對於numpy中的矩陣乘法,如果將2D矩陣與1D向量相乘,則最終得到1D數組。
-
當我們將兩個數組相加時,期望它們具有相同形狀,這將成為一個問題。
-
當兩個具有不同維數的數組加在一起時,Python將會執行“廣播broadcasts”。
-
這是一些示例代碼,顯示了使用1D和2D數組之間的區別。
import numpy as np
matrix1 = np.array([[1,1],[2,2],[3,3]]) # (3,2)
matrix2 = np.array([[0],[0],[0]]) # (3,1)
vector1D = np.array([1,1]) # (2,)
vector2D = np.array([[1],[1]]) # (2,1)
np.dot(matrix1,vector1D) # 2D 和 1D 數組相乘: 結果是1D數組 [2 4 6]
np.dot(matrix1,vector2D) # 2D 和 2D 數組相乘: 結果是2D數組 [[2], [4], [6]]
np.dot(matrix1,vector2D) + matrix2 # (3 x 1) 向量和(3 x 1)向量相加是(3 x 1) 向量,這個是我們想要的。 [[2] [4] [6]]
np.dot(matrix1,vector1D) + matrix2 # (3,) 向量和(3 x 1)向量相加,這會在第二維上廣播1D的數組,這不是我們想要的!
-
Step 3: 抽樣:
-
注意我們已經有了
y^{\langle t+1 \rangle}, 我們想選擇恐龍名稱中的下一個字母。如果我們選擇最有可能的情況,那么在給定起始字母的情況下,模型將始終產生相同的結果。
-
為了使結果更有趣,我們將使用np.random.choice選擇可能但並非總是相同的下一個字母。
-
采樣是從一組值中選擇一個值,其中每個值都有一定概率被選擇。
-
采樣使我們能夠生成隨機的序列值。
-
根據
\hat{y}^{\langle t+1 \rangle }中的概率分布選擇下一個字符的索引。
-
這就意味着如果
\hat{y}^{\langle t+1 \rangle }_i = 0.16, 你將以16%的概率選擇索引“ i”。
-
你可以查看np.random.choice.
-
這就意味着你會根據分布來選擇索引:
P(index = 0) = 0.1, P(index = 1) = 0.0, P(index = 2) = 0.7, P(index = 3) = 0.2.
-
注意p的值是1D向量。
-
注意
\hat{y}^{\langle t+1 \rangle}在代碼中用 y 表示, 它是2維數組。
-
Step 4: 更新
x^{\langle t \rangle }
-
sample()函數的最后一步就是更新變量x, 它當前存儲的是
x^{\langle t \rangle }, 換成
x^{\langle t + 1 \rangle }.
-
你將選擇作為預測字符相對應的one-hot矢量來代表
x^{\langle t + 1 \rangle }。
-
你將接着在步驟1中向前傳播
x^{\langle t + 1 \rangle },並繼續重復該過程直到獲得“ \n”字符,它表明你已經到達恐龍名稱的末尾。
# GRADED FUNCTION: sample def sample(parameters, char_to_ix, seed): """ Sample a sequence of characters according to a sequence of probability distributions output of the RNN Arguments: parameters -- python dictionary containing the parameters Waa, Wax, Wya, by, and b. char_to_ix -- python dictionary mapping each character to an index. seed -- used for grading purposes. Do not worry about it. Returns: indices -- a list of length n containing the indices of the sampled characters. """ # Retrieve parameters and relevant shapes from "parameters" dictionary Waa, Wax, Wya, by, b = parameters['Waa'], parameters['Wax'], parameters['Wya'], parameters['by'], parameters['b'] vocab_size = by.shape[0] n_a = Waa.shape[1] ### START CODE HERE ### # Step 1: Create the a zero vector x that can be used as the one-hot vector # representing the first character (initializing the sequence generation). (≈1 line) x = np.zeros((vocab_size, 1)) # 可以看看上面為什么這里是二維 # Step 1': Initialize a_prev as zeros (≈1 line) a_prev = np.zeros((n_a, 1)) # Create an empty list of indices, this is the list which will contain the list of indices of the characters to generate (≈1 line) indices = [] # idx is the index of the one-hot vector x that is set to 1 # All other positions in x are zero. # We will initialize idx to -1 idx = -1 # Loop over time-steps t. At each time-step: # sample a character from a probability distribution # and append its index (`idx`) to the list "indices". # We'll stop if we reach 50 characters # (which should be very unlikely with a well trained model). # Setting the maximum number of characters helps with debugging and prevents infinite loops. counter = 0 newline_character = char_to_ix['\n'] while (idx != newline_character and counter != 50): # Step 2: Forward propagate x using the equations (1), (2) and (3) a = np.tanh(np.dot(Wax, x) + np.dot(Waa, a_prev) + b) z = np.dot(Wya, a) + by y = softmax(z) # for grading purposes np.random.seed(counter+seed) # Step 3: Sample the index of a character within the vocabulary from the probability distribution y # (see additional hints above) idx = np.random.choice(list(range(vocab_size)), p=y.ravel()) # Append the index to "indices" indices.append(idx) # Step 4: Overwrite the input x with one that corresponds to the sampled index `idx`. # (see additional hints above) x = np.zeros((vocab_size, 1)) x[idx] = 1 # Update "a_prev" to be "a" a_prev = a # for grading purposes seed += 1 counter +=1 ### END CODE HERE ### if (counter == 50): indices.append(char_to_ix['\n']) return indices
-
在本節中,你將實現一個函數,該函數執行一步隨機梯度下降(帶有修剪的梯度)。
-
你將一次查看一個訓練示例,因此優化算法將是隨機梯度下降。
-
通過RNN向前傳播以計算損耗
-
隨時間向后傳播以計算相對於參數的損耗梯度
-
梯度裁剪
-
使用梯度下降更新參數
def rnn_forward(X, Y, a_prev, parameters): """ Performs the forward propagation through the RNN and computes the cross-entropy loss. It returns the loss' value as well as a "cache" storing values to be used in backpropagation.""" .... return loss, cache def rnn_backward(X, Y, parameters, cache): """ Performs the backward propagation through time to compute the gradients of the loss with respect to the parameters. It returns also all the hidden states.""" ... return gradients, a def update_parameters(parameters, gradients, learning_rate): """ Updates parameters using the Gradient Descent Update Rule.""" ... return parameters Recall that you previously implemented the clip function: def clip(gradients, maxValue) """Clips the gradients' values between minimum and maximum.""" ... return gradients
-
請注意,即使parameters不是optimize函數的返回值之一,parameters字典中的權重和偏差也會通過優化進行更新。參數字典通過引用傳遞到函數中,因此即使在函數外部訪問該字典,對字典的更改也會對參數字典做出更改。
-
Python字典和列表是“按引用傳遞”,這意味着,如果將字典傳遞給函數並在函數內修改字典,則這將更改同一字典。
def optimize(X, Y, a_prev, parameters, learning_rate = 0.01): """ Execute one step of the optimization to train the model. Arguments: X -- list of integers, where each integer is a number that maps to a character in the vocabulary. Y -- list of integers, exactly the same as X but shifted one index to the left. a_prev -- previous hidden state. parameters -- python dictionary containing: Wax -- Weight matrix multiplying the input, numpy array of shape (n_a, n_x) Waa -- Weight matrix multiplying the hidden state, numpy array of shape (n_a, n_a) Wya -- Weight matrix relating the hidden-state to the output, numpy array of shape (n_y, n_a) b -- Bias, numpy array of shape (n_a, 1) by -- Bias relating the hidden-state to the output, numpy array of shape (n_y, 1) learning_rate -- learning rate for the model. Returns: loss -- value of the loss function (cross-entropy) gradients -- python dictionary containing: dWax -- Gradients of input-to-hidden weights, of shape (n_a, n_x) dWaa -- Gradients of hidden-to-hidden weights, of shape (n_a, n_a) dWya -- Gradients of hidden-to-output weights, of shape (n_y, n_a) db -- Gradients of bias vector, of shape (n_a, 1) dby -- Gradients of output bias vector, of shape (n_y, 1) a[len(X)-1] -- the last hidden state, of shape (n_a, 1) """ ### START CODE HERE ### # Forward propagate through time (≈1 line) loss, cache = rnn_forward(X, Y, a_prev, parameters) # Backpropagate through time (≈1 line) gradients, a = rnn_backward(X, Y, parameters, cache) # Clip your gradients between -5 (min) and 5 (max) (≈1 line) gradients = clip(gradients, 5) # Update parameters (≈1 line) parameters = update_parameters(parameters, gradients, learning_rate) ### END CODE HERE ### return loss, gradients, a[len(X)-1]
-
給定恐龍名稱數據集,我們將數據集的每一行(一個名稱)用作一個訓練樣本。
-
每100步隨機梯度下降,你將抽樣10個隨機選擇的名稱,以查看算法的運行情況。
-
請記住要對數據集進行混洗,以便隨機梯度下降以隨機順序訪問樣本。
-
使用for循環,在“示例”列表中瀏覽經過排序的恐龍名稱列表。
-
如果有100個示例,並且for循環將索引從100開始遞增,請考慮如何使索引循環回到0,以便我們可以在j為100、101,等等
-
提示:101除以100為零,余數為1。
-
%是python中的模運算符。
def model(data, ix_to_char, char_to_ix, num_iterations = 35000, n_a = 50, dino_names = 7, vocab_size = 27): """ Trains the model and generates dinosaur names. Arguments: data -- text corpus ix_to_char -- dictionary that maps the index to a character char_to_ix -- dictionary that maps a character to an index num_iterations -- number of iterations to train the model for n_a -- number of units of the RNN cell dino_names -- number of dinosaur names you want to sample at each iteration. vocab_size -- number of unique characters found in the text (size of the vocabulary) Returns: parameters -- learned parameters """ # Retrieve n_x and n_y from vocab_size n_x, n_y = vocab_size, vocab_size # Initialize parameters parameters = initialize_parameters(n_a, n_x, n_y) # Initialize loss (this is required because we want to smooth our loss) loss = get_initial_loss(vocab_size, dino_names) # Build list of all dinosaur names (training examples). with open("dinos.txt") as f: examples = f.readlines() examples = [x.lower().strip() for x in examples] # Shuffle list of all dinosaur names np.random.seed(0) np.random.shuffle(examples) # Initialize the hidden state of your LSTM a_prev = np.zeros((n_a, 1)) # Optimization loop for j in range(num_iterations): ### START CODE HERE ### # Set the index `idx` (see instructions above) index = j % len(examples) # Set the input X (see instructions above) single_example = examples[index] single_example_chars = [ch for ch in single_example] single_example_ix = [char_to_ix[ch] for ch in single_example_chars] X = [None] + single_example_ix # Set the labels Y (see instructions above) ix_newline = char_to_ix["\n"] Y = X[1:] + [ix_newline] # Perform one optimization step: Forward-prop -> Backward-prop -> Clip -> Update parameters # Choose a learning rate of 0.01 curr_loss, gradients, a_prev = optimize(X, Y, a_prev, parameters) ### END CODE HERE ### # Use a latency trick to keep the loss smooth. It happens here to accelerate the training. loss = smooth(loss, curr_loss) # Every 2000 Iteration, generate "n" characters thanks to sample() to check if the model is learning properly if j % 2000 == 0: print('Iteration: %d, Loss: %f' % (j, loss) + '\n') # The number of dinosaur names to print seed = 0 for name in range(dino_names): # Sample indices and print them sampled_indices = sample(parameters, char_to_ix, seed) print_sample(sampled_indices, ix_to_char) seed += 1 # To get the same result (for grading purposes), increment the seed by one. print('\n') return parameters
