由于TensofFlow不同版本之间API以及库函数变化较大,所以搭建网络方式有很多种,这里总结了常见的三种方式,适合入门级搭建网络,分别是定义类继承Model、函数式API、顺序模型,对于常见简单的网络三种方式都可以,但是对于复杂网络,例如递归式循环、多塔状网络可能函数式API更加适合,另外两种可能就不太适用,对于顺序堆叠执行的网络,三者都差不多。
方式一:继承keras.Model
class LeNet5(tf.keras.Model): def __init__(self): super(LeNet5, self).__init__() self.conv1 = Conv2D(filters=6, kernel_size=5) self.pool1 = AveragePooling2D((2, 2)) self.conv2 = Conv2D(filters=16, kernel_size=5) self.pool2 = AveragePooling2D((2, 2)) self.conv3 = Conv2D(filters=120, kernel_size=5) self.linear1 = Dense(84, activation=nn.relu) self.linear2 = Dense(10, activation=nn.softmax) def call(self, inputs, training=False): x = self.conv1(inputs) x = self.pool1(x) x = self.conv2(x) x = self.pool2(x) x = self.conv3(x) x = Flatten()(x) x = self.linear1(x) outputs = self.linear2(x) return outputs
方式二:函数式API
def LeNet(): # 输入层 inputs = Input(shape=(32, 32, 1)) conv1 = Conv2D(filters=6, kernel_size=5)(inputs) pool1 = AveragePooling2D((2, 2))(conv1) conv2 = Conv2D(filters=16, kernel_size=5)(pool1) pool2 = AveragePooling2D((2, 2))(conv2) conv3 = Conv2D(filters=120, kernel_size=5)(pool2) flatten = Flatten()(conv3) dense1 = Dense(84, activation=nn.relu)(flatten) # 输出层 outputs = Dense(10, activation=nn.softmax)(dense1) # 构建模型 model = Model(inputs, outputs) return model
方式三:mode.Sequential()
def LeNet(): model = keras.Sequential([ Conv2D(filters=6, kernel_size=5), AveragePooling2D((2, 2)), Conv2D(filters=16, kernel_size=5), AveragePooling2D((2, 2)), Conv2D(filters=120, kernel_size=5), Flatten(), Dense(84, activation=nn.relu), Dense(10, activation=nn.softmax) ]) return model