Keras

Keras是由纯python编写的基于theano/tensorflow的深度学习框架。Keras是一个高层神经网络API,支持快速实验,能够把你的idea迅速转换为结果,如果有如下需求,可以优先选择Keras:

a)简易和快速的原型设计(keras具有高度模块化,极简,和可扩充特性)

b)支持CNN和RNN,或二者的结合

c)无缝CPU和GPU切换

Keras模块结构:

Keras_第1张图片

使用Keras搭建一个神经网络:

Keras_第2张图片

【【【一些概念:

          (1)目前主要有两种方式来表示张量: a) th模式或channels_first模式,Theano和caffe使用此模式。b)tf模式或channels_last模式,TensorFlow使用此模式。

            例:对于100张RGB3通道的16×32(高为16宽为32)彩色图,th表示方式:(100,3,16,32);tf表示方式:(100,16,32,3)。唯一的区别就是表示通道个数3的位置不一样。

          (2)Keras有两种类型的模型,序贯模型(Sequential)和函数式模型(Model),函数式模型应用更为广泛,序贯模型是函数式模型的一种特殊情况。 a)序贯模型(Sequential):单输入单输出,一条路通到底,层与层之间只有相邻关系,没有跨层连接。这种模型编译速度快,操作也比较简单  b)函数式模型(Model):多输入多输出,层与层之间任意连接。这种模型编译速度慢。

        (3)neural layers(神经层), cost functions(损失函数), optimizers(优化器), initialization schemes(初始化方案), activation functions(激活函数), regularization(正则化项)在keras中都是独立的模块,可以自由组合。】】】

            

以上内容来自:https://blog.csdn.net/zdy0_2004/article/details/74736656

模型快速教程,可以看:http://keras-cn.readthedocs.io/en/latest/getting_started/sequential_model/

一个keras model的例子(函数式模型):

def model(input_shape):
    # Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!
    X_input = Input(input_shape)

    # Zero-Padding: pads the border of X_input with zeroes
    X = ZeroPadding2D((3, 3))(X_input)

    # CONV -> BN -> RELU Block applied to X
    X = Conv2D(32, (7, 7), strides=(1, 1), name='conv0')(X)
    X = BatchNormalization(axis=3, name='bn0')(X)
    X = Activation('relu')(X)

    # MAXPOOL
    X = MaxPooling2D((2, 2), name='max_pool')(X)

    # FLATTEN X (means convert it to a vector) + FULLYCONNECTED
    X = Flatten()(X)
    X = Dense(1, activation='sigmoid', name='fc')(X)

    # Create model. This creates your Keras model instance, you'll use this instance to train/test the model.
    model = Model(inputs=X_input, outputs=X, name='HappyModel')

    return model

一个keras model的实例:

# number of training examples = 600
# number of test examples = 150
# X_train shape: (600, 64, 64, 3)
# Y_train shape: (600, 1)
# X_test shape: (150, 64, 64, 3)
# Y_test shape: (150, 1)
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, classes = load_dataset()

# Normalize image vectors,像素值为最大255
X_train = X_train_orig / 255.
X_test = X_test_orig / 255.

# Reshape, transfer row to column
Y_train = Y_train_orig.T
Y_test = Y_test_orig.T

