tensorflow1.5、keras2.1.6、pytorch0.4.0
1.tensorflow
tensorflow中文文档:链接地址
基本使用:
- 使用图 (graph) 来表示计算任务.
- 在被称之为
会话 (Session)
的上下文 (context) 中执行图. - 使用 tensor 表示数据.
- 通过
变量 (Variable)
维护状态. - 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.
综述
TensorFlow 是一个编程系统, 使用图来表示计算任务. 图中的节点被称之为 op (operation 的缩写). 一个 op 获得 0 个或多个 Tensor
, 执行计算, 产生 0 个或多个 Tensor
. 每个 Tensor 是一个类型化的多维数组. 例如, 你可以将一小组图像集表示为一个四维浮点数数组, 这四个维度分别是 [batch, height, width, channels]
.
一个 TensorFlow 图描述了计算的过程. 为了进行计算, 图必须在 会话
里被启动. 会话
将图的 op 分发到诸如 CPU 或 GPU 之类的 设备
上, 同时提供执行 op 的方法. 这些方法执行后, 将产生的 tensor 返回. 在 Python 语言中, 返回的 tensor 是numpy ndarray
对象(python)。
变量:创建、初始化、保存和加载
当训练模型时,用变量来存储和更新参数。变量包含张量 (Tensor)存放于内存的缓存区。建模时它们需要被明确地初始化,模型训练后它们必须被存储到磁盘。这些变量的值可在之后模型训练和分析是被加载。
有tf.Variable类和tf.train.Saver类
创建
当创建一个常量或是随机值。
注意,所有这些操作符都需要你指定张量的shape。那个形状自动成为变量的shape。变量的shape通常是固定的,但TensorFlow提供了高级的机制来重新调整其行列数。
# Create two variables.
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")
初始化
变量的初始化必须在模型的其它操作运行之前先明确地完成。最简单的方法就是添加一个给所有变量初始化的操作,并在使用模型之前首先运行那个操作。
你或者可以从检查点文件中重新获取变量值,详见下文。
使用tf.initialize_all_variables()
添加一个操作对变量做初始化。记得在完全构建好模型并加载之后再运行那个操作。
# Create two variables.
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
name="weights")
biases = tf.Variable(tf.zeros([200]), name="biases")
...
# Add an op to initialize the variables.
init_op = tf.initialize_all_variables()
# Later, when launching the model
with tf.Session() as sess:
# Run the init operation.
sess.run(init_op)
...
# Use the model
...
由另一个变量初始化
你有时候会需要用另一个变量的初始化值给当前变量初始化。由于tf.initialize_all_variables()
是并行地初始化所有变量,所以在有这种需求的情况下需要小心。
用其它变量的值初始化一个新的变量时,使用其它变量的initialized_value()
属性。你可以直接把已初始化的值作为新变量的初始值,或者把它当做tensor计算得到一个值赋予新变量。
# Create a variable with a random value.
weights = tf.Variable(tf.random_normal([784, 200], stddev=0.35),
name="weights")
# Create another variable with the same value as 'weights'.
w2 = tf.Variable(weights.initialized_value(), name="w2")
# Create another variable with twice the value of 'weights'
w_twice = tf.Variable(weights.initialized_value() * 0.2, name="w_twice")
保存变量
用tf.train.Saver()
创建一个Saver
来管理模型中的所有变量。
# Create some variables.
v1 = tf.Variable(..., name="v1")
v2 = tf.Variable(..., name="v2")
...
# Add an op to initialize the variables.
init_op = tf.initialize_all_variables()
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Later, launch the model, initialize the variables, do some work, save the
# variables to disk.
with tf.Session() as sess:
sess.run(init_op)
# Do some work with the model.
..
# Save the variables to disk.
save_path = saver.save(sess, "/tmp/model.ckpt")
print "Model saved in file: ", save_path
恢复变量
用同一个Saver
对象来恢复变量。注意,当你从文件中恢复变量时,不需要事先对它们做初始化。
# Create some variables.
v1 = tf.Variable(..., name="v1")
v2 = tf.Variable(..., name="v2")
...
# Add ops to save and restore all the variables.
saver = tf.train.Saver()
# Later, launch the model, use the saver to restore variables from disk, and
# do some work with the model.
with tf.Session() as sess:
# Restore variables from disk.
saver.restore(sess, "/tmp/model.ckpt")
print "Model restored."
# Do some work with the model
...
2.keras
中文文档地址:链接地址
Keras 是一个用 Python 编写的高级神经网络 API,它能够以 TensorFlow, CNTK, 或者 Theano 作为后端运行。Keras 的开发重点是支持快速的实验。能够以最小的时延把你的想法转换为实验结果,是做好研究的关键。
如果你在以下情况下需要深度学习库,请使用 Keras:
- 允许简单而快速的原型设计(由于用户友好,高度模块化,可扩展性)。
- 同时支持卷积神经网络和循环神经网络,以及两者的组合。
- 在 CPU 和 GPU 上无缝运行。
快速开始:30 秒上手 Keras
Keras 的核心数据结构是 model,一种组织网络层的方式。最简单的模型是 Sequential
顺序模型,它是由多个网络层线性堆叠的栈。对于更复杂的结构,你应该使用 Keras 函数式 API,它允许构建任意的神经网络图。
Sequential
顺序模型如下所示:
from keras.models import Sequential
model = Sequential()
可以简单地使用 .add()
来堆叠模型:
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))
现在,你可以批量地在训练数据上进行迭代了:
# x_train 和 y_train 是 Numpy 数组 -- 就像在 Scikit-Learn API 中一样。
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) 模型
顺序模型是多个网络层的线性堆叠。
你可以通过将层的列表传递给 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'),
])
也可以使用 .add()
方法将各层添加到模型中:
model = Sequential()
model.add(Dense(32, input_dim=784))
model.add(Activation('relu'))
指定输入数据的尺寸
模型需要知道它所期望的输入的尺寸。出于这个原因,顺序模型中的第一层(只有第一层,因为下面的层可以自动地推断尺寸)需要接收关于其输入尺寸的信息。有几种方法来做到这一点:
- 传递一个
input_shape
参数给第一层。它是一个表示尺寸的元组 (一个整数或None
的元组,其中None
表示可能为任何正整数)。在input_shape
中不包含数据的 batch 大小。 - 某些 2D 层,例如
Dense
,支持通过参数input_dim
指定输入尺寸,某些 3D 时序层支持input_dim
和input_length
参数。 - 如果你需要为你的输入指定一个固定的 batch 大小(这对 stateful RNNs 很有用),你可以传递一个
batch_size
参数给一个层。如果你同时将batch_size=32
和input_shape=(6, 8)
传递给一个层,那么每一批输入的尺寸就为(32,6,8)
。
因此,下面的代码片段是等价的:
model = Sequential()
model.add(Dense(32, input_shape=(784,)))
model = Sequential()
model.add(Dense(32, input_dim=784))
编译
在训练模型之前,您需要配置学习过程,这是通过 compile
方法完成的。它接收三个参数:
- 优化器 optimizer。它可以是现有优化器的字符串标识符,如
rmsprop
或adagrad
,也可以是 Optimizer 类的实例。详见:optimizers。 - 损失函数 loss,模型试图最小化的目标函数。它可以是现有损失函数的字符串标识符,如
categorical_crossentropy
或mse
,也可以是一个目标函数。详见:losses。 - 评估标准 metrics。对于任何分类问题,你都希望将其设置为
metrics = ['accuracy']
。评估标准可以是现有的标准的字符串标识符,也可以是自定义的评估标准函数。
# 多分类问题
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
# 二分类问题
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy'])
# 均方误差回归问题
model.compile(optimizer='rmsprop',
loss='mse')
# 自定义评估标准函数
import keras.backend as K
def mean_pred(y_true, y_pred):
return K.mean(y_pred)
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy', mean_pred])
关于Keras模型
在 Keras 中有两类模型:Sequential 顺序模型 和 使用函数式 API 的 Model 类模型。
Pytorch
中文文档地址:链接地址
三个框架对比
作者:Scofield
链接:https://www.zhihu.com/question/35396126/answer/308575020
来源:知乎
特点:
- tf:优雅,好理解
- pytorch:定制性好,可DIY指数高
- theano:定制性好,但需要充分造轮子
- keras:非常优雅、最易学好懂,可快速上手实现正常规矩的网络结构。
框架api难易顺序(难->易):
theano -> tf -> pytorch -> keras