Tensorflow2.0實例化 Model 的兩種方式

1、在“函數式API”中,從“輸入層”開始,當前層的輸入層是前一層的輸出層,最後用輸入層和輸出層創建模型:

inputs = tf.keras.Input(shape=(28,28,1))
x = Conv2D(32,3,activation='relu')(inputs)
x = Flatten()(x)
x = Dense(128,activation='relu')(x)
outputs = Dense(10,activation='softmax')(x)
model_1 = tf.keras.Model(inputs,outputs)

2、通過定義tf.keras.Model的子類創建模型,重寫__init__方法和call方法,init方法用來定義需要用到的layers,call用來推理,返回輸出層。

class MyModel(tf.keras.Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.conv1 = Conv2D(32, 1, activation='relu')
        self.flatten = Flatten()
        self.d1 = Dense(128, activation='relu')
        self.d2 = Dense(10, activation='softmax')

    def call(self, x):
        x = self.conv1(x)
        x = self.flatten(x)
        x = self.d1(x)
        return self.d2(x)

model = MyModel()
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章