日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

TensorFlow 2.0 - Keras Pipeline、自定义Layer、Loss、Metric

發(fā)布時間:2024/7/5 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 TensorFlow 2.0 - Keras Pipeline、自定义Layer、Loss、Metric 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

文章目錄

    • 1. Keras Sequential / Functional API
    • 2. 自定義 layer
    • 3. 自定義 loss
    • 4. 自定義 評估方法

學(xué)習(xí)于:簡單粗暴 TensorFlow 2

1. Keras Sequential / Functional API

  • tf.keras.models.Sequential([layers...]),但是它不能表示更復(fù)雜的模型
mymodel = tf.keras.models.Sequential([tf.keras.layers.Flatten(),tf.keras.layers.Dense(100, activation='relu'),tf.keras.layers.Dense(10),tf.keras.layers.Softmax() ])
  • Functional API 可以表示更復(fù)雜的模型
inp = tf.keras.Input(shape=(28, 28, 1)) x = tf.keras.layers.Flatten()(inp) x = tf.keras.layers.Dense(units=100, activation=tf.nn.relu)(x) x = tf.keras.layers.Dense(units=10)(x) out = tf.keras.layers.Softmax()(x) mymodel = tf.keras.Model(inputs=inp, outputs=out) # 配置模型:優(yōu)化器,損失函數(shù),評估方法 mymodel.compile(optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate),loss=tf.keras.losses.sparse_categorical_crossentropy,metrics=[tf.keras.metrics.sparse_categorical_accuracy] )# 訓(xùn)練:X,Y,batch_size, epochs mymodel.fit(data_loader.train_data, data_loader.train_label,batch_size=batch_size,epochs=num_epochs) # 測試 res = mymodel.evaluate(data_loader.test_data, data_loader.test_label) print(res) # [loss, acc]

2. 自定義 layer

  • 繼承 tf.keras.layers.Layer,重寫 __init__ 、 build 和 call 三個方法
import tensorflow as tf# 實現(xiàn)一個 線性layer class myLayer(tf.keras.layers.Layer):def __init__(self, units):super().__init__()self.units = unitsdef build(self, input_shape): # input_shape 是一個tensor# input_shape 是第一次運行 call() 時參數(shù)inputs的形狀# 第一次使用該層的時候,調(diào)用buildself.w = self.add_weight(name='w',shape=[input_shape[-1], self.units],initializer=tf.zeros_initializer())self.b = self.add_weight(name='b',shape=[self.units],initializer=tf.zeros_initializer())def call(self, inputs):y_pred = tf.matmul(inputs, self.w) + self.breturn y_pred
  • 使用自定義的 layer
class LinearModel(tf.keras.Model):def __init__(self):super().__init__()self.dense = myLayer(units=1) # 使用def call(self, inputs):output = self.dense(inputs)return output
  • 簡單的線性回歸
import numpy as np# 原始數(shù)據(jù) X_raw = np.array([0.0, 1., 2., 3., 4.], dtype=np.float32) y_raw = np.array([0.01, 2., 4., 5.98, 8.], dtype=np.float32)X = np.expand_dims(X_raw, axis=-1) y = np.expand_dims(y_raw, axis=-1)# 轉(zhuǎn)成張量 X = tf.constant(X) y = tf.constant(y)model = LinearModel() model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),loss=tf.keras.losses.MeanSquaredError() ) model.fit(X, y, batch_size=6, epochs=10000) print(model.variables)X_test = tf.constant([[5.1], [6.1]]) res = model.predict(X_test) print(res)

輸出:

[<tf.Variable 'linear_model/my_layer/w:0' shape=(1, 1) dtype=float32, numpy=array([[1.9959974]], dtype=float32)>, <tf.Variable 'linear_model/my_layer/b:0' shape=(1,) dtype=float32, numpy=array([0.00600523], dtype=float32)>] [[10.185592][12.181589]]

3. 自定義 loss

  • 繼承 tf.keras.losses.Loss,重寫 call 方法
class myError(tf.keras.losses.Loss):def call(self, y_true, y_pred):return tf.reduce_mean(tf.square(y_true - y_pred))model = LinearModel() model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),loss=myError() # 使用 自定義的loss )

4. 自定義 評估方法

  • 繼承 tf.keras.metrics.Metric ,重寫 __init__ 、 update_state 和 result 三個方法
class myMetric(tf.keras.metrics.Metric):def __init__(self):super().__init__()self.total = self.add_weight(name='total',dtype=tf.int32,initializer=tf.zeros_initializer())self.count = self.add_weight(name='count',dtype=tf.int32,initializer=tf.zeros_initializer())def update_state(self, y_true, y_pred, sample_weight=None):values = tf.cast(tf.abs(y_true - y_pred) < 0.1, tf.int32)# 這里簡單的判斷誤差 < 0.1, 算 trueself.total.assign_add(tf.shape(y_true)[0])self.count.assign_add(tf.reduce_sum(values))def result(self):return self.count / self.totalmodel = LinearModel() model.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),loss=myError(),metrics=[myMetric()] # 調(diào)用自定義的 metric )

總結(jié)

以上是生活随笔為你收集整理的TensorFlow 2.0 - Keras Pipeline、自定义Layer、Loss、Metric的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。