这篇教程深度学习用函数建立模型-Keras框架建立模型方法:函数API写得很实用,希望能帮到您。
# coding: utf-8
from tensorflow.keras import Input, layers
input_tensor = Input(shape=(32, )) # 一个张量
dense = layers.Dense(32, activation='relu') # 一个层就是一个函数
output_tensor = dense(input_tensor) # 可以在一个张量上调用一个层,它会返回一个张量
# coding: utf-8
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras import layers, Input
import numpy as np
# -------------------------------sequential模型-------------------------------
seq_model = Sequential()
seq_model.add(layers.Dense(32, activation='relu', input_shape=(64, )))
seq_model.add(layers.Dense(32, activation='relu'))
seq_model.add(layers.Dense(10, activation='softmax'))
# --------------------------sequential模型与之对应的API-----------------------
input_tensor = Input(shape=(64, ))
x = layers.Dense(32, activation='relu')(input_tensor)
x = layers.Dense(32, activation='relu')(x)
output_tensor = layers.Dense(10, activation='softmax')(x)
# -----------------Model类将输入张量和输出张量转化为一个模型---------------------
model = Model(input_tensor, output_tensor)
model.summary()
# ---------------------------对模型进行编译-------------------------------------
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
# ----------------------生成训练的虚伪数据--------------------------------------
x_train = np.random.random((1000, 64))
y_train = np.random.random((1000, 10))
history = model.fit(x_train, y_train, batch_size=128, epochs=10) # 训练10轮次
score = model.evaluate(x_train, y_train) # 评估模型
print('\n', score) 深度学习—Keras迁移学习(升级版)+模型融合实现详解 深度学习用Keras实现RNN+LSTM的模型自动编写古诗 |