Keras 是一个用 Python 编写的深度学习 API,可以运行在 JAX、TensorFlow 或 PyTorch 之上。
Keras 是
作为一个多框架 API,Keras 可用于开发与任何框架(JAX、TensorFlow 或 PyTorch)兼容的模块化组件。
这种方法有几个关键优势:
Keras 的核心数据结构是层 (layers) 和模型 (models)。最简单的模型是 `Sequential` 模型,它是一个线性层堆栈。对于更复杂的架构,您应该使用 Keras 函数式 API,它允许构建任意的层图,或者通过子类化完全从头开始编写模型。
这是 `Sequential` 模型
import keras
model = keras.Sequential()
堆叠层就像调用 `.add()` 一样简单
from keras import layers
model.add(layers.Dense(units=64, activation='relu'))
model.add(layers.Dense(units=10, activation='softmax'))
模型看起来不错后,请使用 `.compile()` 配置其学习过程
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
如果需要,您可以进一步配置优化器。Keras 的理念是保持简单的事物简单,同时允许用户在需要时完全控制(最终的控制是通过子类化轻松扩展源代码)。
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer=keras.optimizers.SGD(learning_rate=0.01, momentum=0.9, nesterov=True))
您现在可以按批次迭代您的训练数据
# x_train and y_train are Numpy arrays
model.fit(x_train, y_train, epochs=5, batch_size=32)
用一行代码评估您的测试损失和指标
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)
或者对新数据生成预测
classes = model.predict(x_test, batch_size=128)
您刚才看到的是使用 Keras 的最基本方式。
然而,Keras 也是一个高度灵活的框架,适合迭代最新的研究思路。Keras 遵循渐进式复杂性暴露的原则:它易于上手,但又能够处理任意高级用例,每一步只需要渐进式学习。
就像您上面用几行代码训练和评估了一个简单的神经网络一样,您可以使用 Keras 快速开发新的训练程序或最先进的模型架构。
这是一个自定义 Keras 层的示例——它可以在 JAX、TensorFlow 或 PyTorch 的低级工作流中互换使用
import keras
from keras import ops
class TokenAndPositionEmbedding(keras.Layer):
def __init__(self, max_length, vocab_size, embed_dim):
super().__init__()
self.token_embed = self.add_weight(
shape=(vocab_size, embed_dim),
initializer="random_uniform",
trainable=True,
)
self.position_embed = self.add_weight(
shape=(max_length, embed_dim),
initializer="random_uniform",
trainable=True,
)
def call(self, token_ids):
# Embed positions
length = token_ids.shape[-1]
positions = ops.arange(0, length, dtype="int32")
positions_vectors = ops.take(self.position_embed, positions, axis=0)
# Embed tokens
token_ids = ops.cast(token_ids, dtype="int32")
token_vectors = ops.take(self.token_embed, token_ids, axis=0)
# Sum both
embed = token_vectors + positions_vectors
# Normalize embeddings
power_sum = ops.sum(ops.square(embed), axis=-1, keepdims=True)
return embed / ops.sqrt(ops.maximum(power_sum, 1e-7))
有关 Keras 的更深入教程,您可以查看
您可以在 Keras Google 群组上提问并参与开发讨论。
您也可以(仅限)在 GitHub Issues 上报告 Bug 和功能请求。请务必先阅读 我们的指南。
Keras (κέρας) 在古希腊语中意为角。它引用了古希腊和拉丁文学中的一个文学意象,首次出现在《奥德赛》中,书中将梦境精灵(Oneiroi,单数Oneiros)分为两类:一类通过象牙门来到人间,欺骗做梦者,让他们看到虚假的幻象;另一类通过角门而来,预示着将会实现的未来。这是一种对 κέρας (角) / κραίνω (实现) 和 ἐλέφας (象牙) / ἐλεφαίρομαι (欺骗) 的文字游戏。
Keras 最初是在 ONEIROS(开放式神经电子智能机器人操作系统)项目研究的一部分中开发的。
“Oneiroi 难以捉摸——谁能确定它们讲述的是什么故事?人们所寻求的并非都能实现。Two gates there are that give passage to fleeting Oneiroi; one is made of horn, one of ivory. The Oneiroi that pass through sawn ivory are deceitful, bearing a message that will not be fulfilled; those that come out through polished horn have truth behind them, to be accomplished for men who see them.” Homer, Odyssey 19. 562 ff (Shewring translation)。