def HappyModel(input_shape):
    """
    Implementation of the HappyModel.

    Arguments:
    input_shape -- shape of the images of the dataset

    Returns:
    model -- a Model() instance in Keras
    """

    ### START CODE HERE ###
    # Feel free to use the suggested outline in the text above to get started, and run through the whole
    # exercise (including the later portions of this notebook) once. The come back also try out other
    # network architectures as well.

    # Define the input placeholder as a tensor with shape input_shape. Think of this as your input image!
    X_input = Input(input_shape)

    # Zero-Padding: pads the border of X_input with zeroes
    # 一种函数嵌套的形式
    X = ZeroPadding2D((3, 3))(X_input)

    # CONV -> BN -> RELU Block applied to X
    # 第一个参数为filters个数
    X = Conv2D(32, (7, 7), strides=(1, 1), name='conv0')(X)

    # axis: 整数,指定要规范化的轴,通常为特征轴。例如在进行data_format="channels_first的2D卷积后,一般会设axis=1

    X = BatchNormalization(axis=3, name='bn0')(X)
    X = Activation('relu')(X)

    # MAXPOOL
    X = MaxPooling2D((2, 2), name='max_pool')(X)

    # FLATTEN X (means convert it to a vector) + FULLYCONNECTED
    X = Flatten()(X)
    # Dense为全连接层
    X = Dense(1, activation='sigmoid', name='fc')(X)

    # Create model. This creates your Keras model instance, you'll use this instance to train/test the model.
    model = Model(inputs=X_input, outputs=X, name='HappyModel')

    ### END CODE HERE ###

    return model


# mini-batch
happyModel = HappyModel(X_train.shape[1:])
happyModel.compile(optimizer="Adam", loss="binary_crossentropy", metrics=['accuracy'])
happyModel.fit(x=X_train, y=Y_train, epochs=10, batch_size=32)

preds = happyModel.evaluate(X_test, Y_test)
print()
print("Loss = " + str(preds[0]))
print("Test Accuracy = " + str(preds[1]))

1、类Dense,

 

Keras.layers.core.Dense(output_dim, init='glorot_uniform', activation='linear', weights=None, W_regularizer=None, b_regularizer=None, activity_regularizer=None, W_constraint=None, b_constraint=None, input_dim=None)

ouput_dim:int > 0,输出结果的维度

init:初始化权值的函数名称或Theano function。可以使用Keras内置的,也可以传递自己编写的Theano function。如果不给weights传递参数时,则该参数必须指明。

activation:激活函数名称或者Theano function。可以使用Keras内置的,也可以是传递自己编写的Theano function。如果不明确指定,那么将没有激活函数会被应用。

weights:用于初始化权值的numpy arrays组成的list。这个List至少有1个元素,其shape为(input_dim, output_dim)。(如果指定init了,那么weights可以赋值None)
2、

3、为什么有的Keras函数后两个()??

Dense等类都是基于Layer类的,参考class Dense(Layer),因此我们可以看看Layer这个类怎么写的。在Layer这个类里面,有这样一个函数:def __call__(self, inputs, **kwargs);这个函数可以在python的文档中查到,通过定义这个函数,我们可以让一个对象当作函数使用。因此我们可以把下面代码拆分成这样:

X = Dense(64, activation='relu')(X)
# 拆分
fc = Dense(64, activation='relu')
X = fc(X)

或者说:Dense(64, avtivation='relu')执行__init__函数用于初始化得到一个类,然后调用对执行类的__call__函数,X=Dense(64, activation='relu')(inputs),然后得到输出。
4、BatchNormalization():https://keras-cn.readthedocs.io/en/latest/layers/normalization_layer/

该层在每个batch上将前一层的激活值重新规范化,即使得其输出数据的均值接近0,其标准差接近1

(1)、在什么地方来进行BN:BN可以应用于网络中任意的activation set。特别指出在CNN中,BN应作用在非线性映射前,即对做规范化。

2)、为什么用BN?克服深度神经网络难以训练的弊病,为了防止“梯度弥散”。关于梯度弥散,大家都知道一个简单的栗子:在BN中,是通过将activation规范为均值和方差一致的手段使得原本会减小的activation的scale变大。总结起来就是BN解决了反向传播过程中的梯度问题(梯度消失和爆炸),同时使得不同scale的  整体更新步调更一致

(4)、什么时候使用BN?OK,说完BN的优势,自然可以知道什么时候用BN比较好。例如,在神经网络训练时遇到收敛速度很慢,或梯度爆炸等无法训练的状况时可以尝试BN来解决。另外,在一般使用情况下也可以加入BN来加快训练速度,提高模型精度。

 

 

 

 

 

 

你可能感兴趣的:(Machine,Learning)