Posted on

交叉熵相關損失函數的比較

交叉熵(cross-entropy)是什麼

交叉熵是一種常用的測量兩個概率分布差異的度量。它可以用來衡量預測模型的輸出結果與真實標籤之間的差異,从而作為訓練模型的損失函數。

交叉熵的计算公式如下:

H(y, y_pred) = – ∑ y log(y_pred)

其中 y 和 y_pred 分别表示真實標籤的概率分布和預測模型的輸出概率分布。

交叉熵有一些特性,使它特别适用于衡量分類問題中模型的預測結果與真實標籤之間的差異:

交叉熵越小,預測模型的輸出結果就越接近真實標籤,模型的預測能力就越強。
当預測模型的輸出結果完全符合真實標籤時,交叉熵等于零。
交叉熵是一個非負數,且在模型預測結果與真實標籤完全不同時,交叉熵最大。

交叉熵相關損失函數

有以下兩種

  • categorical_crossentropy
  • sparse_categorical_crossentropy

兩者都是用於計算分類問題中模型預測結果與真實標籤之間的交叉熵的損失函數。但是它們有一些重要的區別。

1、在 “categorical_crossentropy” 中,標籤必須是一個 one-hot 編碼,即對每個類別都指定一個二元(0/1)標籤。
2、在 “sparse_categorical_crossentropy” 中,標籤可以是一個整數,表示每個類別的索引。在計算交叉熵損失時,會對這些整數標籤進行單熱編碼。

如果你的標籤已經是 one-hot 編碼,則應使用 “categorical_crossentropy”。如果你的標籤是整數,則應使用 “sparse_categorical_crossentropy”。

通常情況下,使用 “sparse_categorical_crossentropy” 可能比較方便,因為標籤可以直接表示為整數,而不需要先對它們進行 one-hot 編碼。但是,使用 “categorical_crossentropy” 也是可以的,只需要將標籤進行 one-hot 編碼即可。

單熱編碼(one-hot encoding)

單熱編碼(one-hot encoding)是一種將類別特徵轉化為向量的方法。

假設有一個有 N 個不同類別的特徵,那麼我们就可以將每個類別都表示為一個 N 维的二元向量,其中只有一個元素為 1,其余元素都為 0。例如,如果類別有 A、B、C 三個可能的取值,那麼我們就可以將它們分别表示為:

A: [1, 0, 0]
B: [0, 1, 0]
C: [0, 0, 1]

通常情况下,單熱編碼通常用於處理分類問題,並且可以用於訓練深度學習模型。它的主要作用是將類別特徵轉化為可以被訓練模型理解的數值型特徵,以便訓練模型。

Posted on

使用數據增強加強圖像辨識準確率

數據增強

數據增強(Data Augmentation)是一種在不增加真實數據的情況下,通過對現有數據進行變化來增加數據集大小的方法。
請參見: https://www.tensorflow.org/api_docs/python/tf/keras/preprocessing/image/ImageDataGenerator
常見的數據增強技術包括:

  • 尺度變換: 對圖像進行放大或縮小。
  • 旋轉: 對圖像進行旋轉。
  • 平移: 對圖像進行平移。
  • 剪裁: 對圖像進行剪裁。
  • 翻轉: 對圖像進行水平或垂直翻轉。
  • 調整亮度: 對圖像的亮度進行調整。
  • 調整對比度: 對圖像的對比度進行調整。

通過使用這些技術,可以從現有的數據集中生成新的數據,以增加數據集的大小

使用數據增強的範例 – 使用ImageDataGenerator

以下為一個簡單範例

# 建立模型
model = Sequential()
# 加入多個卷積層和池化層
model.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu', input_shape=(img_height,img_width,3)))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(filters=128, kernel_size=(3,3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

# 將特徵圖拉平
model.add(Flatten())

