tensorflow学习012——tf.keras函数式API

2.11tf.keras函数式API

将每一层写成一个函数,每次使用直接调用。
好处:可以建立多输入多输出模型

点击查看代码
from tensorflow import keras
import matplotlib.pyplot as plt
fashion_mnist = keras.datasets.fashion_mnist
(train_images,train_labels),(test_images,test_labels) = fashion_mnist.load_data()
train_images = train_images / 255
test_images = test_images / 255
#先创建一个输入
input = keras.Input(shape=(28,28)) #这里只需要写明图片的形状就可以
x = keras.layers.Flatten()(input)
x = keras.layers.Dense(32,activation='relu')(x)
x = keras.layers.Dropout(0.5)(x)
x = keras.layers.Dense(64,activation='relu')(x)
output = keras.layers.Dense(10,activation='softmax')(x)
model = keras.Model(inputs=input,outputs=output)
model.compile(optimizer=keras.optimizers.Adam(learning_rate=0.001),loss='sparse_categorical_crossentropy',metrics=['acc'])
model.fit(train_images,train_labels,epochs=5,validation_data=(test_images,test_labels))
print(model.evaluate(test_images,test_labels))
posted @ 2021-11-14 21:10  白菜茄子  阅读(70)  评论(0编辑  收藏  举报