Skip to content

TensorFlow tf.keras API

tf.keras is TensorFlow's high-level API, providing layers, models, training and data pipeline abstractions.

1 class · 8 methods

Keras API

8 methods

顺序模型、网络层、编译训练与数据集构建的核心 API。

tf.keras.Sequential(layers)

创建由若干层线性堆叠的顺序模型。

Parameters

NameTypeDescription
layerslist[Layer]层对象列表

Returns

Sequential — 顺序模型

Example

tensorflow
import tensorflow as tf

model = tf.keras.Sequential([
    tf.keras.layers.Dense(16, activation="relu", input_shape=(10,)),
    tf.keras.layers.Dense(1, activation="sigmoid"),
])
model.summary()
tf.keras.layers.Dense(units, activation)

创建全连接层。

Parameters

NameTypeDescription
unitsint输出神经元个数
activationstr | Callable激活函数,如 'relu'

Returns

Dense — 全连接层

Example

tensorflow
import tensorflow as tf

layer = tf.keras.layers.Dense(32, activation="relu")
out = layer(tf.random.normal((4, 10)))
print(out.shape)  # (4, 32)
tf.keras.layers.Conv2D(filters, kernel_size)

创建二维卷积层,用于图像特征提取。

Parameters

NameTypeDescription
filtersint卷积核数量
kernel_sizeint | tuple卷积核大小

Returns

Conv2D — 二维卷积层

Example

tensorflow
import tensorflow as tf

conv = tf.keras.layers.Conv2D(32, 3, activation="relu", input_shape=(28, 28, 1))
out = conv(tf.random.normal((1, 28, 28, 1)))
print(out.shape)  # (1, 26, 26, 32)
model.compile(optimizer, loss, metrics)

配置模型的优化器、损失函数与评估指标。

Parameters

NameTypeDescription
optimizerstr | Optimizer优化器,如 'adam'
lossstr | Loss损失函数,如 'mse'
metricslist评估指标,如 ['accuracy']

Returns

None — 配置模型(原地)

Example

tensorflow
import tensorflow as tf

model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
model.compile(optimizer="adam", loss="mse", metrics=["mae"])
model.fit(x, y, epochs, batch_size)

用训练数据训练模型若干轮。

Parameters

NameTypeDescription
xarray | tensor | Dataset训练输入
yarray | tensor训练标签
epochsint训练轮数
batch_sizeint批大小,默认 32

Returns

History — 训练历史记录

Example

tensorflow
import numpy as np
import tensorflow as tf

model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
model.compile(optimizer="sgd", loss="mse")
x = np.random.rand(100, 2)
y = np.random.rand(100, 1)
hist = model.fit(x, y, epochs=5, batch_size=16)
print(hist.history["loss"])
model.evaluate(x, y)

在测试数据上评估模型损失与指标。

Parameters

NameTypeDescription
xarray | tensor测试输入
yarray | tensor测试标签

Returns

list — 损失与各指标的值

Example

tensorflow
import numpy as np
import tensorflow as tf

model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
model.compile(optimizer="sgd", loss="mse", metrics=["mae"])
x_test = np.random.rand(20, 2)
y_test = np.random.rand(20, 1)
results = model.evaluate(x_test, y_test)
print(results)
model.predict(x)

对输入数据进行前向推理,返回预测结果。

Parameters

NameTypeDescription
xarray | tensor待预测输入

Returns

ndarray — 预测输出

Example

tensorflow
import numpy as np
import tensorflow as tf

model = tf.keras.Sequential([tf.keras.layers.Dense(1)])
x_new = np.random.rand(5, 2)
preds = model.predict(x_new)
print(preds.shape)  # (5, 1)
tf.data.Dataset.from_tensor_slices(data)

从内存中的张量创建数据集,支持批处理、打乱与预取。

Parameters

NameTypeDescription
datatuple | tensor通常是 (x, y) 元组

Returns

Dataset — tf.data 数据集

Example

tensorflow
import numpy as np
import tensorflow as tf

x = np.random.rand(100, 2)
y = np.random.rand(100, 1)
ds = tf.data.Dataset.from_tensor_slices((x, y))
ds = ds.shuffle(100).batch(16).prefetch(2)
for xb, yb in ds.take(1):
    print(xb.shape, yb.shape)