[手抄] Keras官方教程 - Backend

2018-07-02 keras, learn

官方教程,记录以便查阅!

以下代码运行环境为 —— keras[2.2.4], tensorflow[1.11.0]

In [1]:
# $HOME/.keras/keras.json
# default configuration
# avaliable backends: "theano", "tensorflow", or "cntk"
{
    "image_data_format": "channels_last",
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}
Out[1]:
{'image_data_format': 'channels_last',
 'epsilon': 1e-07,
 'floatx': 'float32',
 'backend': 'tensorflow'}
In [2]:
from keras import backend as K
# The code below instantiates an input placeholder. 
# It's equivalent to tf.placeholder() or th.tensor.matrix(), th.tensor.tensor3(), etc.
inputs = K.placeholder(shape=(2, 4, 5))
# also works:
inputs = K.placeholder(shape=(None, 4, 5))
# also works:
inputs = K.placeholder(ndim=3)
Using TensorFlow backend.
In [3]:
# The code below instantiates a variable. It's equivalent to tf.Variable() or th.shared().
import numpy as np
val = np.random.random((3, 4, 5))
var = K.variable(value=val)

# all-zeros variable:
var = K.zeros(shape=(3, 4, 5))
# all-ones:
var = K.ones(shape=(3, 4, 5))
In [4]:
# Most tensor operations you will need can be done as you would in TensorFlow or Theano:
# Initializing Tensors with Random Numbers
b = K.random_uniform_variable(shape=(3, 4), low=0, high=1) # Uniform distribution
c = K.random_normal_variable(shape=(3, 4), mean=0, scale=1) # Gaussian distribution
d = K.random_normal_variable(shape=(3, 4), mean=0, scale=1)

# Tensor Arithmetic
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)
# etc...
In [6]:
import keras
keras.backend.backend()
Out[6]:
'tensorflow'
In [ ]: