tensorflow2建立模型的方法

1.使用Input

tf.keras.Input(shape=None, batch_size=None, name=None, dtype=None, sparse=False, tensor=None, ragged=False, **kwargs)

Input初始化一个占位符 shape:指定模型输入的shape,不包括batch size batch_size:可选 name:可选,图层名称 dtype:字符串,数据类型 sparse:布尔,是否稀疏 tensor:可选,指定tensor,不再是占位符

from tensorflow.keras import Input, Model
from tensorflow.keras.layers import Dense
x = Input(shape=(2,))
y = Dense(5, activation='softmax')(x)
model = Model(x, y)

2.继承Model

import tensorflow as tf
class MyModel(tf.keras.Model):
    def __init__(self):
        super(MyModel, self).__init__()
        self.dense = tf.keras.layers.Dense(5, activation=tf.nn.softmax)

    def call(self, inputs):
        x = self.dense1(inputs)
        return self.dense(x)

model = MyModel()

3.使用Sequential

import tensorflow as tf
model1 = tf.keras.Sequential(
    tf.keras.layers.Dense(5, activation=tf.nn.softmax)
)