创建简单神经网络
直接使用keras.Model方法
def line_fit_model():
"""
Model搭建网络结构
param:
return:
"""
inputs = tf.keras.Input(shape=(1, ), name="inputs")
layer1 = layers.Dense(10, activation="relu", name="layer1")(inputs)
layer2 = layers.Dense(15, activation="relu", name="layer2")(layer1)
outputs = layers.Dense(5, activation="softmax", name="outputs")(layer2)
model = tf.keras.Model(inputs=inputs, outputs=outputs)
model.summary()
return model
继承keras.Model方法
class LiftModel(tf.keras.Model):
"""
继承keras.Model
重写调用函数
"""
def __init__(self):
super(LiftModel, self).__init__()
self.layer1 = layers.Dense(10, activation=tf.nn.relu, name="layer1")
self.layer2 = layers.Dense(15, activation=tf.nn.relu, name="layer2")
self.outputs = layers.Dense(5, activation=tf.nn.softmax, name="outputs")
def call(self, inputs):
layer1 = self.layer1(inputs)
layer2 = self.layer2(layer1)
outputs = self.outputs(layer2)
return outputs
if __name__ =="__main__":
inputs = tf.constant([[1]])
lift = LiftModel()
lift(inputs)
lift.summary()
采用keras.Sequential内建方法
def line_fit_sequetnial():
model = tf.keras.Sequential([
layers.Dense(10, activation="relu", input_shape=(1, ), name="layer1"),
layers.Dense(15, activation="relu", name="layer2"),
layers.Dense(5, activation="softmax", name="outputs")
])
model.summary()
return model
采用Sequential()外建方法
def outline_fit_sequential():
model = tf.keras.Sequential()
model.add(layers.Dense(10, activation="relu", input_shape=(1, ), name="layer1"))
model.add(layers.Dense(15, activation="relu", name="layer2"))
model.add(layers.Dense(5, activation="softmax", name="output"))
model.summary()
return model
创建卷积神经网络
采用内建Sequentia方法
def cnn_sequential():
model = tf.keras.Sequential([
layers.Conv2D(32, (3, 3), activation="relu", input_shape=(28, 28, 3), name="conv-1"),
layers.MaxPooling2D((2, 2), name="pool-1"),
layers.Conv2D(64, (3, 3),activation="relu" ,name="conv-2"),
layers.MaxPooling2D((2, 2), name="pool-2"),
layers.Conv2D(64, (3, 3), activation="relu", name="conv-3"),
layers.Flatten(),
layers.Dense(64, activation="relu", name="full-1"),
layers.Dense(64, activation="softmax", name="softmax-1")
])
model.summary()
采用Sequential外建方法
def outline_cnn_sequential():
model = tf.keras.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation="relu", input_shape=(84, 84, 3), name="conv-1" ))
model.add(layers.MaxPooling2D((2, 2), name="pool-1"))
model.add(layers.Conv2D(64, (3, 3), activation="relu", name="conv-2"))
model.add(layers.MaxPooling2D((2, 2), name="pool-2"))
model.add(layers.Conv2D(64, (3, 3), activation="relu", name="conv-3"))
model.add(layers.MaxPooling2D((2, 2), name="pool-3"))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation="relu", name='full-1'))
model.add(layers.Dense(64, activation="softmax", name="softmax-1"))
model.summary()