tensorflow2建立模型的方法
使用Input
tf.keras.Input(shape=None, batch_size=None, name=None, dtype=None, sparse=False, tensor=None, ragged=False, **kwargs)
Input
初始化一个占位符shape
:指定模型输入的shape,不包括batch sizebatch_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)
继承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.dense(inputs)
return self.dense(x)
model = MyModel()
使用Sequential
import tensorflow as tf
model = tf.keras.Sequential(
tf.keras.layers.Dense(5, activation=tf.nn.softmax)
)