tensorflow2.0(2)-自定義Dense層以及訓(xùn)練過程

??之前展示了tensorflow2.0的一個(gè)初級(jí)的實(shí)用例子作為開始,對(duì)比1.x版本操作還是有好很多的。接下來也將繼續(xù)從比較基礎(chǔ)的層面去了解tf2.0的各種實(shí)現(xiàn)
??tensorflow2.0在上以keras去搭建網(wǎng)絡(luò),這種封裝好的基礎(chǔ)/高級(jí)api在使用上無疑更便捷,但在學(xué)習(xí)的過程中也不妨自己去實(shí)現(xiàn)一些功能,加深理解。
以實(shí)現(xiàn)最簡(jiǎn)單的全連接層和訓(xùn)練過程為例,

Dense層

from tensorflow import keras
# 如果在第一層,則需要加入?yún)?shù):input_shape
keras.layers.Dense(kernel, activation, input_shape)

#反之,一般這么寫
keras.layers.Dense(kernel, activation)

kernel: 這一層神經(jīng)元的個(gè)數(shù)
activation:激活函數(shù),一般取'relu','selu'也是不錯(cuò)的

簡(jiǎn)單搭個(gè)網(wǎng)絡(luò):

model = keras.Sequential([
    keras.layers.Dense(20, activation='relu',input_shape=[224,]),
    keras.layers.Dense(10, activation='relu'),
    keras.layers.Dense(2, activation='softmax')
])

我們可以用類去自定義Dense的功能,也是非常簡(jiǎn)單的

class DenseLayer(keras.layers.Layer):
    def __init__(self, kernel, activation=None, **kwargs):
        self.kernel = kernel
        self.activation = keras.layers.Activation(activation)
        super(DenseLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        self.w = self.add_weight(name='w',
                                 shape=(input_shape[1], self.kernel),
                                 initializer='uniform',
                                 trainable=True)
        self.bias = self.add_weight(name='bias',
                                 shape=(self.kernel,),
                                 initializer='zero',
                                 trainable=True)
        super(DenseLayer, self).build(input_shape)

    def call(self, x, **kwargs):
        return self.activation(x @ self.w + self.bias)

這一樣來,就可以直接用自定義的類DenseLayer去替換keras的全連接層

model = keras.Sequential([
    DenseLayer(20, activation='relu',input_shape=[224,]),
    DenseLayer(10, activation='relu'),
    DenseLayer(2, activation='softmax')
])

訓(xùn)練過程

自定義損失函數(shù)

對(duì)于實(shí)現(xiàn)分類的損失函數(shù)而言,也是簡(jiǎn)單粗暴的,對(duì)于標(biāo)簽的格式是one_hot的,用tf.nn.softmax_cross_entropy_with_logits
反之tf.nn.sparse_softmax_cross_entropy_with_logits,本文自然用到了后者。

# 傳入的logits就是訓(xùn)練數(shù)據(jù)通過model前向運(yùn)算一遍得到的結(jié)果(model(x))
def loss_func(logits, label):
    losses = tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=label)
    return tf.reduce_mean(losses)

自定義梯度更新

關(guān)于tf2.0,貌似tf.GradientTape()保留了下來,自定義梯度計(jì)算這一部分可以作為一個(gè)篇章去講述,以后也會(huì)去探索
所以把單步訓(xùn)練和梯度更新過程寫在一起

def train_per_step(model, x, y, optimizer):
    with tf.GradientTape() as tape:
        logit = model(x)
        loss = loss_func(logit, y)
    grads = tape.gradient(loss, model.trainable_variables)
    optimizer.apply_gradients(zip(grads,
                                  model.trainable_variables))
    return loss

搭建模型

因?yàn)樵趌oss_func的計(jì)算里包含了softmax,所以在最后一層不添加激活函數(shù)

    model = keras.models.Sequential([
        keras.layers.Reshape(target_shape=(28 * 28, ),
                             input_shape=(28, 28)),
        DenseLayer(200, activation='relu'),
        DenseLayer(300, activation='relu'),
        DenseLayer(100, activation='relu'),
        DenseLayer(10)
    ])

數(shù)據(jù)讀取

參考上一篇文章,但也有不一樣的地方,其中沒用到測(cè)試集,只關(guān)注訓(xùn)練時(shí)loss的變化過程

(x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data()
scaler = StandardScaler()
x_train_scaled = scaler.fit_transform(
    x_train.astype(np.float32).reshape(-1, 1)).reshape(-1, 28, 28)
x_train_scaled = tf.cast(x_train_scaled, tf.float32)
y_train = tf.cast(y_train, tf.int32)
train_data = tf.data.Dataset.from_tensor_slices((x_train_scaled, y_train))
train_data = train_data.take(10000).shuffle(10000).batch(256)

訓(xùn)練

optimizer = keras.optimizers.Adam(lr=0.0003)
epoch = 10
for i in range(epoch):
    for _, (x, y) in enumerate(train_data):
        loss = train_per_step(model, x, y, optimizer)
        print(loss.numpy())

最終可以看到loss是降得很快的

end.

最后編輯于
?著作權(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)容