機(jī)器學(xué)習(xí)之分類

分類任務(wù)和回歸任務(wù)的不同之處在于,分類任務(wù)需要做出離散的預(yù)測(cè)。對(duì)于多分類任務(wù)的神經(jīng)網(wǎng)絡(luò)模型,其輸出目標(biāo)通常會(huì)用one-hot編碼來表示,在輸出層中使用softmax函數(shù),同時(shí)使用分類交叉熵?fù)p失函數(shù)進(jìn)行訓(xùn)練。在本博客中,我們將使用TensorFlow的底層API實(shí)現(xiàn)一個(gè)基于全連接層的神經(jīng)網(wǎng)絡(luò)來進(jìn)行MNIST數(shù)字圖像分類。下面是涉及到的相關(guān)概念:

深度學(xué)習(xí)是一種機(jī)器學(xué)習(xí)方法,它通過多層神經(jīng)網(wǎng)絡(luò)層次化地提取特征,以解決各種復(fù)雜的分類和回歸問題。

神經(jīng)網(wǎng)絡(luò)是深度學(xué)習(xí)的基本組成部分,由多個(gè)層次化的神經(jīng)元組成。輸入層接受數(shù)據(jù),中間的隱藏層通過權(quán)重和激活函數(shù)處理數(shù)據(jù),最終輸出層產(chǎn)生分類結(jié)果。在這個(gè)示例中,我們將手動(dòng)實(shí)現(xiàn)神經(jīng)網(wǎng)絡(luò)的核心組件。

前向傳播是神經(jīng)網(wǎng)絡(luò)中的信息傳遞過程,從輸入層到輸出層,每一層的神經(jīng)元根據(jù)權(quán)重和激活函數(shù)計(jì)算輸出。這個(gè)過程將輸入數(shù)據(jù)映射到預(yù)測(cè)輸出。

反向傳播是訓(xùn)練神經(jīng)網(wǎng)絡(luò)的關(guān)鍵步驟,它通過計(jì)算預(yù)測(cè)與真實(shí)標(biāo)簽之間的誤差,并將誤差反向傳播到網(wǎng)絡(luò)中的每一層來更新權(quán)重,以最小化誤差。

內(nèi)容大綱

  1. 神經(jīng)網(wǎng)絡(luò)核心組件的實(shí)現(xiàn)
  2. 數(shù)據(jù)加載處理
  3. 構(gòu)建訓(xùn)練模型
  4. 總結(jié)

神經(jīng)網(wǎng)絡(luò)核心組件的實(shí)現(xiàn)

以下代碼分別實(shí)現(xiàn)了密集層DenseLayer,網(wǎng)絡(luò)模型SequentialModel,批次生成器BatchGenerator,批次權(quán)重更新one_training_step 以及 訓(xùn)練函數(shù)fit。

from keras.datasets import mnist
import math
import tensorflow as tf
import numpy as np

class DenseLayer:  # 簡(jiǎn)單的Dense類
    def __init__(self, input_size, output_size, activation):
        self.activation = activation

        w_shape = (input_size, output_size)  # 創(chuàng)建一個(gè)形狀為(input_size, output_size)的矩陣W,并將其隨機(jī)初始化
        w_initial_value = tf.random.uniform(w_shape, minval=0, maxval=1e-1)
        self.W = tf.Variable(w_initial_value)

        b_shape = (output_size,)  # 創(chuàng)建一個(gè)形狀為(output_size,)的零向量b
        b_initial_value = tf.zeros(b_shape)
        self.b = tf.Variable(b_initial_value)

    def __call__(self, inputs):  # 前向傳播
        return self.activation(tf.matmul(inputs, self.W) + self.b)

    @property
    def weights(self):  # 獲取該層權(quán)重
        return [self.W, self.b]


class SequentialModel:  # 簡(jiǎn)單的Sequential類
    def __init__(self, layers):
        self.layers = layers

    def __call__(self, inputs):
        x = inputs
        for layer in self.layers:
            x = layer(x)
        return x

    @property
    def weights(self):
        weights = []
        for layer in self.layers:
            weights += layer.weights
        return weights



class BatchGenerator:  # 批量生成器
    def __init__(self, images, labels, batch_size=128):
        assert len(images) == len(labels)
        self.index = 0
        self.images = images
        self.labels = labels
        self.batch_size = batch_size
        self.num_batches = math.ceil(len(images) / batch_size)

    def next(self):
        images = self.images[self.index: self.index + self.batch_size]
        labels = self.labels[self.index: self.index + self.batch_size]
        self.index += self.batch_size
        return images, labels


