1. 后端Backend
- Keras 是一个模型级库,为开发深度学习模型提供了高层次的构建模块。它不处理诸如张量乘积和卷积等低级操作。相反,它依赖于一个专门的、优化的张量操作库来完成这个操作,它可以作为 Keras 的「后端引擎」。相比单独地选择一个张量库,而将 Keras 的实现与该库相关联,Keras 以模块方式处理这个问题,并且可以将几个不同的后端引擎无缝嵌入到 Keras 中。
- 目前,Keras 有三个后端实现可用: TensorFlow 后端,Theano 后端,CNTK 后端。
- TensorFlow 是由 Google 开发的一个开源符号级张量操作框架。
- Theano 是由蒙特利尔大学的 LISA Lab 开发的一个开源符号级张量操作框架。
- CNTK 是由微软开发的一个深度学习开源工具包。
2. 切换后端
-
找到
$HOME/.keras/keras.json
,配置文件如下{ "image_data_format": "channels_last", "epsilon": 1e-07, "floatx": "float32", "backend": "tensorflow" //替换为cntk,theano } //或者直接修改linux的环境变量 ?? // KERAS_BACKEND=tensorflow python -c "from keras import backend"
-
keras.josn的详细配置
image_data_format
: 字符串,"channels_last"
或者"channels_first"
。它指定了 Keras 将遵循的数据格式约定。(keras.backend.image_data_format()
返回它。) - 对于 2D 数据 (例如图像),"channels_last"
假定为(rows, cols, channels)
,而"channels_first"
假定为(channels, rows, cols)
。 - 对于 3D 数据,"channels_last"
假定为(conv_dim1, conv_dim2, conv_dim3, channels)
,而"channels_first"
假定为(channels, conv_dim1, conv_dim2, conv_dim3)
。epsilon
: 浮点数,用于避免在某些操作中被零除的数字soft常量。floatx
: 字符串,"float16"
,"float32"
, 或"float64"
。默认浮点精度。backend
: 字符串,"tensorflow"
,"theano"
, 或"cntk"
。
3. keras中backend的api
-
from keras import backend as K
-
实例化一个输入占位符
inputs = K.placeholder(shape=(2, 4, 5)) # 同样可以: inputs = K.placeholder(shape=(None, 4, 5)) # 同样可以: inputs = K.placeholder(ndim=3) #它等价于 tf.placeholder() 或 th.tensor.matrix(), th.tensor.tensor3(), 等等。
-
实例化一个变量:
import numpy as np val = np.random.random((3, 4, 5)) var = K.variable(value=val) # 全 0 变量: var = K.zeros(shape=(3, 4, 5)) # 全 1 变量: var = K.ones(shape=(3, 4, 5)) # 它等价于 tf.Variable() 或 th.shared()
-
你需要的大多数张量操作都可以像在 TensorFlow 或 Theano 中那样完成:
# 使用随机数初始化张量 b = K.random_uniform_variable(shape=(3, 4), low=0, high=1) # 均匀分布 c = K.random_normal_variable(shape=(3, 4), mean=0, scale=1) # 高斯分布 d = K.random_normal_variable(shape=(3, 4), mean=0, scale=1) # 张量运算 a = b + c * K.abs(d) c = K.dot(a, K.transpose(b)) a = K.sum(b, axis=1) a = K.softmax(b) a = K.concatenate([b, c], axis=-1) # 等等
-
常用函数
- 这部分用到再查,太多了。。另外,用到一次就来这里总结一次就好,慢慢积累!