Tensorflow2 -- MNIST

Tensorflow2.X和1.X有多了很多差別和使用方式, 今天用tf2來實作MNIST分類問題 MNIST MNIST是一個很標準的手寫數字分類問題, 數據集下載有很多方式,這次直接使用tf API提供的 28 * 28 且只有黑白的數據 開發 在local 起 jupyter lab 先看看GPU是否啟用 %matplotlib widget import matplotlib.pyplot as plt import tensorflow as tf import numpy as np # check gpu tf.config.list_physical_devices('GPU') tf.test.is_built_with_cuda() # output True 方法一 繼承 tf.keras.model class MLP(tf.keras.Model): def __init__(self): super().__init__() self.flatten = tf.keras.layers.Flatten() self.dense1 = tf.keras.layers.Dense(units=100, activation=tf.nn.relu) self.dense2 = tf.keras.layers.Dense(units=20, activation=tf.nn.leaky_relu) self.dense3 = tf.keras.layers.Dense(units=10) @tf.function def call(self, inputs): # [batch_size, 28, 28, 1] flat1 = self.flatten(inputs) # [batch_size, 784] dens1 = self.dense1(flat1) # [batch_size, 100] dens2 = self.dense2(dens1) # [batch_size, 20] dens3 = self.dense3(dens2) # [batch_size, 10] output = tf.nn.softmax(dens3) return output 使用tf.GradientTape訓練 # @tf.function def one_batch_step(X, y, **kwargs): with tf.GradientTape() as tape: y_pred = model(X) loss = tf.keras.losses.sparse_categorical_crossentropy(y_true=y, y_pred=y_pred) loss = tf.reduce_mean(loss) tf.print(f"{batch_index} loss {loss}", [loss]) with summary_writer.as_default(): tf.summary.scalar("loss", loss, step=batch_index) grads = tape.gradient(loss, model.variables) optimizer.apply_gradients(grads_and_vars=zip(grads, model.variables)) for epoch_index in range(num_epochs): for batch_index in range(num_batches): X, y = data_loader.get_batch(batch_size) one_batch_step(X, y, batch_index=batch_index) with summary_writer.as_default(): tf.summary.trace_export(name="model_trace", step=0, profiler_outdir=log_dir) tf.saved_model.save(model, f"saved/{model_name}") 方法二 使用keras Pipeline來疊每一層要用的函數,彈性較低,但非常適合簡單的Model ...

2020-09-26 · 1 min read · 194 words · KbWen · ZH

LSTM

原文網址:Understanding LSTMs 想像人在思考或閱讀文章時,並不是從零開始,而是會保留過去的記憶。RNN 就是為了解決這方面的問題而設計的。 每次訓練時,網路會保留過去的訊息並持續傳遞。而 LSTM 則是一種特殊的 RNN 形式。 The Problem of Long-Term Dependencies 在許多情況下,我們需要更多的上下文訊息,但這些關鍵資訊可能距離當前時間點非常遙遠。一般的 RNN 在處理這種長距離依賴時,容易產生梯度消失或梯度爆炸的問題。 LSTM LSTM 稱為「長短期記憶網絡」(Long Short Term Memory networks),是一種特殊的 RNN 架構。 不同於傳統 RNN 在每個 Cell 裡只包含一個 tanh 層,LSTM 增加了: input gate (輸入門) output gate (輸出門) forget gate (遺忘門) 這些閘門都是用來精準控制資料的操作。使用 sigmoid 激活函數可以看做是控制記憶與讀取資料量的多寡:0 代表不通過,1 代表全部通過。 詳細的數學推導可以參考原文。文中也介紹了 GRU——一種更為簡煉高效的 LSTM 變體。值得注意的是,現今我們從 RNN 領域獲得的優異成果,幾乎指的都是 LSTM 的應用。 在 TensorFlow 中,LSTM 已經封裝完善,呼叫即可使用。 下圖是用 LSTM (紅虛線) 去學習黑線 (x*sin(x)) 的擬合結果:

2017-06-29 · 1 min read · 66 words · KbWen · ZH

Kaggle Titanic

Kaggle The sinking of the RMS Titanic is one of the most infamous shipwrecks in history. On April 15, 1912, during her maiden voyage, the Titanic sank after colliding with an iceberg, killing 1502 out of 2224 passengers and crew. This sensational tragedy shocked the international community and led to better safety regulations for ships. One of the reasons that the shipwreck led to such loss of life was that there were not enough lifeboats for the passengers and crew. Although there was some element of luck involved in surviving the sinking, some groups of people were more likely to survive than others, such as women, children, and the upper-class. ...

2017-06-09 · 2 min read · 224 words · KbWen · EN

TENSORFLOW 練習4: word2vec

