当前位置:   article > 正文

11.Keras 神经网络框架_keras神经网络框架

keras神经网络框架

Introduction

        Keras是一个高级的神经网络API,用Python实现,并可以基于TensorFlow,CNTK与Theano等计算框架运行。

        Keras的核心是神经网络,它的意义主要在于使得神经网络的实现更加方便快捷,因此它本质上是在一些知名的计算框架上进行了一层简化的封装,只对Keras使用者暴露出一些简单易用的接口,使用者可以很快了解并上手实现复杂的神经网络架构,而不用关心底层的实现细节。

Keras作为一个深度学习的库,有以下显著特征:

  1. 简单、快速地构造原型(兼具用户友好性、模块性以及可扩展性)
  2. 支持卷积网路和循环网络,包括二者的结合体
  3. 可以无缝在CPU和GPU上运行

Installation

     首先需要选择Keras的底层框架:TensorFlow,CNTK或Theano。(鉴于Bengio已经宣布将停止继续维护Theano,故推荐使用Google的TensorFlow),并进行安装,然后再安装Keras的库。另外,Keras默认以TensorFlow作为底层计算框架,如果使用CNTK或者Theano的话,则需要在Keras的配置文件中进行修改

       具体参考官方说明

Fast Overview

        我们知道,神经网络中最基本的构成单元是神经元(neuron),而若干神经元可以组成一个层(layer),若干层(输入层+隐藏层+输出层)就构成了一个神经网络的原型。而Keras中最核心的数据结构就是model,我们便是基于model来进行神经网络层(layers)的组装。而model最简单的一种类型便是Sequential,它对层进行线性堆叠。

       通过以下代码便能实例化一个Sequential:

  1. from keras.models import Sequential
  2. model = Sequential()
  3. 而要往Sequential上面叠加层,只需使用.add()方法:
  4. from keras.layers import Dense
  5. model.add(Dense(units=64, activation='relu', input_dim=100))
  6. model.add(Dense(units=10, activation='softmax'))

       如上是先后加了两层。第一层是Dense层(全连接层),共64个神经元(units=64),激活函数为ReLU(activation=’relu’),输入的是维度为1*100的列向量(input_dim=100)。第二层是也是一个Dense层,10个神经元,激活函数为softmax,输入的是前一层的输出向量,即维度为1*64的列向量。

       第一层默认为神经网络的隐藏层第一层,故需要指定输入向量的维度,即输入的特征向量的维度。

       Once your model looks good, configure its learning process with .compile():

  1. model.compile(loss='categorical_crossentropy',
  2. optimizer='sgd',
  3. metrics=['accuracy'])

      有需要的话,我们也可以自定义优化器(optimizer)。Keras最核心的设计理念就是在最大化保证易用性的同时,提供给使用者充分的自由去对模型进行全面地控制。

  1. model.compile(loss=keras.losses.categorical_crossentropy,
  2. optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9, nesterov=True))

      这里,我们的损失函数选择的是交叉熵(loss=keras.losses.categorical_crossentropy),优化器选择的是学习率为0.01,动量为0.9的随机梯度下降(optimizer=keras.optimizers.SGD(lr=0.01, momentum=0.9),并启用Nesterov动量(不同的优化方法可参考这里)。

       现在我们就可以以batch的形式来迭代训练我们的模型了:

  1. # x_train and y_train are Numpy arrays --just like in the Scikit-Learn API.
  2. model.fit(x_train, y_train, epochs=5, batch_size=32)

      我们也可以手动地把batch分批喂给模型训练:

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)

      无论是想建立一个问题回答系统,一个图像分类模型,一个神经图灵机,还是任何机器模型,都可以尽可能快。这些深度学习背后的思想都很简单,所以为什么它们的实现过程要那么痛苦呢?这就是存在的意义。

Sequential model

       序列模型(Sequential model)是对神经层的堆叠,而要构建一个序列模型也和容易,通过将List形式组织的layer实例给序列类的构造器即可:

  1. from keras.models import Sequential
  2. from keras.layers import Dense, Activation
  3. model = Sequential([
  4. Dense(32, input_shape=(784,)),
  5. Activation('relu'),
  6. Dense(10),
  7. Activation('softmax'),
  8. ])

      也可以用.add()方法来仅仅加上一层:

  1. model = Sequential()
  2. model.add(Dense(32, input_dim=784))
  3. model.add(Activation('relu'))

Specifying the Input Shape

       序贯模型需要知道所预期给它的输入的形状(shape),而也只有模型的第一层需要手动指明input_shape(后面的层会自己进行形状推断)。对于Dense这样的2D层,也可以用参数input_dim来直接声明input shape,而像一些3D层就同时支持input_dim和input_length参数。

       而如果我们需要声明一个固定大小的batch的输入(这在状态循环网络会用到),我们可以传递参数batch_size给某个层。如果我们同时传递了batch_size=32和input_shape=(6,8)给某个层,那么该层就会预期之后每一次传入的batch输入都具备batch形状(32,6,8)。

       如下,两种方式是等价的:

  1. 方式一:
  2. model = Sequential()
  3. model.add(Dense(32, input_shape=(784,)))
  4. 方式二:
  5. model = Sequential()
  6. model.add(Dense(32, input_dim=784))