# 加入多個全連接層
model.add(Dense(units=256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(units=128, activation='relu'))
model.add(Dropout(0.5))

# 加入輸出層
model.add(Dense(units=52, activation='softmax'))

# 編譯模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

# 使用數據增強
datagen = ImageDataGenerator(
rotation_range=30,
width_shift_range=0.2,
height_shift_range=0.2,
horizontal_flip=True
)

# 訓練模型
model.fit_generator(
datagen.flow(x_train, y_train, batch_size=32),
steps_per_epoch=len(x_train) / 32,
epochs=10,
validation_data=(x_val, y_val)
)

數據增強範例2 – 載入圖片decode_jpeg後隨機改變圖像

#现在我们的jpg文件进行解码,变成三维矩阵
def load_preprosess_image(path,label):
    #读取路径
    image=tf.io.read_file(path)
    #解码
    image=tf.image.decode_jpeg(image,channels=3)#彩色图像为3个channel
    #将图像改变为同样的大小,利用裁剪或者扭曲,这里应用了扭曲
    image=tf.image.resize(image,[360,360])
    #随机裁剪图像
    image=tf.image.random_crop(image,[256,256,3])
    #随机上下翻转图像
    image=tf.image.random_flip_left_right(image)
    #随机上下翻转
    image=tf.image.random_flip_up_down(image)
    #随机改变图像的亮度
    image=tf.image.random_brightness(image,0.5)
    #随机改变对比度
    image=tf.image.random_contrast(image,0,1)
    #改变数据类型
    image=tf.cast(image,tf.float32)
    #将图像进行归一化
    image=image/255
    #现在还需要对label进行处理,我们现在是列表[1,2,3],
    #需要变成[[1].[2].[3]]
    label=tf.reshape(label,[1])
    return image,label

梗圖分享

Posted on

模型的權重與偏差值

神經元的權重與偏差

在神經網絡中,權重 (weight) 和偏差 (bias) 是模型的兩個重要參數。

權重 (weight) 指的是神經網絡中的輸入層和輸出層之間的連接強度。每個神經元都有一個權重矩陣,表示與該神經元相連的輸入張量的強度。輸入張量與輸出張量之間的權重越大,該神經元對輸出的貢獻就越大。

偏差 (bias) 指的是神經網絡中的偏移量。每個神經元都有一個偏差值,表示該神經元的輸出在不考慮輸入的情況下的預設值。偏差值可以控制神經網絡的輸出範圍,並且可以用於控制模型的準確性。

在訓練神經網絡模型時,通常會使用梯度下降法來調整權重和偏差的值,以使得模型的輸出與真實值的差異最小。

設定神經元的偏差值

在訓練神經網絡模型時,通常可以自己設定神經元的偏差值。

例如,在 TensorFlow 中可以使用以下方式創建一個帶有偏差的神經元:

 import tensorflow as tf

# 創建一個帶有偏差的神經元
neuron = tf.keras.layers.Dense(units=1, bias_initializer=tf.constant_initializer(1.0))

上面使用了 bias_initializer 參數指定了偏差的初始值為 1.0。

使用梯度下降法調整偏差值

在訓練神經網絡模型時,通常會使用梯度下降法來調整偏差的值,以使得模型的輸出與真實值的差異最小。通常會使用 TensorFlow 的自動微分機制來計算模型的梯度,並使用梯度下降法調整偏差的值。

簡單範例

 import tensorflow as tf

# 創建一個帶有偏差的神經元
neuron = tf.keras.layers.Dense(units=1, bias_initializer=tf.constant_initializer(1.0))

# 創建模型
model = tf.keras.Sequential([neuron])

# 定義損失函數和優化器
loss_fn = tf.keras.losses.MeanSquaredError()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)

# 訓練模型
for epoch in range(10):
  # 訓練數據
  x_train = [1.0, 2.0, 3.0, 4.0]
  y_train = [0.0, 0.0, 0.0, 0.0]

  # 將訓練數據放入模型
  for x, y in zip(x_train, y_train):
    with tf.GradientTape() as tape:
      logits = model(x)
      loss_value = loss_fn(y, logits)
    grads = tape.gradient(loss_value, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))

# 檢查神經元的偏差值
print(neuron.bias)  # 輸出: [0.9]

最後我們檢查了神經元的偏差值,可以看到它已經從 1.0 調整到了 0.9。

手動設定神經元的偏差值