把字詞轉成 word embedding 要在字詞中找到他們之間的某種關聯,而不只是分散無意義的符號代表。 做這個問題的核心概念是: 「假設兩個不同句子中的詞上下文相同,則代表兩個詞的語意相近。」 今天要來使用 skip-gram 模型,一個類似二元分類的方式 (判斷像或是不像)。一開始也同之前的問題,先做數據處理。 計算出現數量:[(most count word1, n1), (second word2, n2)] 文字轉成向量: 例如:The actual code for this tutorial is very short 生成的 skip-gram pairs 示意: ([the, code], actual), ([actual, for], code), … (actual, the), (actual, code), (code, actual), … 在這之間都會給他編號,轉化為 (10, 20), (10, 30), (30, 10), (30, 40) ... 的形式。 用到 nce_loss,目前我還不是非常熟練,概念上是讓目標詞的機率越高越好,並讓其餘 K 個負面樣本 (negative samples) 的機率降低。 經典案例: king - queen = man - woman ==> king - queen + woman = man ...

2017-05-12 · 1 min read · 95 words · KbWen · ZH

Tensorflow 練習3: 'FizzBuzz'

Joel Grus — FizzBuzz in TensorFlow 從網路上看到的幽默問題,算是一個很有趣的使用,適合在做完 Classification 後練習。 輸入資料處理和原版程式碼一樣,因為還蠻直觀的: 1 – 000000001 – [0 0 0 0 0 0 0 0 1] 2 – 000000010 – [0 0 0 0 0 0 0 1 0] ……… 輸出則是用 [1 0 0 0] [0 1 0 0] [0 0 1 0] [0 0 0 1] 來代表四個分類。 輸入輸出都是一個矩陣的形式。利用兩層 hidden layer 分別是 512 和 256,激勵函數選擇 relu,剩下的就交給 tensorflow 分類。 結果 一開始一直分不出來,都會卡在把每個資料都判定成同一類 (0.533)。後來減低每次訓練丟進去的量就 OK 了 (忘記一開始做分類時也只丟一點點進去)。 ...

2017-05-08 · 1 min read · 89 words · KbWen · ZH

Tensorflow 練習2: CNN

利用 CNN 來預測數字 (MNIST) 輸入圖形是一個 2828 灰階 0~9 的數字。輸出是一個 110 的矩陣,代表預測 0~9 的機率分布。 流程如下: 輸入 – convolution – pooling – convolution – pooling – hidden layer – output 在代碼中用到 [None, xx, xx] 和 [-1, XX, xx],代表我們忽略輸入的大小(batch size),它會跟隨著輸入自動改變。 max pooling 表示我們選擇的是那個 kernel size 裡的最大值。結構中也加入了 dropout 來避免 overfitting。 結果 上圖是沒有 dropout,下圖是有 dropout。就這個例子而言差別不大,但還是看得出來上面的訓練會比測試好。 準確率落在 97%~99% 之間 (1000 次訓練)。 (目前使用 GradientDescent,更換優化器應該會更好)。 My GitHub

2017-05-07 · 1 min read · 59 words · KbWen · ZH

Tensorflow 使用GPUs

Tensorflow 支援使用 CPU 和 GPU 做運算: "/cpu:0": The CPU of your machine. "/gpu:0": The GPU of your machine, if you have one. "/gpu:1": The second GPU of your machine, etc. 用 with tf.device() 來分配這個語句下使用的設備。 可以用以下設定來優化運算: log_device_placement = True: 紀錄我們使用 device 的情況。 allow_soft_placement = True: 避免指定的 device 不存在,讓他能自行分配到存在且可運行的地方。 我沒有多顆 CPU,其他的語法先不試。

2017-04-14 · 1 min read · 49 words · KbWen · ZH

Tensorflow 練習1 : Polynomial Regression

使用 Tensorflow 分析 Regression 的基礎練習 Nerual network 分析二維四次多項式 先定義輸入輸出格式,None表示我們不限制它的Row 在 Tensorflow 中,要定義它是常數、變數,或是從外部輸入,必須要分別指定成: tf.constant() tf.Variable() tf.placeholder() 他才會是那個形式;而想使用 Tensorflow 的任何內容,必須要用 sess.run() 去啟動它,不然會是 Tensor 的格式。 其中 sess = tf.Session() 定義一個 Y = W*x + b 的線性方程,在隱藏層中利用 activation function 去改變它。 評估模型好壞常用有 square error 和 cross_entropy,這裡利用 square error 計算 loss。 選擇基本的梯度下降並最小化 loss;optimizer 是個小於 1 的值。 設定要訓練的數值和函數 (記得要有一定的雜訊) W shape = (in_dim, hidden_units) = (10,1) predictions shape = (200,1)*(1,10)*(10,1) = (200,1) 訓練 1000 次每 50 次看結果:視覺化和數據化 ...

2017-04-13 · 1 min read · 79 words · KbWen · ZH