# TensorFlow 中的 LSTM 文本生成
您可以在 Jupyter 筆記本`ch-08b_RNN_Text_TensorFlow`中按照本節的代碼進行操作。
我們使用以下步驟在 TensorFlow 中實現文本生成 LSTM:
1. 讓我們為`x`和`y`定義參數和占位符:
```py
batch_size = 128
n_x = 5 # number of input words
n_y = 1 # number of output words
n_x_vars = 1 # in case of our text, there is only 1 variable at each timestep
n_y_vars = text8.vocab_len
state_size = 128
learning_rate = 0.001
x_p = tf.placeholder(tf.float32, [None, n_x, n_x_vars], name='x_p')
y_p = tf.placeholder(tf.float32, [None, n_y_vars], name='y_p')
```
對于輸入,我們使用單詞的整數表示,因此`n_x_vars`是 1.對于輸出,我們使用單熱編碼值,因此輸出的數量等于詞匯長度。
1. 接下來,創建一個長度為`n_x`的張量列表:
```py
x_in = tf.unstack(x_p,axis=1,name='x_in')
```
1. 接下來,從輸入和單元創建 LSTM 單元和靜態 RNN 網絡:
```py
cell = tf.nn.rnn_cell.LSTMCell(state_size)
rnn_outputs, final_states = tf.nn.static_rnn(cell, x_in,dtype=tf.float32)
```
1. 接下來,我們定義最終層的權重,偏差和公式。最后一層只需要為第六個單詞選擇輸出,因此我們應用以下公式來僅獲取最后一個輸出:
```py
# output node parameters
w = tf.get_variable('w', [state_size, n_y_vars], initializer= tf.random_normal_initializer)
b = tf.get_variable('b', [n_y_vars], initializer=tf.constant_initializer(0.0))
y_out = tf.matmul(rnn_outputs[-1], w) + b
```
1. 接下來,創建一個損失函數和優化器:
```py
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=y_out, labels=y_p))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
.minimize(loss)
```
1. 創建我們可以在會話塊中運行的準確率函數,以檢查訓練模式的準確性:
```py
n_correct_pred = tf.equal(tf.argmax(y_out,1), tf.argmax(y_p,1))
accuracy = tf.reduce_mean(tf.cast(n_correct_pred, tf.float32))
```
1. 最后,我們訓練模型 1000 個周期,并每 100 個周期打印結果。此外,每 100 個周期,我們從上面描述的種子字符串打印生成的文本。
LSTM 和 RNN 網絡需要對大量數據集進行大量周期的訓練,以獲得更好的結果。 請嘗試加載完整的數據集并在計算機上運行 50,000或80,000 個周期,并使用其他超參數來改善結果。
```py
n_epochs = 1000
learning_rate = 0.001
text8.reset_index_in_epoch()
n_batches = text8.n_batches_seq(batch_size=batch_size,n_tx=n_x,n_ty=n_y)
n_epochs_display = 100
with tf.Session() as tfs:
tf.global_variables_initializer().run()
for epoch in range(n_epochs):
epoch_loss = 0
epoch_accuracy = 0
for step in range(n_batches):
x_batch, y_batch = text8.next_batch_seq(batch_size=batch_size,
n_tx=n_x,n_ty=n_y)
y_batch = dsu.to2d(y_batch,unit_axis=1)
y_onehot = np.zeros(shape=[batch_size,text8.vocab_len],
dtype=np.float32)
for i in range(batch_size):
y_onehot[i,y_batch[i]]=1
feed_dict = {x_p: x_batch.reshape(-1, n_x, n_x_vars),
y_p: y_onehot}
_, batch_accuracy, batch_loss = tfs.run([optimizer,accuracy,
loss],feed_dict=feed_dict)
epoch_loss += batch_loss
epoch_accuracy += batch_accuracy
if (epoch+1) % (n_epochs_display) == 0:
epoch_loss = epoch_loss / n_batches
epoch_accuracy = epoch_accuracy / n_batches
print('\nEpoch {0:}, Average loss:{1:}, Average accuracy:{2:}'.
format(epoch,epoch_loss,epoch_accuracy ))
y_pred_r5 = np.empty([10])
y_pred_f5 = np.empty([10])
x_test_r5 = random5.copy()
x_test_f5 = first5.copy()
# let us generate text of 10 words after feeding 5 words
for i in range(10):
for x,y in zip([x_test_r5,x_test_f5],
[y_pred_r5,y_pred_f5]):
x_input = x.copy()
feed_dict = {x_p: x_input.reshape(-1, n_x, n_x_vars)}
y_pred = tfs.run(y_out, feed_dict=feed_dict)
y_pred_id = int(tf.argmax(y_pred, 1).eval())
y[i]=y_pred_id
x[:-1] = x[1:]
x[-1] = y_pred_id
print(' Random 5 prediction:',id2string(y_pred_r5))
print(' First 5 prediction:',id2string(y_pred_f5))
```
結果如下:
```py
Epoch 99, Average loss:1.3972469369570415, Average accuracy:0.8489583333333334
Random 5 prediction: labor warren together strongly profits strongly supported supported co without
First 5 prediction: market own self free together strongly profits strongly supported supported
Epoch 199, Average loss:0.7894854595263799, Average accuracy:0.9186197916666666
Random 5 prediction: syndicalists spanish class movements also also anarcho anarcho anarchist was
First 5 prediction: five civil association class movements also anarcho anarcho anarcho anarcho
Epoch 299, Average loss:1.360412875811259, Average accuracy:0.865234375
Random 5 prediction: anarchistic beginnings influenced true tolstoy tolstoy tolstoy tolstoy tolstoy tolstoy
First 5 prediction: early civil movement be for was two most most most
Epoch 399, Average loss:1.1692512730757396, Average accuracy:0.8645833333333334
Random 5 prediction: including war than than revolutionary than than war than than
First 5 prediction: left including including including other other other other other other
Epoch 499, Average loss:0.5921860883633295, Average accuracy:0.923828125
Random 5 prediction: ever edited interested interested variety variety variety variety variety variety
First 5 prediction: english market herbert strongly price interested variety variety variety variety
Epoch 599, Average loss:0.8356450994809469, Average accuracy:0.8958333333333334
Random 5 prediction: management allow trabajo trabajo national national mag mag ricardo ricardo
First 5 prediction: spain prior am working n war war war self self
Epoch 699, Average loss:0.7057955612738928, Average accuracy:0.8971354166666666
Random 5 prediction: teachings can directive tend resist obey christianity author christianity christianity
First 5 prediction: early early called social called social social social social social
Epoch 799, Average loss:0.772875706354777, Average accuracy:0.90234375
Random 5 prediction: associated war than revolutionary revolutionary revolutionary than than revolutionary revolutionary
First 5 prediction: political been hierarchy war than see anti anti anti anti
Epoch 899, Average loss:0.43675946692625683, Average accuracy:0.9375
Random 5 prediction: individualist which which individualist warren warren tucker benjamin how tucker
First 5 prediction: four at warren individualist warren published considered considered considered considered
Epoch 999, Average loss:0.23202441136042276, Average accuracy:0.9602864583333334
Random 5 prediction: allow allow trabajo you you you you you you you
First 5 prediction: labour spanish they they they movement movement anarcho anarcho two
```
生成的文本中的重復單詞是常見的,并且應該更好地訓練模型。雖然模型的準確性提高到 96%,但仍然不足以生成清晰的文本。嘗試增加 LSTM 單元/隱藏層的數量,同時在較大的數據集上運行模型以獲取大量周期。
現在讓我們在 Keras 建立相同的模型:
- TensorFlow 101
- 什么是 TensorFlow?
- TensorFlow 核心
- 代碼預熱 - Hello TensorFlow
- 張量
- 常量
- 操作
- 占位符
- 從 Python 對象創建張量
- 變量
- 從庫函數生成的張量
- 使用相同的值填充張量元素
- 用序列填充張量元素
- 使用隨機分布填充張量元素
- 使用tf.get_variable()獲取變量
- 數據流圖或計算圖
- 執行順序和延遲加載
- 跨計算設備執行圖 - CPU 和 GPU
- 將圖節點放置在特定的計算設備上
- 簡單放置
- 動態展示位置
- 軟放置
- GPU 內存處理
- 多個圖
- TensorBoard
- TensorBoard 最小的例子
- TensorBoard 詳情
- 總結
- TensorFlow 的高級庫
- TF Estimator - 以前的 TF 學習
- TF Slim
- TFLearn
- 創建 TFLearn 層
- TFLearn 核心層
- TFLearn 卷積層
- TFLearn 循環層
- TFLearn 正則化層
- TFLearn 嵌入層
- TFLearn 合并層
- TFLearn 估計層
- 創建 TFLearn 模型
- TFLearn 模型的類型
- 訓練 TFLearn 模型
- 使用 TFLearn 模型
- PrettyTensor
- Sonnet
- 總結
- Keras 101
- 安裝 Keras
- Keras 中的神經網絡模型
- 在 Keras 建立模型的工作流程
- 創建 Keras 模型
- 用于創建 Keras 模型的順序 API
- 用于創建 Keras 模型的函數式 API
- Keras 層
- Keras 核心層
- Keras 卷積層
- Keras 池化層
- Keras 本地連接層
- Keras 循環層
- Keras 嵌入層
- Keras 合并層
- Keras 高級激活層
- Keras 正則化層
- Keras 噪音層
- 將層添加到 Keras 模型
- 用于將層添加到 Keras 模型的順序 API
- 用于向 Keras 模型添加層的函數式 API
- 編譯 Keras 模型
- 訓練 Keras 模型
- 使用 Keras 模型進行預測
- Keras 的附加模塊
- MNIST 數據集的 Keras 序列模型示例
- 總結
- 使用 TensorFlow 進行經典機器學習
- 簡單的線性回歸
- 數據準備
- 構建一個簡單的回歸模型
- 定義輸入,參數和其他變量
- 定義模型
- 定義損失函數
- 定義優化器函數
- 訓練模型
- 使用訓練的模型進行預測
- 多元回歸
- 正則化回歸
- 套索正則化
- 嶺正則化
- ElasticNet 正則化
- 使用邏輯回歸進行分類
- 二分類的邏輯回歸
- 多類分類的邏輯回歸
- 二分類
- 多類分類
- 總結
- 使用 TensorFlow 和 Keras 的神經網絡和 MLP
- 感知機
- 多層感知機
- 用于圖像分類的 MLP
- 用于 MNIST 分類的基于 TensorFlow 的 MLP
- 用于 MNIST 分類的基于 Keras 的 MLP
- 用于 MNIST 分類的基于 TFLearn 的 MLP
- 使用 TensorFlow,Keras 和 TFLearn 的 MLP 總結
- 用于時間序列回歸的 MLP
- 總結
- 使用 TensorFlow 和 Keras 的 RNN
- 簡單循環神經網絡
- RNN 變種
- LSTM 網絡
- GRU 網絡
- TensorFlow RNN
- TensorFlow RNN 單元類
- TensorFlow RNN 模型構建類
- TensorFlow RNN 單元包裝器類
- 適用于 RNN 的 Keras
- RNN 的應用領域
- 用于 MNIST 數據的 Keras 中的 RNN
- 總結
- 使用 TensorFlow 和 Keras 的時間序列數據的 RNN
- 航空公司乘客數據集
- 加載 airpass 數據集
- 可視化 airpass 數據集
- 使用 TensorFlow RNN 模型預處理數據集
- TensorFlow 中的簡單 RNN
- TensorFlow 中的 LSTM
- TensorFlow 中的 GRU
- 使用 Keras RNN 模型預處理數據集
- 使用 Keras 的簡單 RNN
- 使用 Keras 的 LSTM
- 使用 Keras 的 GRU
- 總結
- 使用 TensorFlow 和 Keras 的文本數據的 RNN
- 詞向量表示
- 為 word2vec 模型準備數據
- 加載和準備 PTB 數據集
- 加載和準備 text8 數據集
- 準備小驗證集
- 使用 TensorFlow 的 skip-gram 模型
- 使用 t-SNE 可視化單詞嵌入
- keras 的 skip-gram 模型
- 使用 TensorFlow 和 Keras 中的 RNN 模型生成文本
- TensorFlow 中的 LSTM 文本生成
- Keras 中的 LSTM 文本生成
- 總結
- 使用 TensorFlow 和 Keras 的 CNN
- 理解卷積
- 了解池化
- CNN 架構模式 - LeNet
- 用于 MNIST 數據的 LeNet
- 使用 TensorFlow 的用于 MNIST 的 LeNet CNN
- 使用 Keras 的用于 MNIST 的 LeNet CNN
- 用于 CIFAR10 數據的 LeNet
- 使用 TensorFlow 的用于 CIFAR10 的 ConvNets
- 使用 Keras 的用于 CIFAR10 的 ConvNets
- 總結
- 使用 TensorFlow 和 Keras 的自編碼器
- 自編碼器類型
- TensorFlow 中的棧式自編碼器
- Keras 中的棧式自編碼器
- TensorFlow 中的去噪自編碼器
- Keras 中的去噪自編碼器
- TensorFlow 中的變分自編碼器
- Keras 中的變分自編碼器
- 總結
- TF 服務:生產中的 TensorFlow 模型
- 在 TensorFlow 中保存和恢復模型
- 使用保護程序類保存和恢復所有圖變量
- 使用保護程序類保存和恢復所選變量
- 保存和恢復 Keras 模型
- TensorFlow 服務
- 安裝 TF 服務
- 保存 TF 服務的模型
- 提供 TF 服務模型
- 在 Docker 容器中提供 TF 服務
- 安裝 Docker
- 為 TF 服務構建 Docker 鏡像
- 在 Docker 容器中提供模型
- Kubernetes 中的 TensorFlow 服務
- 安裝 Kubernetes
- 將 Docker 鏡像上傳到 dockerhub
- 在 Kubernetes 部署
- 總結
- 遷移學習和預訓練模型
- ImageNet 數據集
- 再訓練或微調模型
- COCO 動物數據集和預處理圖像
- TensorFlow 中的 VGG16
- 使用 TensorFlow 中預訓練的 VGG16 進行圖像分類
- TensorFlow 中的圖像預處理,用于預訓練的 VGG16
- 使用 TensorFlow 中的再訓練的 VGG16 進行圖像分類
- Keras 的 VGG16
- 使用 Keras 中預訓練的 VGG16 進行圖像分類
- 使用 Keras 中再訓練的 VGG16 進行圖像分類
- TensorFlow 中的 Inception v3
- 使用 TensorFlow 中的 Inception v3 進行圖像分類
- 使用 TensorFlow 中的再訓練的 Inception v3 進行圖像分類
- 總結
- 深度強化學習
- OpenAI Gym 101
- 將簡單的策略應用于 cartpole 游戲
- 強化學習 101
- Q 函數(在模型不可用時學習優化)
- RL 算法的探索與開發
- V 函數(模型可用時學習優化)
- 強化學習技巧
- 強化學習的樸素神經網絡策略
- 實現 Q-Learning
- Q-Learning 的初始化和離散化
- 使用 Q-Table 進行 Q-Learning
- Q-Network 或深 Q 網絡(DQN)的 Q-Learning
- 總結
- 生成性對抗網絡
- 生成性對抗網絡 101
- 建立和訓練 GAN 的最佳實踐
- 使用 TensorFlow 的簡單的 GAN
- 使用 Keras 的簡單的 GAN
- 使用 TensorFlow 和 Keras 的深度卷積 GAN
- 總結
- 使用 TensorFlow 集群的分布式模型
- 分布式執行策略
- TensorFlow 集群
- 定義集群規范
- 創建服務器實例
- 定義服務器和設備之間的參數和操作
- 定義并訓練圖以進行異步更新
- 定義并訓練圖以進行同步更新
- 總結
- 移動和嵌入式平臺上的 TensorFlow 模型
- 移動平臺上的 TensorFlow
- Android 應用中的 TF Mobile
- Android 上的 TF Mobile 演示
- iOS 應用中的 TF Mobile
- iOS 上的 TF Mobile 演示
- TensorFlow Lite
- Android 上的 TF Lite 演示
- iOS 上的 TF Lite 演示
- 總結
- R 中的 TensorFlow 和 Keras
- 在 R 中安裝 TensorFlow 和 Keras 軟件包
- R 中的 TF 核心 API
- R 中的 TF 估計器 API
- R 中的 Keras API
- R 中的 TensorBoard
- R 中的 tfruns 包
- 總結
- 調試 TensorFlow 模型
- 使用tf.Session.run()獲取張量值
- 使用tf.Print()打印張量值
- 用tf.Assert()斷言條件
- 使用 TensorFlow 調試器(tfdbg)進行調試
- 總結
- 張量處理單元