以下為一個簡單範例

 import tensorflow as tf

# 創建一個帶有偏差的神經元
neuron = tf.keras.layers.Dense(units=1, bias_initializer=tf.constant_initializer(1.0))

# 創建模型
model = tf.keras.Sequential([neuron])

# 定義損失函數和優化器
loss_fn = tf.keras.losses.MeanSquaredError()
optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)

# 訓練模型
for epoch in range(10):
  # 訓練數據
  x_train = [1.0, 2.0, 3.0, 4.0]
  y_train = [0.0, 0.0, 0.0, 0.0]

  # 將訓練數據放入模型
  for x, y in zip(x_train, y_train):
    with tf.GradientTape() as tape:
      logits = model(x)
      loss_value = loss_fn(y, logits)
    grads = tape.gradient(loss_value, model.trainable_variables)
    optimizer.apply_gradients(zip(grads, model.trainable_variables))

# 檢查神經元的偏差值
print(neuron.bias)  # 輸出: [0.9]

# 手動設定神經元的偏差值
neuron.bias.assign([1.0])

# 再次檢查神經元的偏差值
print(neuron.bias)  # 輸出: [1.0]
Posted on

tensorflew的自動求導機制

什麼是自動求導機制

在 TensorFlow 中,有一種特殊的張量類型叫做梯度張量,可以用於計算模型的梯度。

TensorFlow 的梯度張量是一種特殊的張量,其中包含了模型中每個變量的梯度信息。梯度張量是 TensorFlow 的自動微分機制的基礎,可以通過 TensorFlow 的自動微分機制來計算模型的梯度。

使用方法介紹

使用 GradientTape 類的方法是:

在計算圖的上下文中創建一個 GradientTape 對象。
使用 GradientTape 對象的 watch 方法監視計算圖中的變量。
執行計算圖,並在計算圖中使用 TensorFlow 的運算符操作張量。
使用 GradientTape 對象的 gradient 方法計算模型的梯度。

使用範例

在機器學習中,我們經常需要計算函數的導數。TensorFlow 提供了強大的自動求導機制來計算導數。以下程式展示了如何使用 tf. GradientTape()方法計算函數,y(x)=x^2在x=3時的導數:

 import tensorflow as tf
x = tf. Variable (initial value=3.)
with tf.GradientTape () as tape:
    #所有計算步驟都會被記錄以用於求導
    y=tf.sguare (x)
y_grad = tape.gradient (y, x)#計算y關於x的導數
print (ly, y_grad]) 

輸出如下:

