今年 1 月 12 日,Keras 做者 François Chollet 在推特上表示由于中文读者的普遍关注,他已经在 GitHub 上展开了一个 Keras 中文文档项目。而昨日,François Chollet 再一次在推特上表示 Keras 官方文档已经基本完成!他很是感谢翻译和校对人员两个多月的不懈努力,也但愿 Keras 中文使用者能继续帮助提高文档质量。
这一次发布的是 Keras 官方中文文档,它获得了严谨的校对而提高了总体质量。但该项目还在进行中,虽然目前已经上线了不少 API 文档和使用教程,但仍然有一部份内容没有完成。其实早在官方中文文档出现之前,就有开发者构建了 Keras 的中文文档,并且不少读者都在使用 MoyanZitto 等人构建的中文文档。
如下咱们将简要介绍此次官方发布的 Keras 文档。
Keras 是一个用 Python 编写的高级神经网络 API,它可以以 TensorFlow、CNTK、或者 Theano 做为后端运行。Keras 的开发重点是支持快速的实验。可以以最小的时延把你的想法转换为实验结果,是作好研究的关键。
Keras 兼容的 Python 版本: Python 2.7-3.6。
Keras 相对于其它深度学习库很是容易构建:首先它提供一致和简单的 API;其次,它提供独立的、彻底可配置的模块构成序列或图表以完成模型;最后,做为新的类和函数,新的模块很容易扩展。这样说可能比较抽象,但正如文档中所描述的,咱们甚至在 30 秒就能快速上手 Keras。因此在坑外徘徊或准备入坑 Keras 的小伙伴能够开心地开始大家的 30 秒。
快速开始:30 秒上手 Keras
Keras 的核心数据结构是 model,一种组织网络层的方式。最简单的模型是 Sequential 模型,它是由多网络层线性堆叠的栈。对于更复杂的结构,你应该使用 Keras 函数式 API,它容许构建任意的神经网络图。
from keras.models import Sequential
model = Sequential()复制代码
from keras.layers import Dense
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(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(lr=0.01, momentum=0.9, nesterov=True))复制代码
model.fit(x_train, y_train, epochs=5, batch_size=32)复制代码
model.train_on_batch(x_batch, y_batch)复制代码
loss_and_metrics = model.evaluate(x_test, y_test, batch_size=128)复制代码
classes = model.predict(x_test, batch_size=128)复制代码
构建一个问答系统,一个图像分类模型,一个神经图灵机,或者其余的任何模型,就是这么的快。深度学习背后的思想很简单,那么它们的实现又何须要那么痛苦呢?
使用简介
Keras 模型的使用通常能够分为顺序模型(Sequential)和 Keras 函数式 API,顺序模型是多个网络层的线性堆叠,而 Keras 函数式 API 是定义复杂模型(如多输出模型、有向无环图,或具备共享层的模型)的方法。如下将简要介绍两种模型的使用方法:
你能够经过将层的列表传递给 Sequential 的构造函数,来建立一个 Sequential 模型:
from keras.models import Sequential
from keras.layers import Dense, Activation
model = Sequential([
Dense(32, input_shape=(784,)),
Activation('relu'),
Dense(10),
Activation('softmax'),
])复制代码
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))复制代码
以下展现了一个完整的模型,即基于多层感知器 (MLP) 的 softmax 多分类:
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
from keras.optimizers import SGD
import numpy as np
x_train = np.random.random((1000, 20))
y_train = keras.utils.to_categorical(np.random.randint(10, size=(1000, 1)), num_classes=10)
x_test = np.random.random((100, 20))
y_test = keras.utils.to_categorical(np.random.randint(10, size=(100, 1)), num_classes=10)
model = Sequential()
model.add(Dense(64, activation='relu', input_dim=20))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(10, activation='softmax'))
sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy',
optimizer=sgd,
metrics=['accuracy'])
model.fit(x_train, y_train,
epochs=20,
batch_size=128)
score = model.evaluate(x_test, y_test, batch_size=128)复制代码
利用函数式 API,能够轻易地重用训练好的模型:能够将任何模型看做是一个层,而后经过传递一个张量来调用它。注意,在调用模型时,您不只重用模型的结构,还重用了它的权重。
如下是函数式 API 的一个很好的例子:具备多个输入和输出的模型。函数式 API 使处理大量交织的数据流变得容易。
来考虑下面的模型。咱们试图预测 Twitter 上的一条新闻标题有多少转发和点赞数。模型的主要输入将是新闻标题自己,即一系列词语,可是为了增添趣味,咱们的模型还添加了其余的辅助输入来接收额外的数据,例如新闻标题的发布的时间等。该模型也将经过两个损失函数进行监督学习。较早地在模型中使用主损失函数,是深度学习模型的一个良好正则方法。
让咱们用函数式 API 来实现它(详细解释请查看中文文档):
from keras.layers import Input, Embedding, LSTM, Dense
from keras.models import Model
main_input = Input(shape=(100,), dtype='int32', name='main_input')
x = Embedding(output_dim=512, input_dim=10000, input_length=100)(main_input)
lstm_out = LSTM(32)(x)
auxiliary_output = Dense(1, activation='sigmoid', name='aux_output')(lstm_out)
auxiliary_input = Input(shape=(5,), name='aux_input')
x = keras.layers.concatenate([lstm_out, auxiliary_input])
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
x = Dense(64, activation='relu')(x)
main_output = Dense(1, activation='sigmoid', name='main_output')(x)
model = Model(inputs=[main_input, auxiliary_input], outputs=[main_output, auxiliary_output])
model.compile(optimizer='rmsprop', loss='binary_crossentropy',
loss_weights=[1., 0.2])
model.fit([headline_data, additional_data], [labels, labels],
epochs=50, batch_size=32)
model.compile(optimizer='rmsprop',
loss={'main_output': 'binary_crossentropy', 'aux_output': 'binary_crossentropy'},
loss_weights={'main_output': 1., 'aux_output': 0.2})
model.fit({'main_input': headline_data, 'aux_input': additional_data},
{'main_output': labels, 'aux_output': labels},
epochs=50, batch_size=32)复制代码
以上只是一个简单的案例,Keras 函数式 API 还有很是多的应用案例,包括层级共享、有向无环图和残差网络等顶尖视觉模型,读者能够继续阅读中文文档了解更多。
文档的后一部分更可能是描述 Keras 中经常使用的函数与 API,包括 Keras 模型、层级函数、预处理过程、损失函数、最优化方法、数据集和可视化等。这些 API 和对应实现的功能其实不少时候能够在实际使用的时候再查找,固然最基本的 API 咱们仍是须要了解的。如下将简要介绍 Keras 模型和层级 API,其它的模块请查阅原中文文档。
Keras 模型
在 Keras 中有两类模型,顺序模型 和 使用函数式 API 的 Model 类模型。这些模型有许多共同的方法:
config = model.get_config()
model = Model.from_config(config)
model = Sequential.from_config(config)复制代码
-
model.get_weights(): 返回模型权重的张量列表,类型为 Numpy array。
-
model.set_weights(weights): 从 Nympy array 中为模型设置权重。列表中的数组必须与 get_weights() 返回的权重具备相同的尺寸。
-
model.to_json(): 以 JSON 字符串的形式返回模型的表示。请注意,该表示不包括权重,只包含结构。你能够经过如下代码,从 JSON 字符串中从新实例化相同的模型(带有从新初始化的权重):
from keras.models import model_from_json
json_string = model.to_json()
model = model_from_json(json_string)复制代码
from keras.models import model_from_yaml
yaml_string = model.to_yaml()
model = model_from_yaml(yaml_string)复制代码
-
model.save_weights(filepath): 将模型权重存储为 HDF5 文件。
-
model.load_weights(filepath, by_name=False): 从 HDF5 文件(由 save_weights 建立)中加载权重。默认状况下,模型的结构应该是不变的。若是想将权重载入不一样的模型(部分层相同),设置 by_name=True 来载入那些名字相同的层的权重。
Keras 层级
-
layer.get_weights(): 以 Numpy 矩阵的形式返回层的权重。
-
layer.set_weights(weights): 从 Numpy 矩阵中设置层的权重(与 get_weights 的输出形状相同)。
-
layer.get_config(): 返回包含层配置的字典。此图层能够经过如下方式重置:
layer = Dense(32)
config = layer.get_config()
reconstructed_layer = Dense.from_config(config)复制代码
若是一个层具备单个节点 (i.e. 若是它不是共享层), 你能够获得它的输入张量,输出张量,输入尺寸和输出尺寸:
-
layer.input
-
layer.output
-
layer.input_shape
-
layer.output_shape
-
layer.get_input_at(node_index)
-
layer.get_output_at(node_index)
-
layer.get_input_shape_at(node_index)
-
layer.get_output_shape_at(node_index)
这些是 Keras 模型与层级基本的函数,文档的中心内容也是这一部分和下面描述的 API 用途与参数,它包括完整模型所须要的各个模块,包括数据、预处理、网络架构、训练、评估和可视化等。但这一部分咱们并不会介绍,由于不少时候咱们只有在遇到未知的函数时才会详细查阅。