# 更新參數(shù)
learning_rate = 1e-3 # 學(xué)習(xí)率
def update_weights(gradients, weights):
    for g, w in zip(gradients, weights):
        w.assign_sub(g * learning_rate)  # assign_sub相當(dāng)于TensorFlow變量的-=

# 計(jì)算梯度,并更新權(quán)重
def one_training_step(model, images_batch, labels_batch):
    with tf.GradientTape() as tape:  # 運(yùn)行前向傳播,即在GradientTape作用域內(nèi)計(jì)算模型預(yù)測(cè)值
        predictions = model(images_batch)
        # 標(biāo)簽編碼為整數(shù),使用sparse_categorical_crossentropy損失函數(shù)
        per_sample_losses = tf.keras.losses.sparse_categorical_crossentropy(labels_batch, predictions)
        average_loss = tf.reduce_mean(per_sample_losses)
    gradients = tape.gradient(average_loss, model.weights)  # 計(jì)算損失相對(duì)于權(quán)重的梯度。輸出gradients是一個(gè)列表,每個(gè)元素對(duì)應(yīng)model.weights列表中的權(quán)重
    update_weights(gradients, model.weights)  # 利用梯度來更新權(quán)重
    return average_loss


# 完整的訓(xùn)練循環(huán)
def fit(model, images, labels, epochs, batch_size=128):
    for epoch_counter in range(epochs):
        print(f"Epoch {epoch_counter}")
        batch_generator = BatchGenerator(images, labels)
        for batch_counter in range(batch_generator.num_batches):
            images_batch, labels_batch = batch_generator.next()
            loss = one_training_step(model, images_batch, labels_batch)
            if batch_counter % 100 == 0:
                print(f"loss at batch {batch_counter}: {loss:.2f}")

數(shù)據(jù)加載處理

首先,我們需要準(zhǔn)備數(shù)據(jù)。MNIST數(shù)據(jù)集包含手寫數(shù)字圖像,每個(gè)圖像是28x28像素的灰度圖像,總共有10個(gè)類別(0到9)。

# 加載MNIST數(shù)據(jù)集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 歸一化像素值到0到1之間
train_images = train_images.reshape((60000, 28 * 28)).astype("float32") / 255
test_images = test_images.reshape((10000, 28 * 28)).astype("float32") / 255

構(gòu)建訓(xùn)練模型

接下來,我們將使用DenseLayerSequentialModel 類構(gòu)建一個(gè)兩層的全連接神經(jīng)網(wǎng)絡(luò)模型。

# 利用這個(gè)DenseLayer類和SequentialModel類,創(chuàng)建一個(gè)與Keras類似的模型
model = SequentialModel([
    DenseLayer(input_size=28 * 28, output_size=512, activation=tf.nn.relu),# 全連接層,512個(gè)單元,ReLU激活函數(shù)
    DenseLayer(input_size=512, output_size=10, activation=tf.nn.softmax) # 輸出層,10個(gè)輸出單元對(duì)應(yīng)0-9的數(shù)字,使用softmax激活函數(shù)
])

現(xiàn)在,我們將使用手動(dòng)實(shí)現(xiàn)的神經(jīng)網(wǎng)絡(luò)模型來進(jìn)行訓(xùn)練。

# 開始訓(xùn)練
fit(model, train_images, train_labels, epochs=10, batch_size=128)

# 預(yù)測(cè)結(jié)果準(zhǔn)確率
predictions = model(test_images).numpy()
predicted_labels = np.argmax(predictions, axis=1)
matches = predicted_labels == test_labels
print(f"accuracy: {matches.mean():.2f}")

總結(jié)

在本博客中,我們使用TensorFlow的底層API手動(dòng)實(shí)現(xiàn)了一個(gè)基于全連接層的神經(jīng)網(wǎng)絡(luò)模型,并將其應(yīng)用于MNIST數(shù)字圖像分類。我們涵蓋了深度學(xué)習(xí)分類的基本原理,包括神經(jīng)網(wǎng)絡(luò)、前向傳播和反向傳播。通過適當(dāng)?shù)臄?shù)據(jù)處理、模型構(gòu)建、訓(xùn)練和預(yù)測(cè),我們成功地分類了手寫數(shù)字圖像,這是深度學(xué)習(xí)在計(jì)算機(jī)視覺中的一個(gè)典型應(yīng)用。希望本文能幫助你了解深度學(xué)習(xí)分類的基本流程和實(shí)現(xiàn)細(xì)節(jié)。通過底層API的實(shí)現(xiàn),你可以更深入地理解深度學(xué)習(xí)模型的內(nèi)部工作原理。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容