[array ([9.1, dtype=float32), array ([6.], dtype=float32)]
Posted on

使用model.summary()輸出參數Param計算過程

使用方式

使用keras構建深度學習模型,我們會通過model.summary()輸出模型各層的參數狀況,如下:

import tensorflow as tf

# 建立模型
model = tf.keras.Sequential()
model.add(tf.keras.layers.Conv2D(32, (3, 3), input_shape=(32, 32, 3)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(10))

# 顯示模型的摘要信息
model.summary()

輸出範例

Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
conv2d (Conv2D)              (None, 30, 30, 32)        896
_________________________________________________________________
flatten (Flatten)            (None, 28800)             0
_________________________________________________________________
dense (Dense)                (None, 10)                288110
=================================================================
Total params: 288,006
Trainable params: 288,006
Non-trainable params: 0

參數意義

在這個輸出中,Total params 表示模型的總參數數量,可以用來反推模型的大小。請注意,模型的大小不僅僅是參數數量的函數,還可能受到訓練資料的大小、訓練次數等因素的影響。

Param就是參數的意思,也就是每層神經元的權重(w)個數。
怎麼算出來的?Param = (輸入維度+1) * 輸出的神經元個數,但是每個神經元都要考慮到有一個Bias,所以要再加上1。

Posted on

TensorFlow的圖像操作功能筆記

為什麼要盡量使用Tensorflow的圖像操作功能

因為Tensorflow對GPU的支援度高,盡量完全使用Tensorflow內建的圖像操作功能對圖像做操作,可以避免資料在GPU和CPU之間轉換。

將資料集轉為dataset

可以使用 TensorFlow 的 tf.data.Dataset API 將訓練圖像和標籤轉換為數據集。

首先,需要將訓練圖像和標籤轉換為 TensorFlow 張量:

import tensorflow as tf

# Convert training images to tensors
train_images_tensor = tf.convert_to_tensor(train_images, dtype=tf.float32)

# Convert training labels to tensors
train_labels_tensor = tf.convert_to_tensor(train_labels, dtype=tf.int64)

然後,使用 tf.data.Dataset.from_tensor_slices 方法將張量轉換為數據集:

# Create a dataset from tensors
dataset = tf.data.Dataset.from_tensor_slices((train_images_tensor, train_labels_tensor))

使用 tf.data.Dataset 中的方法對數據集進行轉換和操作,例如混淆、重新排列和批次化。例如,要將數據集混淆並分成小批次

# Shuffle and batch the dataset
dataset = dataset.shuffle(buffer_size=1024).batch(32)

將BGR的tensor物件轉為灰階

可以使用rgb_to_grayscale將 BGR 格式的圖片轉換為灰階:

import tensorflow as tf

# 讀取圖片並解碼為張量
image = tf.image.decode_jpeg(image_data)

# 將圖片轉換為灰階
image = tf.image.rgb_to_grayscale(image)

# 將圖片的數據型別轉換為浮點數
image = tf.image.convert_image_dtype(image, tf.float32)

在 TensorFlow 中,通常會將圖片的數據型別轉換為浮點數,因為浮點數能夠提供更大的精度和更多的值域。浮點數通常用於訓練模型和進行數值運算。

例如,在進行影像辨識任務時,您可能會將圖片的像素值轉換為浮點數,以便模型能夠更好地學習圖片中的特徵。同樣地,在進行數值運算時,浮點數也能夠提供更高的精度,以便得到更精確的結果。

注意:不同的數據型別有不同的值域和精度,因此在選擇數據型別時,需要考慮您的應用程序的需求

將灰階圖片轉成黑白

使用以下方法將灰階圖片轉換為黑白圖片(類似 OpenCV 的 threshold):

import tensorflow as tf

# 讀取圖片並轉換為灰階
image = tf.image.rgb_to_grayscale(image)

# 設定閾值並將圖片轉換為黑白圖片
threshold = 128
image = tf.cast(image > threshold, tf.float32)

我們先設定閾值(在這裡設為 128),然後將圖片中的像素值與閾值進行比較。如果像素值大於閾值,則轉換為 1(黑色);否則轉換為 0(白色)。

載入圖片

使用 tf.io.read_file 函數讀取 JPEG 圖片,然後使用 tf.image.decode_jpeg 函數解碼圖片。接著,使用 tf.image.convert_image_dtype 函數將圖片轉換為 GPU 可處理的格式(通常是浮點數)。

import tensorflow as tf

# 讀取 JPEG 圖片
image_raw = tf.io.read_file(image_path)
image = tf.image.decode_jpeg(image_raw)

# 將圖片轉換為 GPU 可處理的格式
image = tf.image.convert_image_dtype(image, tf.float32)

縮小圖片

import tensorflow as tf

# 縮小圖片
image = tf.image.resize(image, (128, 128))

圖片改為灰階

import tensorflow as tf

# 轉換為灰階
image = tf.image.rgb_to_grayscale(image)
Posted on

限制在Tensorflow跑模型時使用的GPU的記憶體上限?

使用tensorflow-gpu結果耗一大堆MEMORY是為什麼

使用 TensorFlow GPU 版本會耗費較多的記憶體,這是正常的。因為 GPU 設備有自己的內存,我們可以使用 GPU 設備加速計算。但是,這意味著 GPU 設備的內存也必須足夠大,以便容納計算所需的資料。
如果GPU的記憶體不夠大,則tensorflow會改將原本要放在GPU的記憶體內的資料放到CPU的記憶體裡面,若是CPU的記憶體也不足夠大,則很有可能會導致程式死掉(因為記憶體不足夠)

改善方案

可考慮的改善方向有以下三點:

  • 模型太大,超出了 GPU 設備的內存限制=>可以考慮使用更大的 GPU 設備或對模型進行優化,以減少模型的大小。(請參見: 如何縮小Tensorflow運算模型時使用的記憶體大小)
  • 程式碼中存在記憶體泄漏。請檢查程式碼,確保正確釋放不再使用的記憶體。
  • GPU 設備的驅動程序版本過舊或損壞

其他方法

請參考這篇文章: https://starriet.medium.com/tensorflow-2-0-wanna-limit-gpu-memory-10ad474e2528
第一個選項:設置set_memory_growth為真。

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    for gpu in gpus:
      tf.config.experimental.set_memory_growth(gpu, True)
  except RuntimeError as e:
    print(e)

第二個選項:將第一個 GPU 的內存使用量限制為 1024MB。gpus只需根據需要更改和的索引memory_limit即可。

import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
  try:
    tf.config.experimental.set_virtual_device_configuration(gpus[0], [tf.config.experimental.VirtualDeviceConfiguration(memory_limit=1024)])
  except RuntimeError as e:
    print(e)

我使用了第二個方法成功解決佔用太大記憶體的問題

使用Task Manager查看GPU使用狀況

使用 Windows 任務管理器檢查 GPU 設備的內存使用情況。要查看 GPU 內存使用情況,請按照以下步驟操作:

  • 在 Windows 任務欄中,右鍵單擊「資源監視器」圖示。
  • 在「資源監視器」窗口中,展開「性能」窗格。
  • 在「性能」窗格中,展開「視覺效果」窗格。
  • 在「視覺效果」窗格中,展開「DirectX 內存使用量」窗格。


「DirectX 內存使用量」只包含 GPU 設備上運行的應用程序所使用的內存,不包含 GPU 設備本身的內存。

如果需要更詳細的信息,可以使用 NVIDIA System Monitor 或其他第三方軟件工具檢查 GPU 設備的內存使用情況。

Posted on 2 Comments

如何縮小Tensorflow運算模型時使用的記憶體大小

使用剪枝法

剪枝是一種常用的方法,用於縮小深度學習模型的大小。在剪枝過程中,可以刪除模型中不重要的權重,以縮小模型的大小。

以下是使用 TensorFlow 2.x 的簡單範例,說明如何在深度學習模型中進行剪枝:

import tensorflow as tf

# 建立模型
model = tf.keras.Sequential([
    tf.keras.layers.Dense(128, input_shape=(32,), activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

# 加載權重
model.load_weights('model_weights.h5')

# 將權重轉換為不為零的權重的比例
model.summary()

# 進行剪枝
pruning_schedule = tf.keras.mixed_precision.experimental.PruningSchedule(initial_sparsity=0.50, final_sparsity=0.90, frequency=100)
model_for_pruning = tf.keras.mixed_precision.experimental.prune_low_magnitude(model, pruning_schedule)

# 繼續訓練模型
model_for_pruning.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model_for_pruning.fit(train_data, train_labels, epochs=5)

# 保存剪枝後的模型
model_for_pruning.save('pruned_model.h5')

訓練過程中使用正則化

正則化是一種常用的方法,用於防止過擬合,並縮小模型的大小。在 TensorFlow 中,您可以使用 tf.keras.regularizers 中的正則化函數,如 tf.keras.regularizers.l1tf.keras.regularizers.l2,在網絡層中使用正則化。

model = tf.keras.Sequential([
    tf.keras.layers.Dense(128, kernel_regularizer=tf.keras.regularizers.l2(0.01), input_shape=(32,), activation='relu'),
    tf.keras.layers.Dense(10, activation='softmax')
])

使用較小的資料集進行訓練

如果資料集較大,則模型也會較大。因此,可以使用較小的資料集來訓練模型,以縮小模型的大小。
使用較少的運算計算。您可以使用較少的運算計算來縮小模型的大小。
例如,可以使用 1×1 卷積層來替代全卷積層預設值的3×3,或使用矩陣乘法來代替多重迴圈。

以下是使用 TensorFlow 2.x 的簡單範例,說明如何使用 1×1 卷積層來替代全卷積層的預設3×3的設定:

import tensorflow as tf

# 建立模型
model = tf.keras.Sequential([
    # 使用 1x1 卷積層替代全卷積層
    tf.keras.layers.Conv2D(64, (1, 1), padding='same', input_shape=(32, 32, 3), activation='relu'),
    tf.keras.layers.Conv2D(64, (3, 3), padding='same', activation='relu'),
    tf.keras.layers.Conv2D(64, (1, 1), padding='same', activation='relu'),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(10, activation='softmax')
])

# 編譯和訓練模型
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(train_data, train_labels, epochs=5)

在這個範例中,我們在網絡中使用了三個卷積層,其中第一個和第三個使用 1×1 卷積核。這有助於縮小模型的大小,同時保留了運算計算的效率。
如果將 kernel_size 設為 (3, 3),則 TensorFlow 會將卷積核的高度設為 3,寬度設為 3。
因此將kernel_size 設定為3或是 (3, 3),卷積核的大小都是 3×3,沒有任何意義上的差別。

修改kernel size

在使用 CNN 時,通常會將較大的 kernel size 放在較早的卷積層,較小的 kernel size 放在較深的卷積層。這樣做的目的是要讓模型能夠先捕捉到較大的特徵,再細究較小的特徵。

當然,也不一定要固守這個規則,如果您有其他的設計想法,也可以嘗試使用。但是,請記住,選擇 kernel size 的過程是一個平衡的過程,需要考慮訓練資料的特性、模型的性能和大小等因素。您可以透過多次嘗試和調整,找到對您的模型最合適的 kernel size。

使用預訓練的模型

使用預訓練的模型,而不是從頭開始訓練新模型。預訓練的模型已經在大型資料集上訓練過,可以直接套用到您的應用程序中。使用預訓練的模型可以使您的應用程序更小且訓練速度更快。

Posted on

tensorflow和keras版本之間不兼容的錯誤

更多資訊請見: https://stackoverflow.com/questions/72255562/cannot-import-name-dtensor-from-tensorflow-compat-v2-experimental

編譯器的錯誤訊息

ImportError: cannot import name 'dtensor' from 'tensorflow.compat.v2.experimental' (C:\Users\user\.conda\envs\py392\lib\site-packages\tensorflow\_api\v2\compat\v2\experimental\__init__.py)

stackoverflow提出的解決方法

tensorflow這可能是由於您和您的keras版本之間不兼容造成的。特別是我在tensorflow和keras中看到了這一點tensorflow==2.6.0,keras==2.9.0但如果其他版本也會導致這種情況,我也不會感到驚訝。

通過以下方式更新您的tensorflow版本:

pip install tensorflow==2.8

或通過以下方式降級您的keras版本:

pip install keras==2.6

我的方法

重新建立一個新的tensorflow環境
參考這篇文章: 使用conda管理python版本和函式庫
用一個新的函式庫來跑tensorflow
並下載正確的套件,在最下方有一個列表: https://www.tensorflow.org/install/pip?hl=zh-tw#package-location

conda create -n tf-gpu python=3.9.2
conda activate tf-gpu
pip install --upgrade pip
pip install tensorflow_gpu-2.6.0-cp39-cp39-win_amd64.whl

結果不行!!
最後還是照著上面的方法降版才OK

pip install keras==2.6
Posted on

使用GPU跑tensorflow的除錯流程

最簡單的範例

這邊的程式碼是官網教學裡的一個簡單範例:
https://www.tensorflow.org/tutorials/keras/classification?hl=zh-tw

# TensorFlow and tf.keras
import tensorflow as tf

# Helper libraries
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)
fashion_mnist = tf.keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

train_images_tensor = tf.convert_to_tensor(train_images, dtype=tf.float32)
train_labels_tensor = tf.convert_to_tensor(train_labels, dtype=tf.int64)

# Create a dataset from tensors
train_ds = tf.data.Dataset.from_tensor_slices((train_images_tensor, train_labels_tensor))

AUTOTUNE = tf.data.AUTOTUNE

def configure_for_performance(ds):
    ds = ds.cache()
    ds = ds.shuffle(buffer_size=1000)
    ds = ds.batch(32)
    ds = ds.prefetch(buffer_size=AUTOTUNE)
    return ds


train_ds = configure_for_performance(train_ds)

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
import time
timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
print(timestamp)
model.fit(
    train_ds,
    epochs=5, batch_size=32
)
timestamp = time.strftime("%Y-%m-%d_%H-%M-%S")
print(timestamp)
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print('\nTest accuracy:', test_acc)

# 作出預測
probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])
predictions = probability_model.predict(test_images)
print(predictions[0], test_labels[0])

使用GPU建模

經過了前三章的教學之後,應該已經設定好了Tensorflow的GPU環境
1. 在python裡面使用GPU 1 – 選擇適合的GPU
2. 在python裡面使用GPU 2 – 安裝正確的套件
3. 在python裡面使用GPU 3 – 開發GPU程式
接著就要嘗試使用GPU來建模,並評估和原本的效能有多大差異,現在就可以將上面的程式碼COPY下來,然後在有GPU的環境嚇跑看看

TensorFlow版本過舊的錯誤

AttributeError: module 'tensorflow.python.util.dispatch' has no attribute 'add_fallback_dispatch_list'

這個錯誤通常是因為您正在使用舊版本的 TensorFlow,而該版本中沒有 dispatch 模塊的 add_fallback_dispatch_list 屬性。

要解決此問題,建議您更新 TensorFlow 到最新版本。您可以使用 pip 升級 TensorFlow:

pip install --upgrade tensorflow

如果正在使用 GPU 版本的 TensorFlow,請使用 tensorflow-gpu 套件升級:

pip install --upgrade tensorflow-gpu

CUDA版本過舊

2023-01-03 14:34:18.036663: W tensorflow/stream_executor/gpu/asm_compiler.cc:111] *** WARNING *** You are using ptxas 11.0.194, which is older than 11.1. ptxas before 11.1 is known to miscompile XLA code, leading to
incorrect results or invalid-address errors.

You may not need to update to CUDA 11.1; cherry-picking the ptxas binary is often sufficient.
這個警告指出正在使用舊版本的 ptxas 編譯器,並表示它可能會導致 XLA 代碼的錯誤編譯,產生不正確的結果或無效地址錯誤。

要解決此問題,建議更新 ptxas 編譯器到最新版本。升級到 CUDA 11.1,或者選擇性地選擇更新 ptxas 編譯器。

可以在 NVIDIA 網站上下載最新版本的 CUDA Toolkit:
https://developer.nvidia.com/cuda-toolkit

zlibwapi.dll找不到

Could not locate zlibwapi.dll. Please make sure it is in your library path!

這個錯誤指出找不到 zlibwapi.dll 文件。這通常是因為您的系統中沒有安裝 zlib 庫。

要解決此問題,建議您安裝 zlib 庫。您可以在此頁面下載 zlib 庫:
https://www.zlib.net/

下載並安裝 zlib 庫後,請將 zlibwapi.dll 文件放在您的系統路徑中。通常,您可以將 zlibwapi.dll 文件放在 C:\Windows\System32 目錄中。

zlibwapi.dll版本錯誤

Could not load library zlibwapi.dll. Error code 193. Please verify that the library is built correctly for your processor architecture (32-bit, 64-bit)

這個錯誤指出無法載入 zlibwapi.dll 文件,並提示錯誤代碼 193。通常是因為您的系統和 zlibwapi.dll 文件的類型不匹配,例如您的系統是 64 位,而 zlibwapi.dll 文件是 32 位。
請參考此文章:https://blog.csdn.net/qq_45071353/article/details/124091856
最後我改下載x64的zlib(下載點)

成功使用GPU跑TF的訊息

2023-01-03 17:05:21.826122: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1616]
Created device /job:localhost/replica:0/task:0/device:GPU:0 with 3971 MB memory:  ->
device: 0, name: NVIDIA GeForce GTX 1660 Ti, pci bus id: 0000:01:00.0, compute capability: 7.5