# 使用 TensorFlow 的用于 MNIST 的 LeNet CNN
在 TensorFlow 中,應用以下步驟為 MNIST 數據構建基于 LeNet 的 CNN 模型:
1. 定義超參數,以及 x 和 y 的占位符(輸入圖像和輸出標簽) :
```py
n_classes = 10 # 0-9 digits
n_width = 28
n_height = 28
n_depth = 1
n_inputs = n_height * n_width * n_depth # total pixels
learning_rate = 0.001
n_epochs = 10
batch_size = 100
n_batches = int(mnist.train.num_examples/batch_size)
# input images shape: (n_samples,n_pixels)
x = tf.placeholder(dtype=tf.float32, name="x", shape=[None, n_inputs])
# output labels
y = tf.placeholder(dtype=tf.float32, name="y", shape=[None, n_classes])
```
將輸入 x 重塑為形狀(`n_samples`,`n_width`,`n_height`,`n_depth`):
```py
x_ = tf.reshape(x, shape=[-1, n_width, n_height, n_depth])
```
1. 使用形狀為 4 x 4 的 32 個內核定義第一個卷積層,從而生成 32 個特征圖。
* 首先,定義第一個卷積層的權重和偏差。我們使用正態分布填充參數:
```py
layer1_w = tf.Variable(tf.random_normal(shape=[4,4,n_depth,32],
stddev=0.1),name='l1_w')
layer1_b = tf.Variable(tf.random_normal([32]),name='l1_b')
```
* 接下來,用 `tf.nn.conv2d`函數定義卷積層。函數參數`stride`定義了內核張量在每個維度中應該滑動的元素。維度順序由`data_format`確定,可以是`'NHWC'`或`'NCHW'`(默認為`'NHWC'`)。
通常,`stride`中的第一個和最后一個元素設置為“1”。函數參數`padding`可以是`SAME`或`VALID`。 `SAME` `padding`表示輸入將用零填充,以便在卷積后輸出與輸入的形狀相同。使用`tf.nn.relu()`函數添加`relu`激活:
```py
layer1_conv = tf.nn.relu(tf.nn.conv2d(x_,layer1_w,
strides=[1,1,1,1],
padding='SAME'
) +
layer1_b
)
```
* 使用 `tf.nn.max_pool()` 函數定義第一個池化層。參數 `ksize` 表示使用 2×2×1 個區域的合并操作,參數 `stride` 表示將區域滑動 2×2×1 個像素。因此,區域彼此不重疊。由于我們使用 `max_pool` ,池化操作選擇 2 x 2 x 1 區域中的最大值:
```py
layer1_pool = tf.nn.max_pool(layer1_conv,ksize=[1,2,2,1],
strides=[1,2,2,1],padding='SAME')
```
第一個卷積層產生 32 個大小為 28 x 28 x 1 的特征圖,然后池化成 32 x 14 x 14 x 1 的數據。
1. 定義第二個卷積層,它將此數據作為輸入并生成 64 個特征圖。
* 首先,定義第二個卷積層的權重和偏差。我們用正態分布填充參數:
```py
layer2_w = tf.Variable(tf.random_normal(shape=[4,4,32,64],
stddev=0.1),name='l2_w')
layer2_b = tf.Variable(tf.random_normal([64]),name='l2_b')
```
* 接下來,用 `tf.nn.conv2d`函數定義卷積層:
```py
layer2_conv = tf.nn.relu(tf.nn.conv2d(layer1_pool,
layer2_w,
strides=[1,1,1,1],
padding='SAME'
) +
layer2_b
)
```
* 用`tf.nn.max_pool`函數定義第二個池化層:
```py
layer2_pool = tf.nn.max_pool(layer2_conv,
ksize=[1,2,2,1],
strides=[1,2,2,1],
padding='SAME'
)
```
第二卷積層的輸出形狀為 64 ×14×14×1,然后池化成 64×7×7×1 的形狀的輸出。
1. 在輸入 1024 個神經元的完全連接層之前重新整形此輸出,以產生大小為 1024 的扁平輸出:
```py
layer3_w = tf.Variable(tf.random_normal(shape=[64*7*7*1,1024],
stddev=0.1),name='l3_w')
layer3_b = tf.Variable(tf.random_normal([1024]),name='l3_b')
layer3_fc = tf.nn.relu(tf.matmul(tf.reshape(layer2_pool,
[-1, 64*7*7*1]),layer3_w) + layer3_b)
```
1. 完全連接層的輸出饋入具有 10 個輸出的線性輸出層。我們在這一層沒有使用 softmax,因為我們的損失函數自動將 softmax 應用于輸出:
```py
layer4_w = tf.Variable(tf.random_normal(shape=[1024, n_classes],
stddev=0.1),name='l)
layer4_b = tf.Variable(tf.random_normal([n_classes]),name='l4_b')
layer4_out = tf.matmul(layer3_fc,layer4_w)+layer4_b
```
這創建了我們保存在變量`model`中的第一個 CNN 模型:
```py
model = layer4_out
```
鼓勵讀者探索具有不同超參數值的 TensorFlow 中可用的不同卷積和池操作符。
為了定義損失,我們使用`tf.nn.softmax_cross_entropy_with_logits`函數,對于優化器,我們使用`AdamOptimizer`函數。您應該嘗試探索 TensorFlow 中可用的不同優化器函數。
```py
entropy = tf.nn.softmax_cross_entropy_with_logits(logits=model, labels=y)
loss = tf.reduce_mean(entropy)
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss)
```
最后,我們通過迭代`n_epochs`來訓練模型,并且在`n_batches`上的每個周期列中,每批`batch_size`的大小:
```py
with tf.Session() as tfs:
tf.global_variables_initializer().run()
for epoch in range(n_epochs):
total_loss = 0.0
for batch in range(n_batches):
batch_x,batch_y = mnist.train.next_batch(batch_size)
feed_dict={x:batch_x, y: batch_y}
batch_loss,_ = tfs.run([loss, optimizer],
feed_dict=feed_dict)
total_loss += batch_loss
average_loss = total_loss / n_batches
print("Epoch: {0:04d} loss = {1:0.6f}".format(epoch,average_loss))
print("Model Trained.")
predictions_check = tf.equal(tf.argmax(model,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(predictions_check, tf.float32))
feed_dict = {x:mnist.test.images, y:mnist.test.labels}
print("Accuracy:", accuracy.eval(feed_dict=feed_dict))
```
我們得到以下輸出:
```py
Epoch: 0000 loss = 1.418295
Epoch: 0001 loss = 0.088259
Epoch: 0002 loss = 0.055410
Epoch: 0003 loss = 0.042798
Epoch: 0004 loss = 0.030471
Epoch: 0005 loss = 0.023837
Epoch: 0006 loss = 0.019800
Epoch: 0007 loss = 0.015900
Epoch: 0008 loss = 0.012918
Epoch: 0009 loss = 0.010322
Model Trained.
Accuracy: 0.9884
```
現在,與我們在前幾章中看到的方法相比,這是一個非常好的準確性。從圖像數據中學習 CNN 模型是不是很神奇?
- 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)進行調試
- 總結
- 張量處理單元