Compilation

      在训练一个模型前,我们需要配置它的学习过程,这通过方法compile来完成。compile方法接受三个参数:

         1.一个优化器(optimizer):用字符串形式指定一个keras已有的优化器名称即可(比如rmsprop或者adagrad),或者传递一个Optimizer类的实例也可以。(参见optimizers

         2.一个损失函数(loss function):这是模型将会尽力去最小化的目标。它也可以是字符串形式指定的keras中已有的损失函数类型(比如交叉熵(categorical_crossentropy)或者最小均方误差(mse)),也可以直接是目标方法名称。(参见losses

         3.一个指标列表(a list of metrics):对任意分类问题,其指标都应该是metrics=[‘accuracy’]。一个指标可以是字符串形式指定的已存在的一种指标,也可以是自定义的指标计算函数。

     下面是一些示例:

  1. # For a multi-class classification problem 多分类问题
  2. model.compile(optimizer='rmsprop',
  3. loss='categorical_crossentropy',
  4. metrics=['accuracy'])
  5. # For a binary classification problem 二分类问题
  6. model.compile(optimizer='rmsprop',
  7. loss='binary_crossentropy',
  8. metrics=['accuracy'])
  9. # For a mean squared error regression problem 以mse为损失函数的回归
  10. model.compile(optimizer='rmsprop',
  11. loss='mse')
  12. # For custom metrics 自定义指标
  13. import keras.backend as K
  14. def mean_pred(y_true, y_pred):
  15. return K.mean(y_pred)
  16. model.compile(optimizer='rmsprop',
  17. loss='binary_crossentropy',
  18. metrics=['accuracy', mean_pred])

Training

      keras中的模型要求训练数据以及相应的标签以Numpy中的arrays类型的方式来组织。

     一般用fit()函数来训练一个模型:

  1. # For a single-input model with 2 classes (binary classification):
  2. model = Sequential()
  3. model.add(Dense(32, activation='relu', input_dim=100))
  4. model.add(Dense(1, activation='sigmoid'))
  5. model.compile(optimizer='rmsprop',
  6. loss='binary_crossentropy',
  7. metrics=['accuracy'])
  8. # Generate dummy data
  9. import numpy as np
  10. data = np.random.random((1000, 100))
  11. labels = np.random.randint(2, size=(1000, 1))
  12. # Train the model, iterating on the data in batches of 32 samples
  13. model.fit(data, labels, epochs=10, batch_size=32)
  14. - - - - - - - - - - - - - - - - - - - - - - - - - - - -这里是分界线 - - - - - - - - - - - - - - - - - - - - - - - -
  15. # For a single-input model with 10 classes (categorical classification):
  16. model = Sequential()
  17. model.add(Dense(32, activation='relu', input_dim=100))
  18. model.add(Dense(10, activation='softmax'))
  19. model.compile(optimizer='rmsprop',
  20. loss='categorical_crossentropy',
  21. metrics=['accuracy'])
  22. # Generate dummy data
  23. import numpy as np
  24. data = np.random.random((1000, 100))
  25. labels = np.random.randint(10, size=(1000, 1))
  26. # Convert labels to categorical one-hot encoding
  27. one_hot_labels = keras.utils.to_categorical(labels, num_classes=10)
  28. # Train the model, iterating on the data in batches of 32 samples
  29. model.fit(data, one_hot_labels, epochs=10, batch_size=32)

Examples

      keras提供了许多参考的示例,我们可以在开始动手搭建自己的网络前先看一下这些范例。

      Example 1: minist_mlp (A simple deep multi-layer perceptron on the MNIST dataset)

  1. # 注意,这里的代码是针对Keras2.0版本的代码,而官网提供的是Keras1.0版本的代码,所以一些模块已经做了调整,包括后面的代码也有一些调整
  2. '''Trains a simple deep NN on the MNIST dataset.
  3. Gets to 98.40% test accuracy after 20 epochs
  4. (there is *a lot* of margin for parameter tuning).
  5. 2 seconds per epoch on a K520 GPU.
  6. '''
  7. from __future__ import print_function
  8. import keras
  9. # keras有一个datasets模块,自带了许多经典数据集,包括mnist
  10. from keras.datasets import mnist
  11. from keras.utils import np_utils
  12. from keras.models import Sequential
  13. from keras.layers import Dense, Dropout
  14. from keras.optimizers import RMSprop
  15. batch_size = 128 # batch的大小为128个样例
  16. num_classes = 10 # 一共0-9是个数字,对应10个类别
  17. epochs = 20 # 训练的epochs为20
  18. # the data, shuffled and split between train and test sets
  19. # 注意load_data()方法会首先看当前文件夹下有木有数据源,如果没有,则去指定地址下载
  20. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  21. # mnist的数据都是28*28=784维(像素)的灰度图像
  22. x_train = x_train.reshape(60000, 784)
  23. x_test = x_test.reshape(10000, 784)
  24. x_train = x_train.astype('float32')
  25. x_test = x_test.astype('float32')
  26. # 将像素的灰度值(0-255)统一除以255以归一化,方便计算
  27. x_train /= 255
  28. x_test /= 255
  29. print(x_train.shape[0], 'train samples')
  30. print(x_test.shape[0], 'test samples')
  31. # convert class vectors to binary class matrices
  32. y_train = np_utils.to_categorical(y_train, num_classes)
  33. y_test = np_utils.to_categorical(y_test, num_classes)
  34. # 三层全连接层,前两层使用Dropout,最后一层是输出层
  35. model = Sequential()
  36. model.add(Dense(512, activation='relu', input_shape=(784,)))
  37. model.add(Dropout(0.2))
  38. model.add(Dense(512, activation='relu'))
  39. model.add(Dropout(0.2))
  40. model.add(Dense(num_classes, activation='softmax'))
  41. model.summary()
  42. model.compile(loss='categorical_crossentropy',
  43. optimizer=RMSprop(),
  44. metrics=['accuracy'])
  45. history = model.fit(x_train, y_train,
  46. batch_size=batch_size,
  47. nb_epoch=epochs,
  48. verbose=1,
  49. validation_data=(x_test, y_test))
  50. score = model.evaluate(x_test, y_test, verbose=0)
  51. print('Test loss:', score[0])
  52. print('Test accuracy:', score[1])

       这里进行模型训练和评估时的verbose参数说一下:verbose的取值只能是0、1或2,表示模型训练或评估时的状况输出模式:0=不输出, 1=进度条, 2=每个epoch输出一行。

      Example 2: Simple Convolutional Neural Network (convnet) on the MNIST dataset

  1. '''Trains a simple convnet on the MNIST dataset.
  2. Gets to 99.25% test accuracy after 12 epochs
  3. (there is still a lot of margin for parameter tuning).
  4. 16 seconds per epoch on a GRID K520 GPU.
  5. '''
  6. from __future__ import print_function
  7. import keras
  8. from keras.datasets import mnist
  9. from keras.models import Sequential
  10. from keras.layers import Dense, Dropout, Flatten
  11. from keras.layers import Conv2D, MaxPooling2D
  12. from keras import backend as K
  13. batch_size = 128
  14. num_classes = 10
  15. epochs = 12
  16. # input image dimensions
  17. img_rows, img_cols = 28, 28
  18. # the data, shuffled and split between train and test sets
  19. (x_train, y_train), (x_test, y_test) = mnist.load_data()
  20. if K.image_data_format() == 'channels_first':
  21. x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
  22. x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
  23. input_shape = (1, img_rows, img_cols)
  24. else:
  25. x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
  26. x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
  27. input_shape = (img_rows, img_cols, 1)
  28. x_train = x_train.astype('float32')
  29. x_test = x_test.astype('float32')
  30. x_train /= 255
  31. x_test /= 255
  32. print('x_train shape:', x_train.shape)
  33. print(x_train.shape[0], 'train samples')
  34. print(x_test.shape[0], 'test samples')
  35. # convert class vectors to binary class matrices
  36. y_train = keras.utils.to_categorical(y_train, num_classes)
  37. y_test = keras.utils.to_categorical(y_test, num_classes)
  38. # 一层卷积,323*3的过滤器
  39. # 一层最大池化层
  40. model = Sequential()
  41. model.add(Conv2D(32, kernel_size=(3, 3),
  42. activation='relu',
  43. input_shape=input_shape))
  44. model.add(Conv2D(64, (3, 3), activation='relu'))
  45. model.add(MaxPooling2D(pool_size=(2, 2)))
  46. model.add(Dropout(0.25))
  47. model.add(Flatten())
  48. model.add(Dense(128, activation='relu'))
  49. model.add(Dropout(0.5))
  50. model.add(Dense(num_classes, activation='softmax'))
  51. model.compile(loss=keras.losses.categorical_crossentropy,
  52. optimizer=keras.optimizers.Adadelta(),
  53. metrics=['accuracy'])
  54. model.fit(x_train, y_train,
  55. batch_size=batch_size,
  56. epochs=epochs,
  57. verbose=1,
  58. validation_data=(x_test, y_test))
  59. score = model.evaluate(x_test, y_test, verbose=0)
  60. print('Test loss:', score[0])
  61. print('Test accuracy:', score[1])

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/47448
推荐阅读
相关标签
  

闽ICP